diff --git a/.gitignore b/.gitignore index 1b63c7698a..b73c89b1d9 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,4 @@ TestResults/** *.swatches /imgui.ini /scripts/project_manager/logs/ +/AutomatedTesting/Gem/PythonTests/scripting/TestResults diff --git a/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt index 1c555c1e17..a589a395c1 100644 --- a/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/AWS/CMakeLists.txt @@ -12,6 +12,11 @@ ################################################################################ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + # Only enable AWS automated tests on Windows + if(NOT "${PAL_PLATFORM_NAME}" STREQUAL "Windows") + return() + endif() + # Enable after installing NodeJS and CDK on jenkins Windows AMI. ly_add_pytest( NAME AutomatedTesting::AWSTests diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py index b899d7dcde..3aa9fe660c 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_GPUTest_AtomFeatureIntegrationBenchmark.py @@ -93,6 +93,7 @@ def run(): general.idle_wait_frames(100) for i in range(1, 101): benchmarker.capture_pass_timestamp(i) + benchmarker.capture_cpu_frame_time(i) general.exit_game_mode() helper.wait_for_condition(function=lambda: not general.is_in_game_mode(), timeout_in_seconds=2.0) general.log("Capturing complete.") diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/benchmark_utils.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/benchmark_utils.py index 21c7489ed3..b4fdfcb8a0 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/benchmark_utils.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/benchmark_utils.py @@ -61,6 +61,25 @@ class BenchmarkHelper(object): general.log('Failed to capture pass timestamps.') return self.capturedData + def capture_cpu_frame_time(self, frame_number): + """ + Capture CPU frame times and block further execution until it has been written to the disk. + """ + self.handler = azlmbr.atom.ProfilingCaptureNotificationBusHandler() + self.handler.connect() + self.handler.add_callback('OnCaptureCpuFrameTimeFinished', self.on_data_captured) + + self.done = False + self.capturedData = False + success = azlmbr.atom.ProfilingCaptureRequestBus( + azlmbr.bus.Broadcast, "CaptureCpuFrameTime", f'{self.output_path}/cpu_frame{frame_number}_time.json') + if success: + self.wait_until_data() + general.log('CPU frame time captured.') + else: + general.log('Failed to capture CPU frame time.') + return self.capturedData + def on_data_captured(self, parameters): # the parameters come in as a tuple if parameters[0]: diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py index ede140c075..9165bced90 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_GPUTests.py @@ -99,6 +99,7 @@ class TestPerformanceBenchmarkSuite(object): expected_lines = [ "Benchmark metadata captured.", "Pass timestamps captured.", + "CPU frame time captured.", "Capturing complete.", "Captured data successfully." ] @@ -106,6 +107,7 @@ class TestPerformanceBenchmarkSuite(object): unexpected_lines = [ "Failed to capture data.", "Failed to capture pass timestamps.", + "Failed to capture CPU frame time.", "Failed to capture benchmark metadata." ] diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py index b07a34dacd..097d3fb42d 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage.py @@ -93,11 +93,11 @@ def ScriptCanvasComponent_OnEntityActivatedDeactivated_PrintMessage(): 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", + "Properties|Variables|EntityToActivate|Datum|Datum|value|EntityToActivate", entity_to_activate.id, ) sc_component.set_component_property_value( - "Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", + "Properties|Variables|EntityToDeactivate|Datum|Datum|value|EntityToDeactivate", entity_to_deactivate.id, ) return entity diff --git a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt index 600911e9f1..2c1d03b5a2 100644 --- a/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/smoke/CMakeLists.txt @@ -11,7 +11,6 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) if (PAL_TRAIT_BUILD_SERIALIZECONTEXTTOOLS) list(APPEND additional_dependencies AZ::SerializeContextTools) # test_CLITool_SerializeContextTools depends on it endif() - list(APPEND additional_dependencies AZ::AssetBundlerBatch) # test_CLITool_AssetBundlerBatch_Works depends on it ly_add_pytest( NAME AutomatedTesting::SmokeTest @@ -26,26 +25,27 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets - ${aditional_dependencies} + AZ::AzTestRunner + AZ::AssetBundlerBatch + ${additional_dependencies} COMPONENT Smoke ) ly_add_pytest( - NAME AutomatedTesting::SandboxTest - TEST_SUITE sandbox + NAME AutomatedTesting::LoadLevelGPU + TEST_SUITE smoke TEST_SERIAL - PATH ${CMAKE_CURRENT_LIST_DIR} - PYTEST_MARKS "SUITE_sandbox" - TIMEOUT 1500 + TEST_REQUIRES gpu + PATH ${CMAKE_CURRENT_LIST_DIR}/test_RemoteConsole_GPULoadLevel_Works.py + TIMEOUT 100 RUNTIME_DEPENDENCIES AZ::AssetProcessor AZ::PythonBindingsExample - Legacy::Editor AutomatedTesting.GameLauncher AutomatedTesting.Assets COMPONENT - Sandbox + Smoke ) ly_add_pytest( @@ -74,4 +74,5 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) AutomatedTesting.GameLauncher AutomatedTesting.Assets ) + endif() diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py new file mode 100644 index 0000000000..6522514f2f --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_CPULoadLevel_Works.py @@ -0,0 +1,44 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + + +UI Apps: AutomatedTesting.GameLauncher +Launch AutomatedTesting.GameLauncher with Simple level +Test should run in both gpu and non gpu +""" + +import pytest +import psutil + +import ly_test_tools.environment.waiter as waiter +import editor_python_test_tools.hydra_test_utils as editor_test_utils +from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole +from ly_remote_console.remote_console_commands import ( + send_command_and_expect_response as send_command_and_expect_response, +) + + +@pytest.mark.parametrize("launcher_platform", ["windows"]) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("level", ["Simple"]) +@pytest.mark.SUITE_smoke +class TestRemoteConsoleLoadLevelWorks(object): + @pytest.fixture + def remote_console_instance(self, request): + console = RemoteConsole() + + def teardown(): + if console.connected: + console.stop() + + request.addfinalizer(teardown) + + return console + + def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform): + expected_lines = ['Level system is loading "Simple"'] + + editor_test_utils.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, null_renderer=True) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py new file mode 100644 index 0000000000..7debcab938 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_GPULoadLevel_Works.py @@ -0,0 +1,43 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + + +UI Apps: AutomatedTesting.GameLauncher +Launch AutomatedTesting.GameLauncher with Simple level +Test should run in both gpu and non gpu +""" + +import pytest +import psutil + +import ly_test_tools.environment.waiter as waiter +import editor_python_test_tools.hydra_test_utils as editor_test_utils +from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole +from ly_remote_console.remote_console_commands import ( + send_command_and_expect_response as send_command_and_expect_response, +) + + +@pytest.mark.parametrize("launcher_platform", ["windows"]) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("level", ["Simple"]) +class TestRemoteConsoleLoadLevelWorks(object): + @pytest.fixture + def remote_console_instance(self, request): + console = RemoteConsole() + + def teardown(): + if console.connected: + console.stop() + + request.addfinalizer(teardown) + + return console + + def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform): + expected_lines = ['Level system is loading "Simple"'] + + editor_test_utils.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines, null_renderer=False) diff --git a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py b/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py deleted file mode 100644 index b1606e1910..0000000000 --- a/AutomatedTesting/Gem/PythonTests/smoke/test_RemoteConsole_LoadLevel_Works.py +++ /dev/null @@ -1,105 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT - - -UI Apps: AutomatedTesting.GameLauncher -Launch AutomatedTesting.GameLauncher with Simple level -Test should run in both gpu and non gpu -""" - -import pytest -import psutil - -# Bail on the test if ly_test_tools doesn't exist. -pytest.importorskip("ly_test_tools") -import ly_test_tools.environment.waiter as waiter -from ly_remote_console.remote_console_commands import RemoteConsole as RemoteConsole -from ly_remote_console.remote_console_commands import ( - send_command_and_expect_response as send_command_and_expect_response, -) - - -@pytest.mark.parametrize("launcher_platform", ["windows"]) -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -@pytest.mark.parametrize("level", ["Simple"]) -@pytest.mark.SUITE_sandbox -class TestRemoteConsoleLoadLevelWorks(object): - @pytest.fixture - def remote_console_instance(self, request): - console = RemoteConsole() - - def teardown(): - if console.connected: - console.stop() - - request.addfinalizer(teardown) - - return console - - def test_RemoteConsole_LoadLevel_Works(self, launcher, level, remote_console_instance, launcher_platform): - expected_lines = ['Level system is loading "Simple"'] - - self.launch_and_validate_results_launcher(launcher, level, remote_console_instance, expected_lines) - - def launch_and_validate_results_launcher( - self, - launcher, - level, - remote_console_instance, - expected_lines, - null_renderer=False, - port_listener_timeout=120, - log_monitor_timeout=300, - remote_console_port=4600, - ): - """ - Runs the launcher with the specified level, and monitors Game.log for expected lines. - :param launcher: Configured launcher object to run test against. - :param level: The level to load in the launcher. - :param remote_console_instance: Configured Remote Console object. - :param expected_lines: Expected lines to search log for. - :oaram null_renderer: Specifies the test does not require the renderer. Defaults to True. - :param port_listener_timeout: Timeout for verifying successful connection to Remote Console. - :param log_monitor_timeout: Timeout for monitoring for lines in Game.log - :param remote_console_port: The port used to communicate with the Remote Console. - """ - - def _check_for_listening_port(port): - """ - Checks to see if the connection to the designated port was established. - :param port: Port to listen to. - :return: True if port is listening. - """ - port_listening = False - for conn in psutil.net_connections(): - if "port={}".format(port) in str(conn): - port_listening = True - return port_listening - - if null_renderer: - launcher.args.extend(["-NullRenderer"]) - - # Start the Launcher - with launcher.start(): - - # Ensure Remote Console can be reached - waiter.wait_for( - lambda: _check_for_listening_port(remote_console_port), - port_listener_timeout, - exc=AssertionError("Port {} not listening.".format(remote_console_port)), - ) - remote_console_instance.start(timeout=30) - - # Load the specified level in the launcher - send_command_and_expect_response( - remote_console_instance, f"loadlevel {level}", "LEVEL_LOAD_END", timeout=30 - ) - - # Monitor the console for expected lines - for line in expected_lines: - assert remote_console_instance.expect_log_line( - line, log_monitor_timeout - ), f"Expected line not found: {line}" diff --git a/CMakeLists.txt b/CMakeLists.txt index 0a38177714..bd02eeb7ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -28,8 +28,8 @@ include(cmake/FileUtil.cmake) include(cmake/PAL.cmake) include(cmake/PALTools.cmake) include(cmake/RuntimeDependencies.cmake) -include(cmake/Install.cmake) include(cmake/Configurations.cmake) # Requires to be after PAL so we get platform variable definitions +include(cmake/Install.cmake) include(cmake/Dependencies.cmake) include(cmake/Deployment.cmake) include(cmake/3rdParty.cmake) diff --git a/Code/Editor/2DViewport.cpp b/Code/Editor/2DViewport.cpp index 56f2e7bdf5..838d30e0b3 100644 --- a/Code/Editor/2DViewport.cpp +++ b/Code/Editor/2DViewport.cpp @@ -952,7 +952,8 @@ void Q2DViewport::DrawViewerMarker(DisplayContext& dc) dc.SetColor(QColor(0, 0, 255)); // blue dc.DrawWireBox(-dim * noScale, dim * noScale); - float fov = GetIEditor()->GetSystem()->GetViewCamera().GetFov(); + constexpr float DefaultFov = 60.f; + float fov = DefaultFov; Vec3 q[4]; float dist = 30; diff --git a/Code/Editor/AboutDialog.cpp b/Code/Editor/AboutDialog.cpp index 8429e86553..f8abe67376 100644 --- a/Code/Editor/AboutDialog.cpp +++ b/Code/Editor/AboutDialog.cpp @@ -25,7 +25,7 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -CAboutDialog::CAboutDialog(QString versionText, QString richTextCopyrightNotice, QWidget* pParent /*=NULL*/) +CAboutDialog::CAboutDialog(QString versionText, QString richTextCopyrightNotice, QWidget* pParent /*=nullptr*/) : QDialog(pParent) , m_ui(new Ui::CAboutDialog) { diff --git a/Code/Editor/AnimationContext.cpp b/Code/Editor/AnimationContext.cpp index debe5e3b01..6e146faacb 100644 --- a/Code/Editor/AnimationContext.cpp +++ b/Code/Editor/AnimationContext.cpp @@ -16,7 +16,6 @@ // Editor #include "TrackView/TrackViewDialog.h" -#include "RenderViewport.h" #include "ViewManager.h" #include "Objects/SelectionGroup.h" #include "Include/IObjectManager.h" @@ -29,7 +28,7 @@ class CMovieCallback : public IMovieCallback { protected: - virtual void OnMovieCallback(ECallbackReason reason, [[maybe_unused]] IAnimNode* pNode) + void OnMovieCallback(ECallbackReason reason, [[maybe_unused]] IAnimNode* pNode) override { switch (reason) { @@ -49,7 +48,7 @@ protected: } } - void OnSetCamera(const SCameraParams& Params) + void OnSetCamera(const SCameraParams& Params) override { // Only switch camera when in Play mode. GUID camObjId = GUID_NULL; @@ -61,15 +60,6 @@ protected: { camObjId = pEditorEntity->GetId(); } - - CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(pViewport)) - { - if (!rvp->IsSequenceCamera()) - { - return; - } - } } // Switch camera in active rendering view. @@ -79,14 +69,14 @@ protected: } }; - bool IsSequenceCamUsed() const + bool IsSequenceCamUsed() const override { if (gEnv->IsEditorGameMode() == true) { return true; } - if (GetIEditor()->GetViewManager() == NULL) + if (GetIEditor()->GetViewManager() == nullptr) { return false; } @@ -113,7 +103,7 @@ public: CAnimationContextPostRender(CAnimationContext* pAC) : m_pAC(pAC){} - void OnPostRender() const { assert(m_pAC); m_pAC->OnPostRender(); } + void OnPostRender() const override { assert(m_pAC); m_pAC->OnPostRender(); } protected: CAnimationContext* m_pAC; @@ -231,7 +221,7 @@ void CAnimationContext::SetSequence(CTrackViewSequence* sequence, bool force, bo m_pSequence->UnBindFromEditorObjects(); } m_pSequence = sequence; - + // Notify a new sequence was just selected. Maestro::EditorSequenceNotificationBus::Broadcast(&Maestro::EditorSequenceNotificationBus::Events::OnSequenceSelected, m_pSequence ? m_pSequence->GetSequenceComponentEntityId() : AZ::EntityId()); @@ -347,7 +337,7 @@ void CAnimationContext::OnSequenceActivated(AZ::EntityId entityId) { // Hang onto this because SetSequence() will reset it. float lastTime = m_mostRecentSequenceTime; - + SetSequence(sequence, false, false); // Restore the current time. diff --git a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp index c93ad087ce..c54fe60c4d 100644 --- a/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp +++ b/Code/Editor/AzAssetBrowser/AzAssetBrowserWindow.cpp @@ -82,6 +82,7 @@ AzAssetBrowserWindow::AzAssetBrowserWindow(QWidget* parent) m_ui->m_assetBrowserTableViewWidget->setVisible(false); m_ui->m_toggleDisplayViewBtn->setVisible(false); + m_ui->m_searchWidget->SetFilterInputInterval(AZStd::chrono::milliseconds(250)); if (ed_useNewAssetBrowserTableView) { m_ui->m_toggleDisplayViewBtn->setVisible(true); diff --git a/Code/Editor/BaseLibrary.cpp b/Code/Editor/BaseLibrary.cpp index ee1c85756d..7c920a7f04 100644 --- a/Code/Editor/BaseLibrary.cpp +++ b/Code/Editor/BaseLibrary.cpp @@ -24,10 +24,10 @@ class CUndoBaseLibrary : public IUndoObject { public: - CUndoBaseLibrary(CBaseLibrary* pLib, const QString& description, const QString& selectedItem = 0) + CUndoBaseLibrary(CBaseLibrary* pLib, const QString& description, const QString& selectedItem = QString()) : m_pLib(pLib) , m_description(description) - , m_redo(0) + , m_redo(nullptr) , m_selectedItem(selectedItem) { assert(m_pLib); @@ -36,16 +36,16 @@ public: m_pLib->Serialize(m_undo, false); } - virtual QString GetEditorObjectName() + QString GetEditorObjectName() override { return m_selectedItem; } protected: - virtual int GetSize() { return sizeof(CUndoBaseLibrary); } - virtual QString GetDescription() { return m_description; }; + int GetSize() override { return sizeof(CUndoBaseLibrary); } + QString GetDescription() override { return m_description; }; - virtual void Undo(bool bUndo) + void Undo(bool bUndo) override { if (bUndo) { @@ -57,7 +57,7 @@ protected: GetIEditor()->Notify(eNotify_OnDataBaseUpdate); } - virtual void Redo() + void Redo() override { m_pLib->Serialize(m_redo, true); m_pLib->SetModified(); @@ -107,7 +107,7 @@ void CBaseLibrary::RemoveAllItems() // Unregister item in case it was registered. It is ok if it wasn't. This is still safe to call. m_pManager->UnregisterItem(m_items[i]); // Clear library item. - m_items[i]->m_library = NULL; + m_items[i]->m_library = nullptr; } m_items.clear(); Release(); @@ -216,7 +216,7 @@ IDataBaseItem* CBaseLibrary::FindItem(const QString& name) return m_items[i]; } } - return NULL; + return nullptr; } bool CBaseLibrary::AddLibraryToSourceControl(const QString& fullPathName) const @@ -233,8 +233,8 @@ bool CBaseLibrary::AddLibraryToSourceControl(const QString& fullPathName) const bool CBaseLibrary::SaveLibrary(const char* name, bool saveEmptyLibrary) { - assert(name != NULL); - if (name == NULL) + assert(name != nullptr); + if (name == nullptr) { CryFatalError("The library you are attempting to save has no name specified."); return false; diff --git a/Code/Editor/BaseLibraryItem.cpp b/Code/Editor/BaseLibraryItem.cpp index fd310eaf9f..252510c951 100644 --- a/Code/Editor/BaseLibraryItem.cpp +++ b/Code/Editor/BaseLibraryItem.cpp @@ -16,7 +16,7 @@ #include -//undo object for multi-changes inside library item. such as set all variables to default values. +//undo object for multi-changes inside library item. such as set all variables to default values. //For example: change particle emitter shape will lead to multiple variable changes class CUndoBaseLibraryItem : public IUndoObject @@ -54,24 +54,24 @@ public: } protected: - virtual int GetSize() - { + int GetSize() override + { return m_size; } QString GetDescription() override - { - return m_description; + { + return m_description; } - virtual void Undo(bool bUndo) + void Undo(bool bUndo) override { //find the libItem IDataBaseItem *libItem = m_libMgr->FindItemByName(m_itemPath); if (libItem == nullptr) { //the undo stack is not reliable any more.. - assert(false); + assert(false); return; } @@ -95,7 +95,7 @@ protected: libItem->Serialize(m_undoCtx); } - virtual void Redo() + void Redo() override { //find the libItem IDataBaseItem *libItem = m_libMgr->FindItemByName(m_itemPath); @@ -124,7 +124,7 @@ private: ////////////////////////////////////////////////////////////////////////// CBaseLibraryItem::CBaseLibraryItem() { - m_library = 0; + m_library = nullptr; GenerateId(); m_bModified = false; } @@ -266,7 +266,7 @@ void CBaseLibraryItem::SetLibrary(CBaseLibrary* pLibrary) void CBaseLibraryItem::SetModified(bool bModified) { m_bModified = bModified; - if (m_bModified && m_library != NULL) + if (m_bModified && m_library != nullptr) { m_library->SetModified(bModified); } diff --git a/Code/Editor/BaseLibraryManager.cpp b/Code/Editor/BaseLibraryManager.cpp index 8e555cae8c..6dd7dc58a5 100644 --- a/Code/Editor/BaseLibraryManager.cpp +++ b/Code/Editor/BaseLibraryManager.cpp @@ -26,7 +26,7 @@ class CUndoBaseLibraryManager : public IUndoObject { public: - CUndoBaseLibraryManager(CBaseLibraryManager* pMngr, const QString& description, const QString& modifiedManager = 0) + CUndoBaseLibraryManager(CBaseLibraryManager* pMngr, const QString& description, const QString& modifiedManager = nullptr) : m_pMngr(pMngr) , m_description(description) , m_editorObject(modifiedManager) @@ -35,16 +35,16 @@ public: SerializeTo(m_undos); } - virtual QString GetEditorObjectName() + QString GetEditorObjectName() override { return m_editorObject; } protected: - virtual int GetSize() { return sizeof(CUndoBaseLibraryManager); } - virtual QString GetDescription() { return m_description; }; + int GetSize() override { return sizeof(CUndoBaseLibraryManager); } + QString GetDescription() override { return m_description; }; - virtual void Undo(bool bUndo) + void Undo(bool bUndo) override { if (bUndo) { @@ -55,7 +55,7 @@ protected: GetIEditor()->Notify(eNotify_OnDataBaseUpdate); } - virtual void Redo() + void Redo() override { m_pMngr->ClearAll(); UnserializeFrom(m_redos); @@ -84,7 +84,7 @@ private: for (int i = 0; i < m_pMngr->GetLibraryCount(); i++) { IDataBaseLibrary* library = m_pMngr->GetLibrary(i); - + const char* tag = library->IsLevelLibrary() ? LEVEL_LIBRARY_TAG : LIBRARY_TAG; XmlNodeRef node = GetIEditor()->GetSystem()->CreateXmlNode(tag); QString file = library->GetFilename().isEmpty() ? library->GetFilename() : library->GetName(); @@ -203,7 +203,7 @@ int CBaseLibraryManager::FindLibraryIndex(const QString& library) ////////////////////////////////////////////////////////////////////////// IDataBaseItem* CBaseLibraryManager::FindItem(REFGUID guid) const { - CBaseLibraryItem* pMtl = stl::find_in_map(m_itemsGuidMap, guid, (CBaseLibraryItem*)0); + CBaseLibraryItem* pMtl = stl::find_in_map(m_itemsGuidMap, guid, nullptr); return pMtl; } @@ -226,7 +226,7 @@ void CBaseLibraryManager::SplitFullItemName(const QString& fullItemName, QString IDataBaseItem* CBaseLibraryManager::FindItemByName(const QString& fullItemName) { AZStd::lock_guard lock(m_itemsNameMapMutex); - return stl::find_in_map(m_itemsNameMap, fullItemName, 0); + return stl::find_in_map(m_itemsNameMap, fullItemName, nullptr); } ////////////////////////////////////////////////////////////////////////// @@ -398,7 +398,7 @@ void CBaseLibraryManager::DeleteLibrary(const QString& library, bool forceDelete UnregisterItem((CBaseLibraryItem*)pLibrary->GetItem(j)); } pLibrary->RemoveAllItems(); - + if (pLibrary->IsLevelLibrary()) { m_pLevelLibrary = nullptr; @@ -420,7 +420,7 @@ IDataBaseLibrary* CBaseLibraryManager::GetLibrary(int index) const ////////////////////////////////////////////////////////////////////////// IDataBaseLibrary* CBaseLibraryManager::GetLevelLibrary() const { - IDataBaseLibrary* pLevelLib = NULL; + IDataBaseLibrary* pLevelLib = nullptr; for (int i = 0; i < GetLibraryCount(); i++) { @@ -531,9 +531,9 @@ QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QS // search for strings in the database that might have a similar name (ignore case) IDataBaseItemEnumerator* pEnum = GetItemEnumerator(); - for (IDataBaseItem* pItem = pEnum->GetFirst(); pItem != NULL; pItem = pEnum->GetNext()) + for (IDataBaseItem* pItem = pEnum->GetFirst(); pItem != nullptr; pItem = pEnum->GetNext()) { - //Check if the item is in the target library first. + //Check if the item is in the target library first. IDataBaseLibrary* itemLibrary = pItem->GetLibrary(); QString itemLibraryName; if (itemLibrary) @@ -590,7 +590,7 @@ QString CBaseLibraryManager::MakeUniqueItemName(const QString& srcName, const QS void CBaseLibraryManager::Validate() { IDataBaseItemEnumerator* pEnum = GetItemEnumerator(); - for (IDataBaseItem* pItem = pEnum->GetFirst(); pItem != NULL; pItem = pEnum->GetNext()) + for (IDataBaseItem* pItem = pEnum->GetFirst(); pItem != nullptr; pItem = pEnum->GetNext()) { pItem->Validate(); } @@ -617,7 +617,7 @@ void CBaseLibraryManager::RegisterItem(CBaseLibraryItem* pItem, REFGUID newGuid) { return; } - CBaseLibraryItem* pOldItem = stl::find_in_map(m_itemsGuidMap, newGuid, (CBaseLibraryItem*)0); + CBaseLibraryItem* pOldItem = stl::find_in_map(m_itemsGuidMap, newGuid, nullptr); if (!pOldItem) { pItem->m_guid = newGuid; @@ -677,7 +677,7 @@ void CBaseLibraryManager::RegisterItem(CBaseLibraryItem* pItem) { return; } - CBaseLibraryItem* pOldItem = stl::find_in_map(m_itemsGuidMap, pItem->GetGUID(), (CBaseLibraryItem*)0); + CBaseLibraryItem* pOldItem = stl::find_in_map(m_itemsGuidMap, pItem->GetGUID(), nullptr); if (!pOldItem) { m_itemsGuidMap[pItem->GetGUID()] = pItem; @@ -789,7 +789,7 @@ QString CBaseLibraryManager::MakeFullItemName(IDataBaseLibrary* pLibrary, const void CBaseLibraryManager::GatherUsedResources(CUsedResources& resources) { IDataBaseItemEnumerator* pEnum = GetItemEnumerator(); - for (IDataBaseItem* pItem = pEnum->GetFirst(); pItem != NULL; pItem = pEnum->GetNext()) + for (IDataBaseItem* pItem = pEnum->GetFirst(); pItem != nullptr; pItem = pEnum->GetNext()) { pItem->GatherUsedResources(resources); } @@ -815,15 +815,15 @@ void CBaseLibraryManager::OnEditorNotifyEvent(EEditorNotifyEvent event) switch (event) { case eNotify_OnBeginNewScene: - SetSelectedItem(0); + SetSelectedItem(nullptr); ClearAll(); break; case eNotify_OnBeginSceneOpen: - SetSelectedItem(0); + SetSelectedItem(nullptr); ClearAll(); break; case eNotify_OnCloseScene: - SetSelectedItem(0); + SetSelectedItem(nullptr); ClearAll(); break; } @@ -913,7 +913,7 @@ void CBaseLibraryManager::ChangeLibraryOrder(IDataBaseLibrary* lib, unsigned int { return; } - + for (int i = 0; i < m_libs.size(); i++) { if (lib == m_libs[i]) diff --git a/Code/Editor/CheckOutDialog.h b/Code/Editor/CheckOutDialog.h index 7e7054ccdf..9ad64c57cf 100644 --- a/Code/Editor/CheckOutDialog.h +++ b/Code/Editor/CheckOutDialog.h @@ -34,7 +34,7 @@ public: CANCEL = QDialog::Rejected }; - CCheckOutDialog(const QString& file, QWidget* pParent = NULL); // standard constructor + CCheckOutDialog(const QString& file, QWidget* pParent = nullptr); // standard constructor virtual ~CCheckOutDialog(); // Dialog Data diff --git a/Code/Editor/ConfigGroup.cpp b/Code/Editor/ConfigGroup.cpp index 4e61c38f4b..c1e0abbf31 100644 --- a/Code/Editor/ConfigGroup.cpp +++ b/Code/Editor/ConfigGroup.cpp @@ -48,7 +48,7 @@ namespace Config } } - return NULL; + return nullptr; } const IConfigVar* CConfigGroup::GetVar(const char* szName) const @@ -63,7 +63,7 @@ namespace Config } } - return NULL; + return nullptr; } IConfigVar* CConfigGroup::GetVar(uint index) @@ -73,7 +73,7 @@ namespace Config return m_vars[index]; } - return NULL; + return nullptr; } const IConfigVar* CConfigGroup::GetVar(uint index) const @@ -83,7 +83,7 @@ namespace Config return m_vars[index]; } - return NULL; + return nullptr; } void CConfigGroup::SaveToXML(XmlNodeRef node) @@ -127,7 +127,7 @@ namespace Config case IConfigVar::eType_STRING: { - string currentValue = 0; + string currentValue = nullptr; var->Get(¤tValue); node->setAttr(szName, currentValue); break; @@ -186,7 +186,7 @@ namespace Config case IConfigVar::eType_STRING: { - string currentValue = 0; + string currentValue = nullptr; var->GetDefault(¤tValue); QString readValue(currentValue.c_str()); if (node->getAttr(szName, readValue)) diff --git a/Code/Editor/ConfigGroup.h b/Code/Editor/ConfigGroup.h index 35c0b8e47f..f772823ad8 100644 --- a/Code/Editor/ConfigGroup.h +++ b/Code/Editor/ConfigGroup.h @@ -37,11 +37,11 @@ namespace Config , m_description(szDescription) , m_type(varType) , m_flags(flags) - , m_ptr(NULL) + , m_ptr(nullptr) {}; virtual ~IConfigVar() = default; - + ILINE EType GetType() const { return m_type; diff --git a/Code/Editor/ControlMRU.cpp b/Code/Editor/ControlMRU.cpp index 47de13950f..a721876624 100644 --- a/Code/Editor/ControlMRU.cpp +++ b/Code/Editor/ControlMRU.cpp @@ -28,7 +28,7 @@ void CControlMRU::OnCalcDynamicSize(DWORD dwMode) CString* pArrNames = pRecentFileList->m_arrNames; - assert(pArrNames != NULL); + assert(pArrNames != nullptr); if (!pArrNames) { return; @@ -52,7 +52,7 @@ void CControlMRU::OnCalcDynamicSize(DWORD dwMode) if (m_pParent->IsCustomizeMode()) { m_dwHideFlags = 0; - SetEnabled(TRUE); + SetEnabled(true); return; } @@ -61,7 +61,7 @@ void CControlMRU::OnCalcDynamicSize(DWORD dwMode) SetCaption(CString(MAKEINTRESOURCE(IDS_NORECENTFILE_CAPTION))); SetDescription("No recently opened files"); m_dwHideFlags = 0; - SetEnabled(FALSE); + SetEnabled(false); return; } @@ -105,7 +105,7 @@ void CControlMRU::OnCalcDynamicSize(DWORD dwMode) int nId = iMRU + GetFirstMruID(); - CXTPControl* pControl = m_pControls->Add(xtpControlButton, nId, _T(""), m_nIndex + iLastValidMRU + 1, TRUE); + CXTPControl* pControl = m_pControls->Add(xtpControlButton, nId, _T(""), m_nIndex + iLastValidMRU + 1, true); assert(pControl); pControl->SetCaption(CXTPControlWindowList::ConstructCaption(strName, iLastValidMRU + 1)); @@ -130,6 +130,6 @@ void CControlMRU::OnCalcDynamicSize(DWORD dwMode) SetCaption(CString(MAKEINTRESOURCE(IDS_NORECENTFILE_CAPTION))); SetDescription("No recently opened files"); m_dwHideFlags = 0; - SetEnabled(FALSE); + SetEnabled(false); } } diff --git a/Code/Editor/CrtDebug.cpp b/Code/Editor/CrtDebug.cpp index a37b3d26e9..f9335373da 100644 --- a/Code/Editor/CrtDebug.cpp +++ b/Code/Editor/CrtDebug.cpp @@ -62,7 +62,7 @@ int crtAllocHook(int nAllocType, void* pvData, { if (nBlockUse == _CRT_BLOCK) { - return(TRUE); + return TRUE; } static int total_cnt = 0; diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index efeb7cdd19..bc96a8f3a8 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -127,7 +127,6 @@ AZ_POP_DISABLE_WARNING #include "Util/AutoDirectoryRestoreFileDialog.h" #include "Util/EditorAutoLevelLoadTest.h" -#include "Util/IndexedFiles.h" #include "AboutDialog.h" #include @@ -267,13 +266,13 @@ CCrySingleDocTemplate* CCryDocManager::SetDefaultTemplate(CCrySingleDocTemplate* // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog void CCryDocManager::OnFileNew() { - assert(m_pDefTemplate != NULL); + assert(m_pDefTemplate != nullptr); - m_pDefTemplate->OpenDocumentFile(NULL); + m_pDefTemplate->OpenDocumentFile(nullptr); // if returns NULL, the user has already been alerted } -BOOL CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle, - [[maybe_unused]] DWORD lFlags, BOOL bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate) +bool CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT nIDSTitle, + [[maybe_unused]] DWORD lFlags, bool bOpenFileDialog, [[maybe_unused]] CDocTemplate* pTemplate) { CLevelFileDialog levelFileDialog(bOpenFileDialog); levelFileDialog.show(); @@ -287,15 +286,15 @@ BOOL CCryDocManager::DoPromptFileName(QString& fileName, [[maybe_unused]] UINT n return false; } -CCryEditDoc* CCryDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU) +CCryEditDoc* CCryDocManager::OpenDocumentFile(LPCTSTR lpszFileName, bool bAddToMRU) { - assert(lpszFileName != NULL); + assert(lpszFileName != nullptr); // find the highest confidence auto pos = m_templateList.begin(); CCrySingleDocTemplate::Confidence bestMatch = CCrySingleDocTemplate::noAttempt; - CCrySingleDocTemplate* pBestTemplate = NULL; - CCryEditDoc* pOpenDocument = NULL; + CCrySingleDocTemplate* pBestTemplate = nullptr; + CCryEditDoc* pOpenDocument = nullptr; if (lpszFileName[0] == '\"') { @@ -312,7 +311,7 @@ CCryEditDoc* CCryDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToM auto pTemplate = *(pos++); CCrySingleDocTemplate::Confidence match; - assert(pOpenDocument == NULL); + assert(pOpenDocument == nullptr); match = pTemplate->MatchDocType(szPath.toUtf8().data(), pOpenDocument); if (match > bestMatch) { @@ -325,18 +324,18 @@ CCryEditDoc* CCryDocManager::OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToM } } - if (pOpenDocument != NULL) + if (pOpenDocument != nullptr) { return pOpenDocument; } - if (pBestTemplate == NULL) + if (pBestTemplate == nullptr) { QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("Failed to open document.")); - return NULL; + return nullptr; } - return pBestTemplate->OpenDocumentFile(szPath.toUtf8().data(), bAddToMRU, FALSE); + return pBestTemplate->OpenDocumentFile(szPath.toUtf8().data(), bAddToMRU, false); } ////////////////////////////////////////////////////////////////////////////// @@ -461,7 +460,7 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_SAVE_LEVEL, OnFileSave) ON_COMMAND(ID_FILE_EXPORTOCCLUSIONMESH, OnFileExportOcclusionMesh) - // Project Manager + // Project Manager ON_COMMAND(ID_FILE_PROJECT_MANAGER_SETTINGS, OnOpenProjectManagerSettings) ON_COMMAND(ID_FILE_PROJECT_MANAGER_NEW, OnOpenProjectManagerNew) ON_COMMAND(ID_FILE_PROJECT_MANAGER_OPEN, OnOpenProjectManager) @@ -654,7 +653,7 @@ struct SharedData // // This function uses a technique similar to that described in KB // article Q141752 to locate the previous instance of the application. . -BOOL CCryEditApp::FirstInstance(bool bForceNewInstance) +bool CCryEditApp::FirstInstance(bool bForceNewInstance) { QSystemSemaphore sem(QString(O3DEApplicationName) + "_sem", 1); sem.acquire(); @@ -802,12 +801,12 @@ void CCryEditApp::InitDirectory() // Needed to work with custom memory manager. ////////////////////////////////////////////////////////////////////////// -CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible /*= true*/) +CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, bool bMakeVisible /*= true*/) { return OpenDocumentFile(lpszPathName, true, bMakeVisible); } -CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL bAddToMRU, [[maybe_unused]] BOOL bMakeVisible) +CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, bool bAddToMRU, [[maybe_unused]] bool bMakeVisible) { CCryEditDoc* pCurDoc = GetIEditor()->GetDocument(); @@ -848,8 +847,8 @@ CCryEditDoc* CCrySingleDocTemplate::OpenDocumentFile(LPCTSTR lpszPathName, BOOL CCrySingleDocTemplate::Confidence CCrySingleDocTemplate::MatchDocType(LPCTSTR lpszPathName, CCryEditDoc*& rpDocMatch) { - assert(lpszPathName != NULL); - rpDocMatch = NULL; + assert(lpszPathName != nullptr); + rpDocMatch = nullptr; // go through all documents CCryEditDoc* pDoc = GetIEditor()->GetDocument(); @@ -1056,7 +1055,7 @@ AZ::Outcome CCryEditApp::InitGameSystem(HWND hwndForInputSy } ///////////////////////////////////////////////////////////////////////////// -BOOL CCryEditApp::CheckIfAlreadyRunning() +bool CCryEditApp::CheckIfAlreadyRunning() { bool bForceNewInstance = false; @@ -1300,7 +1299,7 @@ void CCryEditApp::InitLevel(const CEditCommandLineInfo& cmdInfo) } ///////////////////////////////////////////////////////////////////////////// -BOOL CCryEditApp::InitConsole() +bool CCryEditApp::InitConsole() { // Execute command from cmdline -exec_line if applicable if (!m_execLineCmd.isEmpty()) @@ -1432,7 +1431,7 @@ struct CCryEditApp::PythonOutputHandler AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusConnect(); } - virtual ~PythonOutputHandler() + ~PythonOutputHandler() override { AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); } @@ -1464,7 +1463,7 @@ struct PythonTestOutputHandler final : public CCryEditApp::PythonOutputHandler { PythonTestOutputHandler() = default; - virtual ~PythonTestOutputHandler() = default; + ~PythonTestOutputHandler() override = default; void OnTraceMessage(AZStd::string_view message) override { @@ -1590,7 +1589,7 @@ void CCryEditApp::RunInitPythonScript(CEditCommandLineInfo& cmdInfo) ///////////////////////////////////////////////////////////////////////////// // CCryEditApp initialization -BOOL CCryEditApp::InitInstance() +bool CCryEditApp::InitInstance() { QElapsedTimer startupTimer; startupTimer.start(); @@ -1617,7 +1616,7 @@ BOOL CCryEditApp::InitInstance() { CAboutDialog aboutDlg(FormatVersion(m_pEditor->GetFileVersion()), FormatRichTextCopyrightNotice()); aboutDlg.exec(); - return FALSE; + return false; } // Reflect property control classes to the serialize context... @@ -1627,9 +1626,6 @@ BOOL CCryEditApp::InitInstance() ReflectedVarInit::setupReflection(serializeContext); RegisterReflectedVarHandlers(); - - QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); - CreateSplashScreen(); // Register the application's document templates. Document templates @@ -1715,18 +1711,6 @@ BOOL CCryEditApp::InitInstance() if (IsInRegularEditorMode()) { - CIndexedFiles::Create(); - - if (gEnv->pConsole->GetCVar("ed_indexfiles")->GetIVal()) - { - Log("Started game resource files indexing..."); - CIndexedFiles::StartFileIndexing(); - } - else - { - Log("Game resource files indexing is disabled."); - } - // QuickAccessBar creation should be before m_pMainWnd->SetFocus(), // since it receives the focus at creation time. It brakes MainFrame key accelerators. m_pQuickAccessBar = new CQuickAccessBar; @@ -1772,7 +1756,7 @@ BOOL CCryEditApp::InitInstance() } } - SetEditorWindowTitle(0, AZ::Utils::GetProjectName().c_str(), 0); + SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectName().c_str(), nullptr); if (!GetIEditor()->IsInMatEditMode()) { m_pEditor->InitFinished(); @@ -1857,8 +1841,8 @@ void CCryEditApp::RegisterEventLoopHook(IEventLoopHook* pHook) void CCryEditApp::UnregisterEventLoopHook(IEventLoopHook* pHookToRemove) { - IEventLoopHook* pPrevious = 0; - for (IEventLoopHook* pHook = m_pEventLoopHook; pHook != 0; pHook = pHook->pNextHook) + IEventLoopHook* pPrevious = nullptr; + for (IEventLoopHook* pHook = m_pEventLoopHook; pHook != nullptr; pHook = pHook->pNextHook) { if (pHook == pHookToRemove) { @@ -1871,7 +1855,7 @@ void CCryEditApp::UnregisterEventLoopHook(IEventLoopHook* pHookToRemove) m_pEventLoopHook = pHookToRemove->pNextHook; } - pHookToRemove->pNextHook = 0; + pHookToRemove->pNextHook = nullptr; return; } } @@ -1894,7 +1878,7 @@ void CCryEditApp::LoadFile(QString fileName) if (MainWindow::instance() || m_pConsoleDialog) { - SetEditorWindowTitle(0, AZ::Utils::GetProjectName().c_str(), GetIEditor()->GetGameEngine()->GetLevelName()); + SetEditorWindowTitle(nullptr, AZ::Utils::GetProjectName().c_str(), GetIEditor()->GetGameEngine()->GetLevelName()); } GetIEditor()->SetModifiedFlag(false); @@ -1935,7 +1919,7 @@ void CCryEditApp::EnableAccelerator([[maybe_unused]] bool bEnable) CMainFrame *mainFrame = (CMainFrame*)m_pMainWnd; if (mainFrame->m_hAccelTable) DestroyAcceleratorTable( mainFrame->m_hAccelTable ); - mainFrame->m_hAccelTable = NULL; + mainFrame->m_hAccelTable = nullptr; mainFrame->LoadAccelTable( MAKEINTRESOURCE(IDR_GAMEACCELERATOR) ); CLogFile::WriteLine( "Disable Accelerators" ); } @@ -2163,12 +2147,6 @@ int CCryEditApp::ExitInstance(int exitCode) } } - if (IsInRegularEditorMode()) - { - CIndexedFiles::AbortFileIndexing(); - CIndexedFiles::Destroy(); - } - if (GetIEditor() && !GetIEditor()->IsInMatEditMode()) { //Nobody seems to know in what case that kind of exit can happen so instrumented to see if it happens at all @@ -2278,7 +2256,7 @@ void CCryEditApp::EnableIdleProcessing() AZ_Assert(m_disableIdleProcessingCounter >= 0, "m_disableIdleProcessingCounter must be nonnegative"); } -BOOL CCryEditApp::OnIdle([[maybe_unused]] LONG lCount) +bool CCryEditApp::OnIdle([[maybe_unused]] LONG lCount) { if (0 == m_disableIdleProcessingCounter) { @@ -2286,7 +2264,7 @@ BOOL CCryEditApp::OnIdle([[maybe_unused]] LONG lCount) } else { - return 0; + return false; } } @@ -3161,7 +3139,7 @@ void CCryEditApp::OnCreateLevel() ////////////////////////////////////////////////////////////////////////// bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled) { - BOOL bIsDocModified = GetIEditor()->GetDocument()->IsModified(); + bool bIsDocModified = GetIEditor()->GetDocument()->IsModified(); if (GetIEditor()->GetDocument()->IsDocumentReady() && bIsDocModified) { QString str = QObject::tr("Level %1 has been changed. Save Level?").arg(GetIEditor()->GetGameEngine()->GetLevelName()); @@ -3249,11 +3227,11 @@ bool CCryEditApp::CreateLevel(bool& wasCreateLevelOperationCancelled) #ifdef WIN32 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, + nullptr, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), windowsErrorMessage.data(), - windowsErrorMessage.length(), NULL); + windowsErrorMessage.length(), nullptr); _getcwd(cwd.data(), cwd.length()); #else windowsErrorMessage = strerror(dw); @@ -3663,24 +3641,12 @@ void CCryEditApp::OnToolsPreferences() ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToDefaultCamera() { - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetDefaultCamera(); - } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action) { Q_ASSERT(action->isCheckable()); - CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(pViewport)) - { - action->setEnabled(true); - action->setChecked(rvp->IsDefaultCamera()); - } - else { action->setEnabled(false); } @@ -3689,39 +3655,12 @@ void CCryEditApp::OnUpdateSwitchToDefaultCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToSequenceCamera() { - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetSequenceCamera(); - } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action) { Q_ASSERT(action->isCheckable()); - - CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); - - if (CRenderViewport* rvp = viewport_cast(pViewport)) - { - bool enableAction = false; - - // only enable if we're editing a sequence in Track View and have cameras in the level - if (GetIEditor()->GetAnimation()->GetSequence()) - { - - AZ::EBusAggregateResults componentCameras; - Camera::CameraBus::BroadcastResult(componentCameras, &Camera::CameraRequests::GetCameras); - - const int numCameras = componentCameras.values.size(); - enableAction = (numCameras > 0); - } - - action->setEnabled(enableAction); - action->setChecked(rvp->IsSequenceCamera()); - } - else { action->setEnabled(false); } @@ -3730,31 +3669,12 @@ void CCryEditApp::OnUpdateSwitchToSequenceCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchToSelectedcamera() { - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetSelectedCamera(); - } } ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action) { Q_ASSERT(action->isCheckable()); - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - AZ::EBusAggregateResults cameras; - Camera::CameraBus::BroadcastResult(cameras, &Camera::CameraRequests::GetCameras); - bool isCameraComponentSelected = selectedEntityList.size() > 0 ? AZStd::find(cameras.values.begin(), cameras.values.end(), *selectedEntityList.begin()) != cameras.values.end() : false; - - CViewport* pViewport = GetIEditor()->GetViewManager()->GetSelectedViewport(); - CRenderViewport* rvp = viewport_cast(pViewport); - if (isCameraComponentSelected && rvp) - { - action->setEnabled(true); - action->setChecked(rvp->IsSelectedCamera()); - } - else { action->setEnabled(false); } @@ -3763,11 +3683,7 @@ void CCryEditApp::OnUpdateSwitchToSelectedCamera(QAction* action) ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnSwitchcameraNext() { - CViewport* vp = GetIEditor()->GetActiveView(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->CycleCamera(); - } + } ////////////////////////////////////////////////////////////////////////// @@ -3840,7 +3756,7 @@ bool CCryEditApp::IsInRegularEditorMode() void CCryEditApp::OnOpenQuickAccessBar() { - if (m_pQuickAccessBar == NULL) + if (m_pQuickAccessBar == nullptr) { return; } @@ -4188,7 +4104,7 @@ extern "C" int AZ_DLL_EXPORT CryEditMain(int argc, char* argv[]) int exitCode = 0; - BOOL didCryEditStart = CCryEditApp::instance()->InitInstance(); + bool didCryEditStart = CCryEditApp::instance()->InitInstance(); AZ_Error("Editor", didCryEditStart, "O3DE Editor did not initialize correctly, and will close." "\nThis could be because of incorrectly configured components, or missing required gems." "\nSee other errors for more details."); diff --git a/Code/Editor/CryEdit.h b/Code/Editor/CryEdit.h index 9406b37ea2..9e3dfc98ff 100644 --- a/Code/Editor/CryEdit.h +++ b/Code/Editor/CryEdit.h @@ -135,16 +135,16 @@ public: virtual void AddToRecentFileList(const QString& lpszPathName); ECreateLevelResult CreateLevel(const QString& levelName, QString& fullyQualifiedLevelName); static void InitDirectory(); - BOOL FirstInstance(bool bForceNewInstance = false); + bool FirstInstance(bool bForceNewInstance = false); void InitFromCommandLine(CEditCommandLineInfo& cmdInfo); - BOOL CheckIfAlreadyRunning(); + bool CheckIfAlreadyRunning(); //! @return successful outcome if initialization succeeded. or failed outcome with error message. AZ::Outcome InitGameSystem(HWND hwndForInputSystem); void CreateSplashScreen(); void InitPlugins(); bool InitGame(); - BOOL InitConsole(); + bool InitConsole(); int IdleProcessing(bool bBackground); bool IsWindowInForeground(); void RunInitPythonScript(CEditCommandLineInfo& cmdInfo); @@ -171,9 +171,9 @@ public: // Overrides // ClassWizard generated virtual function overrides public: - virtual BOOL InitInstance(); + virtual bool InitInstance(); virtual int ExitInstance(int exitCode = 0); - virtual BOOL OnIdle(LONG lCount); + virtual bool OnIdle(LONG lCount); virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszFileName); CCryDocManager* GetDocManager() { return m_pDocManager; } @@ -347,7 +347,7 @@ private: // Disable warning for dll export since this member won't be used outside this class AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ::IO::FileDescriptorRedirector m_stdoutRedirection = AZ::IO::FileDescriptorRedirector(1); // < 1 for STDOUT -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING +AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING private: static inline constexpr const char* DefaultLevelTemplateName = "Prefabs/Default_Level.prefab"; @@ -420,7 +420,7 @@ public: }; ////////////////////////////////////////////////////////////////////////// -class CCrySingleDocTemplate +class CCrySingleDocTemplate : public QObject { private: @@ -448,8 +448,8 @@ public: ~CCrySingleDocTemplate() {}; // avoid creating another CMainFrame // close other type docs before opening any things - virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszPathName, BOOL bAddToMRU, BOOL bMakeVisible); - virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszPathName, BOOL bMakeVisible = TRUE); + virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszPathName, bool bAddToMRU, bool bMakeVisible); + virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszPathName, bool bMakeVisible = true); virtual Confidence MatchDocType(LPCTSTR lpszPathName, CCryEditDoc*& rpDocMatch); private: @@ -465,9 +465,9 @@ public: CCrySingleDocTemplate* SetDefaultTemplate(CCrySingleDocTemplate* pNew); // Copied from MFC to get rid of the silly ugly unoverridable doc-type pick dialog virtual void OnFileNew(); - virtual BOOL DoPromptFileName(QString& fileName, UINT nIDSTitle, - DWORD lFlags, BOOL bOpenFileDialog, CDocTemplate* pTemplate); - virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszFileName, BOOL bAddToMRU); + virtual bool DoPromptFileName(QString& fileName, UINT nIDSTitle, + DWORD lFlags, bool bOpenFileDialog, CDocTemplate* pTemplate); + virtual CCryEditDoc* OpenDocumentFile(LPCTSTR lpszFileName, bool bAddToMRU); QVector m_templateList; }; diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp index 9421198de7..e372baf365 100644 --- a/Code/Editor/CryEditDoc.cpp +++ b/Code/Editor/CryEditDoc.cpp @@ -19,6 +19,7 @@ #include #include #include +#include // AzFramework #include @@ -53,6 +54,7 @@ #include "MainWindow.h" #include "LevelFileDialog.h" #include "StatObjBus.h" +#include "Undo/Undo.h" #include #include @@ -95,7 +97,7 @@ namespace Internal { bool SaveLevel() { - if (!GetIEditor()->GetDocument()->DoSave(GetIEditor()->GetDocument()->GetActivePathName(), TRUE)) + if (!GetIEditor()->GetDocument()->DoSave(GetIEditor()->GetDocument()->GetActivePathName(), true)) { return false; } @@ -261,7 +263,7 @@ void CCryEditDoc::DeleteContents() GetIEditor()->GetObjectManager()->DeleteAllObjects(); // Load scripts data - SetModifiedFlag(FALSE); + SetModifiedFlag(false); SetModifiedModules(eModifiedNothing); // Clear error reports if open. CErrorReportDialog::Clear(); @@ -303,7 +305,7 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) { CAutoDocNotReady autoDocNotReady; - if (arrXmlAr[DMAS_GENERAL] != NULL) + if (arrXmlAr[DMAS_GENERAL] != nullptr) { (*arrXmlAr[DMAS_GENERAL]).root = XmlHelpers::CreateXmlNode("Level"); (*arrXmlAr[DMAS_GENERAL]).root->setAttr("WaterColor", m_waterColor); @@ -481,7 +483,7 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) if (!pObj) { - pObj = GetIEditor()->GetObjectManager()->NewObject("SequenceObject", 0, fullname); + pObj = GetIEditor()->GetObjectManager()->NewObject("SequenceObject", nullptr, fullname); } } } @@ -665,7 +667,7 @@ int CCryEditDoc::GetModifiedModule() return m_modifiedModuleFlags; } -BOOL CCryEditDoc::CanCloseFrame() +bool CCryEditDoc::CanCloseFrame() { // Ask the base class to ask for saving, which also includes the save // status of the plugins. Additionaly we query if all the plugins can exit @@ -674,21 +676,21 @@ BOOL CCryEditDoc::CanCloseFrame() // are not serialized in the project file if (!SaveModified()) { - return FALSE; + return false; } if (!GetIEditor()->GetPluginManager()->CanAllPluginsExitNow()) { - return FALSE; + return false; } // If there is an export in process, exiting will corrupt it if (CGameExporter::GetCurrentExporter() != nullptr) { - return FALSE; + return false; } - return TRUE; + return true; } bool CCryEditDoc::SaveModified() @@ -733,7 +735,7 @@ bool CCryEditDoc::OnOpenDocument(const QString& lpszPathName) TOpenDocContext context; if (!BeforeOpenDocument(lpszPathName, context)) { - return FALSE; + return false; } return DoOpenDocument(context); } @@ -776,7 +778,7 @@ bool CCryEditDoc::BeforeOpenDocument(const QString& lpszPathName, TOpenDocContex context.absoluteLevelPath = absolutePath; context.absoluteSlicePath = ""; } - return TRUE; + return true; } bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) @@ -813,7 +815,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) if (!LoadXmlArchiveArray(arrXmlAr, levelFilePath, levelFolderAbsolutePath)) { m_bLoadFailed = true; - return FALSE; + return false; } } if (!LoadLevel(arrXmlAr, context.absoluteLevelPath)) @@ -825,7 +827,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) if (m_bLoadFailed) { - return FALSE; + return false; } // Load AZ entities for the editor. @@ -846,7 +848,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) if (m_bLoadFailed) { - return FALSE; + return false; } StartStreamingLoad(); @@ -863,7 +865,7 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) // level. SetLevelExported(true); - return TRUE; + return true; } bool CCryEditDoc::OnNewDocument() @@ -959,7 +961,7 @@ bool CCryEditDoc::BeforeSaveDocument(const QString& lpszPathName, TSaveDocContex bool bSaved(true); context.bSaved = bSaved; - return TRUE; + return true; } bool CCryEditDoc::HasLayerNameConflicts() const @@ -1044,7 +1046,7 @@ bool CCryEditDoc::AfterSaveDocument([[maybe_unused]] const QString& lpszPathName else { CLogFile::WriteLine("$3Document successfully saved"); - SetModifiedFlag(FALSE); + SetModifiedFlag(false); SetModifiedModules(eModifiedNothing); MainWindow::instance()->ResetAutoSaveTimers(); } @@ -1596,7 +1598,7 @@ bool CCryEditDoc::LoadLevel(TDocMultiArchive& arrXmlAr, const QString& absoluteC // Set level path directly *after* DeleteContents(), since that will unload the previous level and clear the level path. GetIEditor()->GetGameEngine()->SetLevelPath(folderPath); - SetModifiedFlag(TRUE); // dirty during de-serialize + SetModifiedFlag(true); // dirty during de-serialize SetModifiedModules(eModifiedAll); Load(arrXmlAr, absoluteCryFilePath); @@ -1606,7 +1608,7 @@ bool CCryEditDoc::LoadLevel(TDocMultiArchive& arrXmlAr, const QString& absoluteC { pIPak->GetResourceList(AZ::IO::IArchive::RFOM_NextLevel)->Clear(); } - SetModifiedFlag(FALSE); // start off with unmodified + SetModifiedFlag(false); // start off with unmodified SetModifiedModules(eModifiedNothing); SetDocumentReady(true); GetIEditor()->Notify(eNotify_OnEndLoad); @@ -1982,7 +1984,7 @@ void CCryEditDoc::OnStartLevelResourceList() gEnv->pCryPak->GetResourceList(AZ::IO::IArchive::RFOM_Level)->Clear(); } -BOOL CCryEditDoc::DoFileSave() +bool CCryEditDoc::DoFileSave() { if (GetEditMode() == CCryEditDoc::DocumentEditingMode::LevelEdit) { @@ -2000,15 +2002,15 @@ BOOL CCryEditDoc::DoFileSave() QString newLevelPath = filename.left(filename.lastIndexOf('/') + 1); GetIEditor()->GetDocument()->SetPathName(filename); GetIEditor()->GetGameEngine()->SetLevelPath(newLevelPath); - return TRUE; + return true; } } - return FALSE; + return false; } } if (!IsDocumentReady()) { - return FALSE; + return false; } return Internal::SaveLevel(); @@ -2063,7 +2065,7 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_END, 0, 0); GetIEditor()->Notify(eNotify_OnEndNewScene); - SetModifiedFlag(FALSE); + SetModifiedFlag(false); SetLevelExported(false); SetModifiedModules(eModifiedNothing); @@ -2077,13 +2079,13 @@ void CCryEditDoc::CreateDefaultLevelAssets([[maybe_unused]] int resolution, [[ma void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) { - if (pVar == NULL) + if (pVar == nullptr) { return; } XmlNodeRef node = GetEnvironmentTemplate(); - if (node == NULL) + if (node == nullptr) { return; } @@ -2101,7 +2103,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) XmlNodeRef groupNode = node->getChild(nGroup); - if (groupNode == NULL) + if (groupNode == nullptr) { return; } @@ -2112,7 +2114,7 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) } XmlNodeRef childNode = groupNode->getChild(nChild); - if (childNode == NULL) + if (childNode == nullptr) { return; } @@ -2139,7 +2141,7 @@ QString CCryEditDoc::GetCryIndexPath(const LPCTSTR levelFilePath) const return Path::AddPathSlash(levelPath + levelName + "_editor"); } -BOOL CCryEditDoc::LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& absoluteLevelPath, const QString& levelPath) +bool CCryEditDoc::LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& absoluteLevelPath, const QString& levelPath) { auto pIPak = GetIEditor()->GetSystem()->GetIPak(); @@ -2148,7 +2150,7 @@ BOOL CCryEditDoc::LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& CXmlArchive* pXmlAr = new CXmlArchive(); if (!pXmlAr) { - return FALSE; + return false; } CXmlArchive& xmlAr = *pXmlAr; @@ -2159,7 +2161,7 @@ BOOL CCryEditDoc::LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& bool openLevelPakFileSuccess = pIPak->OpenPack(levelPath.toUtf8().data(), absoluteLevelPath.toUtf8().data()); if (!openLevelPakFileSuccess) { - return FALSE; + return false; } CPakFile pakFile; @@ -2167,13 +2169,13 @@ BOOL CCryEditDoc::LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& pIPak->ClosePack(absoluteLevelPath.toUtf8().data()); if (!loadFromPakSuccess) { - return FALSE; + return false; } FillXmlArArray(arrXmlAr, &xmlAr); } - return TRUE; + return true; } void CCryEditDoc::ReleaseXmlArchiveArray(TDocMultiArchive& arrXmlAr) diff --git a/Code/Editor/CryEditDoc.h b/Code/Editor/CryEditDoc.h index d32e8e5bb1..a5b3334818 100644 --- a/Code/Editor/CryEditDoc.h +++ b/Code/Editor/CryEditDoc.h @@ -26,7 +26,7 @@ struct ICVar; // Filename of the temporary file used for the hold / fetch operation // conform to the "$tmp[0-9]_" naming convention -#define HOLD_FETCH_FILE "$tmp_hold" +#define HOLD_FETCH_FILE "$tmp_hold" class CCryEditDoc : public QObject @@ -36,7 +36,7 @@ class CCryEditDoc Q_PROPERTY(bool modified READ IsModified WRITE SetModifiedFlag); Q_PROPERTY(QString pathName READ GetLevelPathName WRITE SetPathName); Q_PROPERTY(QString title READ GetTitle WRITE SetTitle); - + public: // Create from serialization only enum DocumentEditingMode { @@ -82,7 +82,7 @@ public: // Create from serialization only bool DoSave(const QString& pathName, bool replace); SANDBOX_API bool Save(); - virtual BOOL DoFileSave(); + virtual bool DoFileSave(); bool SaveModified(); virtual bool BackupBeforeSave(bool bForce = false); @@ -102,7 +102,7 @@ public: // Create from serialization only bool IsLevelExported() const; void SetLevelExported(bool boExported = true); - BOOL CanCloseFrame(); + bool CanCloseFrame(); enum class FetchPolicy { @@ -144,7 +144,7 @@ protected: }; bool BeforeOpenDocument(const QString& lpszPathName, TOpenDocContext& context); bool DoOpenDocument(TOpenDocContext& context); - virtual BOOL LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& absoluteLevelPath, const QString& levelPath); + virtual bool LoadXmlArchiveArray(TDocMultiArchive& arrXmlAr, const QString& absoluteLevelPath, const QString& levelPath); virtual void ReleaseXmlArchiveArray(TDocMultiArchive& arrXmlAr); virtual void Load(TDocMultiArchive& arrXmlAr, const QString& szFilename); diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp index e65af3a19b..21d2dcced9 100644 --- a/Code/Editor/CryEditPy.cpp +++ b/Code/Editor/CryEditPy.cpp @@ -359,7 +359,7 @@ namespace { AZ::TickBus::Handler::BusConnect(); } - ~Ticker() + ~Ticker() override { AZ::TickBus::Handler::BusDisconnect(); } diff --git a/Code/Editor/CustomAspectRatioDlg.cpp b/Code/Editor/CustomAspectRatioDlg.cpp index 16f50601d1..f24ff9ccdb 100644 --- a/Code/Editor/CustomAspectRatioDlg.cpp +++ b/Code/Editor/CustomAspectRatioDlg.cpp @@ -22,7 +22,7 @@ AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING #define MIN_ASPECT 1 #define MAX_ASPECT 16384 -CCustomAspectRatioDlg::CCustomAspectRatioDlg(int x, int y, QWidget* pParent /*=NULL*/) +CCustomAspectRatioDlg::CCustomAspectRatioDlg(int x, int y, QWidget* pParent /*=nullptr*/) : QDialog(pParent) , m_xDefault(x) , m_yDefault(y) diff --git a/Code/Editor/CustomResolutionDlg.cpp b/Code/Editor/CustomResolutionDlg.cpp index b970b80fe7..9e0e11e2e4 100644 --- a/Code/Editor/CustomResolutionDlg.cpp +++ b/Code/Editor/CustomResolutionDlg.cpp @@ -25,7 +25,7 @@ AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING #define MIN_RES 64 #define MAX_RES 8192 -CCustomResolutionDlg::CCustomResolutionDlg(int w, int h, QWidget* pParent /*=NULL*/) +CCustomResolutionDlg::CCustomResolutionDlg(int w, int h, QWidget* pParent /*=nullptr*/) : QDialog(pParent) , m_wDefault(w) , m_hDefault(h) @@ -50,12 +50,12 @@ void CCustomResolutionDlg::OnInitDialog() m_ui->m_height->setValue(m_hDefault); QString maxDimensionString; - QTextStream(&maxDimensionString) - << "Maximum Dimension: " << MAX_RES << Qt::endl + QTextStream(&maxDimensionString) + << "Maximum Dimension: " << MAX_RES << Qt::endl << Qt::endl << "Note: Dimensions over 8K may be" << Qt::endl << "unstable depending on hardware."; - + m_ui->m_maxDimension->setText(maxDimensionString); } diff --git a/Code/Editor/CustomizeKeyboardDialog.cpp b/Code/Editor/CustomizeKeyboardDialog.cpp index d6bea6860f..ce09f8d878 100644 --- a/Code/Editor/CustomizeKeyboardDialog.cpp +++ b/Code/Editor/CustomizeKeyboardDialog.cpp @@ -87,7 +87,7 @@ public: : QAbstractListModel(parent) { } - virtual ~MenuActionsModel() {} + ~MenuActionsModel() override {} int rowCount([[maybe_unused]] const QModelIndex& parent = QModelIndex()) const override { @@ -134,7 +134,7 @@ public: , m_action(nullptr) { } - virtual ~ActionShortcutsModel() {} + ~ActionShortcutsModel() override {} int rowCount([[maybe_unused]] const QModelIndex& parent = QModelIndex()) const override { diff --git a/Code/Editor/EditorDefs.h b/Code/Editor/EditorDefs.h index c98209befe..6614fa4d72 100644 --- a/Code/Editor/EditorDefs.h +++ b/Code/Editor/EditorDefs.h @@ -37,7 +37,6 @@ #pragma warning (disable : 4786) // identifier was truncated to 'number' characters in the debug information. #pragma warning (disable : 4244) // conversion from 'long' to 'float', possible loss of data #pragma warning (disable : 4018) // signed/unsigned mismatch -#pragma warning (disable : 4800) // BOOL bool conversion // Disable warning when a function returns a value inside an __asm block #pragma warning (disable : 4035) @@ -85,17 +84,17 @@ #endif #ifndef SAFE_DELETE -#define SAFE_DELETE(p) { if (p) { delete (p); (p) = NULL; } \ +#define SAFE_DELETE(p) { if (p) { delete (p); (p) = nullptr; } \ } #endif #ifndef SAFE_DELETE_ARRAY -#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = NULL; } \ +#define SAFE_DELETE_ARRAY(p) { if (p) { delete[] (p); (p) = nullptr; } \ } #endif #ifndef SAFE_RELEASE -#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = NULL; } \ +#define SAFE_RELEASE(p) { if (p) { (p)->Release(); (p) = nullptr; } \ } #endif diff --git a/Code/Editor/EditorFileMonitor.cpp b/Code/Editor/EditorFileMonitor.cpp index 96dc883ab0..5e539f78a8 100644 --- a/Code/Editor/EditorFileMonitor.cpp +++ b/Code/Editor/EditorFileMonitor.cpp @@ -162,7 +162,7 @@ QString RemoveGameName(const QString &filename) void CEditorFileMonitor::OnFileMonitorChange(const SFileChangeInfo& rChange) { CCryEditApp* app = CCryEditApp::instance(); - if (app == NULL || app->IsExiting()) + if (app == nullptr || app->IsExiting()) { return; } diff --git a/Code/Editor/EditorFileMonitor.h b/Code/Editor/EditorFileMonitor.h index ac33fee9f4..7474d5e43a 100644 --- a/Code/Editor/EditorFileMonitor.h +++ b/Code/Editor/EditorFileMonitor.h @@ -42,7 +42,7 @@ private: QString extension; SFileChangeCallback() - : pListener(NULL) + : pListener(nullptr) {} SFileChangeCallback(IFileChangeListener* pListener, const char* item, const char* extension) diff --git a/Code/Editor/EditorPanelUtils.cpp b/Code/Editor/EditorPanelUtils.cpp index 9091bb4c2f..b19bde4583 100644 --- a/Code/Editor/EditorPanelUtils.cpp +++ b/Code/Editor/EditorPanelUtils.cpp @@ -49,7 +49,7 @@ class CEditorPanelUtils_Impl { #pragma region Drag & Drop public: - virtual void SetViewportDragOperation(void(* dropCallback)(CViewport* viewport, int dragPointX, int dragPointY, void* custom), void* custom) override + void SetViewportDragOperation(void(* dropCallback)(CViewport* viewport, int dragPointX, int dragPointY, void* custom), void* custom) override { for (int i = 0; i < GetIEditor()->GetViewManager()->GetViewCount(); i++) { @@ -60,13 +60,13 @@ public: #pragma region Preview Window public: - virtual int PreviewWindow_GetDisplaySettingsDebugFlags(CDisplaySettings* settings) + int PreviewWindow_GetDisplaySettingsDebugFlags(CDisplaySettings* settings) override { CRY_ASSERT(settings); return settings->GetDebugFlags(); } - virtual void PreviewWindow_SetDisplaySettingsDebugFlags(CDisplaySettings* settings, int flags) + void PreviewWindow_SetDisplaySettingsDebugFlags(CDisplaySettings* settings, int flags) override { CRY_ASSERT(settings); settings->SetDebugFlags(flags); @@ -79,7 +79,7 @@ protected: bool m_hotkeysAreEnabled; public: - virtual bool HotKey_Import() override + bool HotKey_Import() override { QVector > keys; QString filepath = QFileDialog::getOpenFileName(nullptr, "Select shortcut configuration to load", @@ -143,7 +143,7 @@ public: return result; } - virtual void HotKey_Export() override + void HotKey_Export() override { auto settingDir = AZ::IO::FixedMaxPath(AZ::Utils::GetEnginePath()) / "Editor" / "Plugins" / "ParticleEditorPlugin" / "settings"; QString filepath = QFileDialog::getSaveFileName(nullptr, "Select shortcut configuration to load", settingDir.c_str(), "HotKey Config Files (*.hkxml)"); @@ -170,7 +170,7 @@ public: file.close(); } - virtual QKeySequence HotKey_GetShortcut(const char* path) override + QKeySequence HotKey_GetShortcut(const char* path) override { for (HotKey combo : hotkeys) { @@ -182,7 +182,7 @@ public: return QKeySequence(); } - virtual bool HotKey_IsPressed(const QKeyEvent* event, const char* path) override + bool HotKey_IsPressed(const QKeyEvent* event, const char* path) override { if (!m_hotkeysAreEnabled) { @@ -221,7 +221,7 @@ public: return false; } - virtual bool HotKey_IsPressed(const QShortcutEvent* event, const char* path) override + bool HotKey_IsPressed(const QShortcutEvent* event, const char* path) override { if (!m_hotkeysAreEnabled) { @@ -239,7 +239,7 @@ public: return false; } - virtual bool HotKey_LoadExisting() override + bool HotKey_LoadExisting() override { QSettings settings("O3DE", "O3DE"); QString group = "Hotkeys/"; @@ -275,7 +275,7 @@ public: return true; } - virtual void HotKey_SaveCurrent() override + void HotKey_SaveCurrent() override { QSettings settings("O3DE", "O3DE"); QString group = "Hotkeys/"; @@ -296,7 +296,7 @@ public: settings.sync(); } - virtual void HotKey_BuildDefaults() override + void HotKey_BuildDefaults() override { m_hotkeysAreEnabled = true; QVector > keys; @@ -356,17 +356,17 @@ public: } } - virtual void HotKey_SetKeys(QVector keys) override + void HotKey_SetKeys(QVector keys) override { hotkeys = keys; } - virtual QVector HotKey_GetKeys() override + QVector HotKey_GetKeys() override { return hotkeys; } - virtual QString HotKey_GetPressedHotkey(const QKeyEvent* event) override + QString HotKey_GetPressedHotkey(const QKeyEvent* event) override { if (!m_hotkeysAreEnabled) { @@ -381,7 +381,7 @@ public: } return ""; } - virtual QString HotKey_GetPressedHotkey(const QShortcutEvent* event) override + QString HotKey_GetPressedHotkey(const QShortcutEvent* event) override { if (!m_hotkeysAreEnabled) { @@ -398,12 +398,12 @@ public: } //building the default hotkey list re-enables hotkeys //do not use this when rebuilding the default list is a possibility. - virtual void HotKey_SetEnabled(bool val) override + void HotKey_SetEnabled(bool val) override { m_hotkeysAreEnabled = val; } - virtual bool HotKey_IsEnabled() const override + bool HotKey_IsEnabled() const override { return m_hotkeysAreEnabled; } @@ -457,13 +457,13 @@ protected: } public: - virtual void ToolTip_LoadConfigXML(QString filepath) override + void ToolTip_LoadConfigXML(QString filepath) override { XmlNodeRef node = GetIEditor()->GetSystem()->LoadXmlFromFile(filepath.toStdString().c_str()); ToolTip_ParseNode(node); } - virtual void ToolTip_BuildFromConfig(IQToolTip* tooltip, QString path, QString option, QString optionalData = "", bool isEnabled = true) + void ToolTip_BuildFromConfig(IQToolTip* tooltip, QString path, QString option, QString optionalData = "", bool isEnabled = true) override { AZ_Assert(tooltip, "tooltip cannot be null"); @@ -488,7 +488,7 @@ public: } } - virtual QString ToolTip_GetTitle(QString path, QString option) override + QString ToolTip_GetTitle(QString path, QString option) override { if (!option.isEmpty() && GetToolTip(path + "." + option).isValid) { @@ -501,7 +501,7 @@ public: return GetToolTip(path).title; } - virtual QString ToolTip_GetContent(QString path, QString option) override + QString ToolTip_GetContent(QString path, QString option) override { if (!option.isEmpty() && GetToolTip(path + "." + option).isValid) { @@ -514,7 +514,7 @@ public: return GetToolTip(path).content; } - virtual QString ToolTip_GetSpecialContentType(QString path, QString option) override + QString ToolTip_GetSpecialContentType(QString path, QString option) override { if (!option.isEmpty() && GetToolTip(path + "." + option).isValid) { @@ -527,7 +527,7 @@ public: return GetToolTip(path).specialContent; } - virtual QString ToolTip_GetDisabledContent(QString path, QString option) override + QString ToolTip_GetDisabledContent(QString path, QString option) override { if (!option.isEmpty() && GetToolTip(path + "." + option).isValid) { diff --git a/Code/Editor/EditorPreferencesDialog.cpp b/Code/Editor/EditorPreferencesDialog.cpp index 893b36b40c..c3fc4139f6 100644 --- a/Code/Editor/EditorPreferencesDialog.cpp +++ b/Code/Editor/EditorPreferencesDialog.cpp @@ -282,7 +282,7 @@ void EditorPreferencesDialog::CreatePages() { auto pUnknown = classes[i]; - IPreferencesPageCreator* pPageCreator = 0; + IPreferencesPageCreator* pPageCreator = nullptr; if (FAILED(pUnknown->QueryInterface(&pPageCreator))) { continue; diff --git a/Code/Editor/EditorPreferencesPageFiles.cpp b/Code/Editor/EditorPreferencesPageFiles.cpp index aa84c7075c..4be3269d42 100644 --- a/Code/Editor/EditorPreferencesPageFiles.cpp +++ b/Code/Editor/EditorPreferencesPageFiles.cpp @@ -43,11 +43,16 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->Field("MaxCount", &AutoBackup::m_maxCount) ->Field("RemindTime", &AutoBackup::m_remindTime); + serialize.Class() + ->Version(1) + ->Field("Max number of items displayed", &AssetBrowserSearch::m_maxNumberOfItemsShownInSearch); + serialize.Class() ->Version(1) ->Field("Files", &CEditorPreferencesPage_Files::m_files) ->Field("Editors", &CEditorPreferencesPage_Files::m_editors) - ->Field("AutoBackup", &CEditorPreferencesPage_Files::m_autoBackup); + ->Field("AutoBackup", &CEditorPreferencesPage_Files::m_autoBackup) + ->Field("AssetBrowserSearch", &CEditorPreferencesPage_Files::m_assetBrowserSearch); AZ::EditContext* editContext = serialize.GetEditContext(); @@ -80,12 +85,19 @@ void CEditorPreferencesPage_Files::Reflect(AZ::SerializeContext& serialize) ->Attribute(AZ::Edit::Attributes::Max, 100) ->DataElement(AZ::Edit::UIHandlers::SpinBox, &AutoBackup::m_remindTime, "Remind Time", "Auto Remind Every (Minutes)"); + editContext->Class("Asset Browser Search View", "Asset Browser Search View") + ->DataElement(AZ::Edit::UIHandlers::SpinBox, &AssetBrowserSearch::m_maxNumberOfItemsShownInSearch, "Maximum number of displayed items", + "Maximum number of displayed items displayed in the Search View") + ->Attribute(AZ::Edit::Attributes::Min, 50) + ->Attribute(AZ::Edit::Attributes::Max, 5000); + editContext->Class("File Preferences", "Class for handling File Preferences") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20)) ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_files, "Files", "File Preferences") ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_editors, "External Editors", "External Editors") - ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_autoBackup, "Auto Backup", "Auto Backup"); + ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_autoBackup, "Auto Backup", "Auto Backup") + ->DataElement(AZ::Edit::UIHandlers::Default, &CEditorPreferencesPage_Files::m_assetBrowserSearch, "Asset Browser Search", "Asset Browser Search"); } } @@ -124,6 +136,8 @@ void CEditorPreferencesPage_Files::OnApply() gSettings.autoBackupTime = m_autoBackup.m_timeInterval; gSettings.autoBackupMaxCount = m_autoBackup.m_maxCount; gSettings.autoRemindTime = m_autoBackup.m_remindTime; + + gSettings.maxNumberOfItemsShownInSearch = m_assetBrowserSearch.m_maxNumberOfItemsShownInSearch; } void CEditorPreferencesPage_Files::InitializeSettings() @@ -148,4 +162,6 @@ void CEditorPreferencesPage_Files::InitializeSettings() m_autoBackup.m_timeInterval = gSettings.autoBackupTime; m_autoBackup.m_maxCount = gSettings.autoBackupMaxCount; m_autoBackup.m_remindTime = gSettings.autoRemindTime; + + m_assetBrowserSearch.m_maxNumberOfItemsShownInSearch = gSettings.maxNumberOfItemsShownInSearch; } diff --git a/Code/Editor/EditorPreferencesPageFiles.h b/Code/Editor/EditorPreferencesPageFiles.h index 2bb806a73e..368cd91fc3 100644 --- a/Code/Editor/EditorPreferencesPageFiles.h +++ b/Code/Editor/EditorPreferencesPageFiles.h @@ -69,10 +69,17 @@ private: int m_remindTime; }; + struct AssetBrowserSearch + { + AZ_TYPE_INFO(AssetBrowserSearch, "{9FBFCD24-9452-49DF-99F4-2711443CEAAE}") + + int m_maxNumberOfItemsShownInSearch; + }; Files m_files; ExternalEditors m_editors; AutoBackup m_autoBackup; + AssetBrowserSearch m_assetBrowserSearch; QIcon m_icon; }; diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 4c638e1f82..dd89d96dc3 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -46,7 +46,7 @@ #include #include #include -#include +#include // AtomToolsFramework #include @@ -73,6 +73,7 @@ #include "EditorPreferencesPageGeneral.h" #include "ViewportManipulatorController.h" #include "LegacyViewportCameraController.h" +#include "EditorViewportSettings.h" #include "ViewPane.h" #include "CustomResolutionDlg.h" @@ -91,6 +92,8 @@ // Atom #include #include +#include + #include #include @@ -163,6 +166,10 @@ namespace AZ::ViewportHelpers { m_renderViewport.OnStopPlayInEditor(); } + void OnStartPlayInEditorBegin() override + { + m_renderViewport.OnStartPlayInEditorBegin(); + } private: EditorViewportWidget& m_renderViewport; @@ -175,16 +182,12 @@ namespace AZ::ViewportHelpers EditorViewportWidget::EditorViewportWidget(const QString& name, QWidget* parent) : QtViewport(parent) - , m_Camera(GetIEditor()->GetSystem()->GetViewCamera()) - , m_camFOV(gSettings.viewports.fDefaultFov) , m_defaultViewName(name) , m_renderViewport(nullptr) //m_renderViewport is initialized later, in SetViewportId { // need this to be set in order to allow for language switching on Windows setAttribute(Qt::WA_InputMethodEnabled); - LockCameraMovement(true); - EditorViewportWidget::SetViewTM(m_Camera.GetMatrix()); m_defaultViewTM.SetIdentity(); if (GetIEditor()->GetViewManager()->GetSelectedViewport() == nullptr) @@ -197,8 +200,6 @@ EditorViewportWidget::EditorViewportWidget(const QString& name, QWidget* parent) m_displayContext.pIconManager = GetIEditor()->GetIconManager(); GetIEditor()->GetUndoManager()->AddListener(this); - m_PhysicalLocation.SetIdentity(); - // The renderer requires something, so don't allow us to shrink to absolutely nothing // This won't in fact stop the viewport from being shrunk, when it's the centralWidget for // the MainWindow, but it will stop the viewport from getting resize events @@ -206,22 +207,14 @@ EditorViewportWidget::EditorViewportWidget(const QString& name, QWidget* parent) // to be the same thing. setMinimumSize(50, 50); - OnCreate(); - setMouseTracking(true); Camera::EditorCameraRequestBus::Handler::BusConnect(); + Camera::CameraNotificationBus::Handler::BusConnect(); + m_editorEntityNotifications = AZStd::make_unique(*this); AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - auto handleCameraChange = [this](const AZ::Matrix4x4&) - { - UpdateCameraFromViewportContext(); - }; - - m_cameraViewMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); - m_cameraProjectionMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); - m_manipulatorManager = GetIEditor()->GetViewManager()->GetManipulatorManager(); if (!m_pPrimaryViewport) { @@ -240,28 +233,20 @@ EditorViewportWidget::~EditorViewportWidget() DisconnectViewportInteractionRequestBus(); m_editorEntityNotifications.reset(); Camera::EditorCameraRequestBus::Handler::BusDisconnect(); - OnDestroy(); + Camera::CameraNotificationBus::Handler::BusDisconnect(); GetIEditor()->GetUndoManager()->RemoveListener(this); GetIEditor()->UnregisterNotifyListener(this); } -////////////////////////////////////////////////////////////////////////// -// EditorViewportWidget message handlers -////////////////////////////////////////////////////////////////////////// -int EditorViewportWidget::OnCreate() -{ - CreateRenderContext(); - - return 0; -} - ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::resizeEvent(QResizeEvent* event) { + // Call base class resize event while not rendering PushDisableRendering(); QtViewport::resizeEvent(event); PopDisableRendering(); + // Emit Legacy system events about the viewport size change const QRect rcWindow = rect().translated(mapToGlobal(QPoint())); gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_MOVE, rcWindow.left(), rcWindow.top()); @@ -271,10 +256,12 @@ void EditorViewportWidget::resizeEvent(QResizeEvent* event) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, width(), height()); - // 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; + // In the case of the default viewport camera, we must re-set the FOV, which also updates the aspect ratio + // Component cameras hand this themselves + if (m_viewSourceType == ViewSourceType::None) + { + SetFOV(GetFOV()); + } } ////////////////////////////////////////////////////////////////////////// @@ -383,15 +370,6 @@ AzToolsFramework::ViewportInteraction::MouseInteraction EditorViewportWidget::Bu BuildMousePick(WidgetToViewport(point))); } -void EditorViewportWidget::InjectFakeMouseMove(int deltaX, int deltaY, Qt::MouseButtons buttons) -{ - // this is required, otherwise the user will see the context menu - OnMouseMove(Qt::NoModifier, buttons, QCursor::pos() + QPoint(deltaX, deltaY)); - // we simply move the prev mouse position, so the change will be picked up - // by the next ProcessMouse call - m_prevMousePos -= QPoint(deltaX, deltaY); -} - ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::event(QEvent* event) { @@ -403,19 +381,6 @@ bool EditorViewportWidget::event(QEvent* event) m_keyDown.clear(); break; - case QEvent::ShortcutOverride: - { - // Ensure we exit game mode on escape, even if something else would eat our escape key event. - if (static_cast(event)->key() == Qt::Key_Escape && GetIEditor()->IsInGameMode()) - { - GetIEditor()->SetInGameMode(false); - event->accept(); - return true; - } - break; - } - - case QEvent::Shortcut: // a shortcut should immediately clear us, otherwise the release event never gets sent m_keyDown.clear(); @@ -425,12 +390,6 @@ bool EditorViewportWidget::event(QEvent* event) return QtViewport::event(event); } -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::ResetContent() -{ - QtViewport::ResetContent(); -} - ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::UpdateContent(int flags) { @@ -461,26 +420,6 @@ void EditorViewportWidget::Update() return; } - if (m_updateCameraPositionNextTick) - { - auto cameraState = GetCameraState(); - AZ::Matrix3x4 matrix; - matrix.SetBasisAndTranslation(cameraState.m_side, cameraState.m_forward, cameraState.m_up, cameraState.m_position); - auto m = AZMatrix3x4ToLYMatrix3x4(matrix); - - SetViewTM(m); - m_Camera.SetZRange(cameraState.m_nearClip, cameraState.m_farClip); - } - - // Ensure the FOV matches our internally stored setting if we're using the Editor camera - if (!m_viewEntityId.IsValid() && !GetIEditor()->IsInGameMode()) - { - SetFOV(GetFOV()); - } - - // Reset the camera update flag now that we're finished updating our viewport context - m_updateCameraPositionNextTick = false; - // Don't wait for changes to update the focused viewport. if (CheckRespondToInput()) { @@ -558,25 +497,13 @@ void EditorViewportWidget::Update() PushDisableRendering(); - m_viewTM = m_Camera.GetMatrix(); // synchronize. - // Render { // TODO: Move out this logic to a controller and refactor to work with Atom - - OnRender(); - ProcessRenderLisneters(m_displayContext); m_displayContext.Flush2D(); - // m_renderer->SwitchToNativeResolutionBackbuffer(); - - // 3D engine stats - - CCamera CurCamera = gEnv->pSystem->GetViewCamera(); - gEnv->pSystem->SetViewCamera(m_Camera); - // Post Render Callback { PostRenderers::iterator itr = m_postRenderers.begin(); @@ -586,8 +513,6 @@ void EditorViewportWidget::Update() (*itr)->OnPostRender(); } } - - gEnv->pSystem->SetViewCamera(CurCamera); } { @@ -609,35 +534,7 @@ void EditorViewportWidget::Update() m_bUpdateViewport = false; } -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::SetViewEntity(const AZ::EntityId& viewEntityId, bool lockCameraMovement) -{ - // if they've picked the same camera, then that means they want to toggle - if (viewEntityId.IsValid() && viewEntityId != m_viewEntityId) - { - LockCameraMovement(lockCameraMovement); - m_viewEntityId = viewEntityId; - AZStd::string entityName; - AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, viewEntityId); - SetName(QString("Camera entity: %1").arg(entityName.c_str())); - } - else - { - SetDefaultCamera(); - } - - PostCameraSet(); -} -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::ResetToViewSourceType(const ViewSourceType& viewSourceType) -{ - LockCameraMovement(true); - m_viewEntityId.SetInvalid(); - m_cameraObjectId = GUID_NULL; - m_viewSourceType = viewSourceType; - SetViewTM(GetViewTM()); -} ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::PostCameraSet() @@ -647,10 +544,28 @@ void EditorViewportWidget::PostCameraSet() m_viewPane->OnFOVChanged(GetFOV()); } + // CryLegacy notify GetIEditor()->Notify(eNotify_CameraChanged); - QScopedValueRollback rb(m_ignoreSetViewFromEntityPerspective, true); + + // Special case in the editor; if the camera is the default editor camera, + // notify that the active view changed. In game mode, it is a hard error to not have + // any cameras on the view stack! + if (m_viewSourceType == ViewSourceType::None) + { + m_sendingOnActiveChanged = true; + Camera::CameraNotificationBus::Broadcast( + &Camera::CameraNotificationBus::Events::OnActiveViewChanged, AZ::EntityId()); + m_sendingOnActiveChanged = false; + } + + // Notify about editor camera change Camera::EditorCameraNotificationBus::Broadcast( &Camera::EditorCameraNotificationBus::Events::OnViewportViewEntityChanged, m_viewEntityId); + + // The editor view entity ID has changed, and the editor camera component "Be This Camera" text needs to be updated + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast( + &AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, + AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); } ////////////////////////////////////////////////////////////////////////// @@ -658,16 +573,7 @@ CBaseObject* EditorViewportWidget::GetCameraObject() const { CBaseObject* pCameraObject = nullptr; - if (m_viewSourceType == ViewSourceType::SequenceCamera) - { - m_cameraObjectId = GetViewManager()->GetCameraObjectId(); - } - if (m_cameraObjectId != GUID_NULL) - { - // Find camera object from id. - pCameraObject = GetIEditor()->GetObjectManager()->FindObject(m_cameraObjectId); - } - else if (m_viewSourceType == ViewSourceType::CameraComponent || m_viewSourceType == ViewSourceType::AZ_Entity) + if (m_viewSourceType == ViewSourceType::CameraComponent) { AzToolsFramework::ComponentEntityEditorRequestBus::EventResult( pCameraObject, m_viewEntityId, &AzToolsFramework::ComponentEntityEditorRequests::GetSandboxObject); @@ -723,10 +629,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (GetIEditor()->GetViewManager()->GetGameViewport() == this) { SetCurrentCursor(STD_CURSOR_DEFAULT); - m_bInRotateMode = false; - m_bInMoveMode = false; - m_bInOrbitMode = false; - m_bInZoomMode = false; if (m_inFullscreenPreview) { @@ -738,7 +640,7 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (m_renderViewport) { - m_renderViewport->SetInputProcessingEnabled(true); + m_renderViewport->GetControllerList()->SetEnabled(true); } break; @@ -818,21 +720,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) } } -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::OnRender() -{ - if (m_rcClient.isEmpty()) - { - // Even in null rendering, update the view camera. - // 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); - return; - } - - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); -} - void EditorViewportWidget::OnBeginPrepareRender() { if (!m_debugDisplay) @@ -853,82 +740,6 @@ void EditorViewportWidget::OnBeginPrepareRender() Update(); m_isOnPaint = false; - float fNearZ = GetIEditor()->GetConsoleVar("cl_DefaultNearPlane"); - float fFarZ = m_Camera.GetFarPlane(); - - CBaseObject* cameraObject = GetCameraObject(); - if (cameraObject) - { - AZ::Matrix3x3 lookThroughEntityCorrection = AZ::Matrix3x3::CreateIdentity(); - if (m_viewEntityId.IsValid()) - { - Camera::CameraRequestBus::EventResult(fNearZ, m_viewEntityId, &Camera::CameraComponentRequests::GetNearClipDistance); - Camera::CameraRequestBus::EventResult(fFarZ, m_viewEntityId, &Camera::CameraComponentRequests::GetFarClipDistance); - LmbrCentral::EditorCameraCorrectionRequestBus::EventResult( - lookThroughEntityCorrection, m_viewEntityId, &LmbrCentral::EditorCameraCorrectionRequests::GetTransformCorrection); - } - - m_viewTM = cameraObject->GetWorldTM() * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection); - m_viewTM.OrthonormalizeFast(); - - m_Camera.SetMatrix(m_viewTM); - - int w = m_rcClient.width(); - int h = m_rcClient.height(); - - m_Camera.SetFrustum(w, h, GetFOV(), fNearZ, fFarZ); - } - else if (m_viewEntityId.IsValid()) - { - Camera::CameraRequestBus::EventResult(fNearZ, m_viewEntityId, &Camera::CameraComponentRequests::GetNearClipDistance); - Camera::CameraRequestBus::EventResult(fFarZ, m_viewEntityId, &Camera::CameraComponentRequests::GetFarClipDistance); - int w = m_rcClient.width(); - int h = m_rcClient.height(); - - m_Camera.SetFrustum(w, h, GetFOV(), fNearZ, fFarZ); - } - else - { - // Normal camera. - m_cameraObjectId = GUID_NULL; - int w = m_rcClient.width(); - int h = m_rcClient.height(); - - // Don't bother doing an FOV calculation if we don't have a valid viewport - // This prevents frustum calculation bugs with a null viewport - if (w <= 1 || h <= 1) - { - return; - } - - float fov = gSettings.viewports.fDefaultFov; - - // match viewport fov to default / selected title menu fov - if (GetFOV() != fov) - { - if (m_viewPane) - { - m_viewPane->OnFOVChanged(fov); - SetFOV(fov); - } - } - - // Just for editor: Aspect ratio fix when changing the viewport - if (!GetIEditor()->IsInGameMode()) - { - float viewportAspectRatio = float( w ) / h; - float targetAspectRatio = GetAspectRatio(); - if (targetAspectRatio > viewportAspectRatio) - { - // Correct for vertical FOV change. - float maxTargetHeight = float( w ) / targetAspectRatio; - fov = 2 * atanf((h * tan(fov / 2)) / maxTargetHeight); - } - } - m_Camera.SetFrustum(w, h, fov, fNearZ); - } - - GetIEditor()->GetSystem()->SetViewCamera(m_Camera); if (GetIEditor()->IsInGameMode()) { @@ -1144,17 +955,6 @@ void EditorViewportWidget::OnMenuSelectCurrentCamera() AzFramework::CameraState EditorViewportWidget::GetCameraState() { - if (m_viewEntityId.IsValid()) - { - bool cameraStateAcquired = false; - AzFramework::CameraState cameraState; - Camera::EditorCameraViewRequestBus::BroadcastResult(cameraStateAcquired, - &Camera::EditorCameraViewRequestBus::Events::GetCameraState, cameraState); - if (cameraStateAcquired) - { - return cameraState; - } - } return m_renderViewport->GetCameraState(); } @@ -1467,13 +1267,11 @@ void EditorViewportWidget::SetViewportId(int id) } auto viewportContext = m_renderViewport->GetViewportContext(); m_defaultViewportContextName = viewportContext->GetName(); + m_defaultView = viewportContext->GetDefaultView(); QBoxLayout* layout = new QBoxLayout(QBoxLayout::Direction::TopToBottom, this); layout->setContentsMargins(QMargins()); layout->addWidget(m_renderViewport); - viewportContext->ConnectViewMatrixChangedHandler(m_cameraViewMatrixChangeHandler); - viewportContext->ConnectProjectionMatrixChangedHandler(m_cameraProjectionMatrixChangeHandler); - m_renderViewport->GetControllerList()->Add(AZStd::make_shared()); if (ed_useNewCameraSystem) @@ -1682,7 +1480,6 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) menu->addSeparator(); } - AZ::ViewportHelpers::AddCheckbox(menu, "Lock Camera Movement", &m_bLockCameraMovement); menu->addSeparator(); // Camera Sub menu @@ -1696,17 +1493,6 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) AZ::EBusAggregateResults getCameraResults; Camera::CameraBus::BroadcastResult(getCameraResults, &Camera::CameraRequests::GetCameras); - const int numCameras = getCameraResults.values.size(); - - // only enable if we're editing a sequence in Track View and have cameras in the level - bool enableSequenceCameraMenu = (GetIEditor()->GetAnimation()->GetSequence() && numCameras); - - action = customCameraMenu->addAction(tr("Sequence Camera")); - action->setCheckable(true); - action->setChecked(m_viewSourceType == ViewSourceType::SequenceCamera); - action->setEnabled(enableSequenceCameraMenu); - connect(action, &QAction::triggered, this, &EditorViewportWidget::SetSequenceCamera); - QVector additionalCameras; additionalCameras.reserve(getCameraResults.values.size()); @@ -1740,28 +1526,6 @@ bool EditorViewportWidget::AddCameraMenuItems(QMenu* menu) customCameraMenu->addAction(cameraAction); } - action = customCameraMenu->addAction(tr("Look through entity")); - bool areAnyEntitiesSelected = false; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(areAnyEntitiesSelected, &AzToolsFramework::ToolsApplicationRequests::AreAnyEntitiesSelected); - action->setCheckable(areAnyEntitiesSelected || m_viewSourceType == ViewSourceType::AZ_Entity); - action->setEnabled(areAnyEntitiesSelected || m_viewSourceType == ViewSourceType::AZ_Entity); - action->setChecked(m_viewSourceType == ViewSourceType::AZ_Entity); - connect(action, &QAction::triggered, this, [this](bool isChecked) - { - if (isChecked) - { - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - if (selectedEntityList.size()) - { - SetEntityAsCamera(*selectedEntityList.begin()); - } - } - else - { - SetDefaultCamera(); - } - }); return true; } @@ -1790,28 +1554,6 @@ void EditorViewportWidget::ResizeView(int width, int height) } } -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::ToggleCameraObject() -{ - if (m_viewSourceType == ViewSourceType::SequenceCamera) - { - ResetToViewSourceType(ViewSourceType::LegacyCamera); - } - else - { - ResetToViewSourceType(ViewSourceType::SequenceCamera); - } - PostCameraSet(); - GetIEditor()->GetAnimation()->ForceAnimation(); -} - -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::SetCamera(const CCamera& camera) -{ - m_Camera = camera; - SetViewTM(m_Camera.GetMatrix()); -} - ////////////////////////////////////////////////////////////////////////// EditorViewportWidget* EditorViewportWidget::GetPrimaryViewport() { @@ -1865,155 +1607,143 @@ void EditorViewportWidget::keyPressEvent(QKeyEvent* event) #endif // defined(AZ_PLATFORM_WINDOWS) } -void EditorViewportWidget::SetViewTM(const Matrix34& viewTM, bool bMoveOnly) +void EditorViewportWidget::SetViewTM(const Matrix34& tm) { - Matrix34 camMatrix = viewTM; - - // If no collision flag set do not check for terrain elevation. - if (GetType() == ET_ViewportCamera) + if (m_viewSourceType == ViewSourceType::None) { - if ((GetIEditor()->GetDisplaySettings()->GetSettings() & SETTINGS_NOCOLLISION) == 0) - { - Vec3 p = camMatrix.GetTranslation(); - bool adjustCameraElevation = true; - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - if (terrain) - { - AZ::Aabb terrainAabb(terrain->GetTerrainAabb()); - - // Adjust the AABB to include all Z values. Since the goal here is to snap the camera to the terrain height if - // it's below the terrain, we only want to verify the camera is within the XY bounds of the terrain to adjust the elevation. - terrainAabb.SetMin(AZ::Vector3(terrainAabb.GetMin().GetX(), terrainAabb.GetMin().GetY(), -AZ::Constants::FloatMax)); - terrainAabb.SetMax(AZ::Vector3(terrainAabb.GetMax().GetX(), terrainAabb.GetMax().GetY(), AZ::Constants::FloatMax)); - - if (!terrainAabb.Contains(LYVec3ToAZVec3(p))) - { - adjustCameraElevation = false; - } - else if (terrain->GetIsHoleFromFloats(p.x, p.y)) - { - adjustCameraElevation = false; - } - } - - if (adjustCameraElevation) - { - float z = GetIEditor()->GetTerrainElevation(p.x, p.y); - if (p.z < z + 0.25) - { - p.z = z + 0.25; - camMatrix.SetTranslation(p); - } - } - } - - // Also force this position on game. - if (GetIEditor()->GetGameEngine()) - { - GetIEditor()->GetGameEngine()->SetPlayerViewMatrix(viewTM); - } + m_defaultViewTM = tm; } + SetViewTM(tm, false); +} +void EditorViewportWidget::SetViewTM(const Matrix34& camMatrix, bool bMoveOnly) +{ + AZ_Warning("EditorViewportWidget", !bMoveOnly, "'Move Only' mode is deprecated"); CBaseObject* cameraObject = GetCameraObject(); - if (cameraObject) + + // Check if the active view entity is the same as the entity having the current view + // Sometimes this isn't the case because the active view is in the process of changing + // If it isn't, then we're doing the wrong thing below: we end up copying data from one (seemingly random) + // camera to another (seemingly random) camera + enum class ShouldUpdateObject { - // Ignore camera movement if locked. - if (IsCameraMovementLocked() || (!GetIEditor()->GetAnimation()->IsRecordMode() && !IsCameraObjectMove())) - { - return; - } + Yes, No, YesButViewsOutOfSync + }; - AZ::Matrix3x3 lookThroughEntityCorrection = AZ::Matrix3x3::CreateIdentity(); - if (m_viewEntityId.IsValid()) + const ShouldUpdateObject shouldUpdateObject = [&]() { + if (!cameraObject) { - LmbrCentral::EditorCameraCorrectionRequestBus::EventResult( - lookThroughEntityCorrection, m_viewEntityId, - &LmbrCentral::EditorCameraCorrectionRequests::GetInverseTransformCorrection); + return ShouldUpdateObject::No; } - if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) + if (m_viewSourceType == ViewSourceType::CameraComponent) { - AzToolsFramework::ScopedUndoBatch undo("Move Camera"); - if (bMoveOnly) - { - // specify eObjectUpdateFlags_UserInput so that an undo command gets logged - cameraObject->SetWorldPos(camMatrix.GetTranslation(), eObjectUpdateFlags_UserInput); - } - else + if (!m_viewEntityId.IsValid()) { - // specify eObjectUpdateFlags_UserInput so that an undo command gets logged - cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection), eObjectUpdateFlags_UserInput); + // Should be impossible anyways + AZ_Assert(false, "Internal logic error - view entity Id and view source type out of sync. Please report this as a bug"); + return ShouldUpdateObject::No; } + + // Check that the current view is the same view as the view entity view + AZ::RPI::ViewPtr viewEntityView; + AZ::RPI::ViewProviderBus::EventResult( + viewEntityView, m_viewEntityId, + &AZ::RPI::ViewProviderBus::Events::GetView + ); + + return viewEntityView == GetCurrentAtomView() ? ShouldUpdateObject::Yes : ShouldUpdateObject::YesButViewsOutOfSync; } else { - if (bMoveOnly) - { - // Do not specify eObjectUpdateFlags_UserInput, so that an undo command does not get logged; we covered it already when m_pressedKeyState was PressedThisFrame - cameraObject->SetWorldPos(camMatrix.GetTranslation()); - } - else - { - // Do not specify eObjectUpdateFlags_UserInput, so that an undo command does not get logged; we covered it already when m_pressedKeyState was PressedThisFrame - cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection)); - } + AZ_Assert(false, "Internal logic error - view source type is the default camera, but there is somehow a camera object. Please report this as a bug."); + + // For non-component cameras, can't do any complicated view-based checks + return ShouldUpdateObject::No; } - } - else if (m_viewEntityId.IsValid()) + }(); + + if (shouldUpdateObject == ShouldUpdateObject::Yes) { - // Ignore camera movement if locked. - if (IsCameraMovementLocked() || (!GetIEditor()->GetAnimation()->IsRecordMode() && !IsCameraObjectMove())) + AZ::Matrix3x3 lookThroughEntityCorrection = AZ::Matrix3x3::CreateIdentity(); + if (m_viewEntityId.IsValid()) { - return; + LmbrCentral::EditorCameraCorrectionRequestBus::EventResult( + lookThroughEntityCorrection, m_viewEntityId, + &LmbrCentral::EditorCameraCorrectionRequests::GetInverseTransformCorrection); } - if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) + int flags = 0; { - AzToolsFramework::ScopedUndoBatch undo("Move Camera"); - if (bMoveOnly) - { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTranslation, - LYVec3ToAZVec3(camMatrix.GetTranslation())); - } - else + // It isn't clear what this logic is supposed to do (it's legacy code)... + // For now, instead of removing it, just assert if the m_pressedKeyState isn't as expected + // Do not touch unless you really know what you're doing! + AZ_Assert(m_pressedKeyState == KeyPressedState::AllUp, "Internal logic error - key pressed state got changed. Please report this as a bug"); + + AZStd::optional undo; + if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTM, - LYTransformToAZTransform(camMatrix)); + flags = eObjectUpdateFlags_UserInput; + undo.emplace("Move Camera"); } - AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequests::AddDirtyEntity, m_viewEntityId); - } - else - { if (bMoveOnly) { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTranslation, - LYVec3ToAZVec3(camMatrix.GetTranslation())); + cameraObject->SetWorldPos(camMatrix.GetTranslation(), flags); } else { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTM, - LYTransformToAZTransform(camMatrix)); + cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection), flags); } } - - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast( - &AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, - AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); + } + else if (shouldUpdateObject == ShouldUpdateObject::YesButViewsOutOfSync) + { + // Technically this should not cause anything to go wrong, but may indicate some underlying bug by a caller + // of SetViewTm, for example, trying to set the view TM in the middle of a camera change. + // If this is an important case, it can potentially be supported by caching the requested view TM + // until the entity and view ptr become synchronized. + AZ_Error("EditorViewportWidget", + m_playInEditorState == PlayInEditorState::Editor, + "Viewport camera entity ID and view out of sync; request view transform will be ignored. " + "Please report this as a bug." + ); } if (m_pressedKeyState == KeyPressedState::PressedThisFrame) { m_pressedKeyState = KeyPressedState::PressedInPreviousFrame; } +} + +const Matrix34& EditorViewportWidget::GetViewTM() const +{ + // `m_viewTmStorage' is only required because we must return a reference + m_viewTmStorage = AZTransformToLYTransform(GetCurrentAtomView()->GetCameraTransform()); + return m_viewTmStorage; +}; - QtViewport::SetViewTM(camMatrix); +AZ::EntityId EditorViewportWidget::GetCurrentViewEntityId() +{ + // Sanity check that this camera entity ID is actually the camera entity which owns the current active render view + if (m_viewSourceType == ViewSourceType::CameraComponent) + { + // Check that the current view is the same view as the view entity view + AZ::RPI::ViewPtr viewEntityView; + AZ::RPI::ViewProviderBus::EventResult( + viewEntityView, m_viewEntityId, + &AZ::RPI::ViewProviderBus::Events::GetView + ); - m_Camera.SetMatrix(camMatrix); + const bool isViewEntityCorrect = viewEntityView == GetCurrentAtomView(); + AZ_Error("EditorViewportWidget", isViewEntityCorrect, + "GetCurrentViewEntityId called while the current view is being changed. " + "You may get inconsistent results if you make use of the returned entity ID. " + "This is an internal error, please report it as a bug." + ); + } + + return m_viewEntityId; } ////////////////////////////////////////////////////////////////////////// @@ -2419,14 +2149,10 @@ void EditorViewportWidget::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& } ////////////////////////////////////////////////////////////////////////// -float EditorViewportWidget::GetScreenScaleFactor(const Vec3& worldPoint) const +float EditorViewportWidget::GetScreenScaleFactor([[maybe_unused]] const Vec3& worldPoint) const { - float dist = m_Camera.GetPosition().GetDistance(worldPoint); - if (dist < m_Camera.GetNearPlane()) - { - dist = m_Camera.GetNearPlane(); - } - return dist; + AZ_Error("CryLegacy", false, "EditorViewportWidget::GetScreenScaleFactor not implemented"); + return 1.f; } ////////////////////////////////////////////////////////////////////////// float EditorViewportWidget::GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position) @@ -2436,12 +2162,6 @@ float EditorViewportWidget::GetScreenScaleFactor(const CCamera& camera, const Ve return dist; } -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::OnDestroy() -{ - DestroyRenderContext(); -} - ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::CheckRespondToInput() const { @@ -2461,16 +2181,16 @@ bool EditorViewportWidget::CheckRespondToInput() const ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::HitTest(const QPoint& point, HitContext& hitInfo) { - hitInfo.camera = &m_Camera; + hitInfo.camera = nullptr; hitInfo.pExcludedObject = GetCameraObject(); return QtViewport::HitTest(point, hitInfo); } ////////////////////////////////////////////////////////////////////////// -bool EditorViewportWidget::IsBoundsVisible(const AABB& box) const +bool EditorViewportWidget::IsBoundsVisible(const AABB&) const { - // If at least part of bbox is visible then its visible. - return m_Camera.IsAABBVisible_F(AABB(box.min, box.max)); + AZ_Assert(false, "Not supported"); + return false; } ////////////////////////////////////////////////////////////////////////// @@ -2515,11 +2235,11 @@ void EditorViewportWidget::CenterOnAABB(const AABB& aabb) Matrix34 newTM = Matrix34(rotationMatrix, newPosition); // Set new orbit distance - m_orbitDistance = distanceToTarget; - m_orbitDistance = fabs(m_orbitDistance); + float orbitDistance = distanceToTarget; + orbitDistance = fabs(orbitDistance); SetViewTM(newTM); - SandboxEditor::OrbitCameraControlsBus::Event(GetViewportId(), &SandboxEditor::OrbitCameraControlsBus::Events::SetOrbitDistance, m_orbitDistance); + SandboxEditor::OrbitCameraControlsBus::Event(GetViewportId(), &SandboxEditor::OrbitCameraControlsBus::Events::SetOrbitDistance, orbitDistance); } void EditorViewportWidget::CenterOnSliceInstance() @@ -2569,130 +2289,121 @@ void EditorViewportWidget::SetFOV(float fov) { if (m_viewEntityId.IsValid()) { - Camera::CameraRequestBus::Event(m_viewEntityId, &Camera::CameraComponentRequests::SetFov, AZ::RadToDeg(fov)); + Camera::CameraRequestBus::Event(m_viewEntityId, &Camera::CameraComponentRequests::SetFovRadians, fov); } else { - m_camFOV = fov; - // Set the active camera's FOV - { - AZ::Matrix4x4 clipMatrix; - AZ::MakePerspectiveFovMatrixRH( - clipMatrix, - GetFOV(), - aznumeric_cast(width()) / aznumeric_cast(height()), - m_Camera.GetNearPlane(), - m_Camera.GetFarPlane(), - true - ); - m_renderViewport->GetViewportContext()->SetCameraProjectionMatrix(clipMatrix); - } - } - - if (m_viewPane) - { - m_viewPane->OnFOVChanged(fov); + auto m = m_defaultView->GetViewToClipMatrix(); + AZ::SetPerspectiveMatrixFOV(m, fov, aznumeric_cast(width()) / aznumeric_cast(height())); + m_defaultView->SetViewToClipMatrix(m); } } ////////////////////////////////////////////////////////////////////////// float EditorViewportWidget::GetFOV() const { - if (m_viewSourceType == ViewSourceType::SequenceCamera) + if (m_viewEntityId.IsValid()) + { + float fov = 0.f; + Camera::CameraRequestBus::EventResult(fov, m_viewEntityId, &Camera::CameraComponentRequests::GetFovRadians); + return fov; + } + else { - CBaseObject* cameraObject = GetCameraObject(); + return AZ::GetPerspectiveMatrixFOV(m_defaultView->GetViewToClipMatrix()); + } +} - AZ::EntityId cameraEntityId; - AzToolsFramework::ComponentEntityObjectRequestBus::EventResult(cameraEntityId, cameraObject, &AzToolsFramework::ComponentEntityObjectRequestBus::Events::GetAssociatedEntityId); - if (cameraEntityId.IsValid()) - { - // component Camera - float fov = DEFAULT_FOV; - Camera::CameraRequestBus::EventResult(fov, cameraEntityId, &Camera::CameraComponentRequests::GetFov); - return AZ::DegToRad(fov); - } +void EditorViewportWidget::OnActiveViewChanged(const AZ::EntityId& viewEntityId) +{ + // Avoid re-entry + if (m_sendingOnActiveChanged) + { + return; } - if (m_viewEntityId.IsValid()) + // Ignore any changes in simulation mode + if (m_playInEditorState != PlayInEditorState::Editor) { - float fov = AZ::RadToDeg(m_camFOV); - Camera::CameraRequestBus::EventResult(fov, m_viewEntityId, &Camera::CameraComponentRequests::GetFov); - return AZ::DegToRad(fov); + return; } - return m_camFOV; -} + // if they've picked the same camera, then that means they want to toggle + if (viewEntityId.IsValid()) + { + // Any such events for game entities should be filtered out by the check above + AZ_Error( + "EditorViewportWidget", + Camera::EditorCameraViewRequestBus::FindFirstHandler(viewEntityId) != nullptr, + "Internal logic error - active view changed to an entity which is not an editor camera. " + "Please report this as a bug." + ); -////////////////////////////////////////////////////////////////////////// -bool EditorViewportWidget::CreateRenderContext() -{ - return true; -} + m_viewEntityId = viewEntityId; + m_viewSourceType = ViewSourceType::CameraComponent; + AZStd::string entityName; + AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, viewEntityId); + SetName(QString("Camera entity: %1").arg(entityName.c_str())); -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::DestroyRenderContext() -{ + PostCameraSet(); + } + else + { + SetDefaultCamera(); + } } ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::SetDefaultCamera() { - if (IsDefaultCamera()) - { - return; - } - ResetToViewSourceType(ViewSourceType::None); - GetViewManager()->SetCameraObjectId(m_cameraObjectId); + m_viewEntityId.SetInvalid(); + m_viewSourceType = ViewSourceType::None; + GetViewManager()->SetCameraObjectId(GUID_NULL); SetName(m_defaultViewName); SetViewTM(m_defaultViewTM); - PostCameraSet(); -} -////////////////////////////////////////////////////////////////////////// -bool EditorViewportWidget::IsDefaultCamera() const -{ - return m_viewSourceType == ViewSourceType::None; + // Synchronize the configured editor viewport FOV to the default camera + if (m_viewPane) + { + const float fov = gSettings.viewports.fDefaultFov; + m_viewPane->OnFOVChanged(fov); + SetFOV(fov); + } + + // Push the default view as the active view + auto atomViewportRequests = AZ::Interface::Get(); + if (atomViewportRequests) + { + const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); + atomViewportRequests->PushView(contextName, m_defaultView); + } + + PostCameraSet(); } ////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::SetSequenceCamera() +AZ::RPI::ViewPtr EditorViewportWidget::GetCurrentAtomView() const { - if (m_viewSourceType == ViewSourceType::SequenceCamera) + if (m_renderViewport && m_renderViewport->GetViewportContext()) { - // Reset if we were checked before - SetDefaultCamera(); + return m_renderViewport->GetViewportContext()->GetDefaultView(); } else { - ResetToViewSourceType(ViewSourceType::SequenceCamera); - - SetName(tr("Sequence Camera")); - SetViewTM(GetViewTM()); - - GetViewManager()->SetCameraObjectId(m_cameraObjectId); - PostCameraSet(); - - // ForceAnimation() so Track View will set the Camera params - // if a camera is animated in the sequences. - if (GetIEditor() && GetIEditor()->GetAnimation()) - { - GetIEditor()->GetAnimation()->ForceAnimation(); - } + return nullptr; } } ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::SetComponentCamera(const AZ::EntityId& entityId) { - ResetToViewSourceType(ViewSourceType::CameraComponent); - SetViewEntity(entityId); + SetViewFromEntityPerspective(entityId); } ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::SetEntityAsCamera(const AZ::EntityId& entityId, bool lockCameraMovement) { - ResetToViewSourceType(ViewSourceType::AZ_Entity); - SetViewEntity(entityId, lockCameraMovement); + SetViewAndMovementLockFromEntityPerspective(entityId, lockCameraMovement); } void EditorViewportWidget::SetFirstComponentCamera() @@ -2740,7 +2451,7 @@ bool EditorViewportWidget::IsSelectedCamera() const AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult( selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - if ((m_viewSourceType == ViewSourceType::CameraComponent || m_viewSourceType == ViewSourceType::AZ_Entity) + if ((m_viewSourceType == ViewSourceType::CameraComponent) && !selectedEntityList.empty() && AZStd::find(selectedEntityList.begin(), selectedEntityList.end(), m_viewEntityId) != selectedEntityList.end()) { @@ -2762,17 +2473,6 @@ void EditorViewportWidget::CycleCamera() SetFirstComponentCamera(); break; } - case EditorViewportWidget::ViewSourceType::SequenceCamera: - { - AZ_Error("EditorViewportWidget", false, "Legacy cameras no longer exist, unable to set sequence camera."); - break; - } - case EditorViewportWidget::ViewSourceType::LegacyCamera: - { - AZ_Warning("EditorViewportWidget", false, "Legacy cameras no longer exist, using first found component camera instead."); - SetFirstComponentCamera(); - break; - } case EditorViewportWidget::ViewSourceType::CameraComponent: { AZ::EBusAggregateResults results; @@ -2791,12 +2491,6 @@ void EditorViewportWidget::CycleCamera() SetDefaultCamera(); break; } - case EditorViewportWidget::ViewSourceType::AZ_Entity: - { - // we may decide to have this iterate over just selected entities - SetDefaultCamera(); - break; - } default: { SetDefaultCamera(); @@ -2810,11 +2504,28 @@ void EditorViewportWidget::SetViewFromEntityPerspective(const AZ::EntityId& enti SetViewAndMovementLockFromEntityPerspective(entityId, false); } -void EditorViewportWidget::SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, bool lockCameraMovement) +void EditorViewportWidget::SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, [[maybe_unused]] bool lockCameraMovement) { - if (!m_ignoreSetViewFromEntityPerspective) + // This is an editor event, so is only serviced during edit mode, not play game mode + // + if (m_playInEditorState != PlayInEditorState::Editor) + { + AZ_Warning("EditorViewportWidget", false, + "Tried to change the editor camera during play game in editor; this is currently unsupported" + ); + return; + } + + AZ_Assert(lockCameraMovement == false, "SetViewAndMovementLockFromEntityPerspective with lockCameraMovement == true not supported"); + + if (entityId.IsValid()) + { + Camera::CameraRequestBus::Event(entityId, &Camera::CameraRequestBus::Events::MakeActiveView); + } + else { - SetEntityAsCamera(entityId, lockCameraMovement); + // The default camera + SetDefaultCamera(); } } @@ -2829,7 +2540,7 @@ bool EditorViewportWidget::GetActiveCameraPosition(AZ::Vector3& cameraPos) else { // Use viewTM, which is synced with the camera and guaranteed to be up-to-date - cameraPos = LYVec3ToAZVec3(m_viewTM.GetTranslation()); + cameraPos = LYVec3ToAZVec3(GetViewTM().GetTranslation()); } return true; @@ -2843,17 +2554,26 @@ bool EditorViewportWidget::GetActiveCameraState(AzFramework::CameraState& camera if (m_pPrimaryViewport == this) { cameraState = GetCameraState(); - return true; } return false; } +void EditorViewportWidget::OnStartPlayInEditorBegin() +{ + m_playInEditorState = PlayInEditorState::Starting; +} + void EditorViewportWidget::OnStartPlayInEditor() { + m_playInEditorState = PlayInEditorState::Started; + if (m_viewEntityId.IsValid()) { + // Note that this is assuming that the Atom camera components will share the same view ptr + // in editor as in game mode + m_viewEntityIdCachedForEditMode = m_viewEntityId; AZ::EntityId runtimeEntityId; AzToolsFramework::EditorEntityContextRequestBus::Broadcast( @@ -2866,20 +2586,14 @@ void EditorViewportWidget::OnStartPlayInEditor() void EditorViewportWidget::OnStopPlayInEditor() { - if (m_viewEntityIdCachedForEditMode.IsValid()) - { - m_viewEntityId = m_viewEntityIdCachedForEditMode; - m_viewEntityIdCachedForEditMode.SetInvalid(); - } -} + m_playInEditorState = PlayInEditorState::Editor; -////////////////////////////////////////////////////////////////////////// -void EditorViewportWidget::OnCameraFOVVariableChanged([[maybe_unused]] IVariable* var) -{ - if (m_viewPane) - { - m_viewPane->OnFOVChanged(GetFOV()); - } + // Note that: + // - this is assuming that the Atom camera components will share the same view ptr in editor as in game mode. + // - if `m_viewEntityIdCachedForEditMode' is invalid, the camera before game mode was the default editor camera + // - we MUST set the camera again when exiting game mode, because when rendering with trackview, the editor camera gets set somehow + SetViewFromEntityPerspective(m_viewEntityIdCachedForEditMode); + m_viewEntityIdCachedForEditMode.SetInvalid(); } ////////////////////////////////////////////////////////////////////////// @@ -2912,11 +2626,6 @@ void EditorViewportWidget::ShowCursor() m_bCursorHidden = false; } -bool EditorViewportWidget::IsKeyDown(Qt::Key key) const -{ - return m_keyDown.contains(key); -} - ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::PushDisableRendering() { @@ -2954,6 +2663,17 @@ QSize EditorViewportWidget::WidgetToViewport(const QSize& size) const return size * WidgetToViewportFactor(); } +////////////////////////////////////////////////////////////////////////// +double EditorViewportWidget::WidgetToViewportFactor() const +{ +#if defined(AZ_PLATFORM_WINDOWS) + // Needed for high DPI mode on windows + return devicePixelRatioF(); +#else + return 1.0; +#endif +} + ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::BeginUndoTransaction() { @@ -2967,12 +2687,6 @@ void EditorViewportWidget::EndUndoTransaction() Update(); } -void EditorViewportWidget::UpdateCurrentMousePos(const QPoint& newPosition) -{ - m_prevMousePos = m_mousePos; - m_mousePos = newPosition; -} - void* EditorViewportWidget::GetSystemCursorConstraintWindow() const { AzFramework::SystemCursorState systemCursorState = AzFramework::SystemCursorState::Unknown; @@ -3048,7 +2762,8 @@ void EditorViewportWidget::RestoreViewportAfterGameMode() } else { - SetViewTM(m_gameTM); + AZ_Error("CryLegacy", false, "Not restoring the editor viewport camera is currently unsupported"); + SetViewTM(preGameModeViewTM); } } @@ -3067,12 +2782,6 @@ void EditorViewportWidget::UpdateScene() } } -void EditorViewportWidget::UpdateCameraFromViewportContext() -{ - // Queue a sync for the next tick, to ensure the latest version of the viewport context transform is used - m_updateCameraPositionNextTick = true; -} - void EditorViewportWidget::SetAsActiveViewport() { auto viewportContextManager = AZ::Interface::Get(); diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index b682de1cc3..33ed001735 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -8,8 +8,6 @@ #pragma once -// RenderViewport.h : header file -// #if !defined(Q_MOC_RUN) #include @@ -34,6 +32,7 @@ #include #include #include +#include #endif #include @@ -65,130 +64,120 @@ namespace AzToolsFramework // EditorViewportWidget window AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -class SANDBOX_API EditorViewportWidget +class SANDBOX_API EditorViewportWidget final : public QtViewport - , public IEditorNotifyListener - , public IUndoManagerListener - , public Camera::EditorCameraRequestBus::Handler - , public AzFramework::InputSystemCursorConstraintRequestBus::Handler - , public AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler - , public AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler - , public AzFramework::AssetCatalogEventBus::Handler - , public AZ::RPI::SceneNotificationBus::Handler + , private IEditorNotifyListener + , private IUndoManagerListener + , private Camera::EditorCameraRequestBus::Handler + , private Camera::CameraNotificationBus::Handler + , private AzFramework::InputSystemCursorConstraintRequestBus::Handler + , private AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler + , private AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler + , private AzFramework::AssetCatalogEventBus::Handler + , private AZ::RPI::SceneNotificationBus::Handler { AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING Q_OBJECT -public: - struct SResolution - { - SResolution() - : width(0) - , height(0) - { - } - - SResolution(int w, int h) - : width(w) - , height(h) - { - } - - int width; - int height; - }; public: EditorViewportWidget(const QString& name, QWidget* parent = nullptr); + ~EditorViewportWidget() override; static const GUID& GetClassID() { return QtViewport::GetClassID(); } - /** Get type of this viewport. - */ - virtual EViewportType GetType() const { return ET_ViewportCamera; } - virtual void SetType([[maybe_unused]] EViewportType type) { assert(type == ET_ViewportCamera); }; - - virtual ~EditorViewportWidget(); - - Q_INVOKABLE void InjectFakeMouseMove(int deltaX, int deltaY, Qt::MouseButtons buttons); - - // Replacement for still used CRenderer methods - void UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const; - void ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const; + static EditorViewportWidget* GetPrimaryViewport(); -public: - virtual void Update(); + // Used by ViewPan in some circumstances + void ConnectViewportInteractionRequestBus(); + void DisconnectViewportInteractionRequestBus(); - virtual void ResetContent(); - virtual void UpdateContent(int flags); + // QtViewport/IDisplayViewport/CViewport + // These methods are made public in the derived class because they are called with an object whose static type is known to be this class type. + void SetFOV(float fov) override; + float GetFOV() const override; - void OnTitleMenu(QMenu* menu) override; +private: + //////////////////////////////////////////////////////////////////////// + // Private types ... - void SetCamera(const CCamera& camera); - const CCamera& GetCamera() const { return m_Camera; }; - virtual void SetViewTM(const Matrix34& tm) + enum class ViewSourceType { - if (m_viewSourceType == ViewSourceType::None) - { - m_defaultViewTM = tm; - } - SetViewTM(tm, false); - } + None, + CameraComponent, + ViewSourceTypesCount, + }; + enum class PlayInEditorState + { + Editor, Starting, Started + }; + enum class KeyPressedState + { + AllUp, + PressedThisFrame, + PressedInPreviousFrame, + }; - //! Map world space position to viewport position. - virtual QPoint WorldToView(const Vec3& wp) const; - virtual QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const; - virtual Vec3 WorldToView3D(const Vec3& wp, int nFlags = 0) const; - - //! Map viewport position to world space position. - virtual Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; - virtual void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; - virtual Vec3 ViewToWorldNormal(const QPoint& vp, bool onlyTerrain, bool bTestRenderMesh = false) override; - virtual float GetScreenScaleFactor(const Vec3& worldPoint) const; - virtual float GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position); - virtual float GetAspectRatio() const; - virtual bool HitTest(const QPoint& point, HitContext& hitInfo); - virtual bool IsBoundsVisible(const AABB& box) const; - virtual void CenterOnSelection(); - virtual void CenterOnAABB(const AABB& aabb); - void CenterOnSliceInstance() override; + //////////////////////////////////////////////////////////////////////// + // Method overrides ... + // QWidget void focusOutEvent(QFocusEvent* event) override; void keyPressEvent(QKeyEvent* event) override; + bool event(QEvent* event) override; + void resizeEvent(QResizeEvent* event) override; + void paintEvent(QPaintEvent* event) override; + void mousePressEvent(QMouseEvent* event) override; - void SetFOV(float fov); - float GetFOV() const; + // QtViewport/IDisplayViewport/CViewport + EViewportType GetType() const override { return ET_ViewportCamera; } + void SetType([[maybe_unused]] EViewportType type) override { assert(type == ET_ViewportCamera); }; + AzToolsFramework::ViewportInteraction::MouseInteraction BuildMouseInteraction( + Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, const QPoint& point) override; + void SetViewportId(int id) override; + QPoint WorldToView(const Vec3& wp) const override; + QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const override; + Vec3 WorldToView3D(const Vec3& wp, int nFlags = 0) const override; + Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; + void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; + Vec3 ViewToWorldNormal(const QPoint& vp, bool onlyTerrain, bool bTestRenderMesh = false) override; + float GetScreenScaleFactor(const Vec3& worldPoint) const override; + float GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position) override; + float GetAspectRatio() const override; + bool HitTest(const QPoint& point, HitContext& hitInfo) override; + bool IsBoundsVisible(const AABB& box) const override; + void CenterOnSelection() override; + void CenterOnAABB(const AABB& aabb) override; + void CenterOnSliceInstance() override; + void OnTitleMenu(QMenu* menu) override; + void SetViewTM(const Matrix34& tm) override; + const Matrix34& GetViewTM() const override; + void Update() override; + void UpdateContent(int flags) override; - void SetDefaultCamera(); - bool IsDefaultCamera() const; - void SetSequenceCamera(); - bool IsSequenceCamera() const { return m_viewSourceType == ViewSourceType::SequenceCamera; } - void SetSelectedCamera(); - bool IsSelectedCamera() const; - void SetComponentCamera(const AZ::EntityId& entityId); - void SetEntityAsCamera(const AZ::EntityId& entityId, bool lockCameraMovement = false); - void SetFirstComponentCamera(); - void SetViewEntity(const AZ::EntityId& cameraEntityId, bool lockCameraMovement = false); - void PostCameraSet(); - // This switches the active camera to the next one in the list of (default, all custom cams). - void CycleCamera(); + // SceneNotificationBus + void OnBeginPrepareRender() override; - // Camera::EditorCameraRequestBus - void SetViewFromEntityPerspective(const AZ::EntityId& entityId) override; - void SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, bool lockCameraMovement) override; - AZ::EntityId GetCurrentViewEntityId() override { return m_viewEntityId; } - bool GetActiveCameraPosition(AZ::Vector3& cameraPos) override; - bool GetActiveCameraState(AzFramework::CameraState& cameraState) override; + // Camera::CameraNotificationBus + void OnActiveViewChanged(const AZ::EntityId&) override; + + // IEditorEventListener + void OnEditorNotifyEvent(EEditorNotifyEvent event) override; // AzToolsFramework::EditorEntityContextNotificationBus (handler moved to cpp to resolve link issues in unity builds) - virtual void OnStartPlayInEditor(); - virtual void OnStopPlayInEditor(); + void OnStartPlayInEditor(); + void OnStopPlayInEditor(); + void OnStartPlayInEditorBegin(); - AzFramework::CameraState GetCameraState(); - AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); + // IUndoManagerListener + void BeginUndoTransaction() override; + void EndUndoTransaction() override; + + // AzFramework::InputSystemCursorConstraintRequestBus + void* GetSystemCursorConstraintWindow() const override; // AzToolsFramework::ViewportFreezeRequestBus bool IsViewportInputFrozen() override; @@ -204,142 +193,19 @@ public: void BeginWidgetContext() override; void EndWidgetContext() override; - // CViewport... - void SetViewportId(int id) override; - - void ConnectViewportInteractionRequestBus(); - void DisconnectViewportInteractionRequestBus(); - - void LockCameraMovement(bool bLock) { m_bLockCameraMovement = bLock; } - bool IsCameraMovementLocked() const { return m_bLockCameraMovement; } - - void EnableCameraObjectMove(bool bMove) { m_bMoveCameraObject = bMove; } - bool IsCameraObjectMove() const { return m_bMoveCameraObject; } - - void SetPlayerControl(uint32 i) { m_PlayerControl = i; }; - uint32 GetPlayerControl() { return m_PlayerControl; }; - - const DisplayContext& GetDisplayContext() const { return m_displayContext; } - CBaseObject* GetCameraObject() const; - - QPoint WidgetToViewport(const QPoint& point) const; - QPoint ViewportToWidget(const QPoint& point) const; - QSize WidgetToViewport(const QSize& size) const; - - AzToolsFramework::ViewportInteraction::MouseInteraction BuildMouseInteraction( - Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, const QPoint& point) override; - - void SetPlayerPos() - { - Matrix34 m = GetViewTM(); - m.SetTranslation(m.GetTranslation() - m_PhysicalLocation.t); - SetViewTM(m); - - m_AverageFrameTime = 0.14f; - - m_PhysicalLocation.SetIdentity(); - - m_LocalEntityMat.SetIdentity(); - m_PrevLocalEntityMat.SetIdentity(); - - m_absCameraHigh = 2.0f; - m_absCameraPos = Vec3(0, 3, 2); - m_absCameraPosVP = Vec3(0, -3, 1.5); - - m_absCurrentSlope = 0.0f; - - m_absLookDirectionXY = Vec2(0, 1); - - m_LookAt = Vec3(ZERO); - m_LookAtRate = Vec3(ZERO); - m_vCamPos = Vec3(ZERO); - m_vCamPosRate = Vec3(ZERO); - - m_relCameraRotX = 0; - m_relCameraRotZ = 0; - - uint32 numSample6 = static_cast(m_arrAnimatedCharacterPath.size()); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrAnimatedCharacterPath[i] = Vec3(ZERO); - } - - numSample6 = static_cast(m_arrSmoothEntityPath.size()); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrSmoothEntityPath[i] = Vec3(ZERO); - } - - uint32 numSample7 = static_cast(m_arrRunStrafeSmoothing.size()); - for (uint32 i = 0; i < numSample7; i++) - { - m_arrRunStrafeSmoothing[i] = 0; - } - - m_vWorldDesiredBodyDirection = Vec2(0, 1); - m_vWorldDesiredBodyDirectionSmooth = Vec2(0, 1); - m_vWorldDesiredBodyDirectionSmoothRate = Vec2(0, 1); - - m_vWorldDesiredBodyDirection2 = Vec2(0, 1); - - m_vWorldDesiredMoveDirection = Vec2(0, 1); - m_vWorldDesiredMoveDirectionSmooth = Vec2(0, 1); - m_vWorldDesiredMoveDirectionSmoothRate = Vec2(0, 1); - m_vLocalDesiredMoveDirection = Vec2(0, 1); - m_vLocalDesiredMoveDirectionSmooth = Vec2(0, 1); - m_vLocalDesiredMoveDirectionSmoothRate = Vec2(0, 1); - - m_vWorldAimBodyDirection = Vec2(0, 1); - - m_MoveSpeedMSec = 5.0f; - m_key_W = 0; - m_keyrcr_W = 0; - m_key_S = 0; - m_keyrcr_S = 0; - m_key_A = 0; - m_keyrcr_A = 0; - m_key_D = 0; - m_keyrcr_D = 0; - m_key_SPACE = 0; - m_keyrcr_SPACE = 0; - m_ControllMode = 0; - - m_State = -1; - m_Stance = 1; //combat - - m_udGround = 0.0f; - m_lrGround = 0.0f; - AABB aabb = AABB(Vec3(-40.0f, -40.0f, -0.25f), Vec3(+40.0f, +40.0f, +0.0f)); - m_GroundOBB = OBB::CreateOBBfromAABB(Matrix33(IDENTITY), aabb); - m_GroundOBBPos = Vec3(0, 0, -0.01f); - }; - - static EditorViewportWidget* GetPrimaryViewport(); - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - CCamera m_Camera; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -protected: - struct SScopedCurrentContext; + // Camera::EditorCameraRequestBus + void SetViewFromEntityPerspective(const AZ::EntityId& entityId) override; + void SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, bool lockCameraMovement) override; + AZ::EntityId GetCurrentViewEntityId() override; + bool GetActiveCameraPosition(AZ::Vector3& cameraPos) override; + bool GetActiveCameraState(AzFramework::CameraState& cameraState) override; + //////////////////////////////////////////////////////////////////////// + // Private helpers... void SetViewTM(const Matrix34& tm, bool bMoveOnly); - - // Called to render stuff. - virtual void OnRender(); - - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - - //! Get currently active camera object. - void ToggleCameraObject(); - - void RenderConstructionPlane(); void RenderSnapMarker(); - void RenderAll(); - void OnBeginPrepareRender() override; - // Update the safe frame, safe action, safe title, and borders rectangles based on // viewport size and target aspect ratio. void UpdateSafeFrame(); @@ -353,242 +219,173 @@ protected: // Draw a selected region if it has been selected void RenderSelectedRegion(); - virtual bool CreateRenderContext(); - virtual void DestroyRenderContext(); - - void OnMenuCommandChangeAspectRatio(unsigned int commandId); - bool AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, Vec3& outPos) const; bool RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const; bool AddCameraMenuItems(QMenu* menu); void ResizeView(int width, int height); - void OnCameraFOVVariableChanged(IVariable* var); - void HideCursor(); void ShowCursor(); - bool IsKeyDown(Qt::Key key) const; - - enum class ViewSourceType - { - None, - SequenceCamera, - LegacyCamera, - CameraComponent, - AZ_Entity, - ViewSourceTypesCount, - }; - void ResetToViewSourceType(const ViewSourceType& viewSourType); + double WidgetToViewportFactor() const; bool ShouldPreviewFullscreen() const; void StartFullscreenPreview(); void StopFullscreenPreview(); - bool m_inFullscreenPreview = false; - bool m_bRenderContextCreated = false; - bool m_bInRotateMode = false; - bool m_bInMoveMode = false; - bool m_bInOrbitMode = false; - bool m_bInZoomMode = false; - - QPoint m_mousePos = QPoint(0, 0); - QPoint m_prevMousePos = QPoint(0, 0); // for tablets, you can't use SetCursorPos and need to remember the prior point and delta with that. - - - float m_moveSpeed = 1; - - float m_orbitDistance = 10.0f; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Vec3 m_orbitTarget; + void OnMenuResolutionCustom(); + void OnMenuCreateCameraEntityFromCurrentView(); + void OnMenuSelectCurrentCamera(); - //------------------------------------------- - //--- player-control in CharEdit --- - //------------------------------------------- - f32 m_MoveSpeedMSec; + // From a series of input primitives, compose a complete mouse interaction. + AzToolsFramework::ViewportInteraction::MouseInteraction BuildMouseInteractionInternal( + AzToolsFramework::ViewportInteraction::MouseButtons buttons, + AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers, + const AzToolsFramework::ViewportInteraction::MousePick& mousePick) const; - uint32 m_key_W, m_keyrcr_W; - uint32 m_key_S, m_keyrcr_S; - uint32 m_key_A, m_keyrcr_A; - uint32 m_key_D, m_keyrcr_D; + // Given a point in the viewport, return the pick ray into the scene. + // note: The argument passed to parameter **point**, originating + // from a Qt event, must first be passed to WidgetToViewport before being + // passed to BuildMousePick. + AzToolsFramework::ViewportInteraction::MousePick BuildMousePick(const QPoint& point); - uint32 m_key_SPACE, m_keyrcr_SPACE; - uint32 m_ControllMode; + bool CheckRespondToInput() const; - int32 m_Stance; - int32 m_State; - f32 m_AverageFrameTime; + void BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) override; - uint32 m_PlayerControl = 0; + void SetAsActiveViewport(); + void PushDisableRendering(); + void PopDisableRendering(); + bool IsRenderingDisabled() const; + AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal(const QPoint& point) const; - f32 m_absCameraHigh; - Vec3 m_absCameraPos; - Vec3 m_absCameraPosVP; + void RestoreViewportAfterGameMode(); - f32 m_absCurrentSlope; //in radiants + void UpdateScene(); - Vec2 m_absLookDirectionXY; + void SetDefaultCamera(); + void SetSelectedCamera(); + bool IsSelectedCamera() const; + void SetComponentCamera(const AZ::EntityId& entityId); + void SetEntityAsCamera(const AZ::EntityId& entityId, bool lockCameraMovement = false); + void SetFirstComponentCamera(); + void PostCameraSet(); + // This switches the active camera to the next one in the list of (default, all custom cams). + void CycleCamera(); - Vec3 m_LookAt; - Vec3 m_LookAtRate; - Vec3 m_vCamPos; - Vec3 m_vCamPosRate; - float m_camFOV; + AzFramework::CameraState GetCameraState(); + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); - f32 m_relCameraRotX; - f32 m_relCameraRotZ; + QPoint WidgetToViewport(const QPoint& point) const; + QPoint ViewportToWidget(const QPoint& point) const; + QSize WidgetToViewport(const QSize& size) const; - QuatTS m_PhysicalLocation; + const DisplayContext& GetDisplayContext() const { return m_displayContext; } + CBaseObject* GetCameraObject() const; - Matrix34 m_AnimatedCharacterMat; + void UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const; + void ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const; - Matrix34 m_LocalEntityMat; //this is used for data-driven animations where the character is running on the spot - Matrix34 m_PrevLocalEntityMat; + AZ::RPI::ViewPtr GetCurrentAtomView() const; - std::vector m_arrVerticesHF; - std::vector m_arrIndicesHF; + //////////////////////////////////////////////////////////////////////// + // Members ... + friend class AZ::ViewportHelpers::EditorEntityNotifications; - std::vector m_arrAnimatedCharacterPath; - std::vector m_arrSmoothEntityPath; - std::vector m_arrRunStrafeSmoothing; + AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Vec2 m_vWorldDesiredBodyDirection; - Vec2 m_vWorldDesiredBodyDirectionSmooth; - Vec2 m_vWorldDesiredBodyDirectionSmoothRate; + // Singleton for the primary viewport + static EditorViewportWidget* m_pPrimaryViewport; - Vec2 m_vWorldDesiredBodyDirection2; + // The simulation (play-game in editor) state + PlayInEditorState m_playInEditorState = PlayInEditorState::Editor; + // Whether we are doing a full screen game preview (play-game in editor) or a regular one + bool m_inFullscreenPreview = false; - Vec2 m_vWorldDesiredMoveDirection; - Vec2 m_vWorldDesiredMoveDirectionSmooth; - Vec2 m_vWorldDesiredMoveDirectionSmoothRate; - Vec2 m_vLocalDesiredMoveDirection; - Vec2 m_vLocalDesiredMoveDirectionSmooth; - Vec2 m_vLocalDesiredMoveDirectionSmoothRate; - Vec2 m_vWorldAimBodyDirection; + // The entity ID of the current camera for this viewport, or invalid if the default editor camera + AZ::EntityId m_viewEntityId; - f32 m_udGround; - f32 m_lrGround; - OBB m_GroundOBB; - Vec3 m_GroundOBBPos; + // Determines also if the current camera for this viewport is default editor camera + ViewSourceType m_viewSourceType = ViewSourceType::None; - // Index of camera objects. - mutable GUID m_cameraObjectId; - mutable AZ::EntityId m_viewEntityId; - mutable ViewSourceType m_viewSourceType = ViewSourceType::None; + // During play game in editor, holds the editor entity ID of the last AZ::EntityId m_viewEntityIdCachedForEditMode; + + // The editor camera TM before switching to game mode Matrix34 m_preGameModeViewTM; + + // Disables rendering during some periods of time, e.g. undo/redo, resize events uint m_disableRenderingCount = 0; - bool m_bLockCameraMovement; + + // Determines if the viewport needs updating (false when out of focus for example) bool m_bUpdateViewport = false; - bool m_bMoveCameraObject = true; - enum class KeyPressedState - { - AllUp, - PressedThisFrame, - PressedInPreviousFrame, - }; + // Avoid re-entering PostCameraSet->OnActiveViewChanged->PostCameraSet + bool m_sendingOnActiveChanged = false; + + // Legacy... KeyPressedState m_pressedKeyState = KeyPressedState::AllUp; + // The last camera matrix of the default editor camera, used when switching back to editor camera to restore the right TM Matrix34 m_defaultViewTM; + + // The name to use for the default editor camera const QString m_defaultViewName; + // Note that any attempts to draw anything with this object will crash. Exists here for legacy "reasons" DisplayContext m_displayContext; - + // Re-entrency guard for on paint events bool m_isOnPaint = false; - static EditorViewportWidget* m_pPrimaryViewport; + // Shapes of various safe frame helpers which can be displayed in the editor QRect m_safeFrame; QRect m_safeAction; QRect m_safeTitle; + // Aspect ratios available in the title bar CPredefinedAspectRatios m_predefinedAspectRatios; + // Is the cursor hidden or displayed? bool m_bCursorHidden = false; - void OnMenuResolutionCustom(); - void OnMenuCreateCameraEntityFromCurrentView(); - void OnMenuSelectCurrentCamera(); - - int OnCreate(); - void resizeEvent(QResizeEvent* event) override; - void paintEvent(QPaintEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - - // From a series of input primitives, compose a complete mouse interaction. - AzToolsFramework::ViewportInteraction::MouseInteraction BuildMouseInteractionInternal( - AzToolsFramework::ViewportInteraction::MouseButtons buttons, - AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers, - const AzToolsFramework::ViewportInteraction::MousePick& mousePick) const; - // Given a point in the viewport, return the pick ray into the scene. - // note: The argument passed to parameter **point**, originating - // from a Qt event, must first be passed to WidgetToViewport before being - // passed to BuildMousePick. - AzToolsFramework::ViewportInteraction::MousePick BuildMousePick(const QPoint& point); - - bool event(QEvent* event) override; - void OnDestroy(); - - bool CheckRespondToInput() const; - - // AzFramework::InputSystemCursorConstraintRequestBus - void* GetSystemCursorConstraintWindow() const override; - - void BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) override; - -private: - void SetAsActiveViewport(); - void PushDisableRendering(); - void PopDisableRendering(); - bool IsRenderingDisabled() const; - AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal(const QPoint& point) const; - - void RestoreViewportAfterGameMode(); - void UpdateCameraFromViewportContext(); - - double WidgetToViewportFactor() const - { -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - return devicePixelRatioF(); -#else - return 1.0f; -#endif - } - - void BeginUndoTransaction() override; - void EndUndoTransaction() override; - - void UpdateCurrentMousePos(const QPoint& newPosition); - void UpdateScene(); - + // Shim for QtViewport, which used to be responsible for visibility queries in the editor, + // these are now forwarded to EntityVisibilityQuery AzFramework::EntityVisibilityQuery m_entityVisibilityQuery; + // Handlers for grid snapping/editor event callbacks SandboxEditor::GridSnappingChangedEvent::Handler m_gridSnappingHandler; AZStd::unique_ptr m_editorViewportSettingsCallbacks; + // Used for some legacy logic which lets the widget release a grabbed keyboard at the right times + // Unclear if it's still necessary. QSet m_keyDown; + // State for ViewportFreezeRequestBus, currently does nothing bool m_freezeViewportInput = false; + // This widget holds a reference to the manipulator manage because its responsible for drawing manipulators AZStd::shared_ptr m_manipulatorManager; - // Used to prevent circular set camera events - bool m_ignoreSetViewFromEntityPerspective = false; - bool m_windowResizedEvent = false; - + // Helper for getting EditorEntityNotificationBus events AZStd::unique_ptr m_editorEntityNotifications; + + // The widget to which Atom will actually render AtomToolsFramework::RenderViewportWidget* m_renderViewport = nullptr; - bool m_updateCameraPositionNextTick = false; - AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; - AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraProjectionMatrixChangeHandler; + // Atom debug display AzFramework::DebugDisplayRequests* m_debugDisplay = nullptr; + // The default view created for the viewport context, which is used as the "Editor Camera" + AZ::RPI::ViewPtr m_defaultView; + + // The name to set on the viewport context when this viewport widget is set as the active one AZ::Name m_defaultViewportContextName; + // DO NOT USE THIS! It exists only to satisfy the signature of the base class method GetViewTm + mutable Matrix34 m_viewTmStorage; + AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING }; diff --git a/Code/Editor/ErrorReport.cpp b/Code/Editor/ErrorReport.cpp index e1b2b8b6e4..7914511fbe 100644 --- a/Code/Editor/ErrorReport.cpp +++ b/Code/Editor/ErrorReport.cpp @@ -136,11 +136,11 @@ void CErrorReport::ReportError(CErrorRecord& err) } else { - if (err.pObject == NULL && m_pObject != NULL) + if (err.pObject == nullptr && m_pObject != nullptr) { err.pObject = m_pObject; } - else if (err.pItem == NULL && m_pItem != NULL) + else if (err.pItem == nullptr && m_pItem != nullptr) { err.pItem = m_pItem; } diff --git a/Code/Editor/ErrorReportDialog.cpp b/Code/Editor/ErrorReportDialog.cpp index 8b007207d6..2d551d6c8b 100644 --- a/Code/Editor/ErrorReportDialog.cpp +++ b/Code/Editor/ErrorReportDialog.cpp @@ -39,7 +39,7 @@ AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING ////////////////////////////////////////////////////////////////////////// -CErrorReportDialog* CErrorReportDialog::m_instance = 0; +CErrorReportDialog* CErrorReportDialog::m_instance = nullptr; // CErrorReportDialog dialog @@ -88,12 +88,12 @@ CErrorReportDialog::CErrorReportDialog(QWidget* parent) m_instance = this; //CErrorReport *report, //m_pErrorReport = report; - m_pErrorReport = 0; + m_pErrorReport = nullptr; } CErrorReportDialog::~CErrorReportDialog() { - m_instance = 0; + m_instance = nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -141,7 +141,7 @@ void CErrorReportDialog::Clear() { if (m_instance) { - m_instance->SetReport(0); + m_instance->SetReport(nullptr); m_instance->UpdateErrors(); } } @@ -500,7 +500,7 @@ void CErrorReportDialog::OnReportItemDblClick(const QModelIndex& index) { bool bDone = false; const CErrorRecord* pError = index.data(Qt::UserRole).value(); - if (pError && pError->pObject != NULL) + if (pError && pError->pObject != nullptr) { CUndo undo("Select Object(s)"); // Clear other selection. @@ -563,7 +563,7 @@ void CErrorReportDialog::OnReportHyperlink(const QModelIndex& index) { const CErrorRecord* pError = index.data(Qt::UserRole).value(); bool bDone = false; - if (pError && pError->pObject != NULL) + if (pError && pError->pObject != nullptr) { CUndo undo("Select Object(s)"); // Clear other selection. @@ -593,8 +593,8 @@ void CErrorReportDialog::OnShowFieldChooser() CMainFrm* pMainFrm = (CMainFrame*)AfxGetMainWnd(); if (pMainFrm) { - BOOL bShow = !pMainFrm->m_wndFieldChooser.IsVisible(); - pMainFrm->ShowControlBar(&pMainFrm->m_wndFieldChooser, bShow, FALSE); + bool bShow = !pMainFrm->m_wndFieldChooser.IsVisible(); + pMainFrm->ShowControlBar(&pMainFrm->m_wndFieldChooser, bShow, false); } } */ diff --git a/Code/Editor/ErrorReportTableModel.cpp b/Code/Editor/ErrorReportTableModel.cpp index e7a1048a09..c0c24bb7ce 100644 --- a/Code/Editor/ErrorReportTableModel.cpp +++ b/Code/Editor/ErrorReportTableModel.cpp @@ -105,7 +105,7 @@ void CErrorReportTableModel::setErrorReport(CErrorReport* report) { m_errorRecords.clear(); } - if (report != 0) + if (report != nullptr) { const int count = report->GetErrorCount(); m_errorRecords.reserve(count); diff --git a/Code/Editor/Export/ExportManager.cpp b/Code/Editor/Export/ExportManager.cpp index 10f96ce71b..764cc7b6b3 100644 --- a/Code/Editor/Export/ExportManager.cpp +++ b/Code/Editor/Export/ExportManager.cpp @@ -22,7 +22,6 @@ #include "OBJExporter.h" #include "OCMExporter.h" #include "FBXExporterDialog.h" -#include "RenderViewport.h" #include "TrackViewExportKeyTimeDlg.h" #include "AnimationContext.h" #include "TrackView/DirectorNodeAnimator.h" @@ -662,12 +661,6 @@ bool CExportManager::ProcessObjectsForExport() GetIEditor()->GetAnimation()->SetRecording(false); GetIEditor()->GetAnimation()->SetPlaying(false); - CViewport* vp = GetIEditor()->GetViewManager()->GetSelectedViewport(); - if (CRenderViewport* rvp = viewport_cast(vp)) - { - rvp->SetSequenceCamera(); - } - int startFrame = 0; timeValue = startFrame * fpsTimeInterval; diff --git a/Code/Editor/GameEngine.cpp b/Code/Editor/GameEngine.cpp index 173c13c235..137d14c844 100644 --- a/Code/Editor/GameEngine.cpp +++ b/Code/Editor/GameEngine.cpp @@ -57,12 +57,12 @@ struct SSystemUserCallback : public ISystemUserCallback { SSystemUserCallback(IInitializeUIInfo* logo) : m_threadErrorHandler(this) { m_pLogo = logo; }; - virtual void OnSystemConnect(ISystem* pSystem) + void OnSystemConnect(ISystem* pSystem) override { ModuleInitISystem(pSystem, "Editor"); } - virtual bool OnError(const char* szErrorString) + bool OnError(const char* szErrorString) override { // since we show a message box, we have to use the GUI thread if (QThread::currentThread() != qApp->thread()) @@ -95,7 +95,7 @@ struct SSystemUserCallback int res = IDNO; - ICVar* pCVar = gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_crash_dialog") : NULL; + ICVar* pCVar = gEnv->pConsole ? gEnv->pConsole->GetCVar("sys_no_crash_dialog") : nullptr; if (!pCVar || pCVar->GetIVal() == 0) { @@ -116,7 +116,7 @@ struct SSystemUserCallback return true; } - virtual bool OnSaveDocument() + bool OnSaveDocument() override { bool success = false; @@ -133,7 +133,7 @@ struct SSystemUserCallback return success; } - virtual bool OnBackupDocument() + bool OnBackupDocument() override { CCryEditDoc* level = GetIEditor() ? GetIEditor()->GetDocument() : nullptr; if (level) @@ -144,7 +144,7 @@ struct SSystemUserCallback return false; } - virtual void OnProcessSwitch() + void OnProcessSwitch() override { if (GetIEditor()->IsInGameMode()) { @@ -152,7 +152,7 @@ struct SSystemUserCallback } } - virtual void OnInitProgress(const char* sProgressMsg) + void OnInitProgress(const char* sProgressMsg) override { if (m_pLogo) { @@ -160,7 +160,7 @@ struct SSystemUserCallback } } - virtual int ShowMessage(const char* text, const char* caption, unsigned int uType) + int ShowMessage(const char* text, const char* caption, unsigned int uType) override { if (CCryEditApp::instance()->IsInAutotestMode()) { @@ -176,7 +176,7 @@ struct SSystemUserCallback return CryMessageBox(text, caption, uType); } - virtual void GetMemoryUsage(ICrySizer* pSizer) + void GetMemoryUsage(ICrySizer* pSizer) override { GetIEditor()->GetMemoryUsage(pSizer); } @@ -215,7 +215,7 @@ public: { AzFramework::AssetSystemConnectionNotificationsBus::Handler::BusConnect(); }; - ~AssetProcessConnectionStatus() + ~AssetProcessConnectionStatus() override { AzFramework::AssetSystemConnectionNotificationsBus::Handler::BusDisconnect(); } @@ -247,18 +247,18 @@ private: AZ_PUSH_DISABLE_WARNING(4273, "-Wunknown-warning-option") CGameEngine::CGameEngine() - : m_gameDll(0) + : m_gameDll(nullptr) , m_bIgnoreUpdates(false) , m_ePendingGameMode(ePGM_NotPending) , m_modalWindowDismisser(nullptr) AZ_POP_DISABLE_WARNING { - m_pISystem = NULL; + m_pISystem = nullptr; m_bLevelLoaded = false; m_bInGameMode = false; m_bSimulationMode = false; m_bSyncPlayerPosition = true; - m_hSystemHandle = 0; + m_hSystemHandle = nullptr; m_bJustCreated = false; m_levelName = "Untitled"; m_levelExtension = EditorUtils::LevelFile::GetDefaultFileExtension(); @@ -271,7 +271,7 @@ CGameEngine::~CGameEngine() { AZ_POP_DISABLE_WARNING GetIEditor()->UnregisterNotifyListener(this); - m_pISystem->GetIMovieSystem()->SetCallback(NULL); + m_pISystem->GetIMovieSystem()->SetCallback(nullptr); if (m_gameDll) { @@ -279,7 +279,7 @@ AZ_POP_DISABLE_WARNING } delete m_pISystem; - m_pISystem = NULL; + m_pISystem = nullptr; if (m_hSystemHandle) { @@ -572,8 +572,6 @@ void CGameEngine::SwitchToInGame() m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; - gEnv->pSystem->GetViewCamera().SetMatrix(m_playerViewTM); - // Disable accelerators. GetIEditor()->EnableAcceleratos(false); //! Send event to switch into game. @@ -627,13 +625,6 @@ void CGameEngine::SwitchToInEditor() m_bInGameMode = false; - // save the current gameView matrix for editor - if (pGameViewport) - { - Matrix34 gameView = gEnv->pSystem->GetViewCamera().GetMatrix(); - pGameViewport->SetGameTM(gameView); - } - // Out of game in Editor mode. if (pGameViewport) { @@ -875,7 +866,7 @@ void CGameEngine::OnEditorNotifyEvent(EEditorNotifyEvent event) { case eNotify_OnSplashScreenDestroyed: { - if (m_pSystemUserCallback != NULL) + if (m_pSystemUserCallback != nullptr) { m_pSystemUserCallback->OnSplashScreenDone(); } diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 006eb9189c..feea94b34b 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -63,7 +63,7 @@ void SGameExporterSettings::SetHiQuality() nApplySS = 1; } -CGameExporter* CGameExporter::m_pCurrentExporter = NULL; +CGameExporter* CGameExporter::m_pCurrentExporter = nullptr; ////////////////////////////////////////////////////////////////////////// // CGameExporter @@ -76,7 +76,7 @@ CGameExporter::CGameExporter() CGameExporter::~CGameExporter() { - m_pCurrentExporter = NULL; + m_pCurrentExporter = nullptr; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/GenericSelectItemDialog.cpp b/Code/Editor/GenericSelectItemDialog.cpp index ef109336ef..3c51b38d0a 100644 --- a/Code/Editor/GenericSelectItemDialog.cpp +++ b/Code/Editor/GenericSelectItemDialog.cpp @@ -17,7 +17,7 @@ AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING // CGenericSelectItemDialog dialog -CGenericSelectItemDialog::CGenericSelectItemDialog(QWidget* pParent /*=NULL*/) +CGenericSelectItemDialog::CGenericSelectItemDialog(QWidget* pParent /*=nullptr*/) : QDialog(pParent) , ui(new Ui::CGenericSelectItemDialog) , m_initialized(false) diff --git a/Code/Editor/IEditor.h b/Code/Editor/IEditor.h index a56c8e81e9..f66dca412e 100644 --- a/Code/Editor/IEditor.h +++ b/Code/Editor/IEditor.h @@ -570,7 +570,7 @@ struct IEditor ////////////////////////////////////////////////////////////////////////// virtual class CLevelIndependentFileMan* GetLevelIndependentFileMan() = 0; //! Notify all views that data is changed. - virtual void UpdateViews(int flags = 0xFFFFFFFF, const AABB* updateRegion = NULL) = 0; + virtual void UpdateViews(int flags = 0xFFFFFFFF, const AABB* updateRegion = nullptr) = 0; virtual void ResetViews() = 0; //! Update information in track view dialog. virtual void ReloadTrackView() = 0; @@ -589,7 +589,7 @@ struct IEditor //! if bShow is true also returns a valid ITransformManipulator pointer. virtual ITransformManipulator* ShowTransformManipulator(bool bShow) = 0; //! Return a pointer to a ITransformManipulator pointer if shown. - //! NULL is manipulator is not shown. + //! nullptr if manipulator is not shown. virtual ITransformManipulator* GetTransformManipulator() = 0; //! Set constrain on specified axis for objects construction and modifications. //! @param axis one of AxisConstrains enumerations. diff --git a/Code/Editor/IEditorImpl.cpp b/Code/Editor/IEditorImpl.cpp index c09c0a8e62..d9c3af64b0 100644 --- a/Code/Editor/IEditorImpl.cpp +++ b/Code/Editor/IEditorImpl.cpp @@ -415,7 +415,7 @@ void CEditorImpl::Update() } if (IsInPreviewMode()) { - SetModifiedFlag(FALSE); + SetModifiedFlag(false); SetModifiedModule(eModifiedNothing); } @@ -550,7 +550,7 @@ QString CEditorImpl::GetResolvedUserFolder() void CEditorImpl::SetDataModified() { - GetDocument()->SetModifiedFlag(TRUE); + GetDocument()->SetModifiedFlag(true); } void CEditorImpl::SetStatusText(const QString& pszString) @@ -597,9 +597,9 @@ ITransformManipulator* CEditorImpl::ShowTransformManipulator(bool bShow) GetObjectManager()->GetGizmoManager()->RemoveGizmo(m_pAxisGizmo); m_pAxisGizmo->Release(); } - m_pAxisGizmo = 0; + m_pAxisGizmo = nullptr; } - return 0; + return nullptr; } ITransformManipulator* CEditorImpl::GetTransformManipulator() @@ -614,7 +614,7 @@ void CEditorImpl::SetAxisConstraints(AxisConstrains axisFlags) SetTerrainAxisIgnoreObjects(false); // Update all views. - UpdateViews(eUpdateObjects, NULL); + UpdateViews(eUpdateObjects, nullptr); } AxisConstrains CEditorImpl::GetAxisConstrains() @@ -637,15 +637,15 @@ void CEditorImpl::SetReferenceCoordSys(RefCoordSys refCoords) m_refCoordsSys = refCoords; // Update all views. - UpdateViews(eUpdateObjects, NULL); + UpdateViews(eUpdateObjects, nullptr); // Update the construction plane infos. CViewport* pViewport = GetActiveView(); if (pViewport) { //Pre and Post widget rendering calls are made here to make sure that the proper camera state is set. - //MakeConstructionPlane will make a call to ViewToWorldRay which needs the correct camera state - //in the CRenderViewport to be set. + //MakeConstructionPlane will make a call to ViewToWorldRay which needs the correct camera state + //in the CRenderViewport to be set. pViewport->PreWidgetRendering(); pViewport->MakeConstructionPlane(GetIEditor()->GetAxisConstrains()); @@ -671,7 +671,7 @@ CBaseObject* CEditorImpl::NewObject(const char* typeName, const char* fileName, editor->SetModifiedFlag(); editor->SetModifiedModule(eModifiedBrushes); } - CBaseObject* object = editor->GetObjectManager()->NewObject(typeName, 0, fileName, name); + CBaseObject* object = editor->GetObjectManager()->NewObject(typeName, nullptr, fileName, name); if (!object) { return nullptr; @@ -932,7 +932,7 @@ void CEditorImpl::CloseView(const GUID& classId) IDataBaseManager* CEditorImpl::GetDBItemManager([[maybe_unused]] EDataBaseItemType itemType) { - return 0; + return nullptr; } bool CEditorImpl::SelectColor(QColor& color, QWidget* parent) @@ -1109,7 +1109,7 @@ void CEditorImpl::DetectVersion() char ver[1024 * 8]; - GetModuleFileName(NULL, exe, _MAX_PATH); + GetModuleFileName(nullptr, exe, _MAX_PATH); int verSize = GetFileVersionInfoSize(exe, &dwHandle); if (verSize > 0) @@ -1431,7 +1431,7 @@ void CEditorImpl::NotifyExcept(EEditorNotifyEvent event, IEditorNotifyListener* { m_pAxisGizmo->Release(); } - m_pAxisGizmo = 0; + m_pAxisGizmo = nullptr; } if (event == eNotify_OnInit) @@ -1472,7 +1472,7 @@ ISourceControl* CEditorImpl::GetSourceControl() for (int i = 0; i < classes.size(); i++) { IClassDesc* pClass = classes[i]; - ISourceControl* pSCM = NULL; + ISourceControl* pSCM = nullptr; HRESULT hRes = pClass->QueryInterface(__uuidof(ISourceControl), (void**)&pSCM); if (!FAILED(hRes) && pSCM) { @@ -1482,7 +1482,7 @@ ISourceControl* CEditorImpl::GetSourceControl() } } - return 0; + return nullptr; } bool CEditorImpl::IsSourceControlAvailable() diff --git a/Code/Editor/IEditorImpl.h b/Code/Editor/IEditorImpl.h index 65389a212e..db963e83f1 100644 --- a/Code/Editor/IEditorImpl.h +++ b/Code/Editor/IEditorImpl.h @@ -22,7 +22,7 @@ #include #include -#include "Commands/CommandManager.h" +#include "Commands/CommandManager.h" #include "Include/IErrorReport.h" #include "ErrorReport.h" @@ -63,7 +63,7 @@ namespace AssetDatabase class AssetDatabaseLocationListener; } -class CEditorImpl +class CEditorImpl : public IEditor { Q_DECLARE_TR_FUNCTIONS(CEditorImpl) @@ -176,7 +176,7 @@ public: { return m_pSystem->GetIMovieSystem(); } - return NULL; + return nullptr; }; CPluginManager* GetPluginManager() { return m_pPluginManager; } @@ -210,7 +210,7 @@ public: RefCoordSys GetReferenceCoordSys(); XmlNodeRef FindTemplate(const QString& templateName); void AddTemplate(const QString& templateName, XmlNodeRef& tmpl); - + const QtViewPane* OpenView(QString sViewClassName, bool reuseOpened = true) override; /** diff --git a/Code/Editor/IconManager.cpp b/Code/Editor/IconManager.cpp index 7f6f7cd0ab..dc9eb56b88 100644 --- a/Code/Editor/IconManager.cpp +++ b/Code/Editor/IconManager.cpp @@ -81,7 +81,7 @@ void CIconManager::Reset() { m_objects[i]->Release(); } - m_objects[i] = 0; + m_objects[i] = nullptr; } for (i = 0; i < eIcon_COUNT; i++) { @@ -135,7 +135,7 @@ IStatObj* CIconManager::GetObject(EStatObject) ////////////////////////////////////////////////////////////////////////// QImage* CIconManager::GetIconBitmap(const char* filename, bool& bHaveAlpha, uint32 effects /*=0*/) { - QImage* pBitmap = 0; + QImage* pBitmap = nullptr; QString iconFilename = filename; @@ -160,11 +160,11 @@ QImage* CIconManager::GetIconBitmap(const char* filename, bool& bHaveAlpha, uint return pBitmap; } - BOOL bAlphaBitmap = FALSE; + bool bAlphaBitmap = false; QPixmap pm(iconFilename); bAlphaBitmap = pm.hasAlpha(); - bHaveAlpha = (bAlphaBitmap == TRUE); + bHaveAlpha = (bAlphaBitmap == true); if (!pm.isNull()) { pBitmap = new QImage; @@ -252,5 +252,5 @@ QImage* CIconManager::GetIconBitmap(const char* filename, bool& bHaveAlpha, uint return pBitmap; } - return NULL; + return nullptr; } diff --git a/Code/Editor/LayoutConfigDialog.cpp b/Code/Editor/LayoutConfigDialog.cpp index 6722a7d9d7..1074ebc23e 100644 --- a/Code/Editor/LayoutConfigDialog.cpp +++ b/Code/Editor/LayoutConfigDialog.cpp @@ -68,7 +68,7 @@ QVariant LayoutConfigModel::data(const QModelIndex& index, int role) const // CLayoutConfigDialog dialog -CLayoutConfigDialog::CLayoutConfigDialog(QWidget* pParent /*=NULL*/) +CLayoutConfigDialog::CLayoutConfigDialog(QWidget* pParent /*=nullptr*/) : QDialog(pParent) , m_model(new LayoutConfigModel(this)) , ui(new Ui::CLayoutConfigDialog) diff --git a/Code/Editor/LayoutWnd.cpp b/Code/Editor/LayoutWnd.cpp index a3550b39ba..7f73c313d9 100644 --- a/Code/Editor/LayoutWnd.cpp +++ b/Code/Editor/LayoutWnd.cpp @@ -98,7 +98,7 @@ CLayoutWnd::CLayoutWnd(QSettings* settings, QWidget* parent) , m_settings(settings) { m_bMaximized = false; - m_maximizedView = 0; + m_maximizedView = nullptr; m_layout = (EViewLayout) - 1; m_maximizedViewId = 0; @@ -729,7 +729,7 @@ void CLayoutWnd::OnDestroy() if (m_maximizedView) { delete m_maximizedView; - m_maximizedView = 0; + m_maximizedView = nullptr; } } diff --git a/Code/Editor/Lib/Tests/test_EditorUtils.cpp b/Code/Editor/Lib/Tests/test_EditorUtils.cpp index 59deb178a9..3556757ae3 100644 --- a/Code/Editor/Lib/Tests/test_EditorUtils.cpp +++ b/Code/Editor/Lib/Tests/test_EditorUtils.cpp @@ -23,12 +23,12 @@ namespace EditorUtilsTest BusConnect(); } - ~WarningDetector() + ~WarningDetector() override { BusDisconnect(); } - virtual bool OnWarning(const char* /*window*/, const char* /*message*/) override + bool OnWarning(const char* /*window*/, const char* /*message*/) override { m_gotWarning = true; return true; diff --git a/Code/Editor/Lib/Tests/test_Main.cpp b/Code/Editor/Lib/Tests/test_Main.cpp index a30afb0b7c..6250c540db 100644 --- a/Code/Editor/Lib/Tests/test_Main.cpp +++ b/Code/Editor/Lib/Tests/test_Main.cpp @@ -17,7 +17,7 @@ class EditorLibTestEnvironment : public AZ::Test::ITestEnvironment { public: - virtual ~EditorLibTestEnvironment() {} + ~EditorLibTestEnvironment() override = default; protected: void SetupEnvironment() override diff --git a/Code/Editor/Objects/BaseObject.cpp b/Code/Editor/Objects/BaseObject.cpp index c13c5932b0..482055d7ed 100644 --- a/Code/Editor/Objects/BaseObject.cpp +++ b/Code/Editor/Objects/BaseObject.cpp @@ -57,12 +57,12 @@ public: CUndoBaseObject(CBaseObject* pObj, const char* undoDescription); protected: - virtual int GetSize() { return sizeof(*this); } - virtual QString GetDescription() { return m_undoDescription; }; - virtual QString GetObjectName(); + int GetSize() override { return sizeof(*this); } + QString GetDescription() override { return m_undoDescription; }; + QString GetObjectName() override; - virtual void Undo(bool bUndo); - virtual void Redo(); + void Undo(bool bUndo) override; + void Redo() override; protected: QString m_undoDescription; @@ -81,12 +81,12 @@ public: CUndoBaseObjectMinimal(CBaseObject* obj, const char* undoDescription, int flags); protected: - virtual int GetSize() { return sizeof(*this); } - virtual QString GetDescription() { return m_undoDescription; }; - virtual QString GetObjectName(); + int GetSize() override { return sizeof(*this); } + QString GetDescription() override { return m_undoDescription; }; + QString GetObjectName() override; - virtual void Undo(bool bUndo); - virtual void Redo(); + void Undo(bool bUndo) override; + void Redo() override; private: struct StateStruct @@ -119,7 +119,7 @@ public: , m_bKeepPos(bKeepPos) , m_bAttach(bAttach) {} - virtual void Undo([[maybe_unused]] bool bUndo) override + void Undo([[maybe_unused]] bool bUndo) override { if (m_bAttach) { @@ -131,7 +131,7 @@ public: } } - virtual void Redo() override + void Redo() override { if (m_bAttach) { @@ -167,8 +167,8 @@ private: } } - virtual int GetSize() { return sizeof(CUndoAttachBaseObject); } - virtual QString GetDescription() { return "Attachment Changed"; } + int GetSize() override { return sizeof(CUndoAttachBaseObject); } + QString GetDescription() override { return "Attachment Changed"; } GUID m_attachedObjectGUID; GUID m_parentObjectGUID; @@ -184,7 +184,7 @@ CUndoBaseObject::CUndoBaseObject(CBaseObject* obj, const char* undoDescription) m_undoDescription = undoDescription; m_guid = obj->GetId(); - m_redo = 0; + m_redo = nullptr; m_undo = XmlHelpers::CreateXmlNode("Undo"); CObjectArchive ar(GetIEditor()->GetObjectManager(), m_undo, false); ar.bUndo = true; @@ -355,7 +355,7 @@ void CObjectCloneContext::AddClone(CBaseObject* pFromObject, CBaseObject* pToObj ////////////////////////////////////////////////////////////////////////// CBaseObject* CObjectCloneContext::FindClone(CBaseObject* pFromObject) { - CBaseObject* pTarget = stl::find_in_map(m_objectsMap, pFromObject, (CBaseObject*) NULL); + CBaseObject* pTarget = stl::find_in_map(m_objectsMap, pFromObject, (CBaseObject*) nullptr); return pTarget; } @@ -426,7 +426,7 @@ bool CBaseObject::Init([[maybe_unused]] IEditor* ie, CBaseObject* prev, [[maybe_ { SetFlags(m_flags & (~OBJFLAG_DELETED)); - if (prev != 0) + if (prev != nullptr) { SetUniqueName(prev->GetName()); SetLocalTM(prev->GetPos(), prev->GetRotation(), prev->GetScale()); @@ -457,7 +457,7 @@ CBaseObject::~CBaseObject() for (Childs::iterator c = m_childs.begin(); c != m_childs.end(); c++) { CBaseObject* child = *c; - child->m_parent = 0; + child->m_parent = nullptr; } m_childs.clear(); } @@ -470,10 +470,10 @@ void CBaseObject::Done() // From children DetachAll(); - SetLookAt(0); + SetLookAt(nullptr); if (m_lookatSource) { - m_lookatSource->SetLookAt(0); + m_lookatSource->SetLookAt(nullptr); } SetFlags(m_flags | OBJFLAG_DELETED); @@ -1730,7 +1730,7 @@ bool CBaseObject::IntersectRayBounds(const Ray& ray) ////////////////////////////////////////////////////////////////////////// namespace { - typedef std::pair Edge2D; + using Edge2D = std::pair; } bool IsIncludePointsInConvexHull(Edge2D* pEdgeArray0, int nEdgeArray0Size, Edge2D* pEdgeArray1, int nEdgeArray1Size) { @@ -2065,7 +2065,7 @@ void CBaseObject::GetAllChildren(TBaseObjects& outAllChildren, CBaseObject* pObj for (int i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) { CBaseObject* pChild = pBaseObj->GetChild(i); - if (pChild == NULL) + if (pChild == nullptr) { continue; } @@ -2081,7 +2081,7 @@ void CBaseObject::GetAllChildren(DynArray< _smart_ptr >& outAllChil for (int i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) { CBaseObject* pChild = pBaseObj->GetChild(i); - if (pChild == NULL) + if (pChild == nullptr) { continue; } @@ -2097,7 +2097,7 @@ void CBaseObject::GetAllChildren(CSelectionGroup& outAllChildren, CBaseObject* p for (int i = 0, iChildCount(pBaseObj->GetChildCount()); i < iChildCount; ++i) { CBaseObject* pChild = pBaseObj->GetChild(i); - if (pChild == NULL) + if (pChild == nullptr) { continue; } @@ -2109,7 +2109,7 @@ void CBaseObject::GetAllChildren(CSelectionGroup& outAllChildren, CBaseObject* p ////////////////////////////////////////////////////////////////////////// void CBaseObject::CloneChildren(CBaseObject* pFromObject) { - if (pFromObject == NULL) + if (pFromObject == nullptr) { return; } @@ -2119,7 +2119,7 @@ void CBaseObject::CloneChildren(CBaseObject* pFromObject) CBaseObject* pFromChildObject = pFromObject->GetChild(i); CBaseObject* pChildClone = GetObjectManager()->CloneObject(pFromChildObject); - if (pChildClone == NULL) + if (pChildClone == nullptr) { continue; } @@ -2248,7 +2248,7 @@ void CBaseObject::DetachThis(bool bKeepPos) // Copy parent to temp var, erasing child from parent may delete this node if child referenced only from parent. CBaseObject* parent = m_parent; - m_parent = 0; + m_parent = nullptr; parent->RemoveChild(this); if (bKeepPos) @@ -2389,7 +2389,7 @@ void CBaseObject::InvalidateTM([[maybe_unused]] int flags) // Invalidate matrices off all child objects. for (int i = 0; i < m_childs.size(); i++) { - if (m_childs[i] != 0 && m_childs[i]->m_bMatrixValid) + if (m_childs[i] != nullptr && m_childs[i]->m_bMatrixValid) { m_childs[i]->InvalidateTM(eObjectUpdateFlags_ParentChanged); } @@ -2538,7 +2538,7 @@ void CBaseObject::SetLookAt(CBaseObject* target) ////////////////////////////////////////////////////////////////////////// bool CBaseObject::IsLookAtTarget() const { - return m_lookatSource != 0; + return m_lookatSource != nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -2806,7 +2806,7 @@ bool CBaseObject::IntersectRayMesh(const Vec3& raySrc, const Vec3& rayDir, SRayH outHitInfo.bInFirstHit = false; outHitInfo.bUseCache = false; - return pStatObj->RayIntersection(outHitInfo, 0); + return pStatObj->RayIntersection(outHitInfo, nullptr); } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Objects/BaseObject.h b/Code/Editor/Objects/BaseObject.h index a05bbb61af..47dba99ab7 100644 --- a/Code/Editor/Objects/BaseObject.h +++ b/Code/Editor/Objects/BaseObject.h @@ -321,7 +321,7 @@ public: //! Set object selected status. virtual void SetSelected(bool bSelect); //! Return associated 3DEngine render node - virtual IRenderNode* GetEngineNode() const { return NULL; }; + virtual IRenderNode* GetEngineNode() const { return nullptr; }; //! Set object highlighted (Note: not selected) virtual void SetHighlight(bool bHighlight); //! Check if object is highlighted. @@ -410,9 +410,9 @@ public: //! Scans hierarchy up to determine if we child of specified node. virtual bool IsChildOf(CBaseObject* node); //! Get all child objects - void GetAllChildren(TBaseObjects& outAllChildren, CBaseObject* pObj = NULL) const; - void GetAllChildren(DynArray< _smart_ptr >& outAllChildren, CBaseObject* pObj = NULL) const; - void GetAllChildren(CSelectionGroup& outAllChildren, CBaseObject* pObj = NULL) const; + void GetAllChildren(TBaseObjects& outAllChildren, CBaseObject* pObj = nullptr) const; + void GetAllChildren(DynArray< _smart_ptr >& outAllChildren, CBaseObject* pObj = nullptr) const; + void GetAllChildren(CSelectionGroup& outAllChildren, CBaseObject* pObj = nullptr) const; //! Clone Children void CloneChildren(CBaseObject* pFromObject); //! Attach new child node. @@ -468,8 +468,8 @@ public: //! Called when object is being created (use GetMouseCreateCallback for more advanced mouse creation callback). virtual int MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags); // Return pointer to the callback object used when creating object by the mouse. - // If this function return NULL MouseCreateCallback method will be used instead. - virtual IMouseCreateCallback* GetMouseCreateCallback() { return 0; }; + // If this function return nullptr MouseCreateCallback method will be used instead. + virtual IMouseCreateCallback* GetMouseCreateCallback() { return nullptr; }; //! Draw object to specified viewport. virtual void Display([[maybe_unused]] DisplayContext& disp) {} @@ -598,7 +598,7 @@ public: bool CanBeHightlighted() const; bool IsSkipSelectionHelper() const; - virtual IStatObj* GetIStatObj() { return NULL; } + virtual IStatObj* GetIStatObj() { return nullptr; } // Invalidates cached transformation matrix. // nWhyFlags - Flags that indicate the reason for matrix invalidation. @@ -672,7 +672,7 @@ protected: //! Draw warning icons virtual void DrawWarningIcons(DisplayContext& dc, const Vec3& pos); //! Check if dimension's figures can be displayed before draw them. - virtual void DrawDimensions(DisplayContext& dc, AABB* pMergedBoundBox = NULL); + virtual void DrawDimensions(DisplayContext& dc, AABB* pMergedBoundBox = nullptr); //! Draw highlight. virtual void DrawHighlight(DisplayContext& dc); diff --git a/Code/Editor/Objects/EntityObject.cpp b/Code/Editor/Objects/EntityObject.cpp index 3b23894aac..0f4a17f3ba 100644 --- a/Code/Editor/Objects/EntityObject.cpp +++ b/Code/Editor/Objects/EntityObject.cpp @@ -56,18 +56,18 @@ public: } protected: - virtual void Release() { delete this; }; - virtual int GetSize() { return sizeof(*this); }; // Return size of xml state. - virtual QString GetDescription() { return "Entity Link"; }; - virtual QString GetObjectName(){ return ""; }; + void Release() override { delete this; }; + int GetSize() override { return sizeof(*this); }; // Return size of xml state. + QString GetDescription() override { return "Entity Link"; }; + QString GetObjectName() override{ return ""; }; - virtual void Undo([[maybe_unused]] bool bUndo) + void Undo([[maybe_unused]] bool bUndo) override { for (int i = 0, iLinkSize(m_Links.size()); i < iLinkSize; ++i) { SLink& link = m_Links[i]; CBaseObject* pObj = GetIEditor()->GetObjectManager()->FindObject(link.entityID); - if (pObj == NULL) + if (pObj == nullptr) { continue; } @@ -83,7 +83,7 @@ protected: pEntity->LoadLink(link.linkXmlNode->getChild(0)); } } - virtual void Redo(){} + void Redo() override{} private: @@ -109,7 +109,7 @@ public: , m_bAttach(bAttach) {} - virtual void Undo([[maybe_unused]] bool bUndo) override + void Undo([[maybe_unused]] bool bUndo) override { if (!m_bAttach) { @@ -117,7 +117,7 @@ public: } } - virtual void Redo() override + void Redo() override { if (m_bAttach) { @@ -138,8 +138,8 @@ private: } } - virtual int GetSize() { return sizeof(CUndoAttachEntity); } - virtual QString GetDescription() { return "Attachment Changed"; } + int GetSize() override { return sizeof(CUndoAttachEntity); } + QString GetDescription() override { return "Attachment Changed"; } GUID m_attachedEntityGUID; CEntityObject::EAttachmentType m_attachmentType; @@ -167,7 +167,7 @@ CEntityObject::CEntityObject() { m_bLoadFailed = false; - m_visualObject = 0; + m_visualObject = nullptr; m_box.min.Set(0, 0, 0); m_box.max.Set(0, 0, 0); @@ -225,7 +225,7 @@ CEntityObject::CEntityObject() mv_ratioLOD.SetLimits(0, 255); mv_viewDistanceMultiplier.SetLimits(0.0f, IRenderNode::VIEW_DISTANCE_MULTIPLIER_MAX); - m_physicsState = 0; + m_physicsState = nullptr; m_attachmentType = eAT_Pivot; @@ -540,7 +540,7 @@ IVariable* CEntityObject::FindVariableInSubBlock(CVarBlockPtr& properties, IVari ////////////////////////////////////////////////////////////////////////// void CEntityObject::AdjustLightProperties(CVarBlockPtr& properties, const char* pSubBlock) { - IVariable* pSubBlockVar = pSubBlock ? properties->FindVariable(pSubBlock) : NULL; + IVariable* pSubBlockVar = pSubBlock ? properties->FindVariable(pSubBlock) : nullptr; if (IVariable* pRadius = FindVariableInSubBlock(properties, pSubBlockVar, "Radius")) { @@ -933,7 +933,7 @@ void CEntityObject::Serialize(CObjectArchive& ar) { XmlNodeRef eventTarget = eventTargets->getChild(i); CEntityEventTarget et; - et.target = 0; + et.target = nullptr; GUID targetId = GUID_NULL; eventTarget->getAttr("TargetId", targetId); eventTarget->getAttr("Event", et.event); @@ -1029,7 +1029,7 @@ void CEntityObject::Serialize(CObjectArchive& ar) { CEntityEventTarget& et = m_eventTargets[i]; GUID targetId = GUID_NULL; - if (et.target != 0) + if (et.target != nullptr) { targetId = et.target->GetId(); } @@ -1060,7 +1060,7 @@ XmlNodeRef CEntityObject::Export([[maybe_unused]] const QString& levelPath, XmlN { if (m_bLoadFailed) { - return 0; + return nullptr; } // Do not export entity with bad id. @@ -1268,7 +1268,7 @@ void CEntityObject::OnEvent(ObjectEvent event) IObjectManager* objMan = GetIEditor()->GetObjectManager(); if (objMan && objMan->IsLightClass(this)) { - OnPropertyChange(NULL); + OnPropertyChange(nullptr); } break; } @@ -1314,7 +1314,7 @@ IVariable* CEntityObject::GetLightVariable(const char* name0) const { IVariable* pChild = pLightProperties->GetVariable(i); - if (pChild == NULL) + if (pChild == nullptr) { continue; } @@ -1341,7 +1341,7 @@ QString CEntityObject::GetLightAnimation() const { IVariable* pChild = pStyleGroup->GetVariable(i); - if (pChild == NULL) + if (pChild == nullptr) { continue; } @@ -1617,7 +1617,7 @@ void CEntityObject::RemoveEventTarget(int index, [[maybe_unused]] bool bUpdateSc ////////////////////////////////////////////////////////////////////////// int CEntityObject::AddEntityLink(const QString& name, GUID targetEntityId) { - CEntityObject* target = 0; + CEntityObject* target = nullptr; if (targetEntityId != GUID_NULL) { CBaseObject* pObject = FindObject(targetEntityId); @@ -1635,7 +1635,7 @@ int CEntityObject::AddEntityLink(const QString& name, GUID targetEntityId) StoreUndo("Add EntityLink"); - CLineGizmo* pLineGizmo = 0; + CLineGizmo* pLineGizmo = nullptr; // Assign event target. if (target) @@ -1968,7 +1968,7 @@ void CEntityObject::ResetCallbacks() //@FIXME Hack to display radii of properties. // wires properties from param block, to this entity internal variables. - IVariable* var = 0; + IVariable* var = nullptr; var = pProperties->FindVariable("Radius", false); if (var && (var->GetType() == IVariable::FLOAT || var->GetType() == IVariable::INT)) { @@ -2194,7 +2194,7 @@ template T CEntityObject::GetEntityProperty(const char* pName, T defaultvalue) const { CVarBlock* pProperties = GetProperties2(); - IVariable* pVariable = NULL; + IVariable* pVariable = nullptr; if (pProperties) { pVariable = pProperties->FindVariable(pName); @@ -2228,7 +2228,7 @@ template void CEntityObject::SetEntityProperty(const char* pName, T value) { CVarBlock* pProperties = GetProperties2(); - IVariable* pVariable = NULL; + IVariable* pVariable = nullptr; if (pProperties) { pVariable = pProperties->FindVariable(pName); diff --git a/Code/Editor/Objects/EntityObject.h b/Code/Editor/Objects/EntityObject.h index 34d3342ad4..d5600d15b7 100644 --- a/Code/Editor/Objects/EntityObject.h +++ b/Code/Editor/Objects/EntityObject.h @@ -185,7 +185,7 @@ public: void RemoveAllEntityLinks(); virtual void EntityLinked([[maybe_unused]] const QString& name, [[maybe_unused]] GUID targetEntityId){} virtual void EntityUnlinked([[maybe_unused]] const QString& name, [[maybe_unused]] GUID targetEntityId) {} - void LoadLink(XmlNodeRef xmlNode, CObjectArchive* pArchive = NULL); + void LoadLink(XmlNodeRef xmlNode, CObjectArchive* pArchive = nullptr); void SaveLink(XmlNodeRef xmlNode); ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Objects/Gizmo.h b/Code/Editor/Objects/Gizmo.h index 1e5b07abff..0dba75ae9c 100644 --- a/Code/Editor/Objects/Gizmo.h +++ b/Code/Editor/Objects/Gizmo.h @@ -67,7 +67,7 @@ public: //! Set this gizmo to be deleted. void DeleteThis(); - virtual CBaseObjectPtr GetBaseObject() const { return NULL; } + virtual CBaseObjectPtr GetBaseObject() const { return nullptr; } protected: diff --git a/Code/Editor/Objects/GizmoManager.cpp b/Code/Editor/Objects/GizmoManager.cpp index 697ca3e93c..e0fdd69c8e 100644 --- a/Code/Editor/Objects/GizmoManager.cpp +++ b/Code/Editor/Objects/GizmoManager.cpp @@ -79,7 +79,7 @@ CGizmo* CGizmoManager::GetGizmoByIndex(int nIndex) const return *ii; } } - return NULL; + return nullptr; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Editor/Objects/LineGizmo.cpp b/Code/Editor/Objects/LineGizmo.cpp index 46026be614..31ea341f5b 100644 --- a/Code/Editor/Objects/LineGizmo.cpp +++ b/Code/Editor/Objects/LineGizmo.cpp @@ -37,8 +37,8 @@ CLineGizmo::~CLineGizmo() { m_object[1]->RemoveEventListener(this); } - m_object[0] = 0; - m_object[1] = 0; + m_object[0] = nullptr; + m_object[1] = nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -164,7 +164,7 @@ void CLineGizmo::SetName(const char* sName) ////////////////////////////////////////////////////////////////////////// bool CLineGizmo::HitTest([[maybe_unused]] HitContext& hc) { - return 0; + return false; /* if (hc.distanceTollerance != 0) return 0; diff --git a/Code/Editor/Objects/ObjectLoader.cpp b/Code/Editor/Objects/ObjectLoader.cpp index 98f771dc76..2583eb6230 100644 --- a/Code/Editor/Objects/ObjectLoader.cpp +++ b/Code/Editor/Objects/ObjectLoader.cpp @@ -28,8 +28,8 @@ CObjectArchive::CObjectArchive(IObjectManager* objMan, XmlNodeRef xmlRoot, bool m_nFlags = 0; node = xmlRoot; m_pCurrentErrorReport = GetIEditor()->GetErrorReport(); - m_pGeometryPak = NULL; - m_pCurrentObject = NULL; + m_pGeometryPak = nullptr; + m_pCurrentObject = nullptr; m_bNeedResolveObjects = false; m_bProgressBarEnabled = true; } @@ -145,7 +145,7 @@ void CObjectArchive::ResolveObjects() // Objects can be added to the list here (from Groups). numObj = m_loadedObjects.size(); } - m_pCurrentErrorReport->SetCurrentValidatorObject(NULL); + m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); ////////////////////////////////////////////////////////////////////////// GetIEditor()->ResumeUndo(); } @@ -238,7 +238,7 @@ void CObjectArchive::ResolveObjects() // might generate unrelated errors m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); } - m_pCurrentErrorReport->SetCurrentValidatorObject(NULL); + m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); ////////////////////////////////////////////////////////////////////////// } @@ -257,7 +257,7 @@ void CObjectArchive::ResolveObjects() } m_bNeedResolveObjects = false; - m_pCurrentErrorReport->SetCurrentValidatorObject(NULL); + m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); m_sequenceIdRemap.clear(); m_pendingIds.clear(); } @@ -314,7 +314,7 @@ void CObjectArchive::LoadObjects(XmlNodeRef& rootObjectsNode) for (int i = 0; i < numObjects; i++) { XmlNodeRef objNode = rootObjectsNode->getChild(i); - LoadObject(objNode, NULL); + LoadObject(objNode, nullptr); } } @@ -401,7 +401,7 @@ void CObjectArchive::AddSequenceIdMapping(uint32 oldId, uint32 newId) { assert(oldId != newId); assert(GetIEditor()->GetMovieSystem()->FindSequenceById(oldId) || stl::find(m_pendingIds, oldId)); - assert(GetIEditor()->GetMovieSystem()->FindSequenceById(newId) == NULL); + assert(GetIEditor()->GetMovieSystem()->FindSequenceById(newId) == nullptr); assert(stl::find(m_pendingIds, newId) == false); m_sequenceIdRemap[oldId] = newId; m_pendingIds.push_back(newId); diff --git a/Code/Editor/Objects/ObjectLoader.h b/Code/Editor/Objects/ObjectLoader.h index ccfaeb78f0..9410a4845a 100644 --- a/Code/Editor/Objects/ObjectLoader.h +++ b/Code/Editor/Objects/ObjectLoader.h @@ -67,7 +67,7 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING void LoadObjects(XmlNodeRef& rootObjectsNode); //! Load one object from archive. - CBaseObject* LoadObject(const XmlNodeRef& objNode, CBaseObject* pPrevObject = NULL); + CBaseObject* LoadObject(const XmlNodeRef& objNode, CBaseObject* pPrevObject = nullptr); ////////////////////////////////////////////////////////////////////////// int GetLoadedObjectsCount() { return static_cast(m_loadedObjects.size()); } diff --git a/Code/Editor/Objects/ObjectManager.cpp b/Code/Editor/Objects/ObjectManager.cpp index 58cd016e22..fbdd56f080 100644 --- a/Code/Editor/Objects/ObjectManager.cpp +++ b/Code/Editor/Objects/ObjectManager.cpp @@ -32,7 +32,11 @@ #include AZ_CVAR_EXTERNED(bool, ed_visibility_logTiming); -AZ_CVAR_EXTERNED(bool, ed_visibility_use); + +AZ_CVAR( + bool, ed_visibility_use, true, nullptr, AZ::ConsoleFunctorFlags::Null, + "Enable/disable using the new IVisibilitySystem for Entity visibility determination"); + /*! * Class Description used for object templates. @@ -49,16 +53,16 @@ public: GUID guid; public: - REFGUID ClassID() + REFGUID ClassID() override { return guid; } - ObjectType GetObjectType() { return superType->GetObjectType(); }; - QString ClassName() { return type; }; - QString Category() { return category; }; + ObjectType GetObjectType() override { return superType->GetObjectType(); }; + QString ClassName() override { return type; }; + QString Category() override { return category; }; QObject* CreateQObject() const override { return superType->CreateQObject(); } - QString GetTextureIcon() { return superType->GetTextureIcon(); }; - QString GetFileSpec() + QString GetTextureIcon() override { return superType->GetTextureIcon(); }; + QString GetFileSpec() override { if (!fileSpec.isEmpty()) { @@ -69,7 +73,7 @@ public: return superType->GetFileSpec(); } }; - virtual int GameCreationOrder() { return superType->GameCreationOrder(); }; + int GameCreationOrder() override { return superType->GameCreationOrder(); }; }; void CBaseObjectsCache::AddObject(CBaseObject* object) @@ -86,7 +90,7 @@ void CBaseObjectsCache::AddObject(CBaseObject* object) ////////////////////////////////////////////////////////////////////////// // CObjectManager implementation. ////////////////////////////////////////////////////////////////////////// -CObjectManager* g_pObjectManager = 0; +CObjectManager* g_pObjectManager = nullptr; ////////////////////////////////////////////////////////////////////////// CObjectManager::CObjectManager() @@ -182,19 +186,19 @@ CBaseObject* CObjectManager::NewObject(CObjectClassDesc* cls, CBaseObject* prev, if (!AddObject(obj)) { - obj = 0; + obj = nullptr; } } else { - obj = 0; + obj = nullptr; } - GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(NULL); + GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr); } GetIEditor()->ResumeUndo(); - if (obj != 0 && GetIEditor()->IsUndoRecording()) + if (obj != nullptr && GetIEditor()->IsUndoRecording()) { // AZ entity creations are handled through the AZ undo system. if (obj->GetType() != OBJTYPE_AZENTITY) @@ -228,7 +232,7 @@ CBaseObject* CObjectManager::NewObject(CObjectArchive& ar, CBaseObject* pUndoObj if (!objNode->getAttr("Type", typeName)) { - return 0; + return nullptr; } if (!objNode->getAttr("Id", id)) @@ -268,7 +272,7 @@ CBaseObject* CObjectManager::NewObject(CObjectArchive& ar, CBaseObject* pUndoObj if (!cls) { CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_ERROR, "RuntimeClass %s not registered", typeName.toUtf8().data()); - return 0; + return nullptr; } pObject = qobject_cast(cls->CreateQObject()); @@ -301,29 +305,29 @@ CBaseObject* CObjectManager::NewObject(CObjectArchive& ar, CBaseObject* pUndoObj GetIEditor()->GetErrorReport()->ReportError(errorRecord); } - return 0; + return nullptr; //CoCreateGuid( &pObject->m_guid ); // generate uniq GUID for this object. } } GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(pObject); - if (!pObject->Init(GetIEditor(), 0, "")) + if (!pObject->Init(GetIEditor(), nullptr, "")) { - GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(NULL); - return 0; + GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr); + return nullptr; } if (!AddObject(pObject)) { - GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(NULL); - return 0; + GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr); + return nullptr; } //pObject->Serialize( ar ); - GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(NULL); + GetIEditor()->GetErrorReport()->SetCurrentValidatorObject(nullptr); - if (pObject != 0 && pUndoObject == 0) + if (pObject != nullptr && pUndoObject == nullptr) { // If new object with no undo, record it. if (CUndo::IsRecording()) @@ -355,7 +359,7 @@ CBaseObject* CObjectManager::NewObject(const QString& typeName, CBaseObject* pre if (!cls) { GetIEditor()->GetSystem()->GetILog()->Log("Warning: RuntimeClass %s (as well as %s) not registered", typeName.toUtf8().data(), fullName.toUtf8().data()); - return 0; + return nullptr; } CBaseObject* pObject = NewObject(cls, prev, file, newObjectName); return pObject; @@ -411,7 +415,7 @@ void CObjectManager::DeleteObject(CBaseObject* obj) void CObjectManager::DeleteSelection(CSelectionGroup* pSelection) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); - if (pSelection == NULL) + if (pSelection == nullptr) { return; } @@ -527,7 +531,7 @@ CBaseObject* CObjectManager::CloneObject(CBaseObject* obj) ////////////////////////////////////////////////////////////////////////// CBaseObject* CObjectManager::FindObject(REFGUID guid) const { - CBaseObject* result = stl::find_in_map(m_objects, guid, (CBaseObject*)0); + CBaseObject* result = stl::find_in_map(m_objects, guid, (CBaseObject*)nullptr); return result; } @@ -603,7 +607,7 @@ void CObjectManager::FindObjectsInAABB(const AABB& aabb, std::vectorGetId(), 0); + CBaseObjectPtr p = stl::find_in_map(m_objects, obj->GetId(), nullptr); if (p) { CErrorRecord err; @@ -908,7 +912,7 @@ void CObjectManager::UnfreezeAll() bool CObjectManager::SelectObject(CBaseObject* obj, bool bUseMask) { assert(obj); - if (obj == NULL) + if (obj == nullptr) { return false; } @@ -974,7 +978,7 @@ void CObjectManager::UnselectObject(CBaseObject* obj) CSelectionGroup* CObjectManager::GetSelection(const QString& name) const { - CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)0); + CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr); return selection; } @@ -993,7 +997,7 @@ void CObjectManager::NameSelection(const QString& name) return; } - CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)0); + CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr); if (selection) { assert(selection != 0); @@ -1020,7 +1024,7 @@ void CObjectManager::SerializeNameSelection(XmlNodeRef& rootNode, bool bLoading) return; } - _smart_ptr tmpGroup(0); + _smart_ptr tmpGroup(nullptr); QString selRootStr("NameSelection"); QString selNodeStr("NameSelectionNode"); @@ -1075,7 +1079,7 @@ void CObjectManager::SerializeNameSelection(XmlNodeRef& rootNode, bool bLoading) else { startNode = rootNode->newChild(selRootStr.toUtf8().data()); - CSelectionGroup* objSelection = 0; + CSelectionGroup* objSelection = nullptr; for (TNameSelectionMap::iterator it = m_selections.begin(); it != m_selections.end(); ++it) { @@ -1186,7 +1190,7 @@ int CObjectManager::InvertSelection() void CObjectManager::SetSelection(const QString& name) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); - CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)0); + CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr); if (selection) { UnselectCurrent(); @@ -1201,7 +1205,7 @@ void CObjectManager::RemoveSelection(const QString& name) AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); QString selName = name; - CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)0); + CSelectionGroup* selection = stl::find_in_map(m_selections, name, (CSelectionGroup*)nullptr); if (selection) { if (selection == m_currSelection) @@ -1327,7 +1331,6 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] pDispayedViewObjects->SetSerialNumber(m_visibilitySerialNumber); // update viewport to be latest serial number - const CCamera& camera = GetIEditor()->GetSystem()->GetViewCamera(); AABB bbox; bbox.min.zero(); bbox.max.zero(); @@ -1359,7 +1362,7 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] for (int i = 0, iCount(pSelection->GetCount()); i < iCount; ++i) { CBaseObject* pObj(pSelection->GetObject(i)); - if (pObj == NULL) + if (pObj == nullptr) { continue; } @@ -1376,11 +1379,9 @@ void CObjectManager::FindDisplayableObjects(DisplayContext& dc, [[maybe_unused]] { CBaseObject* obj = m_visibleObjects[i]; - if (obj && obj->IsInCameraView(camera)) + if (obj) { - // Check if object is too far. - float visRatio = obj->GetCameraVisRatio(camera); - if (visRatio > m_maxObjectViewDistRatio || (dc.flags & DISPLAY_SELECTION_HELPERS) || obj->IsSelected()) + if ((dc.flags & DISPLAY_SELECTION_HELPERS) || obj->IsSelected()) { pDispayedViewObjects->AddObject(obj); } @@ -1443,7 +1444,7 @@ void CObjectManager::BeginEditParams(CBaseObject* obj, int flags) void CObjectManager::EndEditParams([[maybe_unused]] int flags) { m_bSingleSelection = false; - m_currEditObject = 0; + m_currEditObject = nullptr; //m_bSelectionChanged = false; // don't need to clear for ungroup } @@ -1657,7 +1658,7 @@ bool CObjectManager::HitTest(HitContext& hitInfo) HitContext hcOrg = hitInfo; if (hcOrg.view) { - hcOrg.view->GetPerpendicularAxis(0, &hcOrg.b2DViewport); + hcOrg.view->GetPerpendicularAxis(nullptr, &hcOrg.b2DViewport); } hcOrg.rayDir = hcOrg.rayDir.GetNormalized(); @@ -1692,7 +1693,7 @@ bool CObjectManager::HitTest(HitContext& hitInfo) const bool iconsPrioritized = true; // Force icons to always be prioritized over other things you hit. Can change to be a configurable option in the future. - CBaseObject* selected = 0; + CBaseObject* selected = nullptr; const char* name = nullptr; bool iconHit = false; int numVis = pDispayedViewObjects->GetObjectCount(); @@ -1993,11 +1994,11 @@ bool CObjectManager::EnableUniqObjectNames(bool bEnable) CObjectClassDesc* CObjectManager::FindClass(const QString& className) { IClassDesc* cls = CClassFactory::Instance()->FindClass(className.toUtf8().data()); - if (cls != NULL && cls->SystemClassID() == ESYSTEM_CLASS_OBJECT) + if (cls != nullptr && cls->SystemClassID() == ESYSTEM_CLASS_OBJECT) { return (CObjectClassDesc*)cls; } - return 0; + return nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -2101,7 +2102,7 @@ void CObjectManager::LoadClassTemplates(const QString& path) { // Construct the full filepath of the current file XmlNodeRef node = XmlHelpers::LoadXmlFromFile((dir + files[k].filename).toUtf8().data()); - if (node != 0 && node->isTag("ObjectTemplates")) + if (node != nullptr && node->isTag("ObjectTemplates")) { QString name; for (int i = 0; i < node->getChildCount(); i++) @@ -2449,7 +2450,7 @@ void CObjectManager::EndObjectsLoading() { delete m_pLoadProgress; } - m_pLoadProgress = 0; + m_pLoadProgress = nullptr; } ////////////////////////////////////////////////////////////////////////// @@ -2481,20 +2482,20 @@ bool CObjectManager::IsLightClass(CBaseObject* pObject) { if (pEntity->GetEntityClass().compare(CLASS_LIGHT) == 0) { - return TRUE; + return true; } if (pEntity->GetEntityClass().compare(CLASS_RIGIDBODY_LIGHT) == 0) { - return TRUE; + return true; } if (pEntity->GetEntityClass().compare(CLASS_DESTROYABLE_LIGHT) == 0) { - return TRUE; + return true; } } } - return FALSE; + return false; } void CObjectManager::FindAndRenameProperty2(const char* property2Name, const QString& oldValue, const QString& newValue) diff --git a/Code/Editor/Objects/SelectionGroup.cpp b/Code/Editor/Objects/SelectionGroup.cpp index 5912cf050e..027c88172e 100644 --- a/Code/Editor/Objects/SelectionGroup.cpp +++ b/Code/Editor/Objects/SelectionGroup.cpp @@ -636,7 +636,7 @@ void CSelectionGroup::FinishChanges() for (int i = 0; i < iObjectSize; ++i) { CBaseObject* pObject = selectedObjects[i]; - if (pObject == NULL) + if (pObject == nullptr) { continue; } diff --git a/Code/Editor/Objects/TrackGizmo.cpp b/Code/Editor/Objects/TrackGizmo.cpp index ed1132bd2b..8cbd7df2e5 100644 --- a/Code/Editor/Objects/TrackGizmo.cpp +++ b/Code/Editor/Objects/TrackGizmo.cpp @@ -34,7 +34,7 @@ namespace { ////////////////////////////////////////////////////////////////////////// CTrackGizmo::CTrackGizmo() { - m_pAnimNode = 0; + m_pAnimNode = nullptr; m_worldBbox.min = Vec3(-10000, -10000, -10000); m_worldBbox.max = Vec3(10000, 10000, 10000); diff --git a/Code/Editor/Platform/Mac/editor_mac.cmake b/Code/Editor/Platform/Mac/editor_mac.cmake index 2afbee4251..fdccfafb46 100644 --- a/Code/Editor/Platform/Mac/editor_mac.cmake +++ b/Code/Editor/Platform/Mac/editor_mac.cmake @@ -13,3 +13,27 @@ set_target_properties(Editor PROPERTIES RESOURCE ${CMAKE_CURRENT_LIST_DIR}/Images.xcassets XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME EditorAppIcon ) + +# We cannot use ly_add_target here because we're already including this file from inside ly_add_target +# So we need to setup target, dependencies and install logic manually. +add_executable(EditorDummy Platform/Mac/main_dummy.cpp) +add_executable(AZ::EditorDummy ALIAS EditorDummy) + +ly_target_link_libraries(EditorDummy + PRIVATE + AZ::AzCore + AZ::AzFramework) + +ly_add_dependencies(Editor EditorDummy) + +# Store the aliased target into a DIRECTORY property +set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS AZ::EditorDummy) + +# Store the directory path in a GLOBAL property so that it can be accessed +# in the layout install logic. Skip if the directory has already been added +get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) +if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories) + set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +ly_install_add_install_path_setreg(Editor) \ No newline at end of file diff --git a/Code/Editor/Platform/Mac/gui_info.plist b/Code/Editor/Platform/Mac/gui_info.plist index 5b5f94e977..cc87cbbb47 100644 --- a/Code/Editor/Platform/Mac/gui_info.plist +++ b/Code/Editor/Platform/Mac/gui_info.plist @@ -3,7 +3,7 @@ CFBundleExecutable - Editor + EditorDummy CFBundleIdentifier org.O3DE.Editor CFBundlePackageType diff --git a/Code/Editor/Platform/Mac/main_dummy.cpp b/Code/Editor/Platform/Mac/main_dummy.cpp new file mode 100644 index 0000000000..fb4a431295 --- /dev/null +++ b/Code/Editor/Platform/Mac/main_dummy.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +#include + +int main(int argc, char* argv[]) +{ + // Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry + AZ::ComponentApplication::Descriptor desc; + AZ::ComponentApplication application; + application.Create(desc); + + AZStd::vector envVars; + + const char* homePath = std::getenv("HOME"); + envVars.push_back(AZStd::string::format("HOME=%s", homePath)); + + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + const char* dyldLibPathOrig = std::getenv("DYLD_LIBRARY_PATH"); + AZStd::string dyldSearchPath = AZStd::string::format("DYLD_LIBRARY_PATH=%s", dyldLibPathOrig); + if (AZ::IO::FixedMaxPath projectModulePath; + settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) + { + dyldSearchPath.append(":"); + dyldSearchPath.append(projectModulePath.c_str()); + } + + if (AZ::IO::FixedMaxPath installedBinariesFolder; + settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder)) + { + if (AZ::IO::FixedMaxPath engineRootFolder; + settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder)) + { + installedBinariesFolder = engineRootFolder / installedBinariesFolder; + dyldSearchPath.append(":"); + dyldSearchPath.append(installedBinariesFolder.c_str()); + } + } + envVars.push_back(dyldSearchPath); + } + + AZStd::string commandArgs; + for (int i = 1; i < argc; i++) + { + commandArgs.append(argv[i]); + commandArgs.append(" "); + } + + AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; + AZ::IO::Path processPath{ AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()) }; + processPath /= "Editor"; + processLaunchInfo.m_processExecutableString = AZStd::move(processPath.Native()); + processLaunchInfo.m_commandlineParameters = commandArgs; + processLaunchInfo.m_environmentVariables = &envVars; + processLaunchInfo.m_showWindow = true; + + AzFramework::ProcessWatcher* processWatcher = AzFramework::ProcessWatcher::LaunchProcess(processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE); + + application.Destroy(); + + return 0; +} + diff --git a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp index e7cc8658f0..7ac1181cdd 100644 --- a/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp +++ b/Code/Editor/Platform/Windows/Util/Mailer_Windows.cpp @@ -51,8 +51,8 @@ bool CMailer::SendMail(const char* subject, attachments[i].flFlags = 0; attachments[i].nPosition = (ULONG)-1; attachments[i].lpszPathName = (char*)(const char*)_attachments[k]; - attachments[i].lpszFileName = NULL; - attachments[i].lpFileType = NULL; + attachments[i].lpszFileName = nullptr; + attachments[i].lpFileType = nullptr; i++; } int numAttachments = i; @@ -74,14 +74,14 @@ bool CMailer::SendMail(const char* subject, recipients[i].lpszName = (char*)(const char*)_recipients[i]; recipients[i].lpszAddress = (char*)addresses[i].c_str(); recipients[i].ulEIDSize = 0; - recipients[i].lpEntryID = NULL; + recipients[i].lpEntryID = nullptr; } MapiMessage message; memset(&message, 0, sizeof(message)); message.lpszSubject = (char*)(const char*)subject; message.lpszNoteText = (char*)(const char*)messageBody; - message.lpszMessageType = NULL; + message.lpszMessageType = nullptr; message.nRecipCount = numRecipients; message.lpRecips = recipients; diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ead320367e..072625936b 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -84,6 +84,7 @@ #include #include #include "CryEdit.h" +#include "Undo/Undo.h" #include #include @@ -1815,7 +1816,7 @@ void SandboxIntegrationManager::ContextMenu_PushEntitiesToSlice(AzToolsFramework (void)targetAncestorId; (void)affectEntireHierarchy; - AZ::SerializeContext* serializeContext = NULL; + AZ::SerializeContext* serializeContext = nullptr; EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); AZ_Assert(serializeContext, "No serialize context"); diff --git a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentPaletteWindow.cpp b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentPaletteWindow.cpp index 78d3e51e4d..1791301654 100644 --- a/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentPaletteWindow.cpp +++ b/Code/Editor/Plugins/ComponentEntityEditorPlugin/UI/ComponentPalette/ComponentPaletteWindow.cpp @@ -42,7 +42,7 @@ void ComponentPaletteWindow::Init() layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); - QHBoxLayout* gridLayout = new QHBoxLayout(NULL); + QHBoxLayout* gridLayout = new QHBoxLayout(nullptr); gridLayout->setSizeConstraint(QLayout::SetMaximumSize); gridLayout->setContentsMargins(0, 0, 0, 0); gridLayout->setSpacing(0); diff --git a/Code/Editor/Plugins/EditorCommon/DockTitleBarWidget.cpp b/Code/Editor/Plugins/EditorCommon/DockTitleBarWidget.cpp index adb8ef0bc5..0569adf069 100644 --- a/Code/Editor/Plugins/EditorCommon/DockTitleBarWidget.cpp +++ b/Code/Editor/Plugins/EditorCommon/DockTitleBarWidget.cpp @@ -30,13 +30,13 @@ class CDockWidgetTitleButton public: CDockWidgetTitleButton(QWidget* parent); - QSize sizeHint() const; - QSize minimumSizeHint() const { return sizeHint(); } + QSize sizeHint() const override; + QSize minimumSizeHint() const override { return sizeHint(); } protected: - void enterEvent(QEvent* ev); - void leaveEvent(QEvent* ev); - void paintEvent(QPaintEvent* ev); + void enterEvent(QEvent* ev) override; + void leaveEvent(QEvent* ev) override; + void paintEvent(QPaintEvent* ev) override; }; class CTitleBarText @@ -85,10 +85,10 @@ QSize CDockWidgetTitleButton::sizeHint() const { ensurePolished(); - int size = 2 * style()->pixelMetric(QStyle::PM_DockWidgetTitleBarButtonMargin, 0, this); + int size = 2 * style()->pixelMetric(QStyle::PM_DockWidgetTitleBarButtonMargin, nullptr, this); if (!icon().isNull()) { - int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this); + int iconSize = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this); QSize sz = icon().actualSize(QSize(iconSize, iconSize)); size += qMax(sz.width(), sz.height()); } @@ -145,7 +145,7 @@ void CDockWidgetTitleButton::paintEvent([[maybe_unused]] QPaintEvent* ev) opt.activeSubControls = QStyle::SubControls(); opt.features = QStyleOptionToolButton::None; opt.arrowType = Qt::NoArrow; - int size = style()->pixelMetric(QStyle::PM_SmallIconSize, 0, this); + int size = style()->pixelMetric(QStyle::PM_SmallIconSize, nullptr, this); opt.iconSize = QSize(size, size); style()->drawComplexControl(QStyle::CC_ToolButton, &opt, &painter, this); } diff --git a/Code/Editor/Plugins/FFMPEGPlugin/main.cpp b/Code/Editor/Plugins/FFMPEGPlugin/main.cpp index 3432a9975e..ce0e91942b 100644 --- a/Code/Editor/Plugins/FFMPEGPlugin/main.cpp +++ b/Code/Editor/Plugins/FFMPEGPlugin/main.cpp @@ -15,7 +15,7 @@ PLUGIN_API IPlugin* CreatePluginInstance(PLUGIN_INIT_PARAM* pInitParam) if (pInitParam->pluginVersion != SANDBOX_PLUGIN_SYSTEM_VERSION) { pInitParam->outErrorCode = IPlugin::eError_VersionMismatch; - return 0; + return nullptr; } ModuleInitISystem(GetIEditor()->GetSystem(), "FFMPEGPlugin"); diff --git a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp index aec613b8df..581f9a576d 100644 --- a/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp +++ b/Code/Editor/Plugins/PerforcePlugin/PerforceSourceControl.cpp @@ -56,7 +56,7 @@ void CPerforceSourceControl::ShowSettings() void CPerforceSourceControl::SetSourceControlState(SourceControlState state) { - AUTO_LOCK(g_cPerforceValues); + CryAutoLock lock(g_cPerforceValues); switch (state) { diff --git a/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp b/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp index d11cc04ba0..ea65cf3e59 100644 --- a/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp +++ b/Code/Editor/Plugins/ProjectSettingsTool/PlatformSettings_Android.cpp @@ -165,8 +165,8 @@ namespace ProjectSettingsTool if (editContext) { editContext->Class("Splashscreens", "All splashscreen overrides for Android.") - ->DataElement(0, &AndroidSplashscreens::m_landscapeSplashscreens) - ->DataElement(0, &AndroidSplashscreens::m_portraitSplashscreens) + ->DataElement(AZ::Edit::UIHandlers::Default, &AndroidSplashscreens::m_landscapeSplashscreens) + ->DataElement(AZ::Edit::UIHandlers::Default, &AndroidSplashscreens::m_portraitSplashscreens) ; } } diff --git a/Code/Editor/Plugins/ProjectSettingsTool/Validators.cpp b/Code/Editor/Plugins/ProjectSettingsTool/Validators.cpp index e8bb900be9..4dfc4ee25a 100644 --- a/Code/Editor/Plugins/ProjectSettingsTool/Validators.cpp +++ b/Code/Editor/Plugins/ProjectSettingsTool/Validators.cpp @@ -16,7 +16,7 @@ namespace { - typedef ProjectSettingsTool::FunctorValidator::ReturnType RetType; + using RetType = ProjectSettingsTool::FunctorValidator::ReturnType; static const int noMaxLength = -1; static const int maxIosVersionLength = 18; diff --git a/Code/Editor/RenderViewport.cpp b/Code/Editor/RenderViewport.cpp deleted file mode 100644 index 47e5106221..0000000000 --- a/Code/Editor/RenderViewport.cpp +++ /dev/null @@ -1,4142 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : implementation filefov - - -#include "EditorDefs.h" - -#include "RenderViewport.h" - -// Qt -#include -#include -#include -#include -#include - -// AzCore -#include -#include -#include -#include -#include -#include -#include - -// AzFramework -#include -#include -#include -#if defined(AZ_PLATFORM_WINDOWS) -# include -#endif // defined(AZ_PLATFORM_WINDOWS) -#include // for AzFramework::InputDeviceMouse - -// AzQtComponents -#include - -// AzToolsFramework -#include -#include -#include -#include -#include -#include - - -// CryCommon -#include - -// AzFramework -#include - -// Editor -#include "Util/fastlib.h" -#include "CryEditDoc.h" -#include "GameEngine.h" -#include "ViewManager.h" -#include "Objects/DisplayContext.h" -#include "DisplaySettings.h" -#include "Include/IObjectManager.h" -#include "Include/IDisplayViewport.h" -#include "Objects/ObjectManager.h" -#include "ProcessInfo.h" -#include "IPostEffectGroup.h" -#include "EditorPreferencesPageGeneral.h" - -#include "ViewPane.h" -#include "CustomResolutionDlg.h" -#include "AnimationContext.h" -#include "Objects/SelectionGroup.h" -#include "Core/QtEditorApplication.h" - -// ComponentEntityEditorPlugin -#include - -// LmbrCentral -#include - -#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"); - -CRenderViewport* CRenderViewport::m_pPrimaryViewport = nullptr; - -#if AZ_TRAIT_OS_PLATFORM_APPLE -void StopFixedCursorMode(); -void StartFixedCursorMode(QObject *viewport); -#endif - -#define MAX_ORBIT_DISTANCE (2000.0f) -#define RENDER_MESH_TEST_DISTANCE (0.2f) -#define CURSOR_FONT_HEIGHT 8.0f -#define FORWARD_DIRECTION Vec3(0, 1, 0) - -static const char TextCantCreateCameraNoLevel[] = "Cannot create camera when no level is loaded."; - -class EditorEntityNotifications - : public AzToolsFramework::EditorEntityContextNotificationBus::Handler - , public AzToolsFramework::EditorContextMenuBus::Handler -{ -public: - EditorEntityNotifications(CRenderViewport& renderViewport) - : m_renderViewport(renderViewport) - { - AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); - AzToolsFramework::EditorContextMenuBus::Handler::BusConnect(); - } - - ~EditorEntityNotifications() override - { - AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusDisconnect(); - AzToolsFramework::EditorContextMenuBus::Handler::BusDisconnect(); - } - - // AzToolsFramework::EditorEntityContextNotificationBus - void OnStartPlayInEditor() override - { - m_renderViewport.OnStartPlayInEditor(); - } - void OnStopPlayInEditor() override - { - m_renderViewport.OnStopPlayInEditor(); - } - - // AzToolsFramework::EditorContextMenu::Bus - void PopulateEditorGlobalContextMenu(QMenu* menu, const AZ::Vector2& point, int flags) override - { - m_renderViewport.PopulateEditorGlobalContextMenu(menu, point, flags); - } -private: - CRenderViewport& m_renderViewport; -}; - -struct CRenderViewport::SScopedCurrentContext -{ - const CRenderViewport* m_viewport; - CRenderViewport::SPreviousContext m_previousContext; - - explicit SScopedCurrentContext(const CRenderViewport* viewport) - : m_viewport(viewport) - { - m_previousContext = viewport->SetCurrentContext(); - - // During normal updates of RenderViewport the value of m_cameraSetForWidgetRenderingCount is expected to be 0. - // This is to guarantee no loss in performance by tracking unnecessary calls to SetCurrentContext/RestorePreviousContext. - // If some code makes additional calls to Pre/PostWidgetRendering then the assert will be triggered because - // m_cameraSetForWidgetRenderingCount will be greater than 0. - // There is a legitimate case where the counter can be greater than 0. This is when QtViewport is processing mouse callbacks. - // QtViewport::MouseCallback() is surrounded by Pre/PostWidgetRendering and the m_processingMouseCallbacksCounter - // tracks this specific case. If an update of a RenderViewport happens while processing the mouse callback, - // for example when showing a QMessageBox, then both counters must match. - AZ_Assert(viewport->m_cameraSetForWidgetRenderingCount == viewport->m_processingMouseCallbacksCounter, - "SScopedCurrentContext constructor was called while viewport widget context is active " - "- this is unnecessary"); - } - - ~SScopedCurrentContext() - { - m_viewport->RestorePreviousContext(m_previousContext); - } -}; - -////////////////////////////////////////////////////////////////////////// -// CRenderViewport -////////////////////////////////////////////////////////////////////////// - -CRenderViewport::CRenderViewport(const QString& name, QWidget* parent) - : QtViewport(parent) - , m_Camera(GetIEditor()->GetSystem()->GetViewCamera()) - , m_camFOV(gSettings.viewports.fDefaultFov) - , m_defaultViewName(name) -{ - // need this to be set in order to allow for language switching on Windows - setAttribute(Qt::WA_InputMethodEnabled); - LockCameraMovement(true); - - CRenderViewport::SetViewTM(m_Camera.GetMatrix()); - m_defaultViewTM.SetIdentity(); - - if (GetIEditor()->GetViewManager()->GetSelectedViewport() == nullptr) - { - GetIEditor()->GetViewManager()->SelectViewport(this); - } - - GetIEditor()->RegisterNotifyListener(this); - - m_displayContext.pIconManager = GetIEditor()->GetIconManager(); - GetIEditor()->GetUndoManager()->AddListener(this); - - m_PhysicalLocation.SetIdentity(); - - // The renderer requires something, so don't allow us to shrink to absolutely nothing - // This won't in fact stop the viewport from being shrunk, when it's the centralWidget for - // the MainWindow, but it will stop the viewport from getting resize events - // once it's smaller than that, which from the renderer's perspective works out - // to be the same thing. - setMinimumSize(50, 50); - - OnCreate(); - - setFocusPolicy(Qt::StrongFocus); - - Camera::EditorCameraRequestBus::Handler::BusConnect(); - m_editorEntityNotifications = AZStd::make_unique(*this); - - m_manipulatorManager = GetIEditor()->GetViewManager()->GetManipulatorManager(); - if (!m_pPrimaryViewport) - { - m_pPrimaryViewport = this; - } - - m_hwnd = renderOverlayHWND(); -} - -////////////////////////////////////////////////////////////////////////// -CRenderViewport::~CRenderViewport() -{ - AzFramework::WindowNotificationBus::Event(m_hwnd, &AzFramework::WindowNotificationBus::Handler::OnWindowClosed); - - if (m_pPrimaryViewport == this) - { - m_pPrimaryViewport = nullptr; - } - - AzFramework::WindowRequestBus::Handler::BusDisconnect(); - DisconnectViewportInteractionRequestBus(); - m_editorEntityNotifications.reset(); - Camera::EditorCameraRequestBus::Handler::BusDisconnect(); - OnDestroy(); - GetIEditor()->GetUndoManager()->RemoveListener(this); - GetIEditor()->UnregisterNotifyListener(this); -} - -////////////////////////////////////////////////////////////////////////// -// CRenderViewport message handlers -////////////////////////////////////////////////////////////////////////// -int CRenderViewport::OnCreate() -{ - CreateRenderContext(); - - return 0; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::resizeEvent(QResizeEvent* event) -{ - PushDisableRendering(); - QtViewport::resizeEvent(event); - PopDisableRendering(); - - const QRect rcWindow = rect().translated(mapToGlobal(QPoint())); - - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_MOVE, rcWindow.left(), rcWindow.top()); - - m_rcClient = rect(); - m_rcClient.setBottomRight(WidgetToViewport(m_rcClient.bottomRight())); - - gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, width(), height()); - - // 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; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::paintEvent([[maybe_unused]] QPaintEvent* event) -{ - // Do not call CViewport::OnPaint() for painting messages - // FIXME: paintEvent() isn't the best place for such logic. Should listen to proper eNotify events and to the stuff there instead. (Repeats for other view port classes too). - CGameEngine* ge = GetIEditor()->GetGameEngine(); - if ((ge && ge->IsLevelLoaded()) || (GetType() != ET_ViewportCamera)) - { - setRenderOverlayVisible(true); - m_isOnPaint = true; - Update(); - m_isOnPaint = false; - } - else - { - setRenderOverlayVisible(false); - QPainter painter(this); // device context for painting - - // draw gradient background - const QRect rc = rect(); - QLinearGradient gradient(rc.topLeft(), rc.bottomLeft()); - gradient.setColorAt(0, QColor(80, 80, 80)); - gradient.setColorAt(1, QColor(200, 200, 200)); - painter.fillRect(rc, gradient); - - // if we have some level loaded/loading/new - // we draw a text - if (!GetIEditor()->GetLevelFolder().isEmpty()) - { - const int kFontSize = 200; - const char* kFontName = "Arial"; - const QColor kTextColor(255, 255, 255); - const QColor kTextShadowColor(0, 0, 0); - const QFont font(kFontName, kFontSize / 10.0); - painter.setFont(font); - - QString friendlyName = QFileInfo(GetIEditor()->GetLevelName()).fileName(); - const QString strMsg = tr("Preparing level %1...").arg(friendlyName); - - // draw text shadow - painter.setPen(kTextShadowColor); - painter.drawText(rc, Qt::AlignCenter, strMsg); - painter.setPen(kTextColor); - // offset rect for normal text - painter.drawText(rc.translated(-1, -1), Qt::AlignCenter, strMsg); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::mousePressEvent(QMouseEvent* event) -{ - // There's a bug caused by having a mix of MFC and Qt where if the render viewport - // had focus and then an MFC widget gets focus, Qt internally still thinks - // that the widget that had focus before (the render viewport) has it now. - // Because of this, Qt won't set the window that the viewport is in as the - // focused widget, and the render viewport won't get keyboard input. - // Forcing the window to activate should allow the window to take focus - // and then the call to setFocus() will give it focus. - // All so that the ::keyPressEvent() gets called. - ActivateWindowAndSetFocus(); - - GetIEditor()->GetViewManager()->SelectViewport(this); - - QtViewport::mousePressEvent(event); -} - -AzToolsFramework::ViewportInteraction::MousePick CRenderViewport::BuildMousePickInternal(const QPoint& point) const -{ - using namespace AzToolsFramework::ViewportInteraction; - - MousePick mousePick; - Vec3 from, dir; - ViewToWorldRay(point, from, dir); - mousePick.m_rayOrigin = LYVec3ToAZVec3(from); - mousePick.m_rayDirection = LYVec3ToAZVec3(dir); - mousePick.m_screenCoordinates = AzFramework::ScreenPoint(point.x(), point.y()); - return mousePick; -} - -AzToolsFramework::ViewportInteraction::MousePick CRenderViewport::BuildMousePick(const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - - PreWidgetRendering(); - const MousePick mousePick = BuildMousePickInternal(point); - PostWidgetRendering(); - return mousePick; -} - -AzToolsFramework::ViewportInteraction::MouseInteraction CRenderViewport::BuildMouseInteractionInternal( - const AzToolsFramework::ViewportInteraction::MouseButtons buttons, - const AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers, - const AzToolsFramework::ViewportInteraction::MousePick& mousePick) const -{ - using namespace AzToolsFramework::ViewportInteraction; - - MouseInteraction mouse; - mouse.m_interactionId.m_cameraId = m_viewEntityId; - mouse.m_interactionId.m_viewportId = GetViewportId(); - mouse.m_mouseButtons = buttons; - mouse.m_mousePick = mousePick; - mouse.m_keyboardModifiers = modifiers; - return mouse; -} - -AzToolsFramework::ViewportInteraction::MouseInteraction CRenderViewport::BuildMouseInteraction( - const Qt::MouseButtons buttons, const Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - - return BuildMouseInteractionInternal( - BuildMouseButtons(buttons), - BuildKeyboardModifiers(modifiers), - BuildMousePick(WidgetToViewport(point))); -} - -namespace RenderViewportUtil -{ - static bool JustAltHeld(const Qt::KeyboardModifiers modifiers) - { - return (modifiers & Qt::ShiftModifier) == 0 - && (modifiers & Qt::ControlModifier) == 0 - && (modifiers & Qt::AltModifier) != 0; - } - - static bool NoModifiersHeld(const Qt::KeyboardModifiers modifiers) - { - return (modifiers & Qt::ShiftModifier) == 0 - && (modifiers & Qt::ControlModifier) == 0 - && (modifiers & Qt::AltModifier) == 0; - } - - static bool AllowDolly(const Qt::KeyboardModifiers modifiers) - { - return JustAltHeld(modifiers); - } - - static bool AllowOrbit(const Qt::KeyboardModifiers modifiers) - { - return JustAltHeld(modifiers); - } - - static bool AllowPan(const Qt::KeyboardModifiers modifiers) - { - // begin pan with alt (inverted movement) or no modifiers - return JustAltHeld(modifiers) || NoModifiersHeld(modifiers); - } - - static bool InvertPan(const Qt::KeyboardModifiers modifiers) - { - return JustAltHeld(modifiers); - } -} // namespace RenderViewportUtil - - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnLButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - if (!m_renderer) - { - return; - } - - // Force the visible object cache to be updated - this is to ensure that - // selection will work properly even if helpers are not being displayed, - // in which case the cache is not updated every frame. - if (m_displayContext.settings && !m_displayContext.settings->IsDisplayHelpers()) - { - GetIEditor()->GetObjectManager()->ForceUpdateVisibleObjectCache(m_displayContext); - } - - const auto scaledPoint = WidgetToViewport(point); - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Left), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - bool manipulatorInteraction = false; - EditorInteractionSystemViewportSelectionRequestBus::EventResult( - manipulatorInteraction, AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleMouseManipulatorInteraction, - MouseInteractionEvent(mouseInteraction, MouseEvent::Down)); - - if (!manipulatorInteraction) - { - if (RenderViewportUtil::AllowOrbit(modifiers)) - { - m_bInOrbitMode = true; - m_orbitTarget = - GetViewTM().GetTranslation() + GetViewTM().TransformVector(FORWARD_DIRECTION) * m_orbitDistance; - - // mouse buttons are treated as keys as well - if (m_pressedKeyState == KeyPressedState::AllUp) - { - m_pressedKeyState = KeyPressedState::PressedThisFrame; - } - - m_mousePos = scaledPoint; - m_prevMousePos = scaledPoint; - - HideCursor(); - CaptureMouse(); - - // no further handling of left mouse button down - return; - } - - EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleMouseViewportInteraction, - MouseInteractionEvent(mouseInteraction, MouseEvent::Down)); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnLButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - // Convert point to position on terrain. - if (!m_renderer) - { - return; - } - - // Update viewports after done with actions. - GetIEditor()->UpdateViews(eUpdateObjects); - - const auto scaledPoint = WidgetToViewport(point); - - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Left), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - if (m_bInOrbitMode) - { - m_bInOrbitMode = false; - - ReleaseMouse(); - ShowCursor(); - } - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::Up)); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnLButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto scaledPoint = WidgetToViewport(point); - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Left), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::DoubleClick)); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - SetFocus(); - - const auto scaledPoint = WidgetToViewport(point); - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Right), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::Down)); - - if (RenderViewportUtil::AllowDolly(modifiers)) - { - m_bInZoomMode = true; - } - else - { - m_bInRotateMode = true; - } - - // mouse buttons are treated as keys as well - if (m_pressedKeyState == KeyPressedState::AllUp) - { - m_pressedKeyState = KeyPressedState::PressedThisFrame; - } - - m_mousePos = scaledPoint; - m_prevMousePos = m_mousePos; - - HideCursor(); - - // we can't capture the mouse here, or it will stop the popup menu - // when the mouse is released. -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnRButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto scaledPoint = WidgetToViewport(point); - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Right), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::Up)); - - m_bInRotateMode = false; - m_bInZoomMode = false; - - ReleaseMouse(); - - if (!m_bInMoveMode) - { - ShowCursor(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnMButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto scaledPoint = WidgetToViewport(point); - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Middle), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - if (RenderViewportUtil::AllowPan(modifiers)) - { - m_bInMoveMode = true; - - // mouse buttons are treated as keys as well - if (m_pressedKeyState == KeyPressedState::AllUp) - { - m_pressedKeyState = KeyPressedState::PressedThisFrame; - } - - m_mousePos = scaledPoint; - m_prevMousePos = scaledPoint; - - HideCursor(); - CaptureMouse(); - } - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::Down)); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnMButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto scaledPoint = WidgetToViewport(point); - UpdateCurrentMousePos(scaledPoint); - - const auto tryRestoreMouse = [this] - { - // if we are currently looking (rotateMode) or dollying (zoomMode) - // do not show the cursor on mouse up as rmb is still held - if (!m_bInZoomMode && !m_bInRotateMode) - { - ReleaseMouse(); - ShowCursor(); - } - }; - - if (m_bInMoveMode) - { - m_bInMoveMode = false; - tryRestoreMouse(); - } - - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::Middle), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::Up)); -} - -void CRenderViewport::OnMouseMove(Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto scaledPoint = WidgetToViewport(point); - - const auto mouseInteraction = BuildMouseInteractionInternal( - BuildMouseButtons(buttons), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( - AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, MouseEvent::Move)); -} - -void CRenderViewport::InjectFakeMouseMove(int deltaX, int deltaY, Qt::MouseButtons buttons) -{ - // this is required, otherwise the user will see the context menu - OnMouseMove(Qt::NoModifier, buttons, QCursor::pos() + QPoint(deltaX, deltaY)); - // we simply move the prev mouse position, so the change will be picked up - // by the next ProcessMouse call - m_prevMousePos -= QPoint(deltaX, deltaY); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ProcessMouse() -{ - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto point = WidgetToViewport(mapFromGlobal(QCursor::pos())); - - if (point == m_prevMousePos) - { - return; - } - - // specifically for the right mouse button click, which triggers rotate or zoom, - // we can't capture the mouse until the user has moved the mouse, otherwise the - // right click context menu won't popup - if (!m_mouseCaptured && (m_bInZoomMode || m_bInRotateMode)) - { - if ((point - m_mousePos).manhattanLength() > QApplication::startDragDistance()) - { - CaptureMouse(); - } - } - - float speedScale = GetCameraMoveSpeed(); - - if (CheckVirtualKey(Qt::Key_Control)) - { - speedScale *= gSettings.cameraFastMoveSpeed; - } - - if (m_PlayerControl) - { - if (m_bInRotateMode) - { - f32 MousedeltaX = (m_mousePos.x() - point.x()); - f32 MousedeltaY = (m_mousePos.y() - point.y()); - m_relCameraRotZ += MousedeltaX; - - if (GetCameraInvertYRotation()) - { - MousedeltaY = -MousedeltaY; - } - m_relCameraRotZ += MousedeltaX; - m_relCameraRotX += MousedeltaY; - - ResetCursor(); - } - } - else if ((m_bInRotateMode && m_bInMoveMode) || m_bInZoomMode) - { - // Zoom. - Matrix34 m = GetViewTM(); - - Vec3 ydir = m.GetColumn1().GetNormalized(); - Vec3 pos = m.GetTranslation(); - - const float posDelta = 0.2f * (m_prevMousePos.y() - point.y()) * speedScale; - pos = pos - ydir * posDelta; - m_orbitDistance = m_orbitDistance + posDelta; - m_orbitDistance = fabs(m_orbitDistance); - - m.SetTranslation(pos); - SetViewTM(m); - - ResetCursor(); - } - else if (m_bInRotateMode) - { - Ang3 angles(-point.y() + m_prevMousePos.y(), 0, -point.x() + m_prevMousePos.x()); - angles = angles * 0.002f * GetCameraRotateSpeed(); - if (GetCameraInvertYRotation()) - { - angles.x = -angles.x; - } - Matrix34 camtm = GetViewTM(); - Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(camtm)); - ypr.x += angles.z; - ypr.y += angles.x; - - ypr.y = CLAMP(ypr.y, -1.5f, 1.5f); // to keep rotation in reasonable range - // In the recording mode of a custom camera, the z rotation is allowed. - if (GetCameraObject() == nullptr || (!GetIEditor()->GetAnimation()->IsRecordMode() && !IsCameraObjectMove())) - { - ypr.z = 0; // to have camera always upward - } - - camtm = Matrix34(CCamera::CreateOrientationYPR(ypr), camtm.GetTranslation()); - SetViewTM(camtm); - - ResetCursor(); - } - else if (m_bInMoveMode) - { - // Slide. - Matrix34 m = GetViewTM(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - Vec3 zdir = m.GetColumn2().GetNormalized(); - - const auto modifiers = QGuiApplication::queryKeyboardModifiers(); - if (RenderViewportUtil::InvertPan(modifiers)) - { - xdir = -xdir; - zdir = -zdir; - } - - Vec3 pos = m.GetTranslation(); - pos += 0.1f * xdir * (point.x() - m_prevMousePos.x()) * speedScale + 0.1f * zdir * (m_prevMousePos.y() - point.y()) * speedScale; - m.SetTranslation(pos); - SetViewTM(m, true); - - ResetCursor(); - } - else if (m_bInOrbitMode) - { - Ang3 angles(-point.y() + m_prevMousePos.y(), 0, -point.x() + m_prevMousePos.x()); - angles = angles * 0.002f * GetCameraRotateSpeed(); - - if (GetCameraInvertPan()) - { - angles.z = -angles.z; - } - - Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(GetViewTM())); - ypr.x += angles.z; - ypr.y = CLAMP(ypr.y, -1.5f, 1.5f); // to keep rotation in reasonable range - ypr.y += angles.x; - - Matrix33 rotateTM = CCamera::CreateOrientationYPR(ypr); - - Vec3 src = GetViewTM().GetTranslation(); - Vec3 trg = m_orbitTarget; - float fCameraRadius = (trg - src).GetLength(); - - // Calc new source. - src = trg - rotateTM * Vec3(0, 1, 0) * fCameraRadius; - Matrix34 camTM = rotateTM; - camTM.SetTranslation(src); - - SetViewTM(camTM); - - ResetCursor(); - } -} - -void CRenderViewport::ResetCursor() -{ -#ifdef AZ_PLATFORM_WINDOWS - if (!gSettings.stylusMode) - { - const QPoint point = mapToGlobal(ViewportToWidget(m_prevMousePos)); - AzQtComponents::SetCursorPos(point); - } -#endif - - // Recalculate the prev mouse pos even if we just reset to it to avoid compounding floating point math issues with DPI scaling - m_prevMousePos = WidgetToViewport(mapFromGlobal(QCursor::pos())); -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::event(QEvent* event) -{ - switch (event->type()) - { - case QEvent::WindowActivate: - GetIEditor()->GetViewManager()->SelectViewport(this); - // also kill the keys; if we alt-tab back to the viewport, or come back from the debugger, it's done (and there's no guarantee we'll get the keyrelease event anyways) - m_keyDown.clear(); - break; - - case QEvent::Shortcut: - // a shortcut should immediately clear us, otherwise the release event never gets sent - m_keyDown.clear(); - break; - - case QEvent::ShortcutOverride: - { - // since we respond to the following things, let Qt know so that shortcuts don't override us - bool respondsToEvent = false; - - auto keyEvent = static_cast(event); - bool manipulatorInteracting = false; - AzToolsFramework::ManipulatorManagerRequestBus::EventResult( - manipulatorInteracting, - AzToolsFramework::g_mainManipulatorManagerId, - &AzToolsFramework::ManipulatorManagerRequestBus::Events::Interacting); - - // If a manipulator is active, stop all shortcuts from working, except for the escape key, which cancels in some cases - if ((keyEvent->key() != Qt::Key_Escape) && manipulatorInteracting) - { - respondsToEvent = true; - } - else - { - // In game mode we never want to be overridden by shortcuts - if (GetIEditor()->IsInGameMode() && GetType() == ET_ViewportCamera) - { - respondsToEvent = true; - } - else - { - if (!(keyEvent->modifiers() & Qt::ControlModifier)) - { - switch (keyEvent->key()) - { - case Qt::Key_Up: - case Qt::Key_W: - case Qt::Key_Down: - case Qt::Key_S: - case Qt::Key_Left: - case Qt::Key_A: - case Qt::Key_Right: - case Qt::Key_D: - respondsToEvent = true; - break; - - default: - break; - } - } - } - } - - if (respondsToEvent) - { - event->accept(); - return true; - } - - // because we're doing keyboard grabs, we need to detect - // when a shortcut matched so that we can track the buttons involved - // in the shortcut, since the key released event won't be generated in that case - ProcessKeyRelease(keyEvent); - } - break; - default: - // do nothing - break; - } - - return QtViewport::event(event); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ResetContent() -{ - QtViewport::ResetContent(); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::UpdateContent(int flags) -{ - QtViewport::UpdateContent(flags); - if (flags & eUpdateObjects) - { - m_bUpdateViewport = true; - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::Update() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - if (Editor::EditorQtApplication::instance()->isMovingOrResizing()) - { - return; - } - - if (!m_renderer || m_rcClient.isEmpty() || GetIEditor()->IsInMatEditMode()) - { - return; - } - - if (!isVisible()) - { - return; - } - - // Only send the resize event if the render overlay is visible. This is to make sure - // the native window has resized. - if (m_windowResizedEvent && isRenderOverlayVisible()) - { - AzFramework::WindowNotificationBus::Event(renderOverlayHWND(), &AzFramework::WindowNotificationBus::Handler::OnWindowResized, m_rcClient.width(), m_rcClient.height()); - m_windowResizedEvent = false; - } - - // Don't wait for changes to update the focused viewport. - if (CheckRespondToInput()) - { - m_bUpdateViewport = true; - } - - // While Renderer doesn't support fast rendering of the scene to more then 1 viewport - // render only focused viewport if more then 1 are opened and always update is off. - if (!m_isOnPaint && m_viewManager->GetNumberOfGameViewports() > 1 && GetType() == ET_ViewportCamera) - { - if (m_pPrimaryViewport != this) - { - if (CheckRespondToInput()) // If this is the focused window, set primary viewport. - { - m_pPrimaryViewport = this; - } - else if (!m_bUpdateViewport) // Skip this viewport. - { - return; - } - } - } - - if (CheckRespondToInput()) - { - ProcessMouse(); - ProcessKeys(); - } - - const bool isGameMode = GetIEditor()->IsInGameMode(); - const bool isSimulationMode = GetIEditor()->GetGameEngine()->GetSimulationMode(); - - // Allow debug visualization in both 'game' (Ctrl-G) and 'simulation' (Ctrl-P) modes - if (isGameMode || isSimulationMode) - { - if (!IsRenderingDisabled()) - { - // Disable rendering to avoid recursion into Update() - PushDisableRendering(); - - // draw debug visualizations - { - const AzFramework::DisplayContextRequestGuard displayContextGuard(m_displayContext); - - const AZ::u32 prevState = m_displayContext.GetState(); - m_displayContext.SetState( - e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOn | e_DepthTestOn); - - AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; - AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); - AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); - - AzFramework::DebugDisplayRequests* debugDisplay = - AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus); - - AzFramework::EntityDebugDisplayEventBus::Broadcast( - &AzFramework::EntityDebugDisplayEvents::DisplayEntityViewport, - AzFramework::ViewportInfo{ GetViewportId() }, *debugDisplay); - - m_displayContext.SetState(prevState); - } - - QtViewport::Update(); - PopDisableRendering(); - } - - // Game mode rendering is handled by CryAction - if (isGameMode) - { - return; - } - } - - // Prevents rendering recursion due to recursive Paint messages. - if (IsRenderingDisabled()) - { - return; - } - - PushDisableRendering(); - - m_viewTM = m_Camera.GetMatrix(); // synchronize. - - // Render - if (!m_bRenderContextCreated) - { - if (!CreateRenderContext()) - { - return; - } - } - - if (ed_visibility_use) - { - auto start = std::chrono::steady_clock::now(); - - m_entityVisibilityQuery.UpdateVisibility(GetCameraState()); - } - - { - SScopedCurrentContext context(this); - - m_renderer->SetClearColor(Vec3(0.4f, 0.4f, 0.4f)); - - InitDisplayContext(); - - OnRender(); - - ProcessRenderLisneters(m_displayContext); - - m_displayContext.Flush2D(); - - m_renderer->SwitchToNativeResolutionBackbuffer(); - - // 3D engine stats - - CCamera CurCamera = gEnv->pSystem->GetViewCamera(); - gEnv->pSystem->SetViewCamera(m_Camera); - - // Post Render Callback - { - PostRenderers::iterator itr = m_postRenderers.begin(); - PostRenderers::iterator end = m_postRenderers.end(); - for (; itr != end; ++itr) - { - (*itr)->OnPostRender(); - } - } - - gEnv->pSystem->SetViewCamera(CurCamera); - } - - QtViewport::Update(); - - PopDisableRendering(); - m_bUpdateViewport = false; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetViewEntity(const AZ::EntityId& viewEntityId, bool lockCameraMovement) -{ - // if they've picked the same camera, then that means they want to toggle - if (viewEntityId.IsValid() && viewEntityId != m_viewEntityId) - { - LockCameraMovement(lockCameraMovement); - m_viewEntityId = viewEntityId; - AZStd::string entityName; - AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, viewEntityId); - SetName(QString("Camera entity: %1").arg(entityName.c_str())); - } - else - { - SetDefaultCamera(); - } - - PostCameraSet(); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ResetToViewSourceType(const ViewSourceType& viewSourceType) -{ - LockCameraMovement(true); - m_pCameraFOVVariable = nullptr; - m_viewEntityId.SetInvalid(); - m_cameraObjectId = GUID_NULL; - m_viewSourceType = viewSourceType; - SetViewTM(GetViewTM()); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::PostCameraSet() -{ - if (m_viewPane) - { - m_viewPane->OnFOVChanged(GetFOV()); - } - - GetIEditor()->Notify(eNotify_CameraChanged); - QScopedValueRollback rb(m_ignoreSetViewFromEntityPerspective, true); - Camera::EditorCameraNotificationBus::Broadcast( - &Camera::EditorCameraNotificationBus::Events::OnViewportViewEntityChanged, m_viewEntityId); -} - -////////////////////////////////////////////////////////////////////////// -CBaseObject* CRenderViewport::GetCameraObject() const -{ - CBaseObject* pCameraObject = nullptr; - - if (m_viewSourceType == ViewSourceType::SequenceCamera) - { - m_cameraObjectId = GetViewManager()->GetCameraObjectId(); - } - if (m_cameraObjectId != GUID_NULL) - { - // Find camera object from id. - pCameraObject = GetIEditor()->GetObjectManager()->FindObject(m_cameraObjectId); - } - else if (m_viewSourceType == ViewSourceType::CameraComponent || m_viewSourceType == ViewSourceType::AZ_Entity) - { - AzToolsFramework::ComponentEntityEditorRequestBus::EventResult( - pCameraObject, m_viewEntityId, &AzToolsFramework::ComponentEntityEditorRequests::GetSandboxObject); - } - return pCameraObject; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnBeginGameMode: - { - if (GetIEditor()->GetViewManager()->GetGameViewport() == this) - { - m_preGameModeViewTM = GetViewTM(); - // this should only occur for the main viewport and no others. - ShowCursor(); - - // If the user has selected game mode, enable outputting to any attached HMD and properly size the context - // to the resolution specified by the VR device. - if (gSettings.bEnableGameModeVR) - { - const AZ::VR::HMDDeviceInfo* deviceInfo = nullptr; - EBUS_EVENT_RESULT(deviceInfo, AZ::VR::HMDDeviceRequestBus, GetDeviceInfo); - AZ_Warning("Render Viewport", deviceInfo, "No VR device detected"); - - if (deviceInfo) - { - m_previousContext = SetCurrentContext(deviceInfo->renderWidth, deviceInfo->renderHeight); - if (m_renderer->GetIStereoRenderer()) - { - m_renderer->GetIStereoRenderer()->OnResolutionChanged(); - } - SetActiveWindow(); - SetFocus(); - SetSelected(true); - } - } - else - { - m_previousContext = SetCurrentContext(); - } - SetCurrentCursor(STD_CURSOR_GAME); - } - } - break; - - case eNotify_OnEndGameMode: - if (GetIEditor()->GetViewManager()->GetGameViewport() == this) - { - SetCurrentCursor(STD_CURSOR_DEFAULT); - if (m_renderer->GetCurrentContextHWND() != renderOverlayHWND()) - { - // if this warning triggers it means that someone else (ie, some other part of the code) - // called SetCurrentContext(...) on the renderer, probably did some rendering, but then either - // failed to set the context back when done, or set it back to the wrong one. - CryWarning(VALIDATOR_MODULE_3DENGINE, VALIDATOR_WARNING, "RenderViewport render context was not correctly restored by someone else."); - } - RestorePreviousContext(m_previousContext); - m_bInRotateMode = false; - m_bInMoveMode = false; - m_bInOrbitMode = false; - m_bInZoomMode = false; - - RestoreViewportAfterGameMode(); - } - break; - - case eNotify_OnCloseScene: - SetDefaultCamera(); - break; - - case eNotify_OnBeginNewScene: - PushDisableRendering(); - break; - - case eNotify_OnEndNewScene: - PopDisableRendering(); - - { - // Default this to the size of default terrain in case there is no listener on the buss - AZ::Aabb terrainAabb = AZ::Aabb::CreateFromMinMaxValues(0, 0, 32, 1024, 1024, 32); - AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(terrainAabb, &AzFramework::Terrain::TerrainDataRequests::GetTerrainAabb); - float sx = terrainAabb.GetXExtent(); - float sy = terrainAabb.GetYExtent(); - - Matrix34 viewTM; - viewTM.SetIdentity(); - // Initial camera will be at middle of the map at the height of 2 - // meters above the terrain (default terrain height is 32) - viewTM.SetTranslation(Vec3(sx * 0.5f, sy * 0.5f, 34.0f)); - SetViewTM(viewTM); - } - break; - - case eNotify_OnBeginTerrainCreate: - PushDisableRendering(); - break; - - case eNotify_OnEndTerrainCreate: - PopDisableRendering(); - - { - // Default this to the size of default terrain in case there is no listener on the buss - AZ::Aabb terrainAabb = AZ::Aabb::CreateFromMinMaxValues(0, 0, 32, 1024, 1024, 32); - AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult(terrainAabb, &AzFramework::Terrain::TerrainDataRequests::GetTerrainAabb); - float sx = terrainAabb.GetXExtent(); - float sy = terrainAabb.GetYExtent(); - - Matrix34 viewTM; - viewTM.SetIdentity(); - // Initial camera will be at middle of the map at the height of 2 - // meters above the terrain (default terrain height is 32) - viewTM.SetTranslation(Vec3(sx * 0.5f, sy * 0.5f, 34.0f)); - SetViewTM(viewTM); - } - break; - - case eNotify_OnBeginLayerExport: - case eNotify_OnBeginSceneSave: - PushDisableRendering(); - break; - case eNotify_OnEndLayerExport: - case eNotify_OnEndSceneSave: - PopDisableRendering(); - break; - - case eNotify_OnBeginLoad: // disables viewport input when starting to load an existing level - case eNotify_OnBeginCreate: // disables viewport input when starting to create a new level - m_freezeViewportInput = true; - break; - - case eNotify_OnEndLoad: // enables viewport input when finished loading an existing level - case eNotify_OnEndCreate: // enables viewport input when finished creating a new level - m_freezeViewportInput = false; - break; - } -} - -////////////////////////////////////////////////////////////////////////// -namespace { - inline Vec3 NegY(const Vec3& v, float y) - { - return Vec3(v.x, y - v.y, v.z); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnRender() -{ - if (m_rcClient.isEmpty() || m_renderer->GetRenderType() == eRT_Null) // Null is crashing in CryEngine on macOS - { - // Even in null rendering, update the view camera. - // 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); - return; - } - - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - float fNearZ = GetIEditor()->GetConsoleVar("cl_DefaultNearPlane"); - float fFarZ = m_Camera.GetFarPlane(); - - CBaseObject* cameraObject = GetCameraObject(); - if (cameraObject) - { - AZ::Matrix3x3 lookThroughEntityCorrection = AZ::Matrix3x3::CreateIdentity(); - if (m_viewEntityId.IsValid()) - { - Camera::CameraRequestBus::EventResult(fNearZ, m_viewEntityId, &Camera::CameraComponentRequests::GetNearClipDistance); - Camera::CameraRequestBus::EventResult(fFarZ, m_viewEntityId, &Camera::CameraComponentRequests::GetFarClipDistance); - LmbrCentral::EditorCameraCorrectionRequestBus::EventResult( - lookThroughEntityCorrection, m_viewEntityId, - &LmbrCentral::EditorCameraCorrectionRequests::GetTransformCorrection); - } - - m_viewTM = cameraObject->GetWorldTM() * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection); - m_viewTM.OrthonormalizeFast(); - - m_Camera.SetMatrix(m_viewTM); - - int w = m_rcClient.width(); - int h = m_rcClient.height(); - - m_Camera.SetFrustum(w, h, GetFOV(), fNearZ, fFarZ); - } - else if (m_viewEntityId.IsValid()) - { - Camera::CameraRequestBus::EventResult(fNearZ, m_viewEntityId, &Camera::CameraComponentRequests::GetNearClipDistance); - Camera::CameraRequestBus::EventResult(fFarZ, m_viewEntityId, &Camera::CameraComponentRequests::GetFarClipDistance); - int w = m_rcClient.width(); - int h = m_rcClient.height(); - - m_Camera.SetFrustum(w, h, GetFOV(), fNearZ, fFarZ); - } - else - { - // Normal camera. - m_cameraObjectId = GUID_NULL; - int w = m_rcClient.width(); - int h = m_rcClient.height(); - - float fov = gSettings.viewports.fDefaultFov; - - // match viewport fov to default / selected title menu fov - if (GetFOV() != fov) - { - if (m_viewPane) - { - m_viewPane->OnFOVChanged(fov); - SetFOV(fov); - } - } - - // Just for editor: Aspect ratio fix when changing the viewport - if (!GetIEditor()->IsInGameMode()) - { - float viewportAspectRatio = float( w ) / h; - float targetAspectRatio = GetAspectRatio(); - if (targetAspectRatio > viewportAspectRatio) - { - // Correct for vertical FOV change. - float maxTargetHeight = float( w ) / targetAspectRatio; - fov = 2 * atanf((h * tan(fov / 2)) / maxTargetHeight); - } - } - - m_Camera.SetFrustum(w, h, fov, fNearZ); - } - - GetIEditor()->GetSystem()->SetViewCamera(m_Camera); - - CGameEngine* ge = GetIEditor()->GetGameEngine(); - - bool levelIsDisplayable = (ge && ge->IsLevelLoaded() && GetIEditor()->GetDocument() && GetIEditor()->GetDocument()->IsDocumentReady()); - - //Handle scene render tasks such as gizmos and handles but only when not in VR - if (!m_renderer->IsStereoEnabled()) - { - DisplayContext& displayContext = m_displayContext; - - PreWidgetRendering(); - - RenderAll(); - - // Draw 2D helpers. - TransformationMatrices backupSceneMatrices; - m_renderer->Set2DMode(m_rcClient.right(), m_rcClient.bottom(), backupSceneMatrices); - displayContext.SetState(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOn | e_DepthTestOn); - - // Display cursor string. - RenderCursorString(); - - if (gSettings.viewports.bShowSafeFrame) - { - UpdateSafeFrame(); - RenderSafeFrame(); - } - - const AzFramework::DisplayContextRequestGuard displayContextGuard(displayContext); - - AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; - AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); - AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); - - AzFramework::DebugDisplayRequests* debugDisplay = - AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus); - - AzFramework::ViewportDebugDisplayEventBus::Event( - AzToolsFramework::GetEntityContextId(), &AzFramework::ViewportDebugDisplayEvents::DisplayViewport2d, - AzFramework::ViewportInfo{ GetViewportId() }, *debugDisplay); - - m_renderer->Unset2DMode(backupSceneMatrices); - - PostWidgetRendering(); - } - - if (levelIsDisplayable) - { - m_renderer->SetViewport(0, 0, m_renderer->GetWidth(), m_renderer->GetHeight(), m_nCurViewportID); - } - else - { - ColorF viewportBackgroundColor(pow(71.0f / 255.0f, 2.2f), pow(71.0f / 255.0f, 2.2f), pow(71.0f / 255.0f, 2.2f)); - m_renderer->ClearTargetsLater(FRT_CLEAR_COLOR, viewportBackgroundColor); - DrawBackground(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderSelectionRectangle() -{ - if (m_selectedRect.isEmpty()) - { - return; - } - - Vec3 topLeft(m_selectedRect.left(), m_selectedRect.top(), 1); - Vec3 bottomRight(m_selectedRect.right() +1, m_selectedRect.bottom() + 1, 1); - - m_displayContext.DepthTestOff(); - m_displayContext.SetColor(1, 1, 1, 0.4f); - m_displayContext.DrawWireBox(topLeft, bottomRight); - m_displayContext.DepthTestOn(); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::InitDisplayContext() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - // Draw all objects. - DisplayContext& displayContext = m_displayContext; - displayContext.settings = GetIEditor()->GetDisplaySettings(); - displayContext.view = this; - displayContext.renderer = m_renderer; - displayContext.box.min = Vec3(-100000.0f, -100000.0f, -100000.0f); - displayContext.box.max = Vec3(100000.0f, 100000.0f, 100000.0f); - displayContext.camera = &m_Camera; - displayContext.flags = 0; - - if (!displayContext.settings->IsDisplayLabels() || !displayContext.settings->IsDisplayHelpers()) - { - displayContext.flags |= DISPLAY_HIDENAMES; - } - - if (displayContext.settings->IsDisplayLinks() && displayContext.settings->IsDisplayHelpers()) - { - displayContext.flags |= DISPLAY_LINKS; - } - - if (m_bDegradateQuality) - { - displayContext.flags |= DISPLAY_DEGRADATED; - } - - if (displayContext.settings->GetRenderFlags() & RENDER_FLAG_BBOX) - { - displayContext.flags |= DISPLAY_BBOX; - } - - if (displayContext.settings->IsDisplayTracks() && displayContext.settings->IsDisplayHelpers()) - { - displayContext.flags |= DISPLAY_TRACKS; - displayContext.flags |= DISPLAY_TRACKTICKS; - } - - if (GetIEditor()->GetReferenceCoordSys() == COORDS_WORLD) - { - displayContext.flags |= DISPLAY_WORLDSPACEAXIS; - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::PopulateEditorGlobalContextMenu(QMenu* /*menu*/, const AZ::Vector2& /*point*/, int /*flags*/) -{ - m_bInMoveMode = false; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderAll() -{ - // Draw all objects. - DisplayContext& displayContext = m_displayContext; - - m_renderer->ResetToDefault(); - - displayContext.SetState(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOn | e_DepthTestOn); - GetIEditor()->GetObjectManager()->Display(displayContext); - - RenderSelectedRegion(); - - RenderSnapMarker(); - - if (gSettings.viewports.bShowGridGuide - && GetIEditor()->GetDisplaySettings()->IsDisplayHelpers()) - { - RenderSnappingGrid(); - } - - if (displayContext.settings->GetDebugFlags() & DBG_MEMINFO) - { - ProcessMemInfo mi; - CProcessInfo::QueryMemInfo(mi); - int MB = 1024 * 1024; - QString str = QStringLiteral("WorkingSet=%1Mb, PageFile=%2Mb, PageFaults=%3").arg(mi.WorkingSet / MB).arg(mi.PagefileUsage / MB).arg(mi.PageFaultCount); - m_renderer->TextToScreenColor(1, 1, 1, 0, 0, 1, str.toUtf8().data()); - } - - { - const AzFramework::DisplayContextRequestGuard displayContextGuard(displayContext); - - AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; - AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); - AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); - - AzFramework::DebugDisplayRequests* debugDisplay = - AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus); - - // allow the override of in-editor visualization - AzFramework::ViewportDebugDisplayEventBus::Event( - AzToolsFramework::GetEntityContextId(), &AzFramework::ViewportDebugDisplayEvents::DisplayViewport, - AzFramework::ViewportInfo{ GetViewportId() }, *debugDisplay); - - m_entityVisibilityQuery.DisplayVisibility(*debugDisplay); - - if (m_manipulatorManager != nullptr) - { - using namespace AzToolsFramework::ViewportInteraction; - - debugDisplay->DepthTestOff(); - m_manipulatorManager->DrawManipulators( - *debugDisplay, GetCameraState(), - BuildMouseInteractionInternal( - MouseButtons(TranslateMouseButtons(QGuiApplication::mouseButtons())), - BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()), - BuildMousePickInternal(WidgetToViewport(mapFromGlobal(QCursor::pos()))))); - debugDisplay->DepthTestOn(); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::DrawAxis() -{ - AZ_Assert(m_cameraSetForWidgetRenderingCount > 0, - "DrawAxis was called but viewport widget rendering was not set. PreWidgetRendering must be called before."); - - DisplayContext& dc = m_displayContext; - - // show axis only if draw helpers is activated - if (!dc.settings->IsDisplayHelpers()) - { - return; - } - - Vec3 colX(1, 0, 0), colY(0, 1, 0), colZ(0, 0, 1), colW(1, 1, 1); - Vec3 pos(50, 50, 0.1f); // Bottom-left corner - - float wx, wy, wz; - m_renderer->UnProjectFromScreen(pos.x, pos.y, pos.z, &wx, &wy, &wz); - Vec3 posInWorld(wx, wy, wz); - float screenScale = GetScreenScaleFactor(posInWorld); - float length = 0.03f * screenScale; - float arrowSize = 0.02f * screenScale; - float textSize = 1.1f; - - Vec3 x(length, 0, 0); - Vec3 y(0, length, 0); - Vec3 z(0, 0, length); - - int prevRState = dc.GetState(); - dc.DepthWriteOff(); - dc.DepthTestOff(); - dc.CullOff(); - dc.SetLineWidth(1); - - dc.SetColor(colX); - dc.DrawLine(posInWorld, posInWorld + x); - dc.DrawArrow(posInWorld + x * 0.9f, posInWorld + x, arrowSize); - dc.SetColor(colY); - dc.DrawLine(posInWorld, posInWorld + y); - dc.DrawArrow(posInWorld + y * 0.9f, posInWorld + y, arrowSize); - dc.SetColor(colZ); - dc.DrawLine(posInWorld, posInWorld + z); - dc.DrawArrow(posInWorld + z * 0.9f, posInWorld + z, arrowSize); - - dc.SetColor(colW); - dc.DrawTextLabel(posInWorld + x, textSize, "x"); - dc.DrawTextLabel(posInWorld + y, textSize, "y"); - dc.DrawTextLabel(posInWorld + z, textSize, "z"); - - dc.DepthWriteOn(); - dc.DepthTestOn(); - dc.CullOn(); - dc.SetState(prevRState); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::DrawBackground() -{ - DisplayContext& dc = m_displayContext; - - if (!dc.settings->IsDisplayHelpers()) // show gradient bg only if draw helpers are activated - { - return; - } - - int heightVP = m_renderer->GetHeight() - 1; - int widthVP = m_renderer->GetWidth() - 1; - Vec3 pos(0, 0, 0); - - Vec3 x(widthVP, 0, 0); - Vec3 y(0, heightVP, 0); - - float height = m_rcClient.height(); - - Vec3 src = NegY(pos, height); - Vec3 trgx = NegY(pos + x, height); - Vec3 trgy = NegY(pos + y, height); - - QColor topColor = palette().color(QPalette::Window); - QColor bottomColor = palette().color(QPalette::Disabled, QPalette::WindowText); - - ColorB firstC(topColor.red(), topColor.green(), topColor.blue(), 255.0f); - ColorB secondC(bottomColor.red(), bottomColor.green(), bottomColor.blue(), 255.0f); - - TransformationMatrices backupSceneMatrices; - - m_renderer->Set2DMode(m_rcClient.right(), m_rcClient.bottom(), backupSceneMatrices); - m_displayContext.SetState(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOn | e_DepthTestOn); - dc.DrawQuadGradient(src, trgx, pos + x, pos, secondC, firstC); - m_renderer->Unset2DMode(backupSceneMatrices); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderCursorString() -{ - if (m_cursorStr.isEmpty()) - { - return; - } - - const auto point = WidgetToViewport(mapFromGlobal(QCursor::pos())); - - // Display hit object name. - float col[4] = { 1, 1, 1, 1 }; - m_renderer->Draw2dLabel(point.x() + 12, point.y() + 4, 1.2f, col, false, "%s", m_cursorStr.toUtf8().data()); - - if (!m_cursorSupplementaryStr.isEmpty()) - { - float col2[4] = { 1, 1, 0, 1 }; - m_renderer->Draw2dLabel(point.x() + 12, point.y() + 4 + CURSOR_FONT_HEIGHT * 1.2f, 1.2f, col2, false, "%s", m_cursorSupplementaryStr.toUtf8().data()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::UpdateSafeFrame() -{ - m_safeFrame = m_rcClient; - - if (m_safeFrame.height() == 0) - { - return; - } - - const bool allowSafeFrameBiggerThanViewport = false; - - float safeFrameAspectRatio = float( m_safeFrame.width()) / m_safeFrame.height(); - float targetAspectRatio = GetAspectRatio(); - bool viewportIsWiderThanSafeFrame = (targetAspectRatio <= safeFrameAspectRatio); - if (viewportIsWiderThanSafeFrame || allowSafeFrameBiggerThanViewport) - { - float maxSafeFrameWidth = m_safeFrame.height() * targetAspectRatio; - float widthDifference = m_safeFrame.width() - maxSafeFrameWidth; - - m_safeFrame.setLeft(m_safeFrame.left() + widthDifference * 0.5); - m_safeFrame.setRight(m_safeFrame.right() - widthDifference * 0.5); - } - else - { - float maxSafeFrameHeight = m_safeFrame.width() / targetAspectRatio; - float heightDifference = m_safeFrame.height() - maxSafeFrameHeight; - - m_safeFrame.setTop(m_safeFrame.top() + heightDifference * 0.5); - m_safeFrame.setBottom(m_safeFrame.bottom() - heightDifference * 0.5); - } - - m_safeFrame.adjust(0, 0, -1, -1); // <-- aesthetic improvement. - - const float SAFE_ACTION_SCALE_FACTOR = 0.05f; - m_safeAction = m_safeFrame; - m_safeAction.adjust(m_safeFrame.width() * SAFE_ACTION_SCALE_FACTOR, m_safeFrame.height() * SAFE_ACTION_SCALE_FACTOR, - -m_safeFrame.width() * SAFE_ACTION_SCALE_FACTOR, -m_safeFrame.height() * SAFE_ACTION_SCALE_FACTOR); - - const float SAFE_TITLE_SCALE_FACTOR = 0.1f; - m_safeTitle = m_safeFrame; - m_safeTitle.adjust(m_safeFrame.width() * SAFE_TITLE_SCALE_FACTOR, m_safeFrame.height() * SAFE_TITLE_SCALE_FACTOR, - -m_safeFrame.width() * SAFE_TITLE_SCALE_FACTOR, -m_safeFrame.height() * SAFE_TITLE_SCALE_FACTOR); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderSafeFrame() -{ - RenderSafeFrame(m_safeFrame, 0.75f, 0.75f, 0, 0.8f); - RenderSafeFrame(m_safeAction, 0, 0.85f, 0.80f, 0.8f); - RenderSafeFrame(m_safeTitle, 0.80f, 0.60f, 0, 0.8f); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderSafeFrame(const QRect& frame, float r, float g, float b, float a) -{ - m_displayContext.SetColor(r, g, b, a); - - const int LINE_WIDTH = 2; - for (int i = 0; i < LINE_WIDTH; i++) - { - Vec3 topLeft(frame.left() + i, frame.top() + i, 0); - Vec3 bottomRight(frame.right() - i, frame.bottom() - i, 0); - m_displayContext.DrawWireBox(topLeft, bottomRight); - } -} - -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetAspectRatio() const -{ - return gSettings.viewports.fDefaultAspectRatio; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderSnapMarker() -{ - if (!gSettings.snap.markerDisplay) - { - return; - } - - QPoint point = QCursor::pos(); - ScreenToClient(point); - Vec3 p = MapViewToCP(point); - - DisplayContext& dc = m_displayContext; - - float fScreenScaleFactor = GetScreenScaleFactor(p); - - Vec3 x(1, 0, 0); - Vec3 y(0, 1, 0); - Vec3 z(0, 0, 1); - x = x * gSettings.snap.markerSize * fScreenScaleFactor * 0.1f; - y = y * gSettings.snap.markerSize * fScreenScaleFactor * 0.1f; - z = z * gSettings.snap.markerSize * fScreenScaleFactor * 0.1f; - - dc.SetColor(gSettings.snap.markerColor); - dc.DrawLine(p - x, p + x); - dc.DrawLine(p - y, p + y); - dc.DrawLine(p - z, p + z); - - point = WorldToView(p); - - int s = 8; - dc.DrawLine2d(point + QPoint(-s, -s), point + QPoint(s, -s), 0); - dc.DrawLine2d(point + QPoint(-s, s), point + QPoint(s, s), 0); - dc.DrawLine2d(point + QPoint(-s, -s), point + QPoint(-s, s), 0); - dc.DrawLine2d(point + QPoint(s, -s), point + QPoint(s, s), 0); -} - -////////////////////////////////////////////////////////////////////////// -static void OnMenuDisplayWireframe() -{ - ICVar* piVar(gEnv->pConsole->GetCVar("r_wireframe")); - int nRenderMode = piVar->GetIVal(); - if (nRenderMode != R_WIREFRAME_MODE) - { - piVar->Set(R_WIREFRAME_MODE); - } - else - { - piVar->Set(R_SOLID_MODE); - } -} - -////////////////////////////////////////////////////////////////////////// -static void OnMenuTargetAspectRatio(float aspect) -{ - gSettings.viewports.fDefaultAspectRatio = aspect; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnMenuResolutionCustom() -{ - CCustomResolutionDlg resDlg(width(), height(), parentWidget()); - if (resDlg.exec() == QDialog::Accepted) - { - ResizeView(resDlg.GetWidth(), resDlg.GetHeight()); - - const QString text = QString::fromLatin1("%1 x %2").arg(resDlg.GetWidth()).arg(resDlg.GetHeight()); - - QStringList customResPresets; - CViewportTitleDlg::LoadCustomPresets("ResPresets", "ResPresetFor2ndView", customResPresets); - CViewportTitleDlg::UpdateCustomPresets(text, customResPresets); - CViewportTitleDlg::SaveCustomPresets("ResPresets", "ResPresetFor2ndView", customResPresets); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnMenuCreateCameraEntityFromCurrentView() -{ - Camera::EditorCameraSystemRequestBus::Broadcast(&Camera::EditorCameraSystemRequests::CreateCameraEntityFromViewport); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnMenuSelectCurrentCamera() -{ - CBaseObject* pCameraObject = GetCameraObject(); - - if (pCameraObject && !pCameraObject->IsSelected()) - { - GetIEditor()->BeginUndo(); - IObjectManager* pObjectManager = GetIEditor()->GetObjectManager(); - pObjectManager->ClearSelection(); - pObjectManager->SelectObject(pCameraObject); - GetIEditor()->AcceptUndo("Select Current Camera"); - } -} - -static AzFramework::CameraState CameraStateFromCCamera( - const CCamera& camera, const float fov, const float width, const float height) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - AzFramework::CameraState state; - state.m_forward = LYVec3ToAZVec3(camera.GetViewdir()); - state.m_up = LYVec3ToAZVec3(camera.GetUp()); - state.m_side = state.m_forward.Cross(state.m_up); - state.m_position = LYVec3ToAZVec3(camera.GetPosition()); - state.m_fovOrZoom = fov; - state.m_nearClip = camera.GetNearPlane(); - state.m_farClip = camera.GetFarPlane(); - state.m_orthographic = false; - state.m_viewportSize = AZ::Vector2(width, height); - - return state; -} - -AzFramework::CameraState CRenderViewport::GetCameraState() -{ - return CameraStateFromCCamera(GetCamera(), GetFOV(), m_rcClient.width(), m_rcClient.height()); -} - -bool CRenderViewport::GridSnappingEnabled() -{ - return false; -} - -float CRenderViewport::GridSize() -{ - return 0.0f; -} - -bool CRenderViewport::ShowGrid() -{ - return false; -} - -bool CRenderViewport::AngleSnappingEnabled() -{ - return false; -} - -float CRenderViewport::AngleStep() -{ - return 0.0f; -} - -AZ::Vector3 CRenderViewport::PickTerrain(const AzFramework::ScreenPoint& point) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - return LYVec3ToAZVec3(ViewToWorld(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), nullptr, true)); -} - -AZ::EntityId CRenderViewport::PickEntity(const AzFramework::ScreenPoint& point) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - PreWidgetRendering(); - - AZ::EntityId entityId; - HitContext hitInfo; - hitInfo.view = this; - if (HitTest(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), hitInfo)) - { - if (hitInfo.object && (hitInfo.object->GetType() == OBJTYPE_AZENTITY)) - { - auto entityObject = static_cast(hitInfo.object); - entityId = entityObject->GetAssociatedEntityId(); - } - } - - PostWidgetRendering(); - - return entityId; -} - -float CRenderViewport::TerrainHeight(const AZ::Vector2& position) -{ - return GetIEditor()->GetTerrainElevation(position.GetX(), position.GetY()); -} - -void CRenderViewport::FindVisibleEntities(AZStd::vector& visibleEntitiesOut) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - if (ed_visibility_use) - { - visibleEntitiesOut.assign(m_entityVisibilityQuery.Begin(), m_entityVisibilityQuery.End()); - } - else - { - if (m_displayContext.GetView() == nullptr) - { - return; - } - - const AZStd::vector& entityIdCache = - m_displayContext.GetView()->GetVisibleObjectsCache()->GetEntityIdCache(); - - visibleEntitiesOut.assign(entityIdCache.begin(), entityIdCache.end()); - } -} - -AzFramework::ScreenPoint CRenderViewport::ViewportWorldToScreen(const AZ::Vector3& worldPosition) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - PreWidgetRendering(); - const AzFramework::ScreenPoint screenPosition = - AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(WorldToView(AZVec3ToLYVec3(worldPosition))); - PostWidgetRendering(); - - return screenPosition; -} - -bool CRenderViewport::IsViewportInputFrozen() -{ - return m_freezeViewportInput; -} - -void CRenderViewport::FreezeViewportInput(bool freeze) -{ - m_freezeViewportInput = freeze; -} - -QWidget* CRenderViewport::GetWidgetForViewportContextMenu() -{ - return this; -} - -void CRenderViewport::BeginWidgetContext() -{ - PreWidgetRendering(); -} - -void CRenderViewport::EndWidgetContext() -{ - PostWidgetRendering(); -} - -bool CRenderViewport::ShowingWorldSpace() -{ - using namespace AzToolsFramework::ViewportInteraction; - return BuildKeyboardModifiers(QGuiApplication::queryKeyboardModifiers()).Shift(); -} - -void CRenderViewport::SetWindowTitle(const AZStd::string& title) -{ - // Do not support the WindowRequestBus changing the editor window title - AZ_UNUSED(title); -} - -AzFramework::WindowSize CRenderViewport::GetClientAreaSize() const -{ - return AzFramework::WindowSize(m_rcClient.width(), m_rcClient.height()); -} - - -void CRenderViewport::ResizeClientArea(AzFramework::WindowSize clientAreaSize) -{ - QWidget* window = this->window(); - window->resize(aznumeric_cast(clientAreaSize.m_width), aznumeric_cast(clientAreaSize.m_height)); -} - -bool CRenderViewport::GetFullScreenState() const -{ - // CRenderViewport does not currently support full screen. - return false; -} - -void CRenderViewport::SetFullScreenState([[maybe_unused]]bool fullScreenState) -{ - // CRenderViewport does not currently support full screen. -} - -bool CRenderViewport::CanToggleFullScreenState() const -{ - // CRenderViewport does not currently support full screen. - return false; -} - -void CRenderViewport::ToggleFullScreenState() -{ - // CRenderViewport does not currently support full screen. -} - -void CRenderViewport::ConnectViewportInteractionRequestBus() -{ - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler::BusConnect(GetViewportId()); - AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); - AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); - m_viewportUi.ConnectViewportUiBus(GetViewportId()); - - AzFramework::InputSystemCursorConstraintRequestBus::Handler::BusConnect(); -} - -void CRenderViewport::DisconnectViewportInteractionRequestBus() -{ - AzFramework::InputSystemCursorConstraintRequestBus::Handler::BusDisconnect(); - - m_viewportUi.DisconnectViewportUiBus(); - AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusDisconnect(); - AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler::BusDisconnect(); - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler::BusDisconnect(); -} - -////////////////////////////////////////////////////////////////////////// -static void ToggleBool(bool* variable, bool* disableVariableIfOn) -{ - *variable = !*variable; - if (*variable && disableVariableIfOn) - { - *disableVariableIfOn = false; - } -} - -////////////////////////////////////////////////////////////////////////// -static void ToggleInt(int* variable) -{ - *variable = !*variable; -} - -////////////////////////////////////////////////////////////////////////// -static void AddCheckbox(QMenu* menu, const QString& text, bool* variable, bool* disableVariableIfOn = nullptr) -{ - QAction* action = menu->addAction(text); - QObject::connect(action, &QAction::triggered, action, [variable, disableVariableIfOn] { ToggleBool(variable, disableVariableIfOn); - }); - action->setCheckable(true); - action->setChecked(*variable); -} - -////////////////////////////////////////////////////////////////////////// -static void AddCheckbox(QMenu* menu, const QString& text, int* variable) -{ - QAction* action = menu->addAction(text); - QObject::connect(action, &QAction::triggered, action, [variable] { ToggleInt(variable); - }); - action->setCheckable(true); - action->setChecked(*variable); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnTitleMenu(QMenu* menu) -{ - const int nWireframe = gEnv->pConsole->GetCVar("r_wireframe")->GetIVal(); - QAction* action = menu->addAction(tr("Wireframe")); - connect(action, &QAction::triggered, action, OnMenuDisplayWireframe); - action->setCheckable(true); - action->setChecked(nWireframe == R_WIREFRAME_MODE); - - const bool bDisplayLabels = GetIEditor()->GetDisplaySettings()->IsDisplayLabels(); - action = menu->addAction(tr("Labels")); - connect(action, &QAction::triggered, this, [bDisplayLabels] {GetIEditor()->GetDisplaySettings()->DisplayLabels(!bDisplayLabels); - }); - action->setCheckable(true); - action->setChecked(bDisplayLabels); - - AddCheckbox(menu, tr("Show Safe Frame"), &gSettings.viewports.bShowSafeFrame); - AddCheckbox(menu, tr("Show Construction Plane"), &gSettings.snap.constructPlaneDisplay); - AddCheckbox(menu, tr("Show Trigger Bounds"), &gSettings.viewports.bShowTriggerBounds); - AddCheckbox(menu, tr("Show Icons"), &gSettings.viewports.bShowIcons, &gSettings.viewports.bShowSizeBasedIcons); - AddCheckbox(menu, tr("Show Size-based Icons"), &gSettings.viewports.bShowSizeBasedIcons, &gSettings.viewports.bShowIcons); - AddCheckbox(menu, tr("Show Helpers of Frozen Objects"), &gSettings.viewports.nShowFrozenHelpers); - - if (!m_predefinedAspectRatios.IsEmpty()) - { - QMenu* aspectRatiosMenu = menu->addMenu(tr("Target Aspect Ratio")); - - for (size_t i = 0; i < m_predefinedAspectRatios.GetCount(); ++i) - { - const QString& aspectRatioString = m_predefinedAspectRatios.GetName(i); - QAction* aspectRatioAction = aspectRatiosMenu->addAction(aspectRatioString); - connect(aspectRatioAction, &QAction::triggered, this, [i, this] { OnMenuTargetAspectRatio(m_predefinedAspectRatios.GetValue(i)); - }); - aspectRatioAction->setCheckable(true); - aspectRatioAction->setChecked(m_predefinedAspectRatios.IsCurrent(i)); - } - } - - // Set ourself as the active viewport so the following actions create a camera from this view - GetIEditor()->GetViewManager()->SelectViewport(this); - - CGameEngine* gameEngine = GetIEditor()->GetGameEngine(); - - if (Camera::EditorCameraSystemRequestBus::HasHandlers()) - { - action = menu->addAction(tr("Create camera entity from current view")); - connect(action, &QAction::triggered, this, &CRenderViewport::OnMenuCreateCameraEntityFromCurrentView); - - if (!gameEngine || !gameEngine->IsLevelLoaded()) - { - action->setEnabled(false); - action->setToolTip(tr(TextCantCreateCameraNoLevel)); - menu->setToolTipsVisible(true); - } - } - - if (!gameEngine || !gameEngine->IsLevelLoaded()) - { - action->setEnabled(false); - action->setToolTip(tr(TextCantCreateCameraNoLevel)); - menu->setToolTipsVisible(true); - } - - if (GetCameraObject()) - { - action = menu->addAction(tr("Select Current Camera")); - connect(action, &QAction::triggered, this, &CRenderViewport::OnMenuSelectCurrentCamera); - } - - // Add Cameras. - bool bHasCameras = AddCameraMenuItems(menu); - CRenderViewport* pFloatingViewport = nullptr; - - if (GetIEditor()->GetViewManager()->GetViewCount() > 1) - { - for (int i = 0; i < GetIEditor()->GetViewManager()->GetViewCount(); ++i) - { - CViewport* vp = GetIEditor()->GetViewManager()->GetView(i); - if (!vp) - { - continue; - } - - if (viewport_cast(vp) == nullptr) - { - continue; - } - - if (vp->GetViewportId() == MAX_NUM_VIEWPORTS - 1) - { - menu->addSeparator(); - - QMenu* floatViewMenu = menu->addMenu(tr("Floating View")); - - pFloatingViewport = (CRenderViewport*)vp; - pFloatingViewport->AddCameraMenuItems(floatViewMenu); - - if (bHasCameras) - { - floatViewMenu->addSeparator(); - } - - QMenu* resolutionMenu = floatViewMenu->addMenu(tr("Resolution")); - - QStringList customResPresets; - CViewportTitleDlg::LoadCustomPresets("ResPresets", "ResPresetFor2ndView", customResPresets); - CViewportTitleDlg::AddResolutionMenus(resolutionMenu, [this](int width, int height) { ResizeView(width, height); }, customResPresets); - if (!resolutionMenu->actions().isEmpty()) - { - resolutionMenu->addSeparator(); - } - QAction* customResolutionAction = resolutionMenu->addAction(tr("Custom...")); - connect(customResolutionAction, &QAction::triggered, this, &CRenderViewport::OnMenuResolutionCustom); - break; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::AddCameraMenuItems(QMenu* menu) -{ - if (!menu->isEmpty()) - { - menu->addSeparator(); - } - - AddCheckbox(menu, "Lock Camera Movement", &m_bLockCameraMovement); - menu->addSeparator(); - - // Camera Sub menu - QMenu* customCameraMenu = menu->addMenu(tr("Camera")); - - QAction* action = customCameraMenu->addAction("Editor Camera"); - action->setCheckable(true); - action->setChecked(m_viewSourceType == ViewSourceType::None); - connect(action, &QAction::triggered, this, &CRenderViewport::SetDefaultCamera); - - AZ::EBusAggregateResults getCameraResults; - Camera::CameraBus::BroadcastResult(getCameraResults, &Camera::CameraRequests::GetCameras); - - const int numCameras = static_cast(getCameraResults.values.size()); - - // only enable if we're editing a sequence in Track View and have cameras in the level - bool enableSequenceCameraMenu = (GetIEditor()->GetAnimation()->GetSequence() && numCameras); - - action = customCameraMenu->addAction(tr("Sequence Camera")); - action->setCheckable(true); - action->setChecked(m_viewSourceType == ViewSourceType::SequenceCamera); - action->setEnabled(enableSequenceCameraMenu); - connect(action, &QAction::triggered, this, &CRenderViewport::SetSequenceCamera); - - QVector additionalCameras; - additionalCameras.reserve(static_cast(getCameraResults.values.size())); - - for (const AZ::EntityId& entityId : getCameraResults.values) - { - AZStd::string entityName; - AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, entityId); - action = new QAction(QString(entityName.c_str()), nullptr); - additionalCameras.append(action); - action->setCheckable(true); - action->setChecked(m_viewEntityId == entityId && m_viewSourceType == ViewSourceType::CameraComponent); - connect(action, &QAction::triggered, this, [this, entityId](bool isChecked) - { - if (isChecked) - { - SetComponentCamera(entityId); - } - else - { - SetDefaultCamera(); - } - }); - } - - std::sort(additionalCameras.begin(), additionalCameras.end(), [] (QAction* a1, QAction* a2) { - return QString::compare(a1->text(), a2->text(), Qt::CaseInsensitive) < 0; - }); - - for (QAction* cameraAction : additionalCameras) - { - customCameraMenu->addAction(cameraAction); - } - - action = customCameraMenu->addAction(tr("Look through entity")); - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - action->setCheckable(selectedEntityList.size() > 0 || m_viewSourceType == ViewSourceType::AZ_Entity); - action->setEnabled(selectedEntityList.size() > 0 || m_viewSourceType == ViewSourceType::AZ_Entity); - action->setChecked(m_viewSourceType == ViewSourceType::AZ_Entity); - connect(action, &QAction::triggered, this, [this](bool isChecked) - { - if (isChecked) - { - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - if (selectedEntityList.size()) - { - SetEntityAsCamera(*selectedEntityList.begin()); - } - } - else - { - SetDefaultCamera(); - } - }); - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ResizeView(int width, int height) -{ - const QRect rView = rect().translated(mapToGlobal(QPoint())); - int deltaWidth = width - rView.width(); - int deltaHeight = height - rView.height(); - - if (window()->isFullScreen()) - { - setGeometry(rView.left(), rView.top(), rView.width() + deltaWidth, rView.height() + deltaHeight); - } - else - { - QWidget* window = this->window(); - if (window->isMaximized()) - { - window->showNormal(); - } - - const QSize deltaSize = QSize(width, height) - size(); - window->move(0, 0); - window->resize(window->size() + deltaSize); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ToggleCameraObject() -{ - if (m_viewSourceType == ViewSourceType::SequenceCamera) - { - ResetToViewSourceType(ViewSourceType::LegacyCamera); - } - else - { - ResetToViewSourceType(ViewSourceType::SequenceCamera); - } - PostCameraSet(); - GetIEditor()->GetAnimation()->ForceAnimation(); -} - -void CRenderViewport::OnMouseWheel(Qt::KeyboardModifiers modifiers, short zDelta, const QPoint& point) -{ - using namespace AzToolsFramework::ViewportInteraction; - using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; - - if (GetIEditor()->IsInGameMode() || m_freezeViewportInput) - { - return; - } - - const auto scaledPoint = WidgetToViewport(point); - const auto mouseInteraction = BuildMouseInteractionInternal( - MouseButtonsFromButton(MouseButton::None), - BuildKeyboardModifiers(modifiers), - BuildMousePick(scaledPoint)); - - bool handled = false; - MouseInteractionResult result = MouseInteractionResult::None; - AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::EventResult( - result, AzToolsFramework::GetEntityContextId(), - &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleAllMouseInteractions, - MouseInteractionEvent(mouseInteraction, zDelta)); - - handled = result != MouseInteractionResult::None; - - if (!handled) - { - Matrix34 m = GetViewTM(); - const Vec3 ydir = m.GetColumn1().GetNormalized(); - - Vec3 pos = m.GetTranslation(); - - const float posDelta = 0.01f * zDelta * gSettings.wheelZoomSpeed; - pos += ydir * posDelta; - m_orbitDistance = m_orbitDistance - posDelta; - m_orbitDistance = fabs(m_orbitDistance); - - m.SetTranslation(pos); - SetViewTM(m, true); - - QtViewport::OnMouseWheel(modifiers, zDelta, scaledPoint); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetCamera(const CCamera& camera) -{ - m_Camera = camera; - SetViewTM(m_Camera.GetMatrix()); -} - -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetCameraMoveSpeed() const -{ - return gSettings.cameraMoveSpeed; -} - -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetCameraRotateSpeed() const -{ - return gSettings.cameraRotateSpeed; -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::GetCameraInvertYRotation() const -{ - return gSettings.invertYRotation; -} - -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetCameraInvertPan() const -{ - return gSettings.invertPan; -} - -////////////////////////////////////////////////////////////////////////// -CRenderViewport* CRenderViewport::GetPrimaryViewport() -{ - return m_pPrimaryViewport; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::focusOutEvent([[maybe_unused]] QFocusEvent* event) -{ - // if we lose focus, the keyboard map needs to be cleared immediately - if (!m_keyDown.isEmpty()) - { - m_keyDown.clear(); - - releaseKeyboard(); - } -} - -void CRenderViewport::keyPressEvent(QKeyEvent* event) -{ - // Special case Escape key and bubble way up to the top level parent so that it can cancel us out of any active tool - // or clear the current selection - if (event->key() == Qt::Key_Escape) - { - 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 - // because we want the movement to be butter smooth. - if (!event->isAutoRepeat()) - { - if (m_keyDown.isEmpty()) - { - grabKeyboard(); - } - - m_keyDown.insert(event->key()); - } - - QtViewport::keyPressEvent(event); - -#if defined(AZ_PLATFORM_WINDOWS) - // In game mode on windows we need to forward raw text events to the input system. - if (GetIEditor()->IsInGameMode() && GetType() == ET_ViewportCamera) - { - // Get the QString as a '\0'-terminated array of unsigned shorts. - // The result remains valid until the string is modified. - const ushort* codeUnitsUTF16 = event->text().utf16(); - while (ushort codeUnitUTF16 = *codeUnitsUTF16) - { - AzFramework::RawInputNotificationBusWindows::Broadcast(&AzFramework::RawInputNotificationsWindows::OnRawInputCodeUnitUTF16Event, codeUnitUTF16); - ++codeUnitsUTF16; - } - } -#endif // defined(AZ_PLATFORM_WINDOWS) -} - -void CRenderViewport::ProcessKeyRelease(QKeyEvent* event) -{ - if (!event->isAutoRepeat()) - { - if (m_keyDown.contains(event->key())) - { - m_keyDown.remove(event->key()); - - if (m_keyDown.isEmpty()) - { - releaseKeyboard(); - } - } - } -} - -void CRenderViewport::keyReleaseEvent(QKeyEvent* event) -{ - ProcessKeyRelease(event); - - QtViewport::keyReleaseEvent(event); -} - -void CRenderViewport::SetViewTM(const Matrix34& viewTM, bool bMoveOnly) -{ - Matrix34 camMatrix = viewTM; - - // If no collision flag set do not check for terrain elevation. - if (GetType() == ET_ViewportCamera) - { - if ((GetIEditor()->GetDisplaySettings()->GetSettings() & SETTINGS_NOCOLLISION) == 0) - { - Vec3 p = camMatrix.GetTranslation(); - bool adjustCameraElevation = true; - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - if (terrain) - { - AZ::Aabb terrainAabb(terrain->GetTerrainAabb()); - - // Adjust the AABB to include all Z values. Since the goal here is to snap the camera to the terrain height if - // it's below the terrain, we only want to verify the camera is within the XY bounds of the terrain to adjust the elevation. - terrainAabb.SetMin(AZ::Vector3(terrainAabb.GetMin().GetX(), terrainAabb.GetMin().GetY(), -AZ::Constants::FloatMax)); - terrainAabb.SetMax(AZ::Vector3(terrainAabb.GetMax().GetX(), terrainAabb.GetMax().GetY(), AZ::Constants::FloatMax)); - - if (!terrainAabb.Contains(LYVec3ToAZVec3(p))) - { - adjustCameraElevation = false; - } - else if (terrain->GetIsHoleFromFloats(p.x, p.y)) - { - adjustCameraElevation = false; - } - } - - if (adjustCameraElevation) - { - float z = GetIEditor()->GetTerrainElevation(p.x, p.y); - if (p.z < z + 0.25) - { - p.z = z + 0.25; - camMatrix.SetTranslation(p); - } - } - } - - // Also force this position on game. - if (GetIEditor()->GetGameEngine()) - { - GetIEditor()->GetGameEngine()->SetPlayerViewMatrix(viewTM); - } - } - - CBaseObject* cameraObject = GetCameraObject(); - if (cameraObject) - { - // Ignore camera movement if locked. - if (IsCameraMovementLocked() || (!GetIEditor()->GetAnimation()->IsRecordMode() && !IsCameraObjectMove())) - { - return; - } - - AZ::Matrix3x3 lookThroughEntityCorrection = AZ::Matrix3x3::CreateIdentity(); - if (m_viewEntityId.IsValid()) - { - LmbrCentral::EditorCameraCorrectionRequestBus::EventResult( - lookThroughEntityCorrection, m_viewEntityId, - &LmbrCentral::EditorCameraCorrectionRequests::GetInverseTransformCorrection); - } - - if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) - { - CUndo undo("Move Camera"); - if (bMoveOnly) - { - // specify eObjectUpdateFlags_UserInput so that an undo command gets logged - cameraObject->SetWorldPos(camMatrix.GetTranslation(), eObjectUpdateFlags_UserInput); - } - else - { - // specify eObjectUpdateFlags_UserInput so that an undo command gets logged - cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection), eObjectUpdateFlags_UserInput); - } - } - else - { - if (bMoveOnly) - { - // Do not specify eObjectUpdateFlags_UserInput, so that an undo command does not get logged; we covered it already when m_pressedKeyState was PressedThisFrame - cameraObject->SetWorldPos(camMatrix.GetTranslation()); - } - else - { - // Do not specify eObjectUpdateFlags_UserInput, so that an undo command does not get logged; we covered it already when m_pressedKeyState was PressedThisFrame - cameraObject->SetWorldTM(camMatrix * AZMatrix3x3ToLYMatrix3x3(lookThroughEntityCorrection)); - } - } - - using namespace AzToolsFramework; - ComponentEntityObjectRequestBus::Event(cameraObject, &ComponentEntityObjectRequestBus::Events::UpdatePreemptiveUndoCache); - } - else if (m_viewEntityId.IsValid()) - { - // Ignore camera movement if locked. - if (IsCameraMovementLocked() || (!GetIEditor()->GetAnimation()->IsRecordMode() && !IsCameraObjectMove())) - { - return; - } - - if (m_pressedKeyState != KeyPressedState::PressedInPreviousFrame) - { - CUndo undo("Move Camera"); - if (bMoveOnly) - { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTranslation, - LYVec3ToAZVec3(camMatrix.GetTranslation())); - } - else - { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTM, - LYTransformToAZTransform(camMatrix)); - } - } - else - { - if (bMoveOnly) - { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTranslation, - LYVec3ToAZVec3(camMatrix.GetTranslation())); - } - else - { - AZ::TransformBus::Event( - m_viewEntityId, &AZ::TransformInterface::SetWorldTM, - LYTransformToAZTransform(camMatrix)); - } - } - - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast( - &AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, - AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); - } - - if (m_pressedKeyState == KeyPressedState::PressedThisFrame) - { - m_pressedKeyState = KeyPressedState::PressedInPreviousFrame; - } - - QtViewport::SetViewTM(camMatrix); - - m_Camera.SetMatrix(camMatrix); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderSelectedRegion() -{ - AABB box; - GetIEditor()->GetSelectedRegion(box); - if (box.IsEmpty()) - { - return; - } - - float x1 = box.min.x; - float y1 = box.min.y; - float x2 = box.max.x; - float y2 = box.max.y; - - DisplayContext& dc = m_displayContext; - - float fMaxSide = MAX(y2 - y1, x2 - x1); - if (fMaxSide < 0.1f) - { - return; - } - float fStep = fMaxSide / 100.0f; - - float fMinZ = 0; - float fMaxZ = 0; - - // Draw yellow border lines. - dc.SetColor(1, 1, 0, 1); - float offset = 0.01f; - Vec3 p1, p2; - - const float defaultTerrainHeight = AzFramework::Terrain::TerrainDataRequests::GetDefaultTerrainHeight(); - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - - for (float y = y1; y < y2; y += fStep) - { - p1.x = x1; - p1.y = y; - p1.z = terrain ? terrain->GetHeightFromFloats(p1.x, p1.y) + offset : defaultTerrainHeight + offset; - - p2.x = x1; - p2.y = y + fStep; - p2.z = terrain ? terrain->GetHeightFromFloats(p2.x, p2.y) + offset : defaultTerrainHeight + offset; - dc.DrawLine(p1, p2); - - p1.x = x2; - p1.y = y; - p1.z = terrain ? terrain->GetHeightFromFloats(p1.x, p1.y) + offset : defaultTerrainHeight + offset; - - p2.x = x2; - p2.y = y + fStep; - p2.z = terrain ? terrain->GetHeightFromFloats(p2.x, p2.y) + offset : defaultTerrainHeight + offset; - dc.DrawLine(p1, p2); - - fMinZ = min(fMinZ, min(p1.z, p2.z)); - fMaxZ = max(fMaxZ, max(p1.z, p2.z)); - } - for (float x = x1; x < x2; x += fStep) - { - p1.x = x; - p1.y = y1; - p1.z = terrain ? terrain->GetHeightFromFloats(p1.x, p1.y) + offset : defaultTerrainHeight + offset; - - p2.x = x + fStep; - p2.y = y1; - p2.z = terrain ? terrain->GetHeightFromFloats(p2.x, p2.y) + offset : defaultTerrainHeight + offset; - dc.DrawLine(p1, p2); - - p1.x = x; - p1.y = y2; - p1.z = terrain ? terrain->GetHeightFromFloats(p1.x, p1.y) + offset : defaultTerrainHeight + offset; - - p2.x = x + fStep; - p2.y = y2; - p2.z = terrain ? terrain->GetHeightFromFloats(p2.x, p2.y) + offset : defaultTerrainHeight + offset; - dc.DrawLine(p1, p2); - - fMinZ = min(fMinZ, min(p1.z, p2.z)); - fMaxZ = max(fMaxZ, max(p1.z, p2.z)); - } - - { - // Draw a box area - float fBoxOver = fMaxSide / 5.0f; - float fBoxHeight = fBoxOver + fMaxZ - fMinZ; - - ColorB boxColor(64, 64, 255, 128); // light blue - ColorB transparent(boxColor.r, boxColor.g, boxColor.b, 0); - - Vec3 base[] = { - Vec3(x1, y1, fMinZ), - Vec3(x2, y1, fMinZ), - Vec3(x2, y2, fMinZ), - Vec3(x1, y2, fMinZ) - }; - - - // Generate vertices - static AABB boxPrev(AABB::RESET); - static std::vector verts; - static std::vector colors; - - if (!IsEquivalent(boxPrev, box)) - { - verts.resize(0); - colors.resize(0); - for (int i = 0; i < 4; ++i) - { - Vec3& p = base[i]; - - verts.push_back(p); - verts.push_back(Vec3(p.x, p.y, p.z + fBoxHeight)); - verts.push_back(Vec3(p.x, p.y, p.z + fBoxHeight + fBoxOver)); - - colors.push_back(boxColor); - colors.push_back(boxColor); - colors.push_back(transparent); - } - boxPrev = box; - } - - // Generate indices - const int numInds = 4 * 12; - static vtx_idx inds[numInds]; - static bool bNeedIndsInit = true; - if (bNeedIndsInit) - { - vtx_idx* pInds = &inds[0]; - - for (int i = 0; i < 4; ++i) - { - int over = 0; - if (i == 3) - { - over = -12; - } - - int ind = i * 3; - *pInds++ = ind; - *pInds++ = ind + 3 + over; - *pInds++ = ind + 1; - - *pInds++ = ind + 1; - *pInds++ = ind + 3 + over; - *pInds++ = ind + 4 + over; - - ind = i * 3 + 1; - *pInds++ = ind; - *pInds++ = ind + 3 + over; - *pInds++ = ind + 1; - - *pInds++ = ind + 1; - *pInds++ = ind + 3 + over; - *pInds++ = ind + 4 + over; - } - bNeedIndsInit = false; - } - - // Draw lines - for (int i = 0; i < 4; ++i) - { - Vec3& p = base[i]; - - dc.DrawLine(p, Vec3(p.x, p.y, p.z + fBoxHeight), ColorF(1, 1, 0, 1), ColorF(1, 1, 0, 1)); - dc.DrawLine(Vec3(p.x, p.y, p.z + fBoxHeight), Vec3(p.x, p.y, p.z + fBoxHeight + fBoxOver), ColorF(1, 1, 0, 1), ColorF(1, 1, 0, 0)); - } - - // Draw volume - dc.DepthWriteOff(); - dc.CullOff(); - dc.pRenderAuxGeom->DrawTriangles(&verts[0], static_cast(verts.size()), &inds[0], numInds, &colors[0]); - dc.CullOn(); - dc.DepthWriteOn(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ProcessKeys() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - if (m_PlayerControl || GetIEditor()->IsInGameMode() || !CheckRespondToInput() || m_freezeViewportInput) - { - return; - } - - //m_Camera.UpdateFrustum(); - Matrix34 m = GetViewTM(); - Vec3 ydir = m.GetColumn1().GetNormalized(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - Vec3 zdir = m.GetColumn2().GetNormalized(); - - Vec3 pos = GetViewTM().GetTranslation(); - - float speedScale = AZStd::GetMin( - 60.0f * GetIEditor()->GetSystem()->GetITimer()->GetFrameTime(), 20.0f); - - speedScale *= GetCameraMoveSpeed(); - - // Use the global modifier keys instead of our keymap. It's more reliable. - const bool shiftPressed = QGuiApplication::queryKeyboardModifiers() & Qt::ShiftModifier; - const bool controlPressed = QGuiApplication::queryKeyboardModifiers() & Qt::ControlModifier; - - if (shiftPressed) - { - speedScale *= gSettings.cameraFastMoveSpeed; - } - - if (controlPressed) - { - return; - } - - bool bIsPressedSome = false; - - if (IsKeyDown(Qt::Key_Up) || IsKeyDown(Qt::Key_W)) - { - // move forward - bIsPressedSome = true; - pos = pos + (speedScale * m_moveSpeed * ydir); - } - - if (IsKeyDown(Qt::Key_Down) || IsKeyDown(Qt::Key_S)) - { - // move backward - bIsPressedSome = true; - pos = pos - (speedScale * m_moveSpeed * ydir); - } - - if (IsKeyDown(Qt::Key_Left) || IsKeyDown(Qt::Key_A)) - { - // move left - bIsPressedSome = true; - pos = pos - (speedScale * m_moveSpeed * xdir); - } - - if (IsKeyDown(Qt::Key_Right) || IsKeyDown(Qt::Key_D)) - { - // move right - bIsPressedSome = true; - pos = pos + (speedScale * m_moveSpeed * xdir); - } - - if (IsKeyDown(Qt::Key_E)) - { - // move Up - bIsPressedSome = true; - pos = pos + (speedScale * m_moveSpeed * zdir); - } - - if (IsKeyDown(Qt::Key_Q)) - { - // move down - bIsPressedSome = true; - pos = pos - (speedScale * m_moveSpeed * zdir); - } - - if (bIsPressedSome) - { - // Only change the keystate to pressed if it wasn't already marked in - // a previous frame. Otherwise, the undo/redo stack will be all off - // from what SetViewTM() does. - if (m_pressedKeyState == KeyPressedState::AllUp) - { - m_pressedKeyState = KeyPressedState::PressedThisFrame; - } - - m.SetTranslation(pos); - SetViewTM(m, true); - } - - bool mouseModifierKeysDown = ((QGuiApplication::mouseButtons() & (Qt::RightButton | Qt::MiddleButton)) != 0); - - if (!bIsPressedSome && !mouseModifierKeysDown) - { - m_pressedKeyState = KeyPressedState::AllUp; - } -} - -Vec3 CRenderViewport::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nFlags) const -{ - AZ_Assert(m_cameraSetForWidgetRenderingCount > 0, - "WorldToView3D was called but viewport widget rendering was not set. PreWidgetRendering must be called before."); - - Vec3 out(0, 0, 0); - float x, y, z; - - m_renderer->ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); - if (_finite(x) && _finite(y) && _finite(z)) - { - out.x = (x / 100) * m_rcClient.width(); - out.y = (y / 100) * m_rcClient.height(); - out.x /= QHighDpiScaling::factor(windowHandle()->screen()); - out.y /= QHighDpiScaling::factor(windowHandle()->screen()); - out.z = z; - } - return out; -} - -////////////////////////////////////////////////////////////////////////// -QPoint CRenderViewport::WorldToView(const Vec3& wp) const -{ - AZ_Assert(m_cameraSetForWidgetRenderingCount > 0, - "WorldToView was called but viewport widget rendering was not set. PreWidgetRendering must be called before."); - - QPoint p; - float x, y, z; - - m_renderer->ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); - if (_finite(x) || _finite(y)) - { - p.rx() = (x / 100) * m_rcClient.width(); - p.ry() = (y / 100) * m_rcClient.height(); - } - else - { - QPoint(0, 0); - } - - return p; -} -////////////////////////////////////////////////////////////////////////// -QPoint CRenderViewport::WorldToViewParticleEditor(const Vec3& wp, int width, int height) const -{ - QPoint p; - float x, y, z; - - m_renderer->ProjectToScreen(wp.x, wp.y, wp.z, &x, &y, &z); - if (_finite(x) || _finite(y)) - { - p.rx() = (x / 100) * width; - p.ry() = (y / 100) * height; - } - else - { - QPoint(0, 0); - } - return p; -} - -////////////////////////////////////////////////////////////////////////// -Vec3 CRenderViewport::ViewToWorld(const QPoint& vp, bool* collideWithTerrain, bool onlyTerrain, bool bSkipVegetation, bool bTestRenderMesh, bool* collideWithObject) const -{ - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); - - // Make sure we initialize the value if a pointer has been passed in - if (collideWithTerrain != nullptr) - { - *collideWithTerrain = false; - } - - // Make sure we initialize the value if a pointer has been passed in - if (collideWithObject != nullptr) -{ - *collideWithObject = false; - } - - if (!m_renderer) - { - return Vec3(0, 0, 0); - } - - QRect rc = m_rcClient; - - Vec3 pos0; - if (!m_Camera.Unproject(Vec3(vp.x(), rc.bottom() - vp.y(), 0), pos0)) - { - return Vec3(0, 0, 0); - } - if (!IsVectorInValidRange(pos0)) - { - pos0.Set(0, 0, 0); - } - - Vec3 pos1; - if (!m_Camera.Unproject(Vec3(vp.x(), rc.bottom() - vp.y(), 1), pos1)) - { - return Vec3(0, 0, 0); - } - if (!IsVectorInValidRange(pos1)) - { - pos1.Set(1, 0, 0); - } - - const float maxDistance = 10000.f; - - Vec3 v = (pos1 - pos0); - v = v.GetNormalized(); - v = v * maxDistance; - - if (!_finite(v.x) || !_finite(v.y) || !_finite(v.z)) - { - return Vec3(0, 0, 0); - } - - Vec3 colp = pos0 + 0.002f * v; - - AZ_UNUSED(vp) - AZ_UNUSED(bTestRenderMesh) - AZ_UNUSED(bSkipVegetation) - AZ_UNUSED(bSkipVegetation) - AZStd::optional> hitDistancePosition; - - if (!onlyTerrain && !GetIEditor()->IsTerrainAxisIgnoreObjects()) - { - AzFramework::EntityContextId editorContextId; - AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult( - editorContextId, &AzToolsFramework::EditorEntityContextRequests::GetEditorEntityContextId); - - AzFramework::RenderGeometry::RayRequest ray; - ray.m_startWorldPosition = LYVec3ToAZVec3(pos0); - ray.m_endWorldPosition = LYVec3ToAZVec3(pos0 + v); - ray.m_onlyVisible = true; - - AzFramework::RenderGeometry::RayResult result; - AzFramework::RenderGeometry::IntersectorBus::EventResult(result, editorContextId, - &AzFramework::RenderGeometry::IntersectorInterface::RayIntersect, ray); - - if (result) - { - if (!hitDistancePosition || result.m_distance < hitDistancePosition->first) - { - hitDistancePosition = {result.m_distance, result.m_worldPosition}; - if (collideWithObject) - { - *collideWithObject = true; - } - } - } - } - - if (hitDistancePosition) - { - colp = AZVec3ToLYVec3(hitDistancePosition->second); - } - - - return colp; -} - -////////////////////////////////////////////////////////////////////////// -Vec3 CRenderViewport::ViewToWorldNormal(const QPoint& vp, bool onlyTerrain, bool bTestRenderMesh) -{ - AZ_UNUSED(vp) - AZ_UNUSED(bTestRenderMesh) - - AZ_Assert(m_cameraSetForWidgetRenderingCount > 0, - "ViewToWorldNormal was called but viewport widget rendering was not set. PreWidgetRendering must be called before."); - - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); - - if (!m_renderer) - { - return Vec3(0, 0, 1); - } - - QRect rc = m_rcClient; - - Vec3 pos0, pos1; - float wx, wy, wz; - m_renderer->UnProjectFromScreen(vp.x(), rc.bottom() - vp.y(), 0, &wx, &wy, &wz); - if (!_finite(wx) || !_finite(wy) || !_finite(wz)) - { - return Vec3(0, 0, 1); - } - pos0(wx, wy, wz); - if (!IsVectorInValidRange(pos0)) - { - pos0.Set(0, 0, 0); - } - - m_renderer->UnProjectFromScreen(vp.x(), rc.bottom() - vp.y(), 1, &wx, &wy, &wz); - if (!_finite(wx) || !_finite(wy) || !_finite(wz)) - { - return Vec3(0, 0, 1); - } - pos1(wx, wy, wz); - - Vec3 v = (pos1 - pos0); - if (!IsVectorInValidRange(pos1)) - { - pos1.Set(1, 0, 0); - } - - const float maxDistance = 2000.f; - v = v.GetNormalized(); - v = v * maxDistance; - - if (!_finite(v.x) || !_finite(v.y) || !_finite(v.z)) - { - return Vec3(0, 0, 1); - } - - Vec3 colp(0, 0, 0); - - - AZStd::optional> hitDistanceNormal; - - if (!onlyTerrain && !GetIEditor()->IsTerrainAxisIgnoreObjects()) - { - AzFramework::EntityContextId editorContextId; - AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult( - editorContextId, &AzToolsFramework::EditorEntityContextRequests::GetEditorEntityContextId); - - AzFramework::RenderGeometry::RayRequest ray; - ray.m_startWorldPosition = LYVec3ToAZVec3(pos0); - ray.m_endWorldPosition = LYVec3ToAZVec3(pos0 + v); - ray.m_onlyVisible = true; - - AzFramework::RenderGeometry::RayResult result; - AzFramework::RenderGeometry::IntersectorBus::EventResult(result, editorContextId, - &AzFramework::RenderGeometry::IntersectorInterface::RayIntersect, ray); - - if (result) - { - if (!hitDistanceNormal || result.m_distance < hitDistanceNormal->first) - { - hitDistanceNormal = { result.m_distance, result.m_worldNormal }; - } - } - } - - return hitDistanceNormal ? AZVec3ToLYVec3(hitDistanceNormal->second) : Vec3(0, 0, 1); -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, Vec3& outPos) const -{ - Matrix34A objMat, objMatInv; - Matrix33 objRot, objRotInv; - - if (hit.pCollider->GetiForeignData() != PHYS_FOREIGN_ID_STATIC) - { - return false; - } - - IRenderNode* pNode = (IRenderNode*) hit.pCollider->GetForeignData(PHYS_FOREIGN_ID_STATIC); - if (!pNode || !pNode->GetEntityStatObj()) - { - return false; - } - - IStatObj* pEntObject = pNode->GetEntityStatObj(hit.partid, 0, &objMat, false); - if (!pEntObject || !pEntObject->GetRenderMesh()) - { - return false; - } - - objRot = Matrix33(objMat); - objRot.NoScale(); // No scale. - objRotInv = objRot; - objRotInv.Invert(); - - float fWorldScale = objMat.GetColumn(0).GetLength(); // GetScale - float fWorldScaleInv = 1.0f / fWorldScale; - - // transform decal into object space - objMatInv = objMat; - objMatInv.Invert(); - - // put into normal object space hit direction of projection - Vec3 invhitn = -(hit.n); - Vec3 vOS_HitDir = objRotInv.TransformVector(invhitn).GetNormalized(); - - // put into position object space hit position - Vec3 vOS_HitPos = objMatInv.TransformPoint(hit.pt); - vOS_HitPos -= vOS_HitDir * RENDER_MESH_TEST_DISTANCE * fWorldScaleInv; - - IRenderMesh* pRM = pEntObject->GetRenderMesh(); - - AABB aabbRNode; - pRM->GetBBox(aabbRNode.min, aabbRNode.max); - Vec3 vOut(0, 0, 0); - if (!Intersect::Ray_AABB(Ray(vOS_HitPos, vOS_HitDir), aabbRNode, vOut)) - { - return false; - } - - if (!pRM || !pRM->GetVerticesCount()) - { - return false; - } - - if (RayRenderMeshIntersection(pRM, vOS_HitPos, vOS_HitDir, outPos, outNormal)) - { - outNormal = objRot.TransformVector(outNormal).GetNormalized(); - outPos = objMat.TransformPoint(outPos); - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::RayRenderMeshIntersection(IRenderMesh*, const Vec3&, const Vec3&, Vec3&, Vec3&) const -{ - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const -{ - AZ_Assert(m_cameraSetForWidgetRenderingCount > 0, - "ViewToWorldRay was called but SScopedCurrentContext was not set at a higher scope! This means the camera for this call is incorrect."); - - if (!m_renderer) - { - return; - } - - QRect rc = m_rcClient; - - Vec3 pos0, pos1; - float wx, wy, wz; - m_renderer->UnProjectFromScreen(vp.x(), rc.bottom() - vp.y(), 0, &wx, &wy, &wz); - if (!_finite(wx) || !_finite(wy) || !_finite(wz)) - { - return; - } - if (fabs(wx) > 1000000 || fabs(wy) > 1000000 || fabs(wz) > 1000000) - { - return; - } - pos0(wx, wy, wz); - m_renderer->UnProjectFromScreen(vp.x(), rc.bottom() - vp.y(), 1, &wx, &wy, &wz); - if (!_finite(wx) || !_finite(wy) || !_finite(wz)) - { - return; - } - if (fabs(wx) > 1000000 || fabs(wy) > 1000000 || fabs(wz) > 1000000) - { - return; - } - pos1(wx, wy, wz); - - Vec3 v = (pos1 - pos0); - v = v.GetNormalized(); - - raySrc = pos0; - rayDir = v; -} - -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetScreenScaleFactor(const Vec3& worldPoint) const -{ - float dist = m_Camera.GetPosition().GetDistance(worldPoint); - if (dist < m_Camera.GetNearPlane()) - { - dist = m_Camera.GetNearPlane(); - } - return dist; -} -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position) -{ - Vec3 camPos = camera.GetPosition(); - float dist = camPos.GetDistance(object_position); - return dist; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnDestroy() -{ - DestroyRenderContext(); -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::CheckRespondToInput() const -{ - if (!Editor::EditorQtApplication::IsActive()) - { - return false; - } - - if (!hasFocus()) - { - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::HitTest(const QPoint& point, HitContext& hitInfo) -{ - hitInfo.camera = &m_Camera; - hitInfo.pExcludedObject = GetCameraObject(); - return QtViewport::HitTest(point, hitInfo); -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::IsBoundsVisible(const AABB& box) const -{ - // If at least part of bbox is visible then its visible. - return m_Camera.IsAABBVisible_F(AABB(box.min, box.max)); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::CenterOnSelection() -{ - if (!GetIEditor()->GetSelection()->IsEmpty()) - { - // Get selection bounds & center - CSelectionGroup* sel = GetIEditor()->GetSelection(); - AABB selectionBounds = sel->GetBounds(); - CenterOnAABB(selectionBounds); - } -} - -void CRenderViewport::CenterOnAABB(const AABB& aabb) -{ - Vec3 selectionCenter = aabb.GetCenter(); - - // Minimum center size is 40cm - const float minSelectionRadius = 0.4f; - const float selectionSize = std::max(minSelectionRadius, aabb.GetRadius()); - - // Move camera 25% further back than required - const float centerScale = 1.25f; - - // Decompose original transform matrix - const Matrix34& originalTM = GetViewTM(); - AffineParts affineParts; - affineParts.SpectralDecompose(originalTM); - - // Forward vector is y component of rotation matrix - Matrix33 rotationMatrix(affineParts.rot); - const Vec3 viewDirection = rotationMatrix.GetColumn1().GetNormalized(); - - // Compute adjustment required by FOV != 90 degrees - const float fov = GetFOV(); - const float fovScale = (1.0f / tan(fov * 0.5f)); - - // Compute new transform matrix - const float distanceToTarget = selectionSize * fovScale * centerScale; - const Vec3 newPosition = selectionCenter - (viewDirection * distanceToTarget); - Matrix34 newTM = Matrix34(rotationMatrix, newPosition); - - // Set new orbit distance - m_orbitDistance = distanceToTarget; - m_orbitDistance = fabs(m_orbitDistance); - - SetViewTM(newTM); -} - -void CRenderViewport::CenterOnSliceInstance() -{ - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - - AZ::SliceComponent::SliceInstanceAddress sliceAddress; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(sliceAddress, - &AzToolsFramework::ToolsApplicationRequestBus::Events::FindCommonSliceInstanceAddress, selectedEntityList); - - if (!sliceAddress.IsValid()) - { - return; - } - - AZ::EntityId sliceRootEntityId; - AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(sliceRootEntityId, - &AzToolsFramework::ToolsApplicationRequestBus::Events::GetRootEntityIdOfSliceInstance, sliceAddress); - - if (!sliceRootEntityId.IsValid()) - { - return; - } - - AzToolsFramework::ToolsApplicationRequestBus::Broadcast( - &AzToolsFramework::ToolsApplicationRequestBus::Events::SetSelectedEntities, AzToolsFramework::EntityIdList{sliceRootEntityId}); - - const AZ::SliceComponent::InstantiatedContainer* instantiatedContainer = sliceAddress.GetInstance()->GetInstantiated(); - - AABB aabb(Vec3(std::numeric_limits::max()), Vec3(-std::numeric_limits::max())); - for (AZ::Entity* entity : instantiatedContainer->m_entities) - { - CEntityObject* entityObject = nullptr; - AzToolsFramework::ComponentEntityEditorRequestBus::EventResult(entityObject, entity->GetId(), - &AzToolsFramework::ComponentEntityEditorRequestBus::Events::GetSandboxObject); - AABB box; - entityObject->GetBoundBox(box); - aabb.Add(box.min); - aabb.Add(box.max); - } - CenterOnAABB(aabb); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetFOV(float fov) -{ - if (m_pCameraFOVVariable) - { - m_pCameraFOVVariable->Set(fov); - } - else - { - m_camFOV = fov; - } - - if (m_viewPane) - { - m_viewPane->OnFOVChanged(fov); - } -} - -////////////////////////////////////////////////////////////////////////// -float CRenderViewport::GetFOV() const -{ - if (m_viewSourceType == ViewSourceType::SequenceCamera) - { - CBaseObject* cameraObject = GetCameraObject(); - - AZ::EntityId cameraEntityId; - AzToolsFramework::ComponentEntityObjectRequestBus::EventResult(cameraEntityId, cameraObject, &AzToolsFramework::ComponentEntityObjectRequestBus::Events::GetAssociatedEntityId); - if (cameraEntityId.IsValid()) - { - // component Camera - float fov = DEFAULT_FOV; - Camera::CameraRequestBus::EventResult(fov, cameraEntityId, &Camera::CameraComponentRequests::GetFov); - return AZ::DegToRad(fov); - } - } - - if (m_pCameraFOVVariable) - { - float fov; - m_pCameraFOVVariable->Get(fov); - return fov; - } - else if (m_viewEntityId.IsValid()) - { - float fov = AZ::RadToDeg(m_camFOV); - Camera::CameraRequestBus::EventResult(fov, m_viewEntityId, &Camera::CameraComponentRequests::GetFov); - return AZ::DegToRad(fov); - } - - return m_camFOV; -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::CreateRenderContext() -{ - // Create context. - if (m_renderer && !m_bRenderContextCreated) - { - m_bRenderContextCreated = true; - - AzFramework::WindowRequestBus::Handler::BusConnect(renderOverlayHWND()); - AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, renderOverlayHWND()); - - WIN_HWND oldContext = m_renderer->GetCurrentContextHWND(); - m_renderer->CreateContext(renderOverlayHWND()); - m_renderer->SetCurrentContext(oldContext); // restore prior context - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::DestroyRenderContext() -{ - // Destroy render context. - if (m_renderer && m_bRenderContextCreated) - { - // Do not delete primary context. - if (m_hwnd != m_renderer->GetHWND()) - { - m_renderer->DeleteContext(m_hwnd); - } - m_bRenderContextCreated = false; - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetDefaultCamera() -{ - if (IsDefaultCamera()) - { - return; - } - ResetToViewSourceType(ViewSourceType::None); - GetViewManager()->SetCameraObjectId(m_cameraObjectId); - SetName(m_defaultViewName); - SetViewTM(m_defaultViewTM); - PostCameraSet(); -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::IsDefaultCamera() const -{ - return m_viewSourceType == ViewSourceType::None; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetSequenceCamera() -{ - if (m_viewSourceType == ViewSourceType::SequenceCamera) - { - // Reset if we were checked before - SetDefaultCamera(); - } - else - { - ResetToViewSourceType(ViewSourceType::SequenceCamera); - - SetName(tr("Sequence Camera")); - SetViewTM(GetViewTM()); - - GetViewManager()->SetCameraObjectId(m_cameraObjectId); - PostCameraSet(); - - // ForceAnimation() so Track View will set the Camera params - // if a camera is animated in the sequences. - if (GetIEditor() && GetIEditor()->GetAnimation()) - { - GetIEditor()->GetAnimation()->ForceAnimation(); - } -} -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetComponentCamera(const AZ::EntityId& entityId) -{ - ResetToViewSourceType(ViewSourceType::CameraComponent); - SetViewEntity(entityId); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetEntityAsCamera(const AZ::EntityId& entityId, bool lockCameraMovement) -{ - ResetToViewSourceType(ViewSourceType::AZ_Entity); - SetViewEntity(entityId, lockCameraMovement); -} - -void CRenderViewport::SetFirstComponentCamera() -{ - AZ::EBusAggregateResults results; - Camera::CameraBus::BroadcastResult(results, &Camera::CameraRequests::GetCameras); - AZStd::sort_heap(results.values.begin(), results.values.end()); - AZ::EntityId entityId; - if (results.values.size() > 0) - { - entityId = results.values[0]; - } - SetComponentCamera(entityId); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::SetSelectedCamera() -{ - AZ::EBusAggregateResults cameraList; - Camera::CameraBus::BroadcastResult(cameraList, &Camera::CameraRequests::GetCameras); - if (cameraList.values.size() > 0) - { - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - for (const AZ::EntityId& entityId : selectedEntityList) - { - if (AZStd::find(cameraList.values.begin(), cameraList.values.end(), entityId) != cameraList.values.end()) - { - SetComponentCamera(entityId); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::IsSelectedCamera() const -{ - CBaseObject* pCameraObject = GetCameraObject(); - if (pCameraObject && pCameraObject == GetIEditor()->GetSelectedObject()) - { - return true; - } - - AzToolsFramework::EntityIdList selectedEntityList; - AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult( - selectedEntityList, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities); - - if ((m_viewSourceType == ViewSourceType::CameraComponent || m_viewSourceType == ViewSourceType::AZ_Entity) - && !selectedEntityList.empty() - && AZStd::find(selectedEntityList.begin(), selectedEntityList.end(), m_viewEntityId) != selectedEntityList.end()) - { - return true; - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::CycleCamera() -{ - // None -> Sequence -> LegacyCamera -> ... LegacyCamera -> CameraComponent -> ... CameraComponent -> None - // AZ_Entity has been intentionally left out of the cycle for now. - switch (m_viewSourceType) - { - case CRenderViewport::ViewSourceType::None: - { - SetFirstComponentCamera(); - break; - } - case CRenderViewport::ViewSourceType::SequenceCamera: - { - AZ_Error("CRenderViewport", false, "Legacy cameras no longer exist, unable to set sequence camera."); - break; - } - case CRenderViewport::ViewSourceType::LegacyCamera: - { - AZ_Warning("CRenderViewport", false, "Legacy cameras no longer exist, using first found component camera instead."); - SetFirstComponentCamera(); - break; - } - case CRenderViewport::ViewSourceType::CameraComponent: - { - AZ::EBusAggregateResults results; - Camera::CameraBus::BroadcastResult(results, &Camera::CameraRequests::GetCameras); - AZStd::sort_heap(results.values.begin(), results.values.end()); - auto&& currentCameraIterator = AZStd::find(results.values.begin(), results.values.end(), m_viewEntityId); - if (currentCameraIterator != results.values.end()) - { - ++currentCameraIterator; - if (currentCameraIterator != results.values.end()) - { - SetComponentCamera(*currentCameraIterator); - break; - } - } - SetDefaultCamera(); - break; - } - case CRenderViewport::ViewSourceType::AZ_Entity: - { - // we may decide to have this iterate over just selected entities - SetDefaultCamera(); - break; - } - default: - { - SetDefaultCamera(); - break; - } - } -} - -void CRenderViewport::SetViewFromEntityPerspective(const AZ::EntityId& entityId) -{ - SetViewAndMovementLockFromEntityPerspective(entityId, false); -} - -void CRenderViewport::SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, bool lockCameraMovement) -{ - if (!m_ignoreSetViewFromEntityPerspective) - { - SetEntityAsCamera(entityId, lockCameraMovement); - } -} - -bool CRenderViewport::GetActiveCameraPosition(AZ::Vector3& cameraPos) -{ - cameraPos = LYVec3ToAZVec3(m_viewTM.GetTranslation()); - return true; -} - -bool CRenderViewport::GetActiveCameraState(AzFramework::CameraState& cameraState) -{ - if (m_pPrimaryViewport == this) - { - if (GetIEditor()->IsInGameMode()) - { - return false; - } - else - { - const auto& camera = GetCamera(); - cameraState = CameraStateFromCCamera(camera, GetFOV(), m_rcClient.width(), m_rcClient.height()); - } - - return true; - } - - return false; -} - -void CRenderViewport::OnStartPlayInEditor() -{ - if (m_viewEntityId.IsValid()) - { - m_viewEntityIdCachedForEditMode = m_viewEntityId; - AZ::EntityId runtimeEntityId; - AzToolsFramework::EditorEntityContextRequestBus::Broadcast( - &AzToolsFramework::EditorEntityContextRequestBus::Events::MapEditorIdToRuntimeId, - m_viewEntityId, runtimeEntityId); - - m_viewEntityId = runtimeEntityId; - } - // Force focus the render viewport, otherwise we don't receive keyPressEvents until the user first clicks a - // mouse button. See also CRenderViewport::mousePressEvent for a deatiled description of the underlying bug. - // We need to queue this up because we don't actually lose focus until sometime after this function returns. - QTimer::singleShot(0, this, &CRenderViewport::ActivateWindowAndSetFocus); -} - -void CRenderViewport::OnStopPlayInEditor() -{ - if (m_viewEntityIdCachedForEditMode.IsValid()) - { - m_viewEntityId = m_viewEntityIdCachedForEditMode; - m_viewEntityIdCachedForEditMode.SetInvalid(); - } -} - -void CRenderViewport::ActivateWindowAndSetFocus() -{ - window()->activateWindow(); - setFocus(); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderConstructionPlane() -{ - // noop -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RenderSnappingGrid() -{ - // noop -} - -////////////////////////////////////////////////////////////////////////// -CRenderViewport::SPreviousContext CRenderViewport::SetCurrentContext(int newWidth, int newHeight) const -{ - SPreviousContext x; - x.window = reinterpret_cast(m_renderer->GetCurrentContextHWND()); - x.mainViewport = m_renderer->IsCurrentContextMainVP(); - x.width = m_renderer->GetCurrentContextViewportWidth(); - x.height = m_renderer->GetCurrentContextViewportHeight(); - x.rendererCamera = m_renderer->GetCamera(); - - const float scale = CLAMP(gEnv->pConsole->GetCVar("r_ResolutionScale")->GetFVal(), MIN_RESOLUTION_SCALE, MAX_RESOLUTION_SCALE); - const QSize newSize = WidgetToViewport(QSize(newWidth, newHeight)) * scale; - - // No way to query the requested Qt scale here, so do it this way for now - float widthScale = aznumeric_cast(newSize.width()) / aznumeric_cast(newWidth); - float heightScale = aznumeric_cast(newSize.height()) / aznumeric_cast(newHeight); - - m_renderer->SetCurrentContext(renderOverlayHWND()); - m_renderer->ChangeViewport(0, 0, newWidth, newHeight, true, widthScale, heightScale); - m_renderer->SetCamera(m_Camera); - - return x; -} - -////////////////////////////////////////////////////////////////////////// -CRenderViewport::SPreviousContext CRenderViewport::SetCurrentContext() const -{ - const auto r = rect(); - return SetCurrentContext(r.width(), r.height()); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::RestorePreviousContext(const SPreviousContext& x) const -{ - if (x.window && x.window != m_renderer->GetCurrentContextHWND()) - { - m_renderer->SetCurrentContext(x.window); - m_renderer->ChangeViewport(0, 0, x.width, x.height, x.mainViewport); - m_renderer->SetCamera(x.rendererCamera); - } -} - -void CRenderViewport::PreWidgetRendering() -{ - // if we have not already set the render context for the viewport, do it now - // based on the current state of the renderer/viewport, record the previous - // context to restore afterwards - if (m_cameraSetForWidgetRenderingCount == 0) - { - m_preWidgetContext = SetCurrentContext(); - } - - // keep track of how many times we've attempted to update the context - m_cameraSetForWidgetRenderingCount++; -} - -void CRenderViewport::PostWidgetRendering() -{ - if (m_cameraSetForWidgetRenderingCount > 0) - { - m_cameraSetForWidgetRenderingCount--; - - // unwinding - when the viewport context is no longer required, - // restore the previous context when widget rendering first began - if (m_cameraSetForWidgetRenderingCount == 0) - { - RestorePreviousContext(m_preWidgetContext); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::OnCameraFOVVariableChanged([[maybe_unused]] IVariable* var) -{ - if (m_viewPane) - { - m_viewPane->OnFOVChanged(GetFOV()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::HideCursor() -{ - if (m_bCursorHidden || !gSettings.viewports.bHideMouseCursorWhenCaptured) - { - return; - } - - qApp->setOverrideCursor(Qt::BlankCursor); -#if AZ_TRAIT_OS_PLATFORM_APPLE - StartFixedCursorMode(this); -#endif - m_bCursorHidden = true; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::ShowCursor() -{ - if (!m_bCursorHidden || !gSettings.viewports.bHideMouseCursorWhenCaptured) - { - return; - } - -#if AZ_TRAIT_OS_PLATFORM_APPLE - StopFixedCursorMode(); -#endif - qApp->restoreOverrideCursor(); - m_bCursorHidden = false; -} - -bool CRenderViewport::IsKeyDown(Qt::Key key) const -{ - return m_keyDown.contains(key); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::PushDisableRendering() -{ - assert(m_disableRenderingCount >= 0); - ++m_disableRenderingCount; -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::PopDisableRendering() -{ - assert(m_disableRenderingCount >= 1); - --m_disableRenderingCount; -} - -////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::IsRenderingDisabled() const -{ - return m_disableRenderingCount > 0; -} - -////////////////////////////////////////////////////////////////////////// -QPoint CRenderViewport::WidgetToViewport(const QPoint &point) const -{ - return point * WidgetToViewportFactor(); -} - -QPoint CRenderViewport::ViewportToWidget(const QPoint &point) const -{ - return point / WidgetToViewportFactor(); -} - -////////////////////////////////////////////////////////////////////////// -QSize CRenderViewport::WidgetToViewport(const QSize &size) const -{ - return size * WidgetToViewportFactor(); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::BeginUndoTransaction() -{ - PushDisableRendering(); -} - -////////////////////////////////////////////////////////////////////////// -void CRenderViewport::EndUndoTransaction() -{ - PopDisableRendering(); - Update(); -} - -void CRenderViewport::UpdateCurrentMousePos(const QPoint& newPosition) -{ - m_prevMousePos = m_mousePos; - m_mousePos = newPosition; -} - -void CRenderViewport::BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) -{ - const auto scaledPoint = WidgetToViewport(pt); - QtViewport::BuildDragDropContext(context, scaledPoint); -} - -void* CRenderViewport::GetSystemCursorConstraintWindow() const -{ - AzFramework::SystemCursorState systemCursorState = AzFramework::SystemCursorState::Unknown; - - AzFramework::InputSystemCursorRequestBus::EventResult( - systemCursorState, - AzFramework::InputDeviceMouse::Id, - &AzFramework::InputSystemCursorRequests::GetSystemCursorState); - - const bool systemCursorConstrained = - (systemCursorState == AzFramework::SystemCursorState::ConstrainedAndHidden || - systemCursorState == AzFramework::SystemCursorState::ConstrainedAndVisible); - - return systemCursorConstrained ? renderOverlayHWND() : nullptr; -} - -void CRenderViewport::RestoreViewportAfterGameMode() -{ - Matrix34 preGameModeViewTM = m_preGameModeViewTM; - - QString text = - QString( - tr("When leaving \" Game Mode \" the engine will automatically restore your camera position to the default position before you " - "had entered Game mode.

If you dislike this setting you can always change this anytime in the global " - "preferences.

")) - .arg(EditorPreferencesGeneralRestoreViewportCameraSettingName); - QString restoreOnExitGameModePopupDisabledRegKey("Editor/AutoHide/ViewportCameraRestoreOnExitGameMode"); - - // Read the popup disabled registry value - QSettings settings; - QVariant restoreOnExitGameModePopupDisabledRegValue = settings.value(restoreOnExitGameModePopupDisabledRegKey); - - // Has the user previously disabled being asked about restoring the camera on exiting game mode? - if (restoreOnExitGameModePopupDisabledRegValue.isNull()) - { - // No, ask them now - QMessageBox messageBox(QMessageBox::Question, "O3DE", text, QMessageBox::StandardButtons(QMessageBox::No | QMessageBox::Yes), this); - messageBox.setDefaultButton(QMessageBox::Yes); - - QCheckBox* checkBox = new QCheckBox(QStringLiteral("Do not show this message again")); - checkBox->setChecked(true); - messageBox.setCheckBox(checkBox); - - // Unconstrain the system cursor and make it visible before we show the dialog box, otherwise the user can't see the cursor. - AzFramework::InputSystemCursorRequestBus::Event(AzFramework::InputDeviceMouse::Id, - &AzFramework::InputSystemCursorRequests::SetSystemCursorState, - AzFramework::SystemCursorState::UnconstrainedAndVisible); - - int response = messageBox.exec(); - - if (checkBox->isChecked()) - { - settings.setValue(restoreOnExitGameModePopupDisabledRegKey, response); - } - - // Update the value only if the popup hasn't previously been disabled and the value has changed - bool newSetting = (response == QMessageBox::Yes); - if (newSetting != GetIEditor()->GetEditorSettings()->restoreViewportCamera) - { - GetIEditor()->GetEditorSettings()->restoreViewportCamera = newSetting; - GetIEditor()->GetEditorSettings()->Save(); - } - } - - bool restoreViewportCamera = GetIEditor()->GetEditorSettings()->restoreViewportCamera; - if (restoreViewportCamera) - { - SetViewTM(preGameModeViewTM); - } - else - { - SetViewTM(m_gameTM); - } -} - -#include diff --git a/Code/Editor/RenderViewport.h b/Code/Editor/RenderViewport.h deleted file mode 100644 index d63f319276..0000000000 --- a/Code/Editor/RenderViewport.h +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_EDITOR_RENDERVIEWPORT_H -#define CRYINCLUDE_EDITOR_RENDERVIEWPORT_H - -#pragma once -// RenderViewport.h : header file -// - -#if !defined(Q_MOC_RUN) -#include - -#include - -#include "Viewport.h" -#include "Objects/DisplayContext.h" -#include "Undo/Undo.h" -#include "Util/PredefinedAspectRatios.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -#include -#include - -// forward declarations. -class CBaseObject; -class QMenu; -class QKeyEvent; -class EditorEntityNotifications; -struct ray_hit; -struct IRenderMesh; -struct IVariable; - -namespace AzToolsFramework -{ - class ManipulatorManager; -} - -// CRenderViewport window -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -class SANDBOX_API CRenderViewport - : public QtViewport - , public IEditorNotifyListener - , public IUndoManagerListener - , public Camera::EditorCameraRequestBus::Handler - , public AzFramework::InputSystemCursorConstraintRequestBus::Handler - , public AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler - , public AzToolsFramework::ViewportInteraction::ViewportInteractionRequestBus::Handler - , public AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler - , public AzFramework::WindowRequestBus::Handler -{ -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - Q_OBJECT -public: - struct SResolution - { - SResolution() - : width(0) - , height(0) - { - } - - SResolution(int w, int h) - : width(w) - , height(h) - { - } - - int width; - int height; - }; - -public: - CRenderViewport(const QString& name, QWidget* parent = nullptr); - - static const GUID& GetClassID() - { - return QtViewport::GetClassID(); - } - - /** Get type of this viewport. - */ - virtual EViewportType GetType() const { return ET_ViewportCamera; } - virtual void SetType([[maybe_unused]] EViewportType type) { assert(type == ET_ViewportCamera); }; - - // Implementation -public: - virtual ~CRenderViewport(); - - Q_INVOKABLE void InjectFakeMouseMove(int deltaX, int deltaY, Qt::MouseButtons buttons); - -public: - virtual void Update(); - - virtual void ResetContent(); - virtual void UpdateContent(int flags); - - void OnTitleMenu(QMenu* menu) override; - - void SetCamera(const CCamera& camera); - const CCamera& GetCamera() const { return m_Camera; }; - virtual void SetViewTM(const Matrix34& tm) - { - if (m_viewSourceType == ViewSourceType::None) - { - m_defaultViewTM = tm; - } - SetViewTM(tm, false); - } - - //! Map world space position to viewport position. - virtual QPoint WorldToView(const Vec3& wp) const; - virtual QPoint WorldToViewParticleEditor(const Vec3& wp, int width, int height) const; - virtual Vec3 WorldToView3D(const Vec3& wp, int nFlags = 0) const; - - //! Map viewport position to world space position. - virtual Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; - virtual void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; - virtual Vec3 ViewToWorldNormal(const QPoint& vp, bool onlyTerrain, bool bTestRenderMesh = false) override; - virtual float GetScreenScaleFactor(const Vec3& worldPoint) const; - virtual float GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position); - virtual float GetAspectRatio() const; - virtual bool HitTest(const QPoint& point, HitContext& hitInfo); - virtual bool IsBoundsVisible(const AABB& box) const; - virtual void CenterOnSelection(); - virtual void CenterOnAABB(const AABB& aabb); - void CenterOnSliceInstance() override; - - void focusOutEvent(QFocusEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; - void keyReleaseEvent(QKeyEvent* event) override; - - void SetFOV(float fov); - float GetFOV() const; - - void SetDefaultCamera(); - bool IsDefaultCamera() const; - void SetSequenceCamera(); - bool IsSequenceCamera() const { return m_viewSourceType == ViewSourceType::SequenceCamera; } - void SetSelectedCamera(); - bool IsSelectedCamera() const; - void SetComponentCamera(const AZ::EntityId& entityId); - void SetEntityAsCamera(const AZ::EntityId& entityId, bool lockCameraMovement = false); - void SetFirstComponentCamera(); - void SetViewEntity(const AZ::EntityId& cameraEntityId, bool lockCameraMovement = false); - void PostCameraSet(); - // This switches the active camera to the next one in the list of (default, all custom cams). - void CycleCamera(); - - // Camera::EditorCameraRequestBus - void SetViewFromEntityPerspective(const AZ::EntityId& entityId) override; - void SetViewAndMovementLockFromEntityPerspective(const AZ::EntityId& entityId, bool lockCameraMovement) override; - AZ::EntityId GetCurrentViewEntityId() override { return m_viewEntityId; } - bool GetActiveCameraPosition(AZ::Vector3& cameraPos) override; - bool GetActiveCameraState(AzFramework::CameraState& cameraState) override; - - // AzToolsFramework::EditorEntityContextNotificationBus (handler moved to cpp to resolve link issues in unity builds) - virtual void OnStartPlayInEditor(); - virtual void OnStopPlayInEditor(); - - // AzToolsFramework::EditorContextMenu::Bus (handler moved to cpp to resolve link issues in unity builds) - // We use this to determine when the viewport context menu is being displayed so we can exit move mode - void PopulateEditorGlobalContextMenu(QMenu* /*menu*/, const AZ::Vector2& /*point*/, int /*flags*/); - - // AzToolsFramework::ViewportInteractionRequestBus - AzFramework::CameraState GetCameraState() override; - bool GridSnappingEnabled() override; - float GridSize() override; - bool ShowGrid() override; - bool AngleSnappingEnabled() override; - float AngleStep() override; - 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 {}; - } - float DeviceScalingFactor() override { return 1.0f; } - - // AzToolsFramework::ViewportFreezeRequestBus - bool IsViewportInputFrozen() override; - void FreezeViewportInput(bool freeze) override; - - // AzToolsFramework::MainEditorViewportInteractionRequestBus - 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; - QWidget* GetWidgetForViewportContextMenu() override; - void BeginWidgetContext() override; - void EndWidgetContext() override; - - // WindowRequestBus::Handler... - void SetWindowTitle(const AZStd::string& title) override; - AzFramework::WindowSize GetClientAreaSize() const override; - void ResizeClientArea(AzFramework::WindowSize) override; - bool GetFullScreenState() const override; - void SetFullScreenState(bool fullScreenState) override; - bool CanToggleFullScreenState() const override; - void ToggleFullScreenState() override; - float GetDpiScaleFactor() const override { return 1.0f; }; - - void ConnectViewportInteractionRequestBus(); - void DisconnectViewportInteractionRequestBus(); - - void ActivateWindowAndSetFocus(); - - void LockCameraMovement(bool bLock) { m_bLockCameraMovement = bLock; } - bool IsCameraMovementLocked() const { return m_bLockCameraMovement; } - - void EnableCameraObjectMove(bool bMove) { m_bMoveCameraObject = bMove; } - bool IsCameraObjectMove() const { return m_bMoveCameraObject; } - - void SetPlayerControl(uint32 i) { m_PlayerControl = i; }; - uint32 GetPlayerControl() { return m_PlayerControl; }; - - const DisplayContext& GetDisplayContext() const { return m_displayContext; } - CBaseObject* GetCameraObject() const; - - QPoint WidgetToViewport(const QPoint& point) const; - QPoint ViewportToWidget(const QPoint& point) const; - QSize WidgetToViewport(const QSize& size) const; - - AzToolsFramework::ViewportInteraction::MouseInteraction BuildMouseInteraction( - Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers, const QPoint& point) override; - - void SetPlayerPos() - { - Matrix34 m = GetViewTM(); - m.SetTranslation(m.GetTranslation() - m_PhysicalLocation.t); - SetViewTM(m); - - m_AverageFrameTime = 0.14f; - - m_PhysicalLocation.SetIdentity(); - - m_LocalEntityMat.SetIdentity(); - m_PrevLocalEntityMat.SetIdentity(); - - m_absCameraHigh = 2.0f; - m_absCameraPos = Vec3(0, 3, 2); - m_absCameraPosVP = Vec3(0, -3, 1.5); - - m_absCurrentSlope = 0.0f; - - m_absLookDirectionXY = Vec2(0, 1); - - m_LookAt = Vec3(ZERO); - m_LookAtRate = Vec3(ZERO); - m_vCamPos = Vec3(ZERO); - m_vCamPosRate = Vec3(ZERO); - - m_relCameraRotX = 0; - m_relCameraRotZ = 0; - - uint32 numSample6 = static_cast(m_arrAnimatedCharacterPath.size()); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrAnimatedCharacterPath[i] = Vec3(ZERO); - } - - numSample6 = static_cast(m_arrSmoothEntityPath.size()); - for (uint32 i = 0; i < numSample6; i++) - { - m_arrSmoothEntityPath[i] = Vec3(ZERO); - } - - uint32 numSample7 = static_cast(m_arrRunStrafeSmoothing.size()); - for (uint32 i = 0; i < numSample7; i++) - { - m_arrRunStrafeSmoothing[i] = 0; - } - - m_vWorldDesiredBodyDirection = Vec2(0, 1); - m_vWorldDesiredBodyDirectionSmooth = Vec2(0, 1); - m_vWorldDesiredBodyDirectionSmoothRate = Vec2(0, 1); - - m_vWorldDesiredBodyDirection2 = Vec2(0, 1); - - m_vWorldDesiredMoveDirection = Vec2(0, 1); - m_vWorldDesiredMoveDirectionSmooth = Vec2(0, 1); - m_vWorldDesiredMoveDirectionSmoothRate = Vec2(0, 1); - m_vLocalDesiredMoveDirection = Vec2(0, 1); - m_vLocalDesiredMoveDirectionSmooth = Vec2(0, 1); - m_vLocalDesiredMoveDirectionSmoothRate = Vec2(0, 1); - - m_vWorldAimBodyDirection = Vec2(0, 1); - - m_MoveSpeedMSec = 5.0f; - m_key_W = 0; - m_keyrcr_W = 0; - m_key_S = 0; - m_keyrcr_S = 0; - m_key_A = 0; - m_keyrcr_A = 0; - m_key_D = 0; - m_keyrcr_D = 0; - m_key_SPACE = 0; - m_keyrcr_SPACE = 0; - m_ControllMode = 0; - - m_State = -1; - m_Stance = 1; //combat - - m_udGround = 0.0f; - m_lrGround = 0.0f; - AABB aabb = AABB(Vec3(-40.0f, -40.0f, -0.25f), Vec3(+40.0f, +40.0f, +0.0f)); - m_GroundOBB = OBB::CreateOBBfromAABB(Matrix33(IDENTITY), aabb); - m_GroundOBBPos = Vec3(0, 0, -0.01f); - }; - - static CRenderViewport* GetPrimaryViewport(); - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - CCamera m_Camera; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -protected: - struct SScopedCurrentContext; - - void SetViewTM(const Matrix34& tm, bool bMoveOnly); - - virtual float GetCameraMoveSpeed() const; - virtual float GetCameraRotateSpeed() const; - virtual bool GetCameraInvertYRotation() const; - virtual float GetCameraInvertPan() const; - - // Called to render stuff. - virtual void OnRender(); - - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - - //! Get currently active camera object. - void ToggleCameraObject(); - - void RenderConstructionPlane(); - void RenderSnapMarker(); - void RenderCursorString(); - void RenderSnappingGrid(); - void ProcessMouse(); - void ProcessKeys(); - - void RenderAll(); - void DrawAxis(); - void DrawBackground(); - void InitDisplayContext(); - void ResetCursor(); - - struct SPreviousContext - { - CCamera rendererCamera; - HWND window; - int width; - int height; - bool mainViewport; - }; - - SPreviousContext m_preWidgetContext; - - // Create an auto-sized render context that is sized based on the Editor's current - // viewport. - SPreviousContext SetCurrentContext() const; - - SPreviousContext SetCurrentContext(int newWidth, int newHeight) const; - void RestorePreviousContext(const SPreviousContext& x) const; - - void PreWidgetRendering() override; - void PostWidgetRendering() override; - - // Update the safe frame, safe action, safe title, and borders rectangles based on - // viewport size and target aspect ratio. - void UpdateSafeFrame(); - - // Draw safe frame, safe action, safe title rectangles and borders. - void RenderSafeFrame(); - - // Draw one of the safe frame rectangles with the desired color. - void RenderSafeFrame(const QRect& frame, float r, float g, float b, float a); - - // Draw the selection rectangle. - void RenderSelectionRectangle(); - - // Draw a selected region if it has been selected - void RenderSelectedRegion(); - - virtual bool CreateRenderContext(); - virtual void DestroyRenderContext(); - - void OnMenuCommandChangeAspectRatio(unsigned int commandId); - - bool AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, Vec3& outPos) const; - bool RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const; - - bool AddCameraMenuItems(QMenu* menu); - void ResizeView(int width, int height); - - void OnCameraFOVVariableChanged(IVariable* var); - - void HideCursor(); - void ShowCursor(); - - bool IsKeyDown(Qt::Key key) const; - - enum class ViewSourceType - { - None, - SequenceCamera, - LegacyCamera, - CameraComponent, - AZ_Entity, - ViewSourceTypesCount, - }; - void ResetToViewSourceType(const ViewSourceType& viewSourType); - - //! Assigned renderer. - IRenderer* m_renderer = nullptr; - bool m_bRenderContextCreated = false; - bool m_bInRotateMode = false; - bool m_bInMoveMode = false; - bool m_bInOrbitMode = false; - bool m_bInZoomMode = false; - - QPoint m_mousePos = QPoint(0, 0); - QPoint m_prevMousePos = QPoint(0, 0); // for tablets, you can't use SetCursorPos and need to remember the prior point and delta with that. - - - float m_moveSpeed = 1; - - float m_orbitDistance = 10.0f; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Vec3 m_orbitTarget; - - //------------------------------------------- - //--- player-control in CharEdit --- - //------------------------------------------- - f32 m_MoveSpeedMSec; - - uint32 m_key_W, m_keyrcr_W; - uint32 m_key_S, m_keyrcr_S; - uint32 m_key_A, m_keyrcr_A; - uint32 m_key_D, m_keyrcr_D; - - uint32 m_key_SPACE, m_keyrcr_SPACE; - uint32 m_ControllMode; - - int32 m_Stance; - int32 m_State; - f32 m_AverageFrameTime; - - uint32 m_PlayerControl = 0; - - f32 m_absCameraHigh; - Vec3 m_absCameraPos; - Vec3 m_absCameraPosVP; - - f32 m_absCurrentSlope; //in radiants - - Vec2 m_absLookDirectionXY; - - Vec3 m_LookAt; - Vec3 m_LookAtRate; - Vec3 m_vCamPos; - Vec3 m_vCamPosRate; - float m_camFOV; - - f32 m_relCameraRotX; - f32 m_relCameraRotZ; - - QuatTS m_PhysicalLocation; - - Matrix34 m_AnimatedCharacterMat; - - Matrix34 m_LocalEntityMat; //this is used for data-driven animations where the character is running on the spot - Matrix34 m_PrevLocalEntityMat; - - std::vector m_arrVerticesHF; - std::vector m_arrIndicesHF; - - std::vector m_arrAnimatedCharacterPath; - std::vector m_arrSmoothEntityPath; - std::vector m_arrRunStrafeSmoothing; - - Vec2 m_vWorldDesiredBodyDirection; - Vec2 m_vWorldDesiredBodyDirectionSmooth; - Vec2 m_vWorldDesiredBodyDirectionSmoothRate; - - Vec2 m_vWorldDesiredBodyDirection2; - - - Vec2 m_vWorldDesiredMoveDirection; - Vec2 m_vWorldDesiredMoveDirectionSmooth; - Vec2 m_vWorldDesiredMoveDirectionSmoothRate; - Vec2 m_vLocalDesiredMoveDirection; - Vec2 m_vLocalDesiredMoveDirectionSmooth; - Vec2 m_vLocalDesiredMoveDirectionSmoothRate; - Vec2 m_vWorldAimBodyDirection; - - f32 m_udGround; - f32 m_lrGround; - OBB m_GroundOBB; - Vec3 m_GroundOBBPos; - - // Index of camera objects. - mutable GUID m_cameraObjectId = GUID_NULL; - mutable AZ::EntityId m_viewEntityId; - mutable ViewSourceType m_viewSourceType = ViewSourceType::None; - AZ::EntityId m_viewEntityIdCachedForEditMode; - Matrix34 m_preGameModeViewTM; - uint m_disableRenderingCount = 0; - bool m_bLockCameraMovement; - bool m_bUpdateViewport = false; - bool m_bMoveCameraObject = true; - - enum class KeyPressedState - { - AllUp, - PressedThisFrame, - PressedInPreviousFrame, - }; - KeyPressedState m_pressedKeyState = KeyPressedState::AllUp; - - Matrix34 m_defaultViewTM; - const QString m_defaultViewName; - - DisplayContext m_displayContext; - - - bool m_isOnPaint = false; - static CRenderViewport* m_pPrimaryViewport; - - QRect m_safeFrame; - QRect m_safeAction; - QRect m_safeTitle; - - CPredefinedAspectRatios m_predefinedAspectRatios; - - IVariable* m_pCameraFOVVariable = nullptr; - bool m_bCursorHidden = false; - - void OnMenuResolutionCustom(); - void OnMenuCreateCameraEntityFromCurrentView(); - void OnMenuSelectCurrentCamera(); - - int OnCreate(); - void resizeEvent(QResizeEvent* event) override; - void paintEvent(QPaintEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void OnLButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnLButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnLButtonDblClk(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnMButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnMButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnRButtonDown(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnRButtonUp(Qt::KeyboardModifiers modifiers, const QPoint& point) override; - void OnMouseMove(Qt::KeyboardModifiers modifiers, Qt::MouseButtons buttons, const QPoint& point) override; - void OnMouseWheel(Qt::KeyboardModifiers modifiers, short zDelta, const QPoint& pt) override; - - // From a series of input primitives, compose a complete mouse interaction. - AzToolsFramework::ViewportInteraction::MouseInteraction BuildMouseInteractionInternal( - AzToolsFramework::ViewportInteraction::MouseButtons buttons, - AzToolsFramework::ViewportInteraction::KeyboardModifiers modifiers, - const AzToolsFramework::ViewportInteraction::MousePick& mousePick) const; - // Given a point in the viewport, return the pick ray into the scene. - // note: The argument passed to parameter **point**, originating - // from a Qt event, must first be passed to WidgetToViewport before being - // passed to BuildMousePick. - AzToolsFramework::ViewportInteraction::MousePick BuildMousePick(const QPoint& point); - - bool event(QEvent* event) override; - void OnDestroy(); - - bool CheckRespondToInput() const; - - // AzFramework::InputSystemCursorConstraintRequestBus - void* GetSystemCursorConstraintWindow() const override; - - void BuildDragDropContext(AzQtComponents::ViewportDragContext& context, const QPoint& pt) override; - -private: - void ProcessKeyRelease(QKeyEvent* event); - void PushDisableRendering(); - void PopDisableRendering(); - bool IsRenderingDisabled() const; - AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal( - const QPoint& point) const; - - void RestoreViewportAfterGameMode(); - - double WidgetToViewportFactor() const - { -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - return devicePixelRatioF(); -#else - return 1.0f; -#endif - } - - void BeginUndoTransaction() override; - void EndUndoTransaction() override; - - void UpdateCurrentMousePos(const QPoint& newPosition); - - AzFramework::EntityVisibilityQuery m_entityVisibilityQuery; - - SPreviousContext m_previousContext; - QSet m_keyDown; - - bool m_freezeViewportInput = false; - - size_t m_cameraSetForWidgetRenderingCount = 0; ///< How many calls to PreWidgetRendering happened before - ///< subsequent calls to PostWidetRendering. - AZStd::shared_ptr m_manipulatorManager; - - // Used to prevent circular set camera events - bool m_ignoreSetViewFromEntityPerspective = false; - bool m_windowResizedEvent = false; - - // Cache hwnd value for teardown to avoid infinite loops in retrieving it from destroyed widgets. - HWND m_hwnd; - - AZStd::unique_ptr m_editorEntityNotifications; - - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_RENDERVIEWPORT_H diff --git a/Code/Editor/Settings.cpp b/Code/Editor/Settings.cpp index 68ef835c67..06aae5b8f1 100644 --- a/Code/Editor/Settings.cpp +++ b/Code/Editor/Settings.cpp @@ -26,6 +26,7 @@ // AzFramework #include +#include // AzToolsFramework #include @@ -500,6 +501,7 @@ void SEditorSettings::Save() SaveValue("Settings", "AutoBackupTime", autoBackupTime); SaveValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); SaveValue("Settings", "AutoRemindTime", autoRemindTime); + SaveValue("Settings", "MaxDisplayedItemsNumInSearch", maxNumberOfItemsShownInSearch); SaveValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); SaveValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); SaveValue("Settings", "StylusMode", stylusMode); @@ -714,6 +716,7 @@ void SEditorSettings::Load() LoadValue("Settings", "AutoBackupTime", autoBackupTime); LoadValue("Settings", "AutoBackupMaxCount", autoBackupMaxCount); LoadValue("Settings", "AutoRemindTime", autoRemindTime); + LoadValue("Settings", "MaxDisplayedItemsNumInSearch", maxNumberOfItemsShownInSearch); LoadValue("Settings", "CameraMoveSpeed", cameraMoveSpeed); LoadValue("Settings", "CameraRotateSpeed", cameraRotateSpeed); LoadValue("Settings", "StylusMode", stylusMode); @@ -1209,3 +1212,8 @@ AzToolsFramework::ConsoleColorTheme SEditorSettings::GetConsoleColorTheme() cons { return consoleBackgroundColorTheme; } + +int SEditorSettings::GetMaxNumberOfItemsShownInSearchView() const +{ + return SEditorSettings::maxNumberOfItemsShownInSearch; +} diff --git a/Code/Editor/Settings.h b/Code/Editor/Settings.h index 39a4093915..51931ab955 100644 --- a/Code/Editor/Settings.h +++ b/Code/Editor/Settings.h @@ -289,6 +289,7 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING SettingOutcome GetValue(const AZStd::string_view path) override; SettingOutcome SetValue(const AZStd::string_view path, const AZStd::any& value) override; AzToolsFramework::ConsoleColorTheme GetConsoleColorTheme() const override; + int GetMaxNumberOfItemsShownInSearchView() const override; void ConvertPath(const AZStd::string_view sourcePath, AZStd::string& category, AZStd::string& attribute); @@ -364,6 +365,13 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING int autoRemindTime; ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// + // Asset Browser Search View. + ////////////////////////////////////////////////////////////////////////// + //! Current maximum number of items that can be displayed in the AssetBrowser Search View. + int maxNumberOfItemsShownInSearch; + ////////////////////////////////////////////////////////////////////////// + //! If true preview windows is displayed when browsing geometries. bool bPreviewGeometryWindow; diff --git a/Code/Editor/TrackView/CommentNodeAnimator.cpp b/Code/Editor/TrackView/CommentNodeAnimator.cpp index 15dcce1566..bb60259203 100644 --- a/Code/Editor/TrackView/CommentNodeAnimator.cpp +++ b/Code/Editor/TrackView/CommentNodeAnimator.cpp @@ -159,18 +159,10 @@ void CCommentNodeAnimator::Render(CTrackViewAnimNode* pNode, [[maybe_unused]] co } } -Vec2 CCommentNodeAnimator::GetScreenPosFromNormalizedPos(const Vec2& unitPos) +Vec2 CCommentNodeAnimator::GetScreenPosFromNormalizedPos(const Vec2&) { - const CCamera& cam = gEnv->pSystem->GetViewCamera(); - float width = (float)cam.GetViewSurfaceX(); - int height = cam.GetViewSurfaceZ(); - float fAspectRatio = gSettings.viewports.fDefaultAspectRatio; - float camWidth = height * fAspectRatio; - - float x = 0.5f * width + 0.5f * camWidth * unitPos.x; - float y = 0.5f * height * (1.f - unitPos.y); - - return Vec2(x, y); + AZ_Error("CryLegacy", false, "CCommentNodeAnimator::GetScreenPosFromNormalizedPos not supported"); + return Vec2(0, 0); } void CCommentNodeAnimator::DrawText(const char* szFontName, float fSize, const Vec2& unitPos, const ColorF col, const char* szText, int align) diff --git a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp index 4a56b2389b..66c4f63d35 100644 --- a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp +++ b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp @@ -44,7 +44,12 @@ namespace { const int g_useActiveViewportResolution = -1; // reserved value to indicate the use of the active viewport resolution int resolutions[][2] = { - { 1280, 720 }, { 1920, 1080 }, { 1998, 1080 }, { 2048, 858 }, { 2560, 1440 }, + {1280, 720}, + {1920, 1080}, + {1998, 1080}, + {2048, 858}, + {2560, 1440}, + {3840, 2160}, { g_useActiveViewportResolution, g_useActiveViewportResolution } // active viewport res must be the last element of the resolution array }; @@ -1066,6 +1071,10 @@ void CSequenceBatchRenderDialog::OnUpdateEnd(IAnimSequence* sequence) { GetIEditor()->GetMovieSystem()->DisableFixedStepForCapture(); + // Important: End batch render mode BEFORE leaving Game Mode. + // Otherwise track view will set the active camera based on the directors in the current sequence while leaving game mode + GetIEditor()->GetMovieSystem()->EnableBatchRenderMode(false); + GetIEditor()->GetMovieSystem()->RemoveMovieListener(sequence, this); GetIEditor()->SetInGameMode(false); GetIEditor()->GetGameEngine()->Update(); // Update is needed because SetInGameMode() queues game mode, Update() executes it. @@ -1185,7 +1194,6 @@ void CSequenceBatchRenderDialog::OnUpdateFinalize() m_ui->m_pGoBtn->setText(tr("Start")); m_ui->m_pGoBtn->setIcon(QPixmap(":/Trackview/clapperboard_ready.png")); - GetIEditor()->GetMovieSystem()->EnableBatchRenderMode(false); m_renderContext.currentItemIndex = -1; m_ui->BATCH_RENDER_PRESS_ESC_TO_CANCEL->setText(m_ffmpegPluginStatusMsg); diff --git a/Code/Editor/TrackView/TrackViewAnimNode.cpp b/Code/Editor/TrackView/TrackViewAnimNode.cpp index 9050808d3b..685cdc528e 100644 --- a/Code/Editor/TrackView/TrackViewAnimNode.cpp +++ b/Code/Editor/TrackView/TrackViewAnimNode.cpp @@ -27,13 +27,13 @@ #include #include #include +#include // Editor #include "AnimationContext.h" #include "Clipboard.h" #include "CommentNodeAnimator.h" #include "DirectorNodeAnimator.h" -#include "RenderViewport.h" #include "ViewManager.h" #include "Include/IObjectManager.h" #include "Objects/GizmoManager.h" diff --git a/Code/Editor/UndoViewRotation.cpp b/Code/Editor/UndoViewRotation.cpp index d226a516d1..a305641d3b 100644 --- a/Code/Editor/UndoViewRotation.cpp +++ b/Code/Editor/UndoViewRotation.cpp @@ -17,10 +17,27 @@ // Editor #include "ViewManager.h" +#include +#include +#include +#include + +Ang3 CUndoViewRotation::GetActiveCameraRotation() +{ + AZ::Transform activeCameraTm = AZ::Transform::CreateIdentity(); + Camera::ActiveCameraRequestBus::BroadcastResult( + activeCameraTm, + &Camera::ActiveCameraRequestBus::Events::GetActiveCameraTransform + ); + const AZ::Matrix3x4 cameraMatrix = AZ::Matrix3x4::CreateFromTransform(activeCameraTm); + const Matrix33 cameraMatrixCry = AZMatrix3x3ToLYMatrix3x3(AZ::Matrix3x3::CreateFromMatrix3x4(cameraMatrix)); + return RAD2DEG(Ang3::GetAnglesXYZ(cameraMatrixCry)); +} + CUndoViewRotation::CUndoViewRotation(const QString& pUndoDescription) { m_undoDescription = pUndoDescription; - m_undo = RAD2DEG(Ang3::GetAnglesXYZ(Matrix33(GetIEditor()->GetSystem()->GetViewCamera().GetMatrix()))); + m_undo = GetActiveCameraRotation(); } int CUndoViewRotation::GetSize() @@ -40,7 +57,7 @@ void CUndoViewRotation::Undo(bool bUndo) { if (bUndo) { - m_redo = RAD2DEG(Ang3::GetAnglesXYZ(Matrix33(GetIEditor()->GetSystem()->GetViewCamera().GetMatrix()))); + m_redo = GetActiveCameraRotation(); } Matrix34 tm = pRenderViewport->GetViewTM(); diff --git a/Code/Editor/UndoViewRotation.h b/Code/Editor/UndoViewRotation.h index 49e9b333eb..2e086a3f05 100644 --- a/Code/Editor/UndoViewRotation.h +++ b/Code/Editor/UndoViewRotation.h @@ -29,6 +29,8 @@ protected: void Redo(); private: + static Ang3 GetActiveCameraRotation(); + Ang3 m_undo; Ang3 m_redo; QString m_undoDescription; diff --git a/Code/Editor/Util/IndexedFiles.cpp b/Code/Editor/Util/IndexedFiles.cpp deleted file mode 100644 index ae777abb49..0000000000 --- a/Code/Editor/Util/IndexedFiles.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Tagged files database for 'SmartFileOpen' dialog - -#include "EditorDefs.h" - -#include "IndexedFiles.h" - -volatile TIntAtomic CIndexedFiles::s_bIndexingDone; -CIndexedFiles* CIndexedFiles::s_pIndexedFiles = nullptr; - -bool CIndexedFiles::m_startedFileIndexing = false; - -void CIndexedFiles::Initialize(const QString& path, IFileUtil::ScanDirectoryUpdateCallBack updateCB) -{ - m_files.clear(); - m_pathToIndex.clear(); - m_tags.clear(); - m_rootPath = path; - - bool anyFiles = CFileUtil::ScanDirectory(path, "*.*", m_files, true, true, updateCB); - - if (anyFiles == false) - { - m_files.clear(); - return; - } - - if (updateCB) - { - updateCB("Parsing & tagging..."); - } - - for (int i = 0; i < m_files.size(); ++i) - { - m_pathToIndex[m_files[i].filename] = i; - } - - PrepareTagTable(); - - InvokeUpdateCallbacks(); -} - -void CIndexedFiles::AddFile(const IFileUtil::FileDesc& path) -{ - assert(m_pathToIndex.find(path.filename) == m_pathToIndex.end()); - m_files.push_back(path); - m_pathToIndex[path.filename] = m_files.size() - 1; - QStringList tags; - GetTags(tags, path.filename); - for (int k = 0; k < tags.size(); ++k) - { - m_tags[tags[k]].insert(m_files.size() - 1); - } -} - -void CIndexedFiles::RemoveFile(const QString& path) -{ - if (m_pathToIndex.find(path) == m_pathToIndex.end()) - { - return; - } - std::map::iterator itr = m_pathToIndex.find(path); - int index = itr->second; - m_pathToIndex.erase(itr); - m_files.erase(m_files.begin() + index); - QStringList tags; - GetTags(tags, path); - for (int k = 0; k < tags.size(); ++k) - { - m_tags[tags[k]].erase(index); - } -} - -void CIndexedFiles::Refresh(const QString& path, bool recursive) -{ - IFileUtil::FileArray files; - bool anyFiles = CFileUtil::ScanDirectory(m_rootPath, Path::Make(path, "*.*"), files, recursive, recursive ? true : false); - - if (anyFiles == false) - { - return; - } - - for (int i = 0; i < files.size(); ++i) - { - if (m_pathToIndex.find(files[i].filename) == m_pathToIndex.end()) - { - AddFile(files[i]); - } - } - - InvokeUpdateCallbacks(); -} - -void CIndexedFiles::GetFilesWithTags(IFileUtil::FileArray& files, const QStringList& tags) const -{ - files.clear(); - if (tags.empty()) - { - return; - } - int_set candidates; - TagTable::const_iterator i; - // Gets candidate files from the first tag. - for (i = m_tags.begin(); i != m_tags.end(); ++i) - { - if (i->first.startsWith(tags[0])) - { - candidates.insert(i->second.begin(), i->second.end()); - } - } - // Reduces the candidates further using additional tags, if any. - for (int k = 1; k < tags.size(); ++k) - { - // Gathers the filter set. - int_set filter; - for (i = m_tags.begin(); i != m_tags.end(); ++i) - { - if (i->first.startsWith(tags[k])) - { - filter.insert(i->second.begin(), i->second.end()); - } - } - - // Filters the candidates using it. - for (int_set::iterator m = candidates.begin(); m != candidates.end(); ) - { - if (filter.find(*m) == filter.end()) - { - int_set::iterator target = m; - ++m; - candidates.erase(target); - } - else - { - ++m; - } - } - } - // Outputs the result. - files.reserve(candidates.size()); - for (int_set::const_iterator m = candidates.begin(); m != candidates.end(); ++m) - { - files.push_back(m_files[*m]); - } -} - -void CIndexedFiles::GetTags(QStringList& tags, const QString& path) const -{ - tags = path.split(QRegularExpression(QStringLiteral(R"([\\/.])")), Qt::SkipEmptyParts); -} - -void CIndexedFiles::GetTagsOfPrefix(QStringList& tags, const QString& prefix) const -{ - tags.clear(); - TagTable::const_iterator i; - for (i = m_tags.begin(); i != m_tags.end(); ++i) - { - if (i->first.startsWith(prefix)) - { - tags.push_back(i->first); - } - } -} - -void CIndexedFiles::PrepareTagTable() -{ - QStringList tags; - for (int i = 0; i < m_files.size(); ++i) - { - GetTags(tags, m_files[i].filename); - for (int k = 0; k < tags.size(); ++k) - { - m_tags[tags[k]].insert(i); - } - } -} - -void CIndexedFiles::AddUpdateCallback(std::function updateCallback) -{ - CryAutoLock lock(m_updateCallbackMutex); - - m_updateCallbacks.push_back(updateCallback); -} - -void CIndexedFiles::InvokeUpdateCallbacks() -{ - CryAutoLock lock(m_updateCallbackMutex); - - for (auto updateCallback : m_updateCallbacks) - { - updateCallback(); - } -} diff --git a/Code/Editor/Util/IndexedFiles.h b/Code/Editor/Util/IndexedFiles.h deleted file mode 100644 index e23c0ea827..0000000000 --- a/Code/Editor/Util/IndexedFiles.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -// Description : Tagged files database for 'SmartFileOpen' dialog -// -// Notice : Refer SmartFileOpenDialog h - - -#ifndef CRYINCLUDE_EDITOR_UTIL_INDEXEDFILES_H -#define CRYINCLUDE_EDITOR_UTIL_INDEXEDFILES_H -#pragma once - - -#include "FileUtil.h" -#include - -class CIndexedFiles -{ - friend class CFileIndexingThread; -public: - static CIndexedFiles& GetDB() - { - if (!s_pIndexedFiles) - { - assert(!"CIndexedFiles not created! Make sure you use CIndexedFiles::GetDB() after CIndexedFiles::StartFileIndexing() is called."); - } - assert(s_pIndexedFiles); - return *s_pIndexedFiles; - } - - static bool HasFileIndexingDone() - { return s_bIndexingDone > 0; } - - static void Create() - { - assert(!s_pIndexedFiles); - s_pIndexedFiles = new CIndexedFiles; - } - - static void Destroy() - { - SAFE_DELETE(s_pIndexedFiles); - } - - static void StartFileIndexing() - { - assert(s_bIndexingDone == 0); - assert(s_pIndexedFiles); - - if (!s_pIndexedFiles) - { - return; - } - - GetFileIndexingThread().Start(-1, "FileIndexing"); - m_startedFileIndexing = true; - } - - static void AbortFileIndexing() - { - if (!m_startedFileIndexing) - { - return; - } - - if (HasFileIndexingDone() == false) - { - GetFileIndexingThread().Abort(); - } - m_startedFileIndexing = false; - } - - static void RegisterCallback(std::function callback) - { - assert(s_pIndexedFiles); - if (!s_pIndexedFiles) - { - return; - } - - s_pIndexedFiles->AddUpdateCallback(callback); - } - -public: - void Initialize(const QString& path, IFileUtil::ScanDirectoryUpdateCallBack updateCB = nullptr); - - // Adds a new file to the database. - void AddFile(const IFileUtil::FileDesc& path); - // Removes a no-longer-existing file from the database. - void RemoveFile(const QString& path); - // Refreshes this database for the subdirectory. - void Refresh(const QString& path, bool recursive = true); - - void GetFilesWithTags(IFileUtil::FileArray& files, const QStringList& tags) const; - - //! This method returns all the tags which start with a given prefix. - //! It is useful for the tag auto-completion. - void GetTagsOfPrefix(QStringList& tags, const QString& prefix) const; - - uint32 GetTotalCount() const - { return (uint32)m_files.size(); } - -private: - static bool m_startedFileIndexing; - - std::vector > m_updateCallbacks; - IFileUtil::FileArray m_files; - std::map m_pathToIndex; - typedef std::set > int_set; - typedef std::map > TagTable; - TagTable m_tags; - QString m_rootPath; - - void GetTags(QStringList& tags, const QString& path) const; - void PrepareTagTable(); - - CryMutex m_updateCallbackMutex; - - void AddUpdateCallback(std::function updateCallback); - void InvokeUpdateCallbacks(); - - // A done flag for the background file indexing - static volatile TIntAtomic s_bIndexingDone; - // A thread for the background file indexing - class CFileIndexingThread - : public CryThread - { - public: - virtual void Run() - { - CIndexedFiles::GetDB().Initialize("@assets@", CallBack); - CryInterlockedAdd(CIndexedFiles::s_bIndexingDone.Addr(), 1); - } - - CFileIndexingThread() - : m_abort(false) {} - - void Abort() - { - m_abort = true; - WaitForThread(); - } - - virtual ~CFileIndexingThread() - { - Abort(); - } - private: - bool m_abort; - static bool CallBack([[maybe_unused]] const QString& msg) - { - if (CIndexedFiles::GetFileIndexingThread().m_abort) - { - return false; - } - return true; - } - }; - - static CFileIndexingThread& GetFileIndexingThread() - { - static CFileIndexingThread s_fileIndexingThread; - - return s_fileIndexingThread; - } - - // A global database for tagged files - static CIndexedFiles* s_pIndexedFiles; -}; -#endif // CRYINCLUDE_EDITOR_UTIL_INDEXEDFILES_H diff --git a/Code/Editor/ViewManager.cpp b/Code/Editor/ViewManager.cpp index d5d932dae1..480a99a9d9 100644 --- a/Code/Editor/ViewManager.cpp +++ b/Code/Editor/ViewManager.cpp @@ -26,18 +26,15 @@ #include "LayoutWnd.h" #include "2DViewport.h" #include "TopRendererWnd.h" -#include "RenderViewport.h" #include "EditorViewportWidget.h" #include "CryEditDoc.h" #include -AZ_CVAR(bool, ed_useAtomNativeViewport, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new Atom-native Editor viewport (experimental, not yet stable"); - bool CViewManager::IsMultiViewportEnabled() { // Enable multi-viewport for legacy renderer, or if we're using the new fully Atom-native viewport - return ed_useAtomNativeViewport; + return true; } ////////////////////////////////////////////////////////////////////// @@ -74,14 +71,7 @@ CViewManager::CViewManager() RegisterQtViewPane(GetIEditor(), "Left", LyViewPane::CategoryViewport, viewportOptions); viewportOptions.viewportType = ET_ViewportCamera; - if (ed_useAtomNativeViewport) - { - RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); - } - else - { - RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); - } + RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); viewportOptions.viewportType = ET_ViewportMap; RegisterQtViewPane(GetIEditor(), "Map", LyViewPane::CategoryViewport, viewportOptions); @@ -251,11 +241,6 @@ void CViewManager::SelectViewport(CViewport* pViewport) ////////////////////////////////////////////////////////////////////////// CViewport* CViewManager::GetGameViewport() const { - if (CRenderViewport::GetPrimaryViewport()) - { - return CRenderViewport::GetPrimaryViewport(); - } - return GetViewport(ET_ViewportCamera);; } diff --git a/Code/Editor/ViewPane.cpp b/Code/Editor/ViewPane.cpp index 1d530ece48..466274c06e 100644 --- a/Code/Editor/ViewPane.cpp +++ b/Code/Editor/ViewPane.cpp @@ -305,10 +305,6 @@ void CLayoutViewPane::AttachViewport(QWidget* pViewport) { vp->SetViewportId(GetId()); vp->SetViewPane(this); - if (CRenderViewport* renderViewport = viewport_cast(vp)) - { - renderViewport->ConnectViewportInteractionRequestBus(); - } if (EditorViewportWidget* renderViewport = viewport_cast(vp)) { renderViewport->ConnectViewportInteractionRequestBus(); @@ -356,10 +352,6 @@ void CLayoutViewPane::DisconnectRenderViewportInteractionRequestBus() { if (QtViewport* vp = qobject_cast(m_viewport)) { - if (CRenderViewport* renderViewport = viewport_cast(vp)) - { - renderViewport->DisconnectViewportInteractionRequestBus(); - } if (EditorViewportWidget* renderViewport = viewport_cast(vp)) { renderViewport->DisconnectViewportInteractionRequestBus(); @@ -469,16 +461,6 @@ void CLayoutViewPane::SetAspectRatio(unsigned int x, unsigned int y) ////////////////////////////////////////////////////////////////////////// void CLayoutViewPane::SetViewportFOV(float fov) { - if (CRenderViewport* pRenderViewport = qobject_cast(m_viewport)) - { - pRenderViewport->SetFOV(DEG2RAD(fov)); - - // if viewport camera is active, make selected fov new default - if (pRenderViewport->GetViewManager()->GetCameraObjectId() == GUID_NULL) - { - gSettings.viewports.fDefaultFov = DEG2RAD(fov); - } - } if (EditorViewportWidget* pRenderViewport = qobject_cast(m_viewport)) { pRenderViewport->SetFOV(DEG2RAD(fov)); diff --git a/Code/Editor/Viewport.cpp b/Code/Editor/Viewport.cpp index 2cc9c78e4b..2bc1b21216 100644 --- a/Code/Editor/Viewport.cpp +++ b/Code/Editor/Viewport.cpp @@ -189,7 +189,6 @@ QtViewport::QtViewport(QWidget* parent) { m_constructionMatrix[i].SetIdentity(); } - m_viewTM.SetIdentity(); m_screenTM.SetIdentity(); m_pMouseOverObject = nullptr; diff --git a/Code/Editor/Viewport.h b/Code/Editor/Viewport.h index 0a23d93d0d..823b8c77b1 100644 --- a/Code/Editor/Viewport.h +++ b/Code/Editor/Viewport.h @@ -165,11 +165,19 @@ public: ////////////////////////////////////////////////////////////////////////// //! Set current view matrix, //! This is a matrix that transforms from world to view space. - virtual void SetViewTM(const Matrix34& tm) { m_viewTM = tm; }; + virtual void SetViewTM([[maybe_unused]] const Matrix34& tm) + { + AZ_Error("CryLegacy", false, "QtViewport::SetViewTM not implemented"); + } //! Get current view matrix. //! This is a matrix that transforms from world space to view space. - virtual const Matrix34& GetViewTM() const { return m_viewTM; }; + virtual const Matrix34& GetViewTM() const + { + AZ_Error("CryLegacy", false, "QtViewport::GetViewTM not implemented"); + static const Matrix34 m; + return m; + }; ////////////////////////////////////////////////////////////////////////// //! Get current screen matrix. @@ -277,8 +285,6 @@ protected: CLayoutViewPane* m_viewPane = nullptr; CViewManager* m_viewManager; AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - // Viewport matrix. - Matrix34 m_viewTM; // Screen Matrix Matrix34 m_screenTM; int m_nCurViewportID; diff --git a/Code/Editor/ViewportTitleDlg.cpp b/Code/Editor/ViewportTitleDlg.cpp index 25f8ca38eb..530e11b01b 100644 --- a/Code/Editor/ViewportTitleDlg.cpp +++ b/Code/Editor/ViewportTitleDlg.cpp @@ -644,13 +644,31 @@ void CViewportTitleDlg::CreateViewportInformationMenu() void CViewportTitleDlg::AddResolutionMenus(QMenu* menu, std::function callback, const QStringList& customPresets) { - static const CRenderViewport::SResolution resolutions[] = { - CRenderViewport::SResolution(1280, 720), - CRenderViewport::SResolution(1920, 1080), - CRenderViewport::SResolution(2560, 1440), - CRenderViewport::SResolution(2048, 858), - CRenderViewport::SResolution(1998, 1080), - CRenderViewport::SResolution(3840, 2160) + struct SResolution + { + SResolution() + : width(0) + , height(0) + { + } + + SResolution(int w, int h) + : width(w) + , height(h) + { + } + + int width; + int height; + }; + + static const SResolution resolutions[] = { + SResolution(1280, 720), + SResolution(1920, 1080), + SResolution(2560, 1440), + SResolution(2048, 858), + SResolution(1998, 1080), + SResolution(3840, 2160) }; static const size_t resolutionCount = sizeof(resolutions) / sizeof(resolutions[0]); diff --git a/Code/Editor/ViewportTitleDlg.h b/Code/Editor/ViewportTitleDlg.h index a5b4da8075..8a1766a764 100644 --- a/Code/Editor/ViewportTitleDlg.h +++ b/Code/Editor/ViewportTitleDlg.h @@ -12,7 +12,6 @@ #pragma once #if !defined(Q_MOC_RUN) -#include "RenderViewport.h" #include #include diff --git a/Code/Editor/editor_lib_files.cmake b/Code/Editor/editor_lib_files.cmake index 386b495faa..c1da19c3fd 100644 --- a/Code/Editor/editor_lib_files.cmake +++ b/Code/Editor/editor_lib_files.cmake @@ -724,8 +724,6 @@ set(FILES Util/GuidUtil.cpp Util/GuidUtil.h Util/IObservable.h - Util/IndexedFiles.cpp - Util/IndexedFiles.h Util/KDTree.cpp Util/Mailer.h Util/NamedData.cpp @@ -807,8 +805,6 @@ set(FILES ViewportManipulatorController.h LegacyViewportCameraController.cpp LegacyViewportCameraController.h - RenderViewport.cpp - RenderViewport.h TopRendererWnd.cpp TopRendererWnd.h ViewManager.cpp diff --git a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp index a578640d0d..eabfcd8cf0 100644 --- a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp +++ b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.cpp @@ -44,6 +44,22 @@ namespace AZ return &out; } + void SetPerspectiveMatrixFOV(Matrix4x4& out, float fovY, float aspectRatio) + { + float sinFov, cosFov; + SinCos(0.5f * fovY, sinFov, cosFov); + float yScale = cosFov / sinFov; //cot(fovY/2) + float xScale = yScale / aspectRatio; + + out.SetElement(0, 0, xScale); + out.SetElement(1, 1, yScale); + } + + float GetPerspectiveMatrixFOV(const Matrix4x4& m) + { + return 2.0 * AZStd::atan(1.0f / m.GetElement(1, 1)); + } + Matrix4x4* MakeFrustumMatrixRH(Matrix4x4& out, float left, float right, float bottom, float top, float nearDist, float farDist, bool reverseDepth) { AZ_Assert(right > left, "right should be greater than left"); diff --git a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.h b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.h index 72a7b29887..2679791fae 100644 --- a/Code/Framework/AzCore/AzCore/Math/MatrixUtils.h +++ b/Code/Framework/AzCore/AzCore/Math/MatrixUtils.h @@ -64,4 +64,8 @@ namespace AZ //! Transforms a position by a matrix. This function can be used with any generic cases which include projection matrices. Vector3 MatrixTransformPosition(const Matrix4x4& matrix, const Vector3& inPosition); + + void SetPerspectiveMatrixFOV(Matrix4x4& out, float fovY, float aspectRatio); + float GetPerspectiveMatrixFOV(const Matrix4x4& m); + } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.h b/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.h index a6e562e592..709e16174d 100644 --- a/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.h +++ b/Code/Framework/AzCore/AzCore/Memory/AllocationRecords.h @@ -27,11 +27,10 @@ namespace AZ struct AllocationInfo { size_t m_byteSize{}; - unsigned int m_alignment{}; const char* m_name{}; - const char* m_fileName{}; int m_lineNum{}; + unsigned int m_alignment{}; void* m_namesBlock{}; ///< Memory block if m_name and m_fileName have been allocated specifically for this allocation record size_t m_namesBlockSize{}; @@ -41,7 +40,7 @@ namespace AZ }; // We use OSAllocator which uses system calls to allocate memory, they are not recorded or tracked! - typedef AZStd::unordered_map, AZStd::equal_to, OSStdAllocator> AllocationRecordsType; + using AllocationRecordsType = AZStd::unordered_map, AZStd::equal_to, OSStdAllocator>; /** * Records enumeration callback @@ -50,7 +49,7 @@ namespace AZ * \param unsigned char number of stack records/levels, if AllocationInfo::m_stackFrames != NULL. * \returns true if you want to continue traverse of the records and false if you want to stop. */ - typedef AZStd::function AllocationInfoCBType; + using AllocationInfoCBType = AZStd::function; /** * Example of records enumeration callback. */ diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptProperty.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptProperty.cpp index 8664842893..dbccda4de2 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptProperty.cpp +++ b/Code/Framework/AzCore/AzCore/Script/ScriptProperty.cpp @@ -31,7 +31,6 @@ namespace AZ ScriptPropertyGenericClassArray::Reflect(reflection); ScriptPropertyAsset::Reflect(reflection); - ScriptPropertyEntityRef::Reflect(reflection); } template @@ -1358,53 +1357,4 @@ namespace AZ m_value = assetProperty->m_value; } } - - //////////////////////////// - // ScriptPropertyEntityRef - //////////////////////////// - void ScriptPropertyEntityRef::Reflect(AZ::ReflectContext* reflection) - { - AZ::SerializeContext* serializeContext = azrtti_cast(reflection); - - if (serializeContext) - { - serializeContext->Class()-> - Version(1)-> - Field("value", &AZ::ScriptPropertyEntityRef::m_value); - } - } - - const AZ::Uuid& ScriptPropertyEntityRef::GetDataTypeUuid() const - { - return AZ::SerializeTypeInfo::GetUuid(); - } - - bool ScriptPropertyEntityRef::DoesTypeMatch(AZ::ScriptDataContext& context, int valueIndex) const - { - return context.IsRegisteredClass(valueIndex); - } - - AZ::ScriptPropertyEntityRef* ScriptPropertyEntityRef::Clone(const char* name) const - { - AZ::ScriptPropertyEntityRef* clonedValue = aznew AZ::ScriptPropertyEntityRef(name ? name : m_name.c_str()); - clonedValue->m_value = m_value; - return clonedValue; - } - - bool ScriptPropertyEntityRef::Write(AZ::ScriptContext& context) - { - AZ::ScriptValue::StackPush(context.NativeContext(), m_value); - return true; - } - - void ScriptPropertyEntityRef::CloneDataFrom(const AZ::ScriptProperty* scriptProperty) - { - const AZ::ScriptPropertyEntityRef* entityProperty = azrtti_cast(scriptProperty); - - AZ_Error("ScriptPropertyEntityRef", entityProperty, "Invalid call to CloneData. Types must match before clone attempt is made.\n"); - if (entityProperty) - { - m_value = entityProperty->m_value; - } } -} diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptProperty.h b/Code/Framework/AzCore/AzCore/Script/ScriptProperty.h index c12fa3e8f1..f38931127d 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptProperty.h +++ b/Code/Framework/AzCore/AzCore/Script/ScriptProperty.h @@ -488,34 +488,6 @@ namespace AZ protected: void CloneDataFrom(const AZ::ScriptProperty* scriptProperty) override; }; - - class ScriptPropertyEntityRef - : public ScriptProperty - { - public: - AZ_CLASS_ALLOCATOR(ScriptPropertyEntityRef, AZ::SystemAllocator, 0); - AZ_RTTI(AZ::ScriptPropertyEntityRef, "{68EDE6C3-0A89-4C50-A86E-06C058C9F862}", ScriptProperty); - - static void Reflect(AZ::ReflectContext* reflection); - - ScriptPropertyEntityRef() {} - ScriptPropertyEntityRef(const char* name) - : ScriptProperty(name) {} - virtual ~ScriptPropertyEntityRef() = default; - const void* GetDataAddress() const override { return &m_value; } - const AZ::Uuid& GetDataTypeUuid() const override; - - bool DoesTypeMatch(AZ::ScriptDataContext& context, int valueIndex) const override; - - ScriptPropertyEntityRef* Clone(const char* name = nullptr) const override; - - bool Write(AZ::ScriptContext& context) override; - - AZ::EntityId m_value; - - protected: - void CloneDataFrom(const AZ::ScriptProperty* scriptProperty) override; - }; } #endif diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.cpp new file mode 100644 index 0000000000..ff889be116 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +namespace AZ +{ + AZ_CLASS_ALLOCATOR_IMPL(ScriptPropertySerializer, SystemAllocator, 0); + + JsonSerializationResult::Result ScriptPropertySerializer::Load + ( void* outputValue + , [[maybe_unused]] const Uuid& outputValueTypeId + , const rapidjson::Value& inputValue + , JsonDeserializerContext& context) + { + namespace JSR = JsonSerializationResult; + + AZ_Assert(outputValueTypeId == azrtti_typeid(), "ScriptPropertySerializer Load against output typeID that was not DynamicSerializableField"); + AZ_Assert(outputValue, "ScriptPropertySerializer Load against null output"); + + auto outputVariable = reinterpret_cast(outputValue); + JsonSerializationResult::ResultCode result(JSR::Tasks::ReadField); + AZ::Uuid typeId = AZ::Uuid::CreateNull(); + + auto typeIdMember = inputValue.FindMember(JsonSerialization::TypeIdFieldIdentifier); + if (typeIdMember == inputValue.MemberEnd()) + { + return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Missing, AZStd::string::format("ScriptPropertySerializer::Load failed to load the %s member", JsonSerialization::TypeIdFieldIdentifier)); + } + + result.Combine(LoadTypeId(typeId, typeIdMember->value, context)); + if (typeId.IsNull()) + { + return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::Catastrophic, "ScriptPropertySerializer::Load failed to load the AZ TypeId of the value"); + } + + AZStd::any storage = context.GetSerializeContext()->CreateAny(typeId); + if (storage.empty() || storage.type() != typeId) + { + return context.Report(result, "ScriptPropertySerializer::Load failed to load a value matched the reported AZ TypeId. The C++ declaration may have been deleted or changed."); + } + + DynamicSerializableField storageField; + storageField.m_data = AZStd::any_cast(&storage); + storageField.m_typeId = typeId; + outputVariable->CopyDataFrom(storageField, context.GetSerializeContext()); + + result.Combine(ContinueLoadingFromJsonObjectField(outputVariable->m_data, typeId, inputValue, "value", context)); + return context.Report(result, result.GetProcessing() != JSR::Processing::Halted + ? "ScriptPropertySerializer Load finished loading DynamicSerializableField" + : "ScriptPropertySerializer Load failed to load DynamicSerializableField"); + } + + JsonSerializationResult::Result ScriptPropertySerializer::Store + ( rapidjson::Value& outputValue + , const void* inputValue + , const void* defaultValue + , [[maybe_unused]] const Uuid& valueTypeId + , JsonSerializerContext& context) + { + namespace JSR = JsonSerializationResult; + + AZ_Assert(valueTypeId == azrtti_typeid(), "DynamicSerializableField Store against value typeID that was not DynamicSerializableField"); + AZ_Assert(inputValue, "DynamicSerializableField Store against null inputValue pointer "); + + auto inputScriptDataPtr = reinterpret_cast(inputValue); + auto inputFieldPtr = inputScriptDataPtr->m_data; + auto defaultScriptDataPtr = reinterpret_cast(defaultValue); + auto defaultFieldPtr = defaultScriptDataPtr ? &defaultScriptDataPtr->m_data : nullptr; + + if (defaultScriptDataPtr && inputScriptDataPtr->IsEqualTo(*defaultScriptDataPtr, context.GetSerializeContext())) + { + return context.Report(JSR::Tasks::WriteValue, JSR::Outcomes::DefaultsUsed, "ScriptPropertySerializer Store used defaults for DynamicSerializableField"); + } + + JSR::ResultCode result(JSR::Tasks::WriteValue); + outputValue.SetObject(); + + { + rapidjson::Value typeValue; + result.Combine(StoreTypeId(typeValue, inputScriptDataPtr->m_typeId, context)); + outputValue.AddMember(rapidjson::StringRef(JsonSerialization::TypeIdFieldIdentifier), AZStd::move(typeValue), context.GetJsonAllocator()); + } + + result.Combine(ContinueStoringToJsonObjectField(outputValue, "value", inputFieldPtr, defaultFieldPtr, inputScriptDataPtr->m_typeId, context)); + + return context.Report(result, result.GetProcessing() != JSR::Processing::Halted + ? "ScriptPropertySerializer Store finished saving DynamicSerializableField" + : "ScriptPropertySerializer Store failed to save DynamicSerializableField"); + } + +} diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.h b/Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.h new file mode 100644 index 0000000000..a3de3e761d --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Script/ScriptPropertySerializer.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +namespace AZ +{ + class ScriptPropertySerializer + : public BaseJsonSerializer + { + public: + AZ_RTTI(ScriptPropertySerializer, "{C7BECA49-84EF-45E6-A89D-052D61766197}", BaseJsonSerializer); + AZ_CLASS_ALLOCATOR_DECL; + + private: + JsonSerializationResult::Result Load + ( void* outputValue + , const Uuid& outputValueTypeId + , const rapidjson::Value& inputValue + , JsonDeserializerContext& context) override; + + JsonSerializationResult::Result Store + ( rapidjson::Value& outputValue + , const void* inputValue + , const void* defaultValue + , const Uuid& valueTypeId, JsonSerializerContext& context) override; + }; +} diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp index 6706d4f8d8..fa61a225c8 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp +++ b/Code/Framework/AzCore/AzCore/Script/ScriptSystemComponent.cpp @@ -8,10 +8,8 @@ #if !defined(AZCORE_EXCLUDE_LUA) -#include - -#include #include +#include #include #include #include @@ -21,13 +19,16 @@ #include #include #include -#include #include #include #include - -#include +#include +#include #include +#include +#include +#include +#include using namespace AZ; @@ -921,6 +922,12 @@ void ScriptSystemComponent::Reflect(ReflectContext* reflection) } } + if (AZ::JsonRegistrationContext* jsonContext = azrtti_cast(reflection)) + { + jsonContext->Serializer() + ->HandlesType(); + } + if (BehaviorContext* behaviorContext = azrtti_cast(reflection)) { // reflect default entity diff --git a/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.cpp b/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.cpp index 16b6a2c48b..036c2df297 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.cpp @@ -98,14 +98,14 @@ namespace AZ return nullptr; } //------------------------------------------------------------------------- - void DynamicSerializableField::CopyDataFrom(const DynamicSerializableField& other) + void DynamicSerializableField::CopyDataFrom(const DynamicSerializableField& other, SerializeContext* useContext) { DestroyData(); m_typeId = other.m_typeId; - m_data = other.CloneData(); + m_data = other.CloneData(useContext); } //------------------------------------------------------------------------- - bool DynamicSerializableField::IsEqualTo(const DynamicSerializableField& other, SerializeContext* useContext) + bool DynamicSerializableField::IsEqualTo(const DynamicSerializableField& other, SerializeContext* useContext) const { if (other.m_typeId != m_typeId) { diff --git a/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.h b/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.h index 70a8924265..4b5a963b26 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.h +++ b/Code/Framework/AzCore/AzCore/Serialization/DynamicSerializableField.h @@ -9,6 +9,8 @@ #define AZCORE_DYNAMIC_SERIALIZABLE_FIELD_H #include +#include +#include namespace AZ { @@ -24,6 +26,7 @@ namespace AZ { public: AZ_TYPE_INFO(DynamicSerializableField, "{D761E0C2-A098-497C-B8EB-EA62F5ED896B}") + AZ_CLASS_ALLOCATOR(DynamicSerializableField, AZ::SystemAllocator, 0); DynamicSerializableField(); DynamicSerializableField(const DynamicSerializableField& serializableField); @@ -33,8 +36,8 @@ namespace AZ void DestroyData(SerializeContext* useContext = nullptr); void* CloneData(SerializeContext* useContext = nullptr) const; - void CopyDataFrom(const DynamicSerializableField& other); - bool IsEqualTo(const DynamicSerializableField& other, SerializeContext* useContext = nullptr); + void CopyDataFrom(const DynamicSerializableField& other, SerializeContext* useContext = nullptr); + bool IsEqualTo(const DynamicSerializableField& other, SerializeContext* useContext = nullptr) const; template void Set(T* object) diff --git a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h index 2926a40252..02346c2ba1 100644 --- a/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h +++ b/Code/Framework/AzCore/AzCore/Settings/SettingsRegistryMergeUtils.h @@ -28,6 +28,7 @@ namespace AZ::SettingsRegistryMergeUtils inline static constexpr char FilePathsRootKey[] = "/Amazon/AzCore/Runtime/FilePaths"; inline static constexpr char FilePathKey_BinaryFolder[] = "/Amazon/AzCore/Runtime/FilePaths/BinaryFolder"; inline static constexpr char FilePathKey_EngineRootFolder[] = "/Amazon/AzCore/Runtime/FilePaths/EngineRootFolder"; + inline static constexpr char FilePathKey_InstalledBinaryFolder[] = "/Amazon/AzCore/Runtime/FilePaths/InstalledBinariesFolder"; //! Stores the absolute path to root of a project's cache. No asset platform in this path, this is where the asset database file lives. //! i.e. /Cache diff --git a/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h b/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h index 86f41c6548..7a66167a96 100644 --- a/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h +++ b/Code/Framework/AzCore/AzCore/Slice/SliceComponent.h @@ -13,7 +13,6 @@ #include #include #include -#include #include namespace AZ diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index 1e2a0b98a0..c33d678730 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -462,6 +462,8 @@ set(FILES Script/ScriptTimePoint.h Script/ScriptProperty.h Script/ScriptProperty.cpp + Script/ScriptPropertySerializer.h + Script/ScriptPropertySerializer.cpp Script/ScriptPropertyTable.h Script/ScriptPropertyTable.cpp Script/ScriptPropertyWatcherBus.h diff --git a/Code/Framework/AzCore/AzCore/std/createdestroy.h b/Code/Framework/AzCore/AzCore/std/createdestroy.h index 3c60266562..94b86a58e4 100644 --- a/Code/Framework/AzCore/AzCore/std/createdestroy.h +++ b/Code/Framework/AzCore/AzCore/std/createdestroy.h @@ -21,7 +21,18 @@ namespace AZStd { // alias std::pointer_traits into the AZStd::namespace using std::pointer_traits; + + //! Bring the names of uninitialized_default_construct and + //! uninitialized_default_construct_n into the AZStd namespace + using std::uninitialized_default_construct; + using std::uninitialized_default_construct_n; + + //! uninitialized_value_construct and uninitialized_value_construct_n + //! are now brought into scope of the AZStd namespace + using std::uninitialized_value_construct; + using std::uninitialized_value_construct_n; } + namespace AZStd::Internal { template @@ -223,107 +234,6 @@ namespace AZStd } } -namespace AZStd -{ - //! C++20 implementation of uninitialized_default_construct - //! Initializes objects by default-initialization via placement new - //! Ex. `new(declval()) T` - Notice no parenthesis after T - //! This performs default initialization instead of value initialization - //! Default initialization performs the following actions - //! # If T is a class type it considers constructors which can be invoked - //! with an empty argument list. The selected constructor is invoked - //! to provide the initial value of the object - //! # If T is an array type, then default initialization is performed - //! on each array element - //! # Otherwise nothing is done and objects with automatic storage duration(i.e scope) - //! are initialized with indeterminate values - //! For example given the following struct - //! struct Foo - //! { - //! int mint; - //! double bubble; - //! }; - //! Invoking uninitialized_default_construct(FooPtr, FooPtr + 1) - //! Will default initialize the FooPtr object (Foo has an implicitly-defined default constructor) - //! The values of mint and bubble are indeterminate - template - constexpr auto uninitialized_default_construct(ForwardIt first, ForwardIt last) - -> enable_if_t, void> - { - for (; first != last; ++first) - { - return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits::value_type; - } - } - // C++20 implementation of uninitialized_default_construct_n - // Constructs "n" objects starting at first via default-initialization - template - constexpr auto uninitialized_default_construct_n(ForwardIt first, Size numElements) - -> enable_if_t, ForwardIt> - { - for (; numElements > 0; ++first, --numElements) - { - return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits::value_type; - } - - return first; - } -} - -namespace AZStd -{ - //! C++20 implementation of uninitialized_value_construct - //! Initializes objects by value-initialization via placement new - //! Ex. `new(declval()) T()` - Notice parenthesis are here after T - //! value-initialization of an object performs different rules depending - //! on the type of T - //! Value initialization performs the following actions - //! # If T is a class type with no default constructor or with a user-provided - //! constructor or a deleted default constructor, then default-initialization - //! is performed - //! # If T is a class type with a default constructor that is neither - //! user-provided nor deleted(i.e a class with an implicitly-defined or defaulted - //! default constructor), then the object is zero-initialized and then it is - //! default-initialized if it has a non-trivial default constructor - //! # If T is an array type, then value initialization is performed - //! on each array element - //! # Otherwise the object is zero-initialized - //! (i.e sets arithmetic and enum objects to 0, bool objects to false, pointers to nullptr) - //! For example given the following struct - //! struct Foo - //! { - //! int mint; - //! double bubble; - //! }; - //! Invoking uninitialized_default_construct(FooPtr, FooPtr + 1) - //! Will value-initialize the FooPtr object. - //! The Foo has an implicitly-defined default constructor. - //! For aggregates such as int and double this will perform zero-initialization - //! which will set their values to 0 - //! Therefore The values of mint will be 0 and and bubble 0.0 - template - constexpr auto uninitialized_value_construct(ForwardIt first, ForwardIt last) - -> enable_if_t, void> - { - for (; first != last; ++first) - { - return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits::value_type(); - } - } - // C++20 implementation of uninitialized_default_construct_n - // Constructs "n" objects starting at the first via by value-initialization - template - constexpr auto uninitialized_value_construct_n(ForwardIt first, Size numElements) - -> enable_if_t, ForwardIt> - { - for (; numElements > 0; ++first, --numElements) - { - return ::new (AZStd::addressof(*first)) typename AZStd::iterator_traits::value_type(); - } - - return first; - } -} namespace AZStd::Internal { diff --git a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/std/time_Apple.cpp b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/std/time_Apple.cpp index 4c67c5cfc5..a8a6ffea21 100644 --- a/Code/Framework/AzCore/Platform/Common/Apple/AzCore/std/time_Apple.cpp +++ b/Code/Framework/AzCore/Platform/Common/Apple/AzCore/std/time_Apple.cpp @@ -25,29 +25,7 @@ namespace AZStd AZStd::sys_time_t GetTimeNowTicks() { AZStd::sys_time_t timeNow; - struct timespec ts; - clock_serv_t cclock; - mach_timespec_t mts; - kern_return_t ret = host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); - if (ret == KERN_SUCCESS) - { - ret = clock_get_time(cclock, &mts); - if (ret == KERN_SUCCESS) - { - ts.tv_sec = mts.tv_sec; - ts.tv_nsec = mts.tv_nsec; - } - else - { - AZ_Assert(false, "clock_get_time error: %d\n", ret); - } - mach_port_deallocate(mach_task_self(), cclock); - } - else - { - AZ_Assert(false, "clock_get_time error: %d\n", ret); - } - timeNow = ts.tv_sec * GetTimeTicksPerSecond() + ts.tv_nsec; + timeNow = clock_gettime_nsec_np(CLOCK_UPTIME_RAW); return timeNow; } @@ -62,29 +40,7 @@ namespace AZStd AZStd::sys_time_t GetTimeNowSecond() { AZStd::sys_time_t timeNowSecond; - struct timespec ts; - clock_serv_t cclock; - mach_timespec_t mts; - kern_return_t ret = host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); - if (ret == KERN_SUCCESS) - { - ret = clock_get_time(cclock, &mts); - if (ret == KERN_SUCCESS) - { - ts.tv_sec = mts.tv_sec; - ts.tv_nsec = mts.tv_nsec; - } - else - { - AZ_Assert(false, "clock_get_time error: %d\n", ret); - } - mach_port_deallocate(mach_task_self(), cclock); - } - else - { - AZ_Assert(false, "clock_get_time error: %d\n", ret); - } - timeNowSecond = ts.tv_sec; + timeNowSecond = GetTimeNowTicks()/GetTimeTicksPerSecond(); return timeNowSecond; } diff --git a/Code/Framework/AzCore/Tests/AZStd/CreateDestroy.cpp b/Code/Framework/AzCore/Tests/AZStd/CreateDestroy.cpp index 9ccd1b0742..f9c72f6260 100644 --- a/Code/Framework/AzCore/Tests/AZStd/CreateDestroy.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/CreateDestroy.cpp @@ -134,4 +134,48 @@ namespace UnitTest EXPECT_FLOAT_EQ(4.0f, resultAddress->m_floatValue); AZStd::destroy_at(resultAddress); } + + TEST(CreateDestroy, UninitializedDefaultConstruct_IsAbleToConstructMultipleElements_Succeeds) + { + struct RefWrapper + { + RefWrapper() + {} + int m_intValue{ 2 }; + }; + constexpr size_t ArraySize = 2; + AZStd::aligned_storage_for_t testArray[ArraySize]; + RefWrapper(&uninitializedAddress)[2] = reinterpret_cast(testArray); + AZStd::uninitialized_default_construct(AZStd::begin(uninitializedAddress), AZStd::end(uninitializedAddress)); + + + EXPECT_EQ(2, uninitializedAddress[0].m_intValue); + EXPECT_EQ(2, uninitializedAddress[1].m_intValue); + // Reset uninitializedAddress to Debug pattern + memset(uninitializedAddress, 0xCD, ArraySize * sizeof(RefWrapper)); + AZStd::uninitialized_default_construct_n(AZStd::data(uninitializedAddress), AZStd::size(uninitializedAddress)); + EXPECT_EQ(2, uninitializedAddress[0].m_intValue); + EXPECT_EQ(2, uninitializedAddress[1].m_intValue); + } + + TEST(CreateDestroy, UninitializedValueConstruct_IsAbleToConstructMultipleElements_Succeeds) + { + struct RefWrapper + { + int m_intValue; + }; + constexpr size_t ArraySize = 2; + AZStd::aligned_storage_for_t testArray[ArraySize]; + RefWrapper(&uninitializedAddress)[2] = reinterpret_cast(testArray); + AZStd::uninitialized_value_construct(AZStd::begin(uninitializedAddress), AZStd::end(uninitializedAddress)); + + + EXPECT_EQ(0, uninitializedAddress[0].m_intValue); + EXPECT_EQ(0, uninitializedAddress[1].m_intValue); + // Reset uninitializedAddress to Debug pattern + memset(uninitializedAddress, 0xCD, ArraySize * sizeof(RefWrapper)); + AZStd::uninitialized_value_construct_n(AZStd::data(uninitializedAddress), AZStd::size(uninitializedAddress)); + EXPECT_EQ(0, uninitializedAddress[0].m_intValue); + EXPECT_EQ(0, uninitializedAddress[1].m_intValue); + } } diff --git a/Code/Framework/AzFramework/AzFramework/Components/CameraBus.h b/Code/Framework/AzFramework/AzFramework/Components/CameraBus.h index 0b2a0cbb78..e20578e939 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/CameraBus.h +++ b/Code/Framework/AzFramework/AzFramework/Components/CameraBus.h @@ -114,6 +114,9 @@ namespace Camera //! Makes the camera the active view virtual void MakeActiveView() = 0; + //! Check if this camera is the active render camera + virtual bool IsActiveView() = 0; + //! Get the camera frustum's aggregate configuration virtual Configuration GetCameraConfiguration() { diff --git a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp index 68e7c4e483..148b1cbdfe 100644 --- a/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp +++ b/Code/Framework/AzFramework/Platform/Mac/AzFramework/Process/ProcessWatcher_Mac.cpp @@ -24,7 +24,9 @@ #include #include // for iopolicy #include +#include +extern char **environ; namespace AzFramework { @@ -45,7 +47,7 @@ namespace AzFramework // result == 0 means child PID is still running, nothing to check if (result == -1) { - AZ_TracePrintf("ProcessWatcher", "IsChildProcessDone could not determine child process status (waitpid errno %d). assuming process either failed to launch or terminated unexpectedly\n", errno); + AZ_TracePrintf("ProcessWatcher", "IsChildProcessDone could not determine child process status (waitpid errno %d(%s)). assuming process either failed to launch or terminated unexpectedly\n", errno, strerror(errno)); exitCode = 0; } else if (result == childProcessId) @@ -274,28 +276,27 @@ namespace AzFramework azstrcat(commandAndArgs[i], token.size(), token.c_str()); } commandAndArgs[commandTokens.size()] = nullptr; - - char** environmentVariables = nullptr; - int numEnvironmentVars = 0; + + constexpr int MaxEnvVariables = 128; + using EnvironmentVariableContainer = AZStd::fixed_vector; + EnvironmentVariableContainer environmentVariables; + for (char **env = ::environ; *env; env++) + { + environmentVariables.push_back(*env); + } if (processLaunchInfo.m_environmentVariables) { - const int numEnvironmentVars = processLaunchInfo.m_environmentVariables->size(); - // Adding one more as exec expects the array to have a nullptr as the last element - environmentVariables = new char*[numEnvironmentVars + 1]; - for (int i = 0; i < numEnvironmentVars; i++) + for (AZStd::string& processLaunchEnv : *processLaunchInfo.m_environmentVariables) { - const AZStd::string& envVarString = processLaunchInfo.m_environmentVariables->at(i); - environmentVariables[i] = new char[envVarString.size() + 1]; - environmentVariables[i][0] = '\0'; - azstrcat(environmentVariables[i], envVarString.size(), envVarString.c_str()); + environmentVariables.push_back(processLaunchEnv.data()); } - environmentVariables[numEnvironmentVars] = NULL; } + environmentVariables.push_back(nullptr); pid_t child_pid = fork(); if (IsIdChildProcess(child_pid)) { - ExecuteCommandAsChild(commandAndArgs, environmentVariables, processLaunchInfo, processData.m_startupInfo); + ExecuteCommandAsChild(commandAndArgs, environmentVariables.data(), processLaunchInfo, processData.m_startupInfo); } processData.m_childProcessId = child_pid; @@ -303,15 +304,6 @@ namespace AzFramework // Close these handles as they are only to be used by the child process processData.m_startupInfo.CloseAllHandles(); - if (processLaunchInfo.m_environmentVariables) - { - for (int i = 0; i < numEnvironmentVars; i++) - { - delete [] environmentVariables[i]; - } - delete [] environmentVariables; - } - for (int i = 0; i < commandTokens.size(); i++) { delete [] commandAndArgs[i]; diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp index e92bbbc6e3..78364fbd0d 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_Windows.cpp @@ -8,6 +8,7 @@ #include <../Common/WinAPI/AzFramework/Input/Devices/Keyboard/InputDeviceKeyboard_WinAPI.h> #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace @@ -29,7 +30,7 @@ namespace AzFramework { //////////////////////////////////////////////////////////////////////////////////////////// //! Count of the number instances of this class that have been created - static int s_instanceCount; + static AZ::EnvironmentVariable s_instanceCount; public: //////////////////////////////////////////////////////////////////////////////////////////// @@ -106,7 +107,7 @@ namespace AzFramework } //////////////////////////////////////////////////////////////////////////////////////////////// - int InputDeviceKeyboardWindows::s_instanceCount = 0; + AZ::EnvironmentVariable InputDeviceKeyboardWindows::s_instanceCount = nullptr; //////////////////////////////////////////////////////////////////////////////////////////////// InputDeviceKeyboardWindows::InputDeviceKeyboardWindows(InputDeviceKeyboard& inputDevice) @@ -116,8 +117,10 @@ namespace AzFramework , m_hasFocus(false) , m_hasTextEntryStarted(false) { - if (s_instanceCount++ == 0) + if (!s_instanceCount) { + s_instanceCount = AZ::Environment::CreateVariable("InputDeviceKeyboardInstanceCount", 1); + // Register for raw keyboard input RAWINPUTDEVICE rawInputDevice; rawInputDevice.usUsagePage = RAW_INPUT_KEYBOARD_USAGE_PAGE; @@ -128,6 +131,10 @@ namespace AzFramework AZ_Assert(result, "Failed to register raw input device: keyboard"); AZ_UNUSED(result); } + else + { + s_instanceCount.Set(s_instanceCount.Get() + 1); + } RawInputNotificationBusWindows::Handler::BusConnect(); } @@ -137,7 +144,8 @@ namespace AzFramework { RawInputNotificationBusWindows::Handler::BusDisconnect(); - if (--s_instanceCount == 0) + int instanceCount = s_instanceCount.Get(); + if (--instanceCount == 0) { // Deregister from raw keyboard input RAWINPUTDEVICE rawInputDevice; @@ -148,7 +156,13 @@ namespace AzFramework const BOOL result = RegisterRawInputDevices(&rawInputDevice, 1, sizeof(rawInputDevice)); AZ_Assert(result, "Failed to deregister raw input device: keyboard"); AZ_UNUSED(result); + + s_instanceCount.Reset(); } + else + { + s_instanceCount.Set(instanceCount); + } } //////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp index 9452696cd2..464f49d620 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Input/Devices/Mouse/InputDeviceMouse_Windows.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -43,7 +44,7 @@ namespace AzFramework { //////////////////////////////////////////////////////////////////////////////////////////// //! Count of the number instances of this class that have been created - static int s_instanceCount; + static AZ::EnvironmentVariable s_instanceCount; public: //////////////////////////////////////////////////////////////////////////////////////////// @@ -125,7 +126,7 @@ namespace AzFramework } //////////////////////////////////////////////////////////////////////////////////////////////// - int InputDeviceMouseWindows::s_instanceCount = 0; + AZ::EnvironmentVariable InputDeviceMouseWindows::s_instanceCount = nullptr; //////////////////////////////////////////////////////////////////////////////////////////////// InputDeviceMouseWindows::InputDeviceMouseWindows(InputDeviceMouse& inputDevice) @@ -137,18 +138,24 @@ namespace AzFramework { memset(&m_lastClientRect, 0, sizeof(m_lastClientRect)); - if (s_instanceCount++ == 0) + if (!s_instanceCount) { + s_instanceCount = AZ::Environment::CreateVariable("InputDeviceMouseInstanceCount", 1); + // Register for raw mouse input RAWINPUTDEVICE rawInputDevice; rawInputDevice.usUsagePage = RAW_INPUT_MOUSE_USAGE_PAGE; - rawInputDevice.usUsage = RAW_INPUT_MOUSE_USAGE; - rawInputDevice.dwFlags = 0; - rawInputDevice.hwndTarget = 0; + rawInputDevice.usUsage = RAW_INPUT_MOUSE_USAGE; + rawInputDevice.dwFlags = 0; + rawInputDevice.hwndTarget = 0; const BOOL result = RegisterRawInputDevices(&rawInputDevice, 1, sizeof(rawInputDevice)); AZ_Assert(result, "Failed to register raw input device: mouse"); AZ_UNUSED(result); } + else + { + s_instanceCount.Set(s_instanceCount.Get() + 1); + } RawInputNotificationBusWindows::Handler::BusConnect(); } @@ -161,7 +168,8 @@ namespace AzFramework // Cleanup system cursor visibility and constraint SetSystemCursorState(SystemCursorState::Unknown); - if (--s_instanceCount == 0) + int instanceCount = s_instanceCount.Get(); + if (--instanceCount == 0) { // Deregister from raw mouse input RAWINPUTDEVICE rawInputDevice; @@ -172,6 +180,12 @@ namespace AzFramework const BOOL result = RegisterRawInputDevices(&rawInputDevice, 1, sizeof(rawInputDevice)); AZ_Assert(result, "Failed to deregister raw input device: mouse"); AZ_UNUSED(result); + + s_instanceCount.Reset(); + } + else + { + s_instanceCount.Set(instanceCount); } } diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Application/AzQtApplication.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Application/AzQtApplication.cpp index 594a339448..9dece6e26a 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Application/AzQtApplication.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Application/AzQtApplication.cpp @@ -22,8 +22,6 @@ namespace AzQtComponents QApplication::setApplicationName("O3DE Tools Application"); AzQtComponents::PrepareQtPaths(); - - QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); } void AzQtApplication::InitializeDpiScaling() diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp index 51ca2b349f..fc8af9e8ce 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Gallery/main.cpp @@ -134,8 +134,6 @@ int main(int argc, char **argv) QApplication::setOrganizationDomain("o3de.org"); QApplication::setApplicationName("O3DEWidgetGallery"); - QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); - QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp index da4d8de4cd..39593a1c58 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Tests/FloatToStringConversionTests.cpp @@ -13,54 +13,94 @@ TEST(AzQtComponents, FloatToString_Truncate2Decimals) { - QLocale testLocal(QLocale::English, QLocale::UnitedStates); + QLocale testLocale(QLocale::English, QLocale::UnitedStates); const bool showThousandsSeparator = false; const int numDecimalPlaces = 2; - EXPECT_EQ(AzQtComponents::toString(0.1234, numDecimalPlaces, testLocal, showThousandsSeparator), "0.12"); + EXPECT_EQ(AzQtComponents::toString(0.1234, numDecimalPlaces, testLocale, showThousandsSeparator), "0.12"); } TEST(AzQtComponents, FloatToString_AllZerosButOne) { - QLocale testLocal(QLocale::English, QLocale::UnitedStates); + QLocale testLocale(QLocale::English, QLocale::UnitedStates); const bool showThousandsSeparator = false; int numDecimalPlaces = 2; - EXPECT_EQ(AzQtComponents::toString(1.0000, numDecimalPlaces, testLocal, showThousandsSeparator), "1.0"); + EXPECT_EQ(AzQtComponents::toString(1.0000, numDecimalPlaces, testLocale, showThousandsSeparator), "1.0"); } TEST(AzQtComponents, FloatToString_TruncateAllZerosButOne) { - QLocale testLocal(QLocale::English, QLocale::UnitedStates); + QLocale testLocale(QLocale::English, QLocale::UnitedStates); const bool showThousandsSeparator = false; int numDecimalPlaces = 2; - EXPECT_EQ(AzQtComponents::toString(1.0001, numDecimalPlaces, testLocal, showThousandsSeparator), "1.0"); + EXPECT_EQ(AzQtComponents::toString(1.0001, numDecimalPlaces, testLocale, showThousandsSeparator), "1.0"); } TEST(AzQtComponents, FloatToString_TruncateNotRound) { - QLocale testLocal(QLocale::English, QLocale::UnitedStates); + QLocale testLocale(QLocale::English, QLocale::UnitedStates); const bool showThousandsSeparator = false; int numDecimalPlaces = 3; - EXPECT_EQ(AzQtComponents::toString(0.1236, numDecimalPlaces, testLocal, showThousandsSeparator), "0.123"); + EXPECT_EQ(AzQtComponents::toString(0.1236, numDecimalPlaces, testLocale, showThousandsSeparator), "0.123"); } TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorTruncateNoRound) { - QLocale testLocal(QLocale::English, QLocale::UnitedStates); + QLocale testLocale(QLocale::English, QLocale::UnitedStates); const bool showThousandsSeparator = true; int numDecimalPlaces = 3; - EXPECT_EQ(AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocal, showThousandsSeparator), "1,000.123"); + EXPECT_EQ(AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocale, showThousandsSeparator), "1,000.123"); } TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorOnlyOneDecimal) { - QLocale testLocal(QLocale::English, QLocale::UnitedStates); + QLocale testLocale(QLocale::English, QLocale::UnitedStates); const bool showThousandsSeparator = true; int numDecimalPlaces = 2; - EXPECT_EQ(AzQtComponents::toString(1000.000, numDecimalPlaces, testLocal, showThousandsSeparator), "1,000.0"); + EXPECT_EQ(AzQtComponents::toString(1000.000, numDecimalPlaces, testLocale, showThousandsSeparator), "1,000.0"); +} + +TEST(AzQtComponents, FloatToString_Truncate2DecimalsWithLocale) +{ + QLocale testLocale{ QLocale() }; + + const bool showThousandsSeparator = false; + const int numDecimalPlaces = 2; + QString testString = "0" + QString(testLocale.decimalPoint()) + "12"; + EXPECT_EQ(testString, AzQtComponents::toString(0.1234, numDecimalPlaces, testLocale, showThousandsSeparator)); +} + +TEST(AzQtComponents, FloatToString_AllZerosButOneWithLocale) +{ + QLocale testLocale{ QLocale() }; + + const bool showThousandsSeparator = false; + const int numDecimalPlaces = 2; + QString testString = "1" + QString(testLocale.decimalPoint()) + "0"; + EXPECT_EQ(testString, AzQtComponents::toString(1.0000, numDecimalPlaces, testLocale, showThousandsSeparator)); +} + +TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorTruncateNoRoundWithLocale) +{ + QLocale testLocale{ QLocale() }; + + const bool showThousandsSeparator = true; + const int numDecimalPlaces = 3; + QString testString = "1" + QString(testLocale.groupSeparator()) + "000" + QString(testLocale.decimalPoint()) + "123"; + EXPECT_EQ(testString, AzQtComponents::toString(1000.1236, numDecimalPlaces, testLocale, showThousandsSeparator)); +} + +TEST(AzQtComponents, FloatToString_TruncateShowThousandsSeparatorOnlyOneDecimalWithLocale) +{ + QLocale testLocale{ QLocale() }; + + const bool showThousandsSeparator = true; + int numDecimalPlaces = 2; + QString testString = "1" + QString(testLocale.groupSeparator()) + "000" + QString(testLocale.decimalPoint()) + "0"; + EXPECT_EQ(testString, AzQtComponents::toString(1000.000, numDecimalPlaces, testLocale, showThousandsSeparator)); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp index 5a8099370b..c729ac4d6f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserFilterModel.cpp @@ -186,6 +186,7 @@ namespace AzToolsFramework } } invalidateFilter(); + Q_EMIT filterChanged(); } @@ -205,6 +206,6 @@ namespace AzToolsFramework } } // namespace AssetBrowser -} // namespace AzToolsFramework// namespace AssetBrowser +} // namespace AzToolsFramework #include "AssetBrowser/moc_AssetBrowserFilterModel.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp index 4588e5ff98..f0e1520aab 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserModel.cpp @@ -134,7 +134,8 @@ namespace AzToolsFramework { return 0; } - + + //If the column of the parent is one of those we don't want any more rows as children if (parent.isValid()) { if ((parent.column() != aznumeric_cast(AssetBrowserEntry::Column::DisplayName)) && diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp index 9f2d232024..efa47e600d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.cpp @@ -90,24 +90,38 @@ namespace AzToolsFramework const QAbstractItemModel* model, const QModelIndex& parent /*= QModelIndex()*/, int row /*= 0*/) { int rows = model ? model->rowCount(parent) : 0; - for (int i = 0; i < rows; ++i) + + if (parent == QModelIndex()) { - QModelIndex index = model->index(i, 0, parent); - AssetBrowserEntry* entry = GetAssetEntry(m_filterModel->mapToSource(index)); - //We only wanna see the source assets. - if (entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Source) - { - beginInsertRows(parent, row, row); - m_indexMap[row] = index; - endInsertRows(); + m_displayedItemsCounter = 0; + } - Q_EMIT dataChanged(index, index); - ++row; + for (int currentRow = 0; currentRow < rows; ++currentRow) + { + if (m_displayedItemsCounter < m_numberOfItemsDisplayed) + { + QModelIndex index = model->index(currentRow, 0, parent); + AssetBrowserEntry* entry = GetAssetEntry(m_filterModel->mapToSource(index)); + // We only want to see the source assets. + if (entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Source) + { + beginInsertRows(parent, row, row); + m_indexMap[row] = index; + endInsertRows(); + + Q_EMIT dataChanged(index, index); + ++row; + ++m_displayedItemsCounter; + } + + if (model->hasChildren(index)) + { + row = BuildTableModelMap(model, index, row); + } } - - if (model->hasChildren(index)) + else { - row = BuildTableModelMap(model, index, row); + break; } } return row; @@ -135,6 +149,10 @@ namespace AzToolsFramework m_indexMap.clear(); endRemoveRows(); } + + AzToolsFramework::EditorSettingsAPIBus::BroadcastResult( + m_numberOfItemsDisplayed, &AzToolsFramework::EditorSettingsAPIBus::Handler::GetMaxNumberOfItemsShownInSearchView); + BuildTableModelMap(sourceModel()); emit layoutChanged(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h index 449de6fcb8..d80e2bd093 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/AssetBrowserTableModel.h @@ -12,6 +12,7 @@ #include #include #endif +#include namespace AzToolsFramework { @@ -50,6 +51,8 @@ namespace AzToolsFramework int BuildTableModelMap(const QAbstractItemModel* model, const QModelIndex& parent = QModelIndex(), int row = 0); private: + int m_numberOfItemsDisplayed = 50; + int m_displayedItemsCounter = 0; QPointer m_filterModel; QMap m_indexMap; }; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp index 40cc503b61..940d64fe94 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.cpp @@ -6,18 +6,10 @@ * */ -#include - -#include - -#include #include #include #include -#include -#include -#include #include #include @@ -28,9 +20,7 @@ AZ_PUSH_DISABLE_WARNING( #include #include #include -#include -#include -#include + #include AZ_POP_DISABLE_WARNING namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h index 9351235b04..e5426037bf 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBrowser/Views/AssetBrowserTableView.h @@ -9,7 +9,6 @@ #if !defined(Q_MOC_RUN) #include #include -#include #include #include @@ -55,7 +54,6 @@ namespace AzToolsFramework void OnAssetBrowserComponentReady() override; ////////////////////////////////////////////////////////////////////////// - Q_SIGNALS: void selectionChangedSignal(const QItemSelection& selected, const QItemSelection& deselected); void ClearStringFilter(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h index 4a3406904a..fedb889fbb 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Editor/EditorSettingsAPIBus.h @@ -38,6 +38,7 @@ namespace AzToolsFramework virtual SettingOutcome GetValue(const AZStd::string_view path) = 0; virtual SettingOutcome SetValue(const AZStd::string_view path, const AZStd::any& value) = 0; virtual ConsoleColorTheme GetConsoleColorTheme() const = 0; + virtual int GetMaxNumberOfItemsShownInSearchView() const = 0; }; using EditorSettingsAPIBus = AZ::EBus; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/ScriptEditorComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/ScriptEditorComponent.cpp index 1ae1a3605a..da12a4bd7a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/ScriptEditorComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/ScriptEditorComponent.cpp @@ -1107,17 +1107,7 @@ namespace AzToolsFramework ElementAttribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)-> Attribute(AZ::Edit::Attributes::NameLabelOverride, &AZ::ScriptProperty::m_name); - ec->Class("Script Property Asset(asset)", "A script asset property")-> - ClassElement(AZ::Edit::ClassElements::EditorData, "ScriptPropertyEditorAsset's class attributes.")-> - Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)-> - DataElement("Asset", &AZ::ScriptPropertyAsset::m_value, "m_value", "An object")-> - Attribute(AZ::Edit::Attributes::NameLabelOverride, &AZ::ScriptProperty::m_name); - ec->Class("Script Property Entity(EntityRef)", "A script entity reference property")-> - ClassElement(AZ::Edit::ClassElements::EditorData, "ScriptPropertyEditorEntityRef's class attributes.")-> - Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)-> - DataElement("EntityRef", &AZ::ScriptPropertyEntityRef::m_value, "m_entity", "An entity reference")-> - Attribute(AZ::Edit::Attributes::NameLabelOverride, &AZ::ScriptProperty::m_name); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp index 5ffbe1b4f3..1bec929223 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.cpp @@ -65,6 +65,35 @@ namespace UnitTest } } + bool FocusInteractionWidget::event(QEvent* event) + { + using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; + + auto eventType = event->type(); + + switch (eventType) + { + case QEvent::MouseButtonPress: + EditorInteractionSystemViewportSelectionRequestBus::Event( + AzToolsFramework::GetEntityContextId(), &EditorInteractionSystemViewportSelectionRequestBus::Events::SetDefaultHandler); + return true; + case QEvent::FocusIn: + case QEvent::FocusOut: + { + bool handled = false; + AzToolsFramework::ViewportInteraction::MouseInteraction mouseInteraction; + EditorInteractionSystemViewportSelectionRequestBus::EventResult( + handled, AzToolsFramework::GetEntityContextId(), + &EditorInteractionSystemViewportSelectionRequestBus::Events::InternalHandleMouseViewportInteraction, + AzToolsFramework::ViewportInteraction::MouseInteractionEvent( + mouseInteraction, AzToolsFramework::ViewportInteraction::MouseEvent::Down)); + return handled; + } + } + + return QWidget::event(event); + } + void TestEditorActions::Connect() { using AzToolsFramework::GetEntityContextId; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h index 7967f58bf6..3c413fd21e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h @@ -8,6 +8,7 @@ #pragma once +#if !defined(Q_MOC_RUN) #include #include #include @@ -31,6 +32,7 @@ #include #include #include +#endif // !defined(Q_MOC_RUN) #include @@ -40,7 +42,7 @@ AZ_POP_DISABLE_WARNING #define AUTO_RESULT_IF_SETTING_TRUE(_settingName, _result) \ { \ - bool settingValue = true; \ + bool settingValue = true; \ if (auto* registry = AZ::SettingsRegistry::Get()) \ { \ registry->Get(settingValue, _settingName); \ @@ -51,23 +53,16 @@ AZ_POP_DISABLE_WARNING EXPECT_TRUE(_result); \ return; \ } \ - } - -namespace AZ -{ - class Entity; - class EntityId; - -} // namespace AZ + } namespace UnitTest { constexpr AZStd::string_view prefabSystemSetting = "/Amazon/Preferences/EnablePrefabSystem"; /// Test widget to store QActions generated by EditorTransformComponentSelection. - class TestWidget - : public QWidget + class TestWidget : public QWidget { + Q_OBJECT public: TestWidget() : QWidget() @@ -79,6 +74,15 @@ namespace UnitTest bool eventFilter(QObject* watched, QEvent* event) override; }; + /// Widget used to trigger a viewport interaction event while a focus change is happening. + class FocusInteractionWidget : public QWidget + { + Q_OBJECT + public: + FocusInteractionWidget(QWidget* parent = nullptr) : QWidget(parent) {} + bool event(QEvent* event) override; + }; + /// Stores actions registered for either normal mode (regular viewport) editing and /// component mode editing. class TestEditorActions diff --git a/Code/Framework/AzToolsFramework/CMakeLists.txt b/Code/Framework/AzToolsFramework/CMakeLists.txt index a2138b8a0e..62f4f43d93 100644 --- a/Code/Framework/AzToolsFramework/CMakeLists.txt +++ b/Code/Framework/AzToolsFramework/CMakeLists.txt @@ -50,6 +50,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( NAME AzToolsFrameworkTestCommon STATIC NAMESPACE AZ + AUTOMOC FILES_CMAKE AzToolsFramework/aztoolsframeworktestcommon_files.cmake INCLUDE_DIRECTORIES @@ -68,6 +69,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_target( NAME AzToolsFramework.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} NAMESPACE AZ + AUTOMOC FILES_CMAKE Tests/aztoolsframeworktests_files.cmake INCLUDE_DIRECTORIES diff --git a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp index f45b3c3b09..895c91b0a4 100644 --- a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp @@ -31,8 +31,10 @@ #include #include #include +#include #include #include +#include namespace AZ { @@ -188,6 +190,47 @@ namespace UnitTest /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // EditorTransformComponentSelection Tests + TEST_F(EditorTransformComponentSelectionFixture, Focus_is_not_changed_while_switching_viewport_interaction_request_instance) + { + // setup a dummy widget and make it the active window to ensure focus in/out events are fired + auto dummyWidget = AZStd::make_unique(); + QApplication::setActiveWindow(dummyWidget.get()); + + // note: it is important to make sure the focus widget is parented to the dummy widget to have focus in/out events fire + auto focusWidget = AZStd::make_unique(dummyWidget.get()); + + const auto previousFocusWidget = QApplication::focusWidget(); + + // Given + // setup viewport ui system + AzToolsFramework::ViewportUi::ViewportUiManager viewportUiManager; + viewportUiManager.ConnectViewportUiBus(AzToolsFramework::ViewportUi::DefaultViewportId); + viewportUiManager.InitializeViewportUi(&m_editorActions.m_defaultWidget, focusWidget.get()); + + // begin EditorPickEntitySelection + using AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus; + EditorInteractionSystemViewportSelectionRequestBus::Event( + AzToolsFramework::GetEntityContextId(), &EditorInteractionSystemViewportSelectionRequestBus::Events::SetHandler, + [](const AzToolsFramework::EditorVisibleEntityDataCache* entityDataCache) + { + return AZStd::make_unique(entityDataCache); + }); + + // When + // a mouse event is sent to the focus widget (set to be the render overlay in the viewport ui system) + QTest::mouseClick(focusWidget.get(), Qt::MouseButton::LeftButton); + + // Then + // focus should not change + EXPECT_FALSE(focusWidget->hasFocus()); + EXPECT_EQ(previousFocusWidget, QApplication::focusWidget()); + + // clean up + viewportUiManager.DisconnectViewportUiBus(); + focusWidget.reset(); + dummyWidget.reset(); + } + TEST_F(EditorTransformComponentSelectionFixture, ManipulatorOrientationIsResetWhenEntityOrientationIsReset) { using AzToolsFramework::EditorTransformComponentSelectionRequestBus; diff --git a/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp b/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp index eb09c68cee..a88cb68638 100644 --- a/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/SpinBoxTests.cpp @@ -245,12 +245,15 @@ namespace UnitTest { using testing::StrEq; + QLocale testLocale{ QLocale() }; + QString testString = "10" + QString(testLocale.decimalPoint()) + "0"; + m_doubleSpinBox->setSuffix("m"); m_doubleSpinBox->setValue(10.0); // test internal logic (textFromValue() calls private StringValue()) QString value = m_doubleSpinBox->textFromValue(10.0); - EXPECT_THAT(value.toUtf8().constData(), StrEq("10.0")); + EXPECT_THAT(value.toUtf8().constData(), testString); m_doubleSpinBox->setFocus(); EXPECT_THAT(m_doubleSpinBox->suffix().toUtf8().constData(), StrEq("")); @@ -293,31 +296,44 @@ namespace UnitTest TEST_F(SpinBoxFixture, SpinBoxCheckHighValueTruncatesCorrectly) { - QString value = setupTruncationTest("0.9999999"); + QLocale testLocale{ QLocale() }; + QString testString = "0" + QString(testLocale.decimalPoint()) + "9999999"; + QString value = setupTruncationTest(testString); - EXPECT_TRUE(value == "0.999"); + testString = "0" + QString(testLocale.decimalPoint()) + "999"; + EXPECT_TRUE(value == testString); } TEST_F(SpinBoxFixture, SpinBoxCheckLowValueTruncatesCorrectly) { - QString value = setupTruncationTest("0.0000001"); + QLocale testLocale{ QLocale() }; + QString testString = "0" + QString(testLocale.decimalPoint()) + "0000001"; + QString value = setupTruncationTest(testString); - EXPECT_TRUE(value == "0.0"); + testString = "0" + QString(testLocale.decimalPoint()) + "0"; + EXPECT_TRUE(value == testString); } TEST_F(SpinBoxFixture, SpinBoxCheckBugValuesTruncatesCorrectly) { - QString value = setupTruncationTest("0.12395"); + QLocale testLocale{ QLocale() }; + QString testString = "0" + QString(testLocale.decimalPoint()) + "12395"; + QString value = setupTruncationTest(testString); - EXPECT_TRUE(value == "0.123"); + testString = "0" + QString(testLocale.decimalPoint()) + "123"; + EXPECT_TRUE(value == testString); - value = setupTruncationTest("0.94496"); + testString = "0" + QString(testLocale.decimalPoint()) + "94496"; + value = setupTruncationTest(testString); - EXPECT_TRUE(value == "0.944"); + testString = "0" + QString(testLocale.decimalPoint()) + "944"; + EXPECT_TRUE(value == testString); - value = setupTruncationTest("0.0009999"); + testString = "0" + QString(testLocale.decimalPoint()) + "0009999"; + value = setupTruncationTest(testString); - EXPECT_TRUE(value == "0.0"); + testString = "0" + QString(testLocale.decimalPoint()) + "0"; + EXPECT_TRUE(value == testString); } } // namespace UnitTest diff --git a/Code/Legacy/CryCommon/AndroidSpecific.h b/Code/Legacy/CryCommon/AndroidSpecific.h index d4832172fc..0cb4a6786c 100644 --- a/Code/Legacy/CryCommon/AndroidSpecific.h +++ b/Code/Legacy/CryCommon/AndroidSpecific.h @@ -30,17 +30,6 @@ #define MOBILE #endif -#if (defined(__clang__) && NDK_REV_MAJOR >= 14) || (defined(_CPU_ARM) && defined(PLATFORM_64BIT)) - // The version of clang that NDK r14+ ships with is seemingly generating different (for better or worse) code for the atomic operations - // used in the LocklessLinkedList. In either case, this is causing deadlocks in the job system and crashes from memory stomps in - // the bucket allocator. By defining INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED it will disable the Cry job system as well as - // change the implementation of the LocklessLinkedList to use a mutex in it's operations instead, essentially use the same behaviour - // as iOS. While not ideal to use this as a band-aid on the problem, it does fix it with a negligible performance impact. - // - // Additionally, arm64 processors do not provide a cmpxchg16b (or equivalent) instruction required for _InterlockedCompareExchange128 - #define INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED -#endif - // Force all allocations to be aligned to TARGET_DEFAULT_ALIGN. // This is because malloc on Android 32 bit returns memory that is not aligned // to what some structs/classes need. diff --git a/Code/Legacy/CryCommon/CryThread.h b/Code/Legacy/CryCommon/CryThread.h index 691616651a..5929bed352 100644 --- a/Code/Legacy/CryCommon/CryThread.h +++ b/Code/Legacy/CryCommon/CryThread.h @@ -78,77 +78,6 @@ public: ~CryAutoLock() { m_pLock->Unlock(); } }; -////////////////////////////////////////////////////////////////////////// -// -// CryOptionalAutoLock implements a helper class to automatically -// lock critical section (if needed) in constructor and release on destructor. -// -////////////////////////////////////////////////////////////////////////// -template -class CryOptionalAutoLock -{ -private: - LockClass* m_Lock; - bool m_bLockAcquired; - - CryOptionalAutoLock(); - CryOptionalAutoLock(const CryOptionalAutoLock&); - CryOptionalAutoLock& operator = (const CryOptionalAutoLock&); - -public: - CryOptionalAutoLock(LockClass& Lock, bool acquireLock) - : m_Lock(&Lock) - , m_bLockAcquired(false) - { - if (acquireLock) - { - Acquire(); - } - } - ~CryOptionalAutoLock() - { - Release(); - } - void Release() - { - if (m_bLockAcquired) - { - m_Lock->Unlock(); - m_bLockAcquired = false; - } - } - void Acquire() - { - if (!m_bLockAcquired) - { - m_Lock->Lock(); - m_bLockAcquired = true; - } - } -}; - -////////////////////////////////////////////////////////////////////////// -// -// CryAutoSet implements a helper class to automatically -// set and reset value in constructor and release on destructor. -// -////////////////////////////////////////////////////////////////////////// -template -class CryAutoSet -{ -private: - ValueClass* m_pValue; - - CryAutoSet(); - CryAutoSet(const CryAutoSet&); - CryAutoSet& operator = (const CryAutoSet&); - -public: - CryAutoSet(ValueClass& value) - : m_pValue(&value) { *m_pValue = (ValueClass)1; } - ~CryAutoSet() { *m_pValue = (ValueClass)0; } -}; - ////////////////////////////////////////////////////////////////////////// // // Auto critical section is the most commonly used type of auto lock. @@ -156,10 +85,6 @@ public: ////////////////////////////////////////////////////////////////////////// typedef CryAutoLock CryAutoCriticalSection; -#define AUTO_LOCK_T(Type, lock) PREFAST_SUPPRESS_WARNING(6246); CryAutoLock __AutoLock(lock) -#define AUTO_LOCK(lock) AUTO_LOCK_T(CryCriticalSection, lock) -#define AUTO_LOCK_CS(csLock) CryAutoCriticalSection __AL__##csLock(csLock) - ///////////////////////////////////////////////////////////////////////////// // // Threads. @@ -235,14 +160,6 @@ struct CryThreadInfo template class CrySimpleThread; -// Standard thread class. -// -// The class provides a lock (mutex) and an associated condition variable. If -// you don't need the lock, then you should used CrySimpleThread instead of -// CryThread. -template -class CryThread; - /////////////////////////////////////////////////////////////////////////////// // Include architecture specific code. #if AZ_LEGACY_CRYCOMMON_TRAIT_USE_PTHREADS @@ -265,560 +182,5 @@ class CryThread; typedef CryLockT CryMutex; #endif // !_CRYTHREAD_CONDLOCK_GLITCH -// The the architecture specific code does not define a class CryRWLock, then -// a default implementation is provided here. -#if !defined _CRYTHREAD_HAVE_RWLOCK && !defined _CRYTHREAD_CONDLOCK_GLITCH -class CryRWLock -{ - CryCriticalSection m_lockExclusiveAccess; - CryCriticalSection m_lockSharedAccessComplete; - CryConditionVariable m_condSharedAccessComplete; - - int m_nSharedAccessCount; - int m_nCompletedSharedAccessCount; - bool m_bExclusiveAccess; - - CryRWLock(const CryRWLock&); - CryRWLock& operator= (const CryRWLock&); - - void AdjustSharedAccessCount() - { - m_nSharedAccessCount -= m_nCompletedSharedAccessCount; - m_nCompletedSharedAccessCount = 0; - } - -public: - CryRWLock() - : m_nSharedAccessCount(0) - , m_nCompletedSharedAccessCount(0) - , m_bExclusiveAccess(false) - { } - - void RLock() - { - m_lockExclusiveAccess.Lock(); - if (++m_nSharedAccessCount == INT_MAX) - { - m_lockSharedAccessComplete.Lock(); - AdjustSharedAccessCount(); - m_lockSharedAccessComplete.Unlock(); - } - m_lockExclusiveAccess.Unlock(); - } - - bool TryRLock() - { - if (!m_lockExclusiveAccess.TryLock()) - { - return false; - } - if (++m_nSharedAccessCount == INT_MAX) - { - m_lockSharedAccessComplete.Lock(); - AdjustSharedAccessCount(); - m_lockSharedAccessComplete.Unlock(); - } - m_lockExclusiveAccess.Unlock(); - return true; - } - - void RUnlock() - { - Unlock(); - } - - void WLock() - { - m_lockExclusiveAccess.Lock(); - m_lockSharedAccessComplete.Lock(); - assert(!m_bExclusiveAccess); - AdjustSharedAccessCount(); - if (m_nSharedAccessCount > 0) - { - m_nCompletedSharedAccessCount -= m_nSharedAccessCount; - do - { - m_condSharedAccessComplete.Wait(m_lockSharedAccessComplete); - } - while (m_nCompletedSharedAccessCount < 0); - m_nSharedAccessCount = 0; - } - m_bExclusiveAccess = true; - } - - bool TryWLock() - { - if (!m_lockExclusiveAccess.TryLock()) - { - return false; - } - if (!m_lockSharedAccessComplete.TryLock()) - { - m_lockExclusiveAccess.Unlock(); - return false; - } - assert(!m_bExclusiveAccess); - AdjustSharedAccessCount(); - if (m_nSharedAccessCount > 0) - { - m_lockSharedAccessComplete.Unlock(); - m_lockExclusiveAccess.Unlock(); - return false; - } - else - { - m_bExclusiveAccess = true; - } - return true; - } - - void WUnlock() - { - Unlock(); - } - - void Unlock() - { - if (!m_bExclusiveAccess) - { - m_lockSharedAccessComplete.Lock(); - if (++m_nCompletedSharedAccessCount == 0) - { - m_condSharedAccessComplete.NotifySingle(); - } - m_lockSharedAccessComplete.Unlock(); - } - else - { - m_bExclusiveAccess = false; - m_lockSharedAccessComplete.Unlock(); - m_lockExclusiveAccess.Unlock(); - } - } -}; -#endif // !defined _CRYTHREAD_HAVE_RWLOCK - -// Thread class. -// -// CryThread is an extension of CrySimpleThread providing a lock (mutex) and a -// condition variable per instance. -template -class CryThread - : public CrySimpleThread -{ - CryMutex m_Lock; - CryConditionVariable m_Cond; - - CryThread(const CryThread&); - void operator = (const CryThread&); - -public: - CryThread() { } - void Lock() { m_Lock.Lock(); } - bool TryLock() { return m_Lock.TryLock(); } - void Unlock() { m_Lock.Unlock(); } - void Wait() { m_Cond.Wait(m_Lock); } - // Timed wait on the associated condition. - // - // The 'milliseconds' parameter specifies the relative timeout in - // milliseconds. The method returns true if a notification was received and - // false if the specified timeout expired without receiving a notification. - // - // UNIX note: the method will _not_ return if the calling thread receives a - // signal. Instead the call is re-started with the _original_ timeout - // value. This misfeature may be fixed in the future. - bool TimedWait(uint32 milliseconds) - { - return m_Cond.TimedWait(m_Lock, milliseconds); - } - void Notify() { m_Cond.Notify(); } - void NotifySingle() { m_Cond.NotifySingle(); } - CryMutex& GetLock() { return m_Lock; } -}; - -////////////////////////////////////////////////////////////////////////// -// -// Sync primitive for multiple reads and exclusive locking change access -// -// Desc: -// Useful in case if you have rarely modified object that needs -// to be read quite often from different threads but still -// need to be exclusively modified sometimes -// Debug functionality: -// Can be used for debug-only lock calls, which verify that no -// simultaneous access is attempted. -// Use the bDebug argument of LockRead or LockModify, -// or use the DEBUG_READLOCK or DEBUG_MODIFYLOCK macros. -// There is no overhead in release builds, if you use the macros, -// and the lock definition is inside #ifdef _DEBUG. -////////////////////////////////////////////////////////////////////////// - -class CryReadModifyLock -{ -public: - CryReadModifyLock() - : m_modifyCount(0) - , m_readCount(0) - { - SetDebugLocked(false); - } - - bool LockRead(bool bTry = false, cstr strDebug = 0, bool bDebug = false) const - { - if (!WriteLock(bTry, bDebug, strDebug)) // wait until write unlocked - { - return false; - } - CryInterlockedIncrement(&m_readCount); // increment read counter - m_writeLock.Unlock(); - return true; - } - void UnlockRead() const - { - SetDebugLocked(false); - const int counter = CryInterlockedDecrement(&m_readCount); // release read - assert(counter >= 0); - if (m_writeLock.TryLock()) - { - m_writeLock.Unlock(); - } - else - if (counter == 0 && m_modifyCount) - { - m_ReadReleased.Set(); // signal the final read released - } - } - bool LockModify(bool bTry = false, cstr strDebug = 0, bool bDebug = false) const - { - if (!WriteLock(bTry, bDebug, strDebug)) - { - return false; - } - CryInterlockedIncrement(&m_modifyCount); // increment write counter (counter is for nested cases) - while (m_readCount) - { - m_ReadReleased.Wait(); // wait for all threads finish read operation - } - return true; - } - void UnlockModify() const - { - SetDebugLocked(false); -#if !defined(NDEBUG) - int counter = -#endif - CryInterlockedDecrement(&m_modifyCount); // decrement write counter - assert(counter >= 0); - m_writeLock.Unlock(); // release exclusive lock - } - -protected: - mutable volatile int m_readCount; - mutable volatile int m_modifyCount; - mutable CryEvent m_ReadReleased; - mutable CryCriticalSection m_writeLock; - mutable bool m_debugLocked; - mutable const char* m_debugLockStr; - - void SetDebugLocked([[maybe_unused]] bool b, [[maybe_unused]] const char* str = 0) const - { -#ifdef _DEBUG - m_debugLocked = b; - m_debugLockStr = str; -#endif - } - - bool WriteLock(bool bTry, [[maybe_unused]] bool bDebug, [[maybe_unused]] const char* strDebug) const - { - if (!m_writeLock.TryLock()) - { -#ifdef _DEBUG - assert(!m_debugLocked); - assert(!bDebug); -#endif - if (bTry) - { - return false; - } - m_writeLock.Lock(); - } -#ifdef _DEBUG - if (!m_readCount && !m_modifyCount) // not yet locked - { - SetDebugLocked(bDebug, strDebug); - } -#endif - return true; - } -}; - -// Auto-locking classes. -template -class AutoLockRead -{ -protected: - const T& m_lock; -public: - AutoLockRead(const T& lock, cstr strDebug = 0) - : m_lock(lock) { m_lock.LockRead(bDEBUG, strDebug, bDEBUG); } - ~AutoLockRead() - { m_lock.UnlockRead(); } -}; - -template -class AutoLockModify -{ -protected: - const T& m_lock; -public: - AutoLockModify(const T& lock, cstr strDebug = 0) - : m_lock(lock) { m_lock.LockModify(bDEBUG, strDebug, bDEBUG); } - ~AutoLockModify() - { m_lock.UnlockModify(); } -}; - -#define AUTO_READLOCK(p) PREFAST_SUPPRESS_WARNING(6246) AutoLockRead AZ_JOIN(__readlock, __LINE__)(p, __FUNC__) -#define AUTO_READLOCK_PROT(p) PREFAST_SUPPRESS_WARNING(6246) AutoLockRead AZ_JOIN(__readlock_prot, __LINE__)(p, __FUNC__) -#define AUTO_MODIFYLOCK(p) PREFAST_SUPPRESS_WARNING(6246) AutoLockModify AZ_JOIN(__modifylock, __LINE__)(p, __FUNC__) - -#if defined(_DEBUG) - #define DEBUG_READLOCK(p) AutoLockRead AZ_JOIN(__readlock, __LINE__)(p, __FUNC__) - #define DEBUG_MODIFYLOCK(p) AutoLockModify AZ_JOIN(__modifylock, __LINE__)(p, __FUNC__) -#else - #define DEBUG_READLOCK(p) - #define DEBUG_MODIFYLOCK(p) -#endif - -// producer consumer queue implementations, but here instead of MultiThread_Container.h -// since they requiere platform specific code, and including windows.h in a very common -// header file leads to all kinds of problems -namespace CryMT -{ - ////////////////////////////////////////////////////////////////////////// - // Producer/Consumer Queue for 1 to 1 thread communication - // Realized with only volatile variables and memory barriers - // *warning* this producer/consumer queue is only thread safe in a 1 to 1 situation - // and doesn't provide any yields or similar to prevent spinning - ////////////////////////////////////////////////////////////////////////// - template - class SingleProducerSingleConsumerQueue - : public CryMT::detail::SingleProducerSingleConsumerQueueBase - { - public: - SingleProducerSingleConsumerQueue(); - ~SingleProducerSingleConsumerQueue(); - - void Init(size_t nSize); - - void Push(const T& rObj); - void Pop(T* pResult); - uint32 Size() { return (m_nProducerIndex - m_nComsumerIndex); } - uint32 BufferSize() { return m_nBufferSize; } - uint32 FreeCount() { return (m_nBufferSize - (m_nProducerIndex - m_nComsumerIndex)); } - - private: - T* m_arrBuffer; - uint32 m_nBufferSize; - - volatile uint32 m_nProducerIndex _ALIGN(16); - volatile uint32 m_nComsumerIndex _ALIGN(16); - } _ALIGN(128); - - /////////////////////////////////////////////////////////////////////////////// - template - inline SingleProducerSingleConsumerQueue::SingleProducerSingleConsumerQueue() - : m_arrBuffer(NULL) - , m_nBufferSize(0) - , m_nProducerIndex(0) - , m_nComsumerIndex(0) - {} - - /////////////////////////////////////////////////////////////////////////////// - template - inline SingleProducerSingleConsumerQueue::~SingleProducerSingleConsumerQueue() - { - CryModuleMemalignFree(m_arrBuffer); - m_nBufferSize = 0; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void SingleProducerSingleConsumerQueue::Init(size_t nSize) - { - assert(m_arrBuffer == NULL); - assert(m_nBufferSize == 0); - assert((nSize & (nSize - 1)) == 0); - - m_arrBuffer = alias_cast(CryModuleMemalign(nSize * sizeof(T), 16)); - m_nBufferSize = nSize; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void SingleProducerSingleConsumerQueue::Push(const T& rObj) - { - assert(m_arrBuffer != NULL); - assert(m_nBufferSize != 0); - SingleProducerSingleConsumerQueueBase::Push((void*)&rObj, m_nProducerIndex, m_nComsumerIndex, m_nBufferSize, m_arrBuffer, sizeof(T)); - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void SingleProducerSingleConsumerQueue::Pop(T* pResult) - { - assert(m_arrBuffer != NULL); - assert(m_nBufferSize != 0); - SingleProducerSingleConsumerQueueBase::Pop(pResult, m_nProducerIndex, m_nComsumerIndex, m_nBufferSize, m_arrBuffer, sizeof(T)); - } - - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // Producer/Consumer Queue for N to 1 thread communication - // lockfree implemenation, to copy with multiple producers, - // a internal producer refcount is managed, the queue is empty - // as soon as there are no more producers and no new elements - ////////////////////////////////////////////////////////////////////////// - template - class N_ProducerSingleConsumerQueue - : public CryMT::detail::N_ProducerSingleConsumerQueueBase - { - public: - N_ProducerSingleConsumerQueue(); - ~N_ProducerSingleConsumerQueue(); - - void Init(size_t nSize); - - void Push(const T& rObj); - bool Pop(T* pResult); - - // needs to be called before using, assumes that there is at least one producer - // so the first one doesn't need to call AddProducer, but he has to deregister itself - void SetRunningState(); - - // to correctly track when the queue is empty(and no new jobs will be added), refcount the producer - void AddProducer(); - void RemoveProducer(); - - uint32 Size() { return (m_nProducerIndex - m_nComsumerIndex); } - uint32 BufferSize() { return m_nBufferSize; } - uint32 FreeCount() { return (m_nBufferSize - (m_nProducerIndex - m_nComsumerIndex)); } - - private: - T* m_arrBuffer; - volatile uint32* m_arrStates; - uint32 m_nBufferSize; - - volatile uint32 m_nProducerIndex; - volatile uint32 m_nComsumerIndex; - volatile uint32 m_nRunning; - volatile uint32 m_nProducerCount; - } _ALIGN(128); - - /////////////////////////////////////////////////////////////////////////////// - template - inline N_ProducerSingleConsumerQueue::N_ProducerSingleConsumerQueue() - : m_arrBuffer(NULL) - , m_arrStates(NULL) - , m_nBufferSize(0) - , m_nProducerIndex(0) - , m_nComsumerIndex(0) - , m_nRunning(0) - , m_nProducerCount(0) - {} - - /////////////////////////////////////////////////////////////////////////////// - template - inline N_ProducerSingleConsumerQueue::~N_ProducerSingleConsumerQueue() - { - CryModuleMemalignFree(m_arrBuffer); - CryModuleMemalignFree((void*)m_arrStates); - m_nBufferSize = 0; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::Init(size_t nSize) - { - assert(m_arrBuffer == NULL); - assert(m_arrStates == NULL); - assert(m_nBufferSize == 0); - assert((nSize & (nSize - 1)) == 0); - - m_arrBuffer = alias_cast(CryModuleMemalign(nSize * sizeof(T), 16)); - m_arrStates = alias_cast(CryModuleMemalign(nSize * sizeof(uint32), 16)); - memset((void*)m_arrStates, 0, sizeof(uint32) * nSize); - m_nBufferSize = nSize; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::SetRunningState() - { -#if !defined(_RELEASE) - if (m_nRunning == 1) - { - __debugbreak(); - } -#endif - m_nRunning = 1; - m_nProducerCount = 1; - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::AddProducer() - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); -#if !defined(_RELEASE) - if (m_nRunning == 0) - { - __debugbreak(); - } -#endif - CryInterlockedIncrement((volatile int*)&m_nProducerCount); - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::RemoveProducer() - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); -#if !defined(_RELEASE) - if (m_nRunning == 0) - { - __debugbreak(); - } -#endif - if (CryInterlockedDecrement((volatile int*)&m_nProducerCount) == 0) - { - m_nRunning = 0; - } - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline void N_ProducerSingleConsumerQueue::Push(const T& rObj) - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); - CryMT::detail::N_ProducerSingleConsumerQueueBase::Push((void*)&rObj, m_nProducerIndex, m_nComsumerIndex, m_nRunning, m_arrBuffer, m_nBufferSize, sizeof(T), m_arrStates); - } - - /////////////////////////////////////////////////////////////////////////////// - template - inline bool N_ProducerSingleConsumerQueue::Pop(T* pResult) - { - assert(m_arrBuffer != NULL); - assert(m_arrStates != NULL); - assert(m_nBufferSize != 0); - return CryMT::detail::N_ProducerSingleConsumerQueueBase::Pop(pResult, m_nProducerIndex, m_nComsumerIndex, m_nRunning, m_arrBuffer, m_nBufferSize, sizeof(T), m_arrStates); - } -} //namespace CryMT - // Include all multithreading containers. #include "MultiThread_Containers.h" diff --git a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h index 895cbde524..c94d4fca90 100644 --- a/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h +++ b/Code/Legacy/CryCommon/CryThreadImpl_pthreads.h @@ -107,195 +107,4 @@ void* CryCreateCriticalSection() return (void*) new TCritSecType; } -#if AZ_TRAIT_SKIP_CRYINTERLOCKED -#elif defined(INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED) -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - AZStd::lock_guard lock(list.mutex); - - element.pNext = list.pNext; - list.pNext = &element; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - AZStd::lock_guard lock(list.mutex); - - SLockFreeSingleLinkedListEntry* returnValue = list.pNext; - if (list.pNext) - { - list.pNext = list.pNext->pNext; - } - return returnValue; -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - AZStd::lock_guard lock(list.mutex); - - list.pNext = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - AZStd::lock_guard lock(list.mutex); - - SLockFreeSingleLinkedListEntry* returnValue = list.pNext; - list.pNext = nullptr; - return returnValue; -} - -#elif defined(LINUX32) -////////////////////////////////////////////////////////////////////////// -// Implementation for Linux32 with gcc using uint64 -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - uint32 curSetting[2]; - uint32 newSetting[2]; - uint32 newPointer = (uint32) & element; - do - { - curSetting[0] = (uint32)list.pNext; - curSetting[1] = list.salt; - element.pNext = (SLockFreeSingleLinkedListEntry*)curSetting[0]; - newSetting[0] = newPointer; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - while (false == __sync_bool_compare_and_swap((volatile uint64*)&list.pNext, *(uint64*)&curSetting[0], *(uint64*)&newSetting[0])); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - uint32 curSetting[2]; - uint32 newSetting[2]; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint32)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = *(uint32*)curSetting[0]; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - while (false == __sync_bool_compare_and_swap((volatile uint64*)&list.pNext, *(uint64*)&curSetting[0], *(uint64*)&newSetting[0])); - return (void*)curSetting[0]; -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - list.salt = 0; - list.pNext = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - uint32 curSetting[2]; - uint32 newSetting[2]; - uint32 newSalt; - uint32 newPointer; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint32)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = 0; - newSetting[1] = curSetting[1] + 1; - } - while (false == __sync_bool_compare_and_swap((volatile uint64*)&list.pNext, *(uint64*)&curSetting[0], *(uint64*)&newSetting[0])); - return (void*)curSetting[0]; -} -#else -// This implementation get's used on multiple platforms that support uint128 compare and swap. - -////////////////////////////////////////////////////////////////////////// -// LINUX64 Implementation of Lockless Single Linked List -////////////////////////////////////////////////////////////////////////// -typedef __uint128_t uint128; - -////////////////////////////////////////////////////////////////////////// -// Implementation for Linux64 with gcc using __int128_t -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - uint64 curSetting[2]; - uint64 newSetting[2]; - uint64 newPointer = (uint64) & element; - do - { - curSetting[0] = (uint64)list.pNext; - curSetting[1] = list.salt; - element.pNext = (SLockFreeSingleLinkedListEntry*)curSetting[0]; - newSetting[0] = newPointer; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - // while (false == __sync_bool_compare_and_swap( (volatile uint128*)&list.pNext,*(uint128*)&curSetting[0],*(uint128*)&newSetting[0] )); - while (0 == _InterlockedCompareExchange128((volatile int64*)&list.pNext, (int64)newSetting[1], (int64)newSetting[0], (int64*)&curSetting[0])); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - uint64 curSetting[2]; - uint64 newSetting[2]; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint64)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = *(uint64*)curSetting[0]; // new pointer - newSetting[1] = curSetting[1] + 1; // new salt - } - //while (false == __sync_bool_compare_and_swap( (volatile uint128*)&list.pNext,*(uint128*)&curSetting[0],*(uint128*)&newSetting[0] )); - while (0 == _InterlockedCompareExchange128((volatile int64*)&list.pNext, (int64)newSetting[1], (int64)newSetting[0], (int64*)&curSetting[0])); - return (void*)curSetting[0]; -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - list.salt = 0; - list.pNext = NULL; -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - uint64 curSetting[2]; - uint64 newSetting[2]; - uint64 newSalt; - uint64 newPointer; - do - { - curSetting[1] = list.salt; - curSetting[0] = (uint64)list.pNext; - if (curSetting[0] == 0) - { - return NULL; - } - newSetting[0] = 0; - newSetting[1] = curSetting[1] + 1; - } - // while (false == __sync_bool_compare_and_swap( (volatile uint128*)&list.pNext,*(uint128*)&curSetting[0],*(uint128*)&newSetting[0] )); - while (0 == _InterlockedCompareExchange128((volatile int64*)&list.pNext, (int64)newSetting[1], (int64)newSetting[0], (int64*)&curSetting[0])); - return (void*)curSetting[0]; -} -////////////////////////////////////////////////////////////////////////// -#endif - #endif // CRYINCLUDE_CRYCOMMON_CRYTHREADIMPL_PTHREADS_H diff --git a/Code/Legacy/CryCommon/CryThreadImpl_windows.h b/Code/Legacy/CryCommon/CryThreadImpl_windows.h index 0451258aac..5cf970414d 100644 --- a/Code/Legacy/CryCommon/CryThreadImpl_windows.h +++ b/Code/Legacy/CryCommon/CryThreadImpl_windows.h @@ -303,78 +303,6 @@ void CryFastSemaphore::Release() } } -////////////////////////////////////////////////////////////////////////// -CryRWLock::CryRWLock() -{ - STATIC_ASSERT(sizeof(m_Lock) == sizeof(PSRWLOCK), "RWLock-pointer has invalid size"); - InitializeSRWLock(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -CryRWLock::~CryRWLock() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::RLock() -{ - AcquireSRWLockShared(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) -bool CryRWLock::TryRLock() -{ - return TryAcquireSRWLockShared(reinterpret_cast(&m_Lock)) != 0; -} -#endif - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::RUnlock() -{ - ReleaseSRWLockShared(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::WLock() -{ - AcquireSRWLockExclusive(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) -bool CryRWLock::TryWLock() -{ - return TryAcquireSRWLockExclusive(reinterpret_cast(&m_Lock)) != 0; -} -#endif - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::WUnlock() -{ - ReleaseSRWLockExclusive(reinterpret_cast(&m_Lock)); -} - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::Lock() -{ - WLock(); -} - -////////////////////////////////////////////////////////////////////////// -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) -bool CryRWLock::TryLock() -{ - return TryWLock(); -} -#endif - -////////////////////////////////////////////////////////////////////////// -void CryRWLock::Unlock() -{ - WUnlock(); -} - ////////////////////////////////////////////////////////////////////////// CrySimpleThreadSelf::CrySimpleThreadSelf() : m_thread(NULL) @@ -415,181 +343,3 @@ void CrySimpleThreadSelf::StartThread(unsigned (__stdcall * func)(void*), void* PREFAST_ASSUME(m_thread); ResumeThread((HANDLE)m_thread); } - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element) -{ - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListEntry) >= sizeof(SLIST_ENTRY), CRY_INTERLOCKED_SLIST_ENTRY_HAS_WRONG_SIZE); - - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - assert(IsAligned(&element, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Entry has wrong Alignment"); - InterlockedPushEntrySList(alias_cast(&list), alias_cast(&element)); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list) -{ - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - return reinterpret_cast(InterlockedPopEntrySList(alias_cast(&list))); -} - -////////////////////////////////////////////////////////////////////////// -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list) -{ - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - InitializeSListHead(alias_cast(&list)); -} - -////////////////////////////////////////////////////////////////////////// -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list) -{ - assert(IsAligned(&list, MEMORY_ALLOCATION_ALIGNMENT) && "LockFree SingleLink List Header has wrong Alignment"); - - STATIC_CHECK(sizeof(SLockFreeSingleLinkedListHeader) == sizeof(SLIST_HEADER), CRY_INTERLOCKED_SLIST_HEADER_HAS_WRONG_SIZE); - return InterlockedFlushSList(alias_cast(&list)); -} - -/////////////////////////////////////////////////////////////////////////////// -// base class for lock less Producer/Consumer queue, due platforms specific they -// are implemeted in CryThead_platform.h -namespace CryMT { - namespace detail { - /////////////////////////////////////////////////////////////////////////////// - void SingleProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - // spin if queue is full - int iter = 0; - while (rProducerIndex - rComsumerIndex == nBufferSize) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - - MemoryBarrier(); - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rProducerIndex % nBufferSize; - - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - MemoryBarrier(); - rProducerIndex += 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - void SingleProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - MemoryBarrier(); - // busy-loop if queue is empty - int iter = 0; - while (rProducerIndex - rComsumerIndex == 0) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - void N_ProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, [[maybe_unused]] volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - uint32 nProducerIndex; - uint32 nComsumerIndex; - - int iter = 0; - do - { - nProducerIndex = rProducerIndex; - nComsumerIndex = rComsumerIndex; - - if (nProducerIndex - nComsumerIndex == nBufferSize) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - if (iter > 20) // 10 spins + 10 ms wait - { - uint32 nSizeToAlloc = sizeof(SFallbackList) + nObjectSize - 1; - SFallbackList* pFallbackEntry = (SFallbackList*)CryModuleMemalign(nSizeToAlloc, 128); - memcpy(pFallbackEntry->object, pObj, nObjectSize); - MemoryBarrier(); - CryInterlockedPushEntrySList(fallbackList, pFallbackEntry->nextEntry); - return; - } - continue; - } - - if (CryInterlockedCompareExchange(alias_cast(&rProducerIndex), nProducerIndex + 1, nProducerIndex) == nProducerIndex) - { - break; - } - } while (true); - - MemoryBarrier(); - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = nProducerIndex % nBufferSize; - - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - MemoryBarrier(); - arrStates[nIndex] = 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - bool N_ProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - - // busy-loop if queue is empty - int iter = 0; - if (rRunning && rProducerIndex - rComsumerIndex == 0) - { - while (rRunning && rProducerIndex - rComsumerIndex == 0) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - } - - if (rRunning == 0 && rProducerIndex - rComsumerIndex == 0) - { - SFallbackList* pFallback = (SFallbackList*)CryInterlockedPopEntrySList(fallbackList); - IF (pFallback, 0) - { - memcpy(pObj, pFallback->object, nObjectSize); - CryModuleMemalignFree(pFallback); - return true; - } - // if the queue was empty, make sure we really are empty - return false; - } - - iter = 0; - while (arrStates[rComsumerIndex % nBufferSize] == 0) - { - CryLowLatencySleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - MemoryBarrier(); - arrStates[nIndex] = 0; - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - - return true; - } - } // namespace detail -} // namespace CryMT diff --git a/Code/Legacy/CryCommon/CryThread_pthreads.h b/Code/Legacy/CryCommon/CryThread_pthreads.h index 4ebc4e9637..72b29344ec 100644 --- a/Code/Legacy/CryCommon/CryThread_pthreads.h +++ b/Code/Legacy/CryCommon/CryThread_pthreads.h @@ -524,57 +524,6 @@ inline void CryFastSemaphore::Release() } } -////////////////////////////////////////////////////////////////////////// -#if !defined _CRYTHREAD_HAVE_RWLOCK -class CryRWLock -{ - pthread_rwlock_t m_Lock; - - CryRWLock(const CryRWLock&); - CryRWLock& operator= (const CryRWLock&); - -public: - CryRWLock() { pthread_rwlock_init(&m_Lock, NULL); } - ~CryRWLock() { pthread_rwlock_destroy(&m_Lock); } - void RLock() { pthread_rwlock_rdlock(&m_Lock); } - bool TryRLock() - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_TRY_RLOCK - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return pthread_rwlock_tryrdlock(&m_Lock) != EBUSY; -#endif - } - void RUnlock() { Unlock(); } - void WLock() { pthread_rwlock_wrlock(&m_Lock); } - bool TryWLock() - { -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION CRYTHREAD_PTHREADS_H_SECTION_TRY_RLOCK - #include AZ_RESTRICTED_FILE(CryThread_pthreads_h) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) - #undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - return pthread_rwlock_trywrlock(&m_Lock) != EBUSY; -#endif - } - void WUnlock() { Unlock(); } - void Lock() { WLock(); } - bool TryLock() { return TryWLock(); } - void Unlock() { pthread_rwlock_unlock(&m_Lock); } -}; - -// Indicate that this implementation header provides an implementation for -// CryRWLock. -#define _CRYTHREAD_HAVE_RWLOCK 1 -#endif // !defined _CRYTHREAD_HAVE_RWLOCK - - //////////////////////////////////////////////////////////////////////////////// // Provide TLS implementation using pthreads for those platforms without __thread //////////////////////////////////////////////////////////////////////////////// @@ -1145,185 +1094,3 @@ public: }; #include "MemoryAccess.h" - - /////////////////////////////////////////////////////////////////////////////// - // base class for lock less Producer/Consumer queue, due platforms specific they - // are implemeted in CryThead_platform.h - namespace CryMT { - namespace detail { - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class SingleProducerSingleConsumerQueueBase - { - public: - SingleProducerSingleConsumerQueueBase() - {} - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - void Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - }; - - /////////////////////////////////////////////////////////////////////////////// - inline void SingleProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - MemoryBarrier(); - // spin if queue is full - int iter = 0; - while (rProducerIndex - rComsumerIndex == nBufferSize) - { - Sleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rProducerIndex % nBufferSize; - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - - MemoryBarrier(); - rProducerIndex += 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - inline void SingleProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize) - { - MemoryBarrier(); - // busy-loop if queue is empty - int iter = 0; - while (rProducerIndex - rComsumerIndex == 0) - { - Sleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - } - - - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class N_ProducerSingleConsumerQueueBase - { - public: - N_ProducerSingleConsumerQueueBase() - { - CryInitializeSListHead(fallbackList); - } - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - bool Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - - SLockFreeSingleLinkedListHeader fallbackList; - struct SFallbackList - { - SLockFreeSingleLinkedListEntry nextEntry; - char alignment_padding[128 - sizeof(SLockFreeSingleLinkedListEntry)]; - char object[1]; // struct will be overallocated with enough memory for the object - }; - }; - - /////////////////////////////////////////////////////////////////////////////// - inline void N_ProducerSingleConsumerQueueBase::Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - uint32 nProducerIndex; - uint32 nComsumerIndex; - - int iter = 0; - do - { - nProducerIndex = rProducerIndex; - nComsumerIndex = rComsumerIndex; - - if (nProducerIndex - nComsumerIndex == nBufferSize) - { - Sleep(iter++ > 10 ? 1 : 0); - if (iter > 20) // 10 spins + 10 ms wait - { - uint32 nSizeToAlloc = sizeof(SFallbackList) + nObjectSize - 1; - SFallbackList* pFallbackEntry = (SFallbackList*)CryModuleMemalign(nSizeToAlloc, 128); - memcpy(pFallbackEntry->object, pObj, nObjectSize); - CryInterlockedPushEntrySList(fallbackList, pFallbackEntry->nextEntry); - return; - } - continue; - } - - if (CryInterlockedCompareExchange(alias_cast(&rProducerIndex), nProducerIndex + 1, nProducerIndex) == nProducerIndex) - { - break; - } - } while (true); - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = nProducerIndex % nBufferSize; - - memcpy(pBuffer + (nIndex * nObjectSize), pObj, nObjectSize); - - MemoryBarrier(); - arrStates[nIndex] = 1; - MemoryBarrier(); - } - - /////////////////////////////////////////////////////////////////////////////// - inline bool N_ProducerSingleConsumerQueueBase::Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates) - { - MemoryBarrier(); - // busy-loop if queue is empty - int iter = 0; - do - { - SFallbackList* pFallback = (SFallbackList*)CryInterlockedPopEntrySList(fallbackList); - IF (pFallback, 0) - { - memcpy(pObj, pFallback->object, nObjectSize); - CryModuleMemalignFree(pFallback); - return true; - } - - if (iter > 10) - { - Sleep(iter > 100 ? 1 : 0); - } - iter++; - } while (rRunning && rProducerIndex - rComsumerIndex == 0); - - if (rRunning == 0 && rProducerIndex - rComsumerIndex == 0) - { - // if the queue was empty, make sure we really are empty - SFallbackList* pFallback = (SFallbackList*)CryInterlockedPopEntrySList(fallbackList); - IF (pFallback, 0) - { - memcpy(pObj, pFallback->object, nObjectSize); - CryModuleMemalignFree(pFallback); - return true; - } - return false; - } - - iter = 0; - while (arrStates[rComsumerIndex % nBufferSize] == 0) - { - Sleep(iter++ > 10 ? 1 : 0); - } - - char* pBuffer = alias_cast(arrBuffer); - uint32 nIndex = rComsumerIndex % nBufferSize; - - memcpy(pObj, pBuffer + (nIndex * nObjectSize), nObjectSize); - - MemoryBarrier(); - arrStates[nIndex] = 0; - MemoryBarrier(); - rComsumerIndex += 1; - MemoryBarrier(); - - return true; - } - } // namespace detail - } // namespace CryMT diff --git a/Code/Legacy/CryCommon/CryThread_windows.h b/Code/Legacy/CryCommon/CryThread_windows.h index b80666ce73..cc09cc530b 100644 --- a/Code/Legacy/CryCommon/CryThread_windows.h +++ b/Code/Legacy/CryCommon/CryThread_windows.h @@ -180,41 +180,6 @@ private: volatile int32 m_nCounter; }; -////////////////////////////////////////////////////////////////////////// -#if !defined(_CRYTHREAD_HAVE_RWLOCK) -class CryRWLock -{ - void* /*SRWLOCK*/ m_Lock; - - CryRWLock(const CryRWLock&); - CryRWLock& operator= (const CryRWLock&); - -public: - CryRWLock(); - ~CryRWLock(); - - void RLock(); - void RUnlock(); - - void WLock(); - void WUnlock(); - - void Lock(); - void Unlock(); - -#if defined(_CRYTHREAD_WANT_TRY_RWLOCK) - // Enabling TryXXX requires Windows 7 or newer - bool TryRLock(); - bool TryWLock(); - bool TryLock(); -#endif -}; - -// Indicate that this implementation header provides an implementation for -// CryRWLock. -#define _CRYTHREAD_HAVE_RWLOCK 1 -#endif - ////////////////////////////////////////////////////////////////////////// class CrySimpleThreadSelf { @@ -420,46 +385,3 @@ public: bool IsStarted() const { return m_bIsStarted; } bool IsRunning() const { return m_bIsRunning; } }; - -/////////////////////////////////////////////////////////////////////////////// -// base class for lock less Producer/Consumer queue, due platforms specific they -// are implemented in CryThead_platform.h -namespace CryMT { - namespace detail { - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class SingleProducerSingleConsumerQueueBase - { - public: - SingleProducerSingleConsumerQueueBase() - {} - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - void Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, uint32 nBufferSize, void* arrBuffer, uint32 nObjectSize); - }; - - - /////////////////////////////////////////////////////////////////////////////// - /////////////////////////////////////////////////////////////////////////////// - class N_ProducerSingleConsumerQueueBase - { - public: - N_ProducerSingleConsumerQueueBase() - { - CryInitializeSListHead(fallbackList); - } - - void Push(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - bool Pop(void* pObj, volatile uint32& rProducerIndex, volatile uint32& rComsumerIndex, volatile uint32& rRunning, void* arrBuffer, uint32 nBufferSize, uint32 nObjectSize, volatile uint32* arrStates); - - private: - SLockFreeSingleLinkedListHeader fallbackList; - struct SFallbackList - { - SLockFreeSingleLinkedListEntry nextEntry; - char alignment_padding[128 - sizeof(SLockFreeSingleLinkedListEntry)]; - char object[1]; // struct will be overallocated with enough memory for the object - }; - }; - } // namespace detail -} // namespace CryMT diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index d934995b4d..1e1aae99be 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -900,9 +900,6 @@ struct ISystem // Retrieves access to XML utilities interface. virtual IXmlUtils* GetXmlUtils() = 0; - virtual void SetViewCamera(CCamera& Camera) = 0; - virtual CCamera& GetViewCamera() = 0; - // Description: // When ignore update sets to true, system will ignore and updates and render calls. virtual void IgnoreUpdates(bool bIgnore) = 0; diff --git a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h index 2dea83925d..23cd7faf7f 100644 --- a/Code/Legacy/CryCommon/Linux_Win32Wrapper.h +++ b/Code/Legacy/CryCommon/Linux_Win32Wrapper.h @@ -145,9 +145,6 @@ inline void MemoryBarrier() { typedef int64 __m128; #endif -#if defined(LINUX64) || defined(APPLE) -unsigned char _InterlockedCompareExchange128(int64 volatile* dst, int64 exchangehigh, int64 exchangelow, int64* comperand); -#endif ////////////////////////////////////////////////////////////////////////// // io.h stuff #if !defined(ANDROID) diff --git a/Code/Legacy/CryCommon/Mocks/ISystemMock.h b/Code/Legacy/CryCommon/Mocks/ISystemMock.h index d891365696..e357af6d87 100644 --- a/Code/Legacy/CryCommon/Mocks/ISystemMock.h +++ b/Code/Legacy/CryCommon/Mocks/ISystemMock.h @@ -100,10 +100,6 @@ public: XmlNodeRef(const char*, bool)); MOCK_METHOD0(GetXmlUtils, IXmlUtils * ()); - MOCK_METHOD1(SetViewCamera, - void(CCamera & Camera)); - MOCK_METHOD0(GetViewCamera, - CCamera & ()); MOCK_METHOD1(IgnoreUpdates, void(bool bIgnore)); MOCK_METHOD1(SetIProcess, diff --git a/Code/Legacy/CryCommon/MultiThread.h b/Code/Legacy/CryCommon/MultiThread.h index 2454ade6ab..2b224c4743 100644 --- a/Code/Legacy/CryCommon/MultiThread.h +++ b/Code/Legacy/CryCommon/MultiThread.h @@ -29,78 +29,13 @@ #define MULTITHREAD_H_SECTION_IMPLEMENT_CRYINTERLOCKEDCOMPAREEXCHANGE64 8 #endif -#define THREAD_NAME_LENGTH_MAX 64 - #define WRITE_LOCK_VAL (1 << 16) // Traits #if defined(AZ_RESTRICTED_PLATFORM) #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_TRAITS #include AZ_RESTRICTED_FILE(MultiThread_h) -#else -#define MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_ATTRIBUTE_ALIGN_16 0 -#if defined(WIN64) -#define MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_MSALIGN_16 1 -#endif -#if defined(APPLE) || defined(LINUX) -#define MULTITHREAD_H_TRAIT_USE_SALTED_LINKEDLISTHEADER 1 #endif -#endif - -//as PowerPC operates via cache line reservation, lock variables should reside ion their own cache line -template -struct SAtomicVar -{ - T val; - - inline operator T() const{return val; } - inline operator T() volatile const{return val; } - inline SAtomicVar& operator =(const T& rV){val = rV; return *this; } - inline void Assign(const T& rV){val = rV; } - inline void Assign(const T& rV) volatile{val = rV; } - inline T* Addr() {return &val; } - inline volatile T* Addr() volatile {return &val; } - - inline bool operator<(const T& v) const{return val < v; } - inline bool operator<(const SAtomicVar& v) const{return val < v.val; } - inline bool operator>(const T& v) const{return val > v; } - inline bool operator>(const SAtomicVar& v) const{return val > v.val; } - inline bool operator<=(const T& v) const{return val <= v; } - inline bool operator<=(const SAtomicVar& v) const{return val <= v.val; } - inline bool operator>=(const T& v) const{return val >= v; } - inline bool operator>=(const SAtomicVar& v) const{return val >= v.val; } - inline bool operator==(const T& v) const{return val == v; } - inline bool operator==(const SAtomicVar& v) const{return val == v.val; } - inline bool operator!=(const T& v) const{return val != v; } - inline bool operator!=(const SAtomicVar& v) const{return val != v.val; } - inline T operator*(const T& v) const{return val * v; } - inline T operator/(const T& v) const{return val / v; } - inline T operator+(const T& v) const{return val + v; } - inline T operator-(const T& v) const{return val - v; } - - inline bool operator<(const T& v) volatile const{return val < v; } - inline bool operator<(const SAtomicVar& v) volatile const{return val < v.val; } - inline bool operator>(const T& v) volatile const{return val > v; } - inline bool operator>(const SAtomicVar& v) volatile const{return val > v.val; } - inline bool operator<=(const T& v) volatile const{return val <= v; } - inline bool operator<=(const SAtomicVar& v) volatile const{return val <= v.val; } - inline bool operator>=(const T& v) volatile const{return val >= v; } - inline bool operator>=(const SAtomicVar& v) volatile const{return val >= v.val; } - inline bool operator==(const T& v) volatile const{return val == v; } - inline bool operator==(const SAtomicVar& v) volatile const{return val == v.val; } - inline bool operator!=(const T& v) volatile const{return val != v; } - inline bool operator!=(const SAtomicVar& v) volatile const{return val != v.val; } - inline T operator*(const T& v) volatile const{return val * v; } - inline T operator/(const T& v) volatile const{return val / v; } - inline T operator+(const T& v) volatile const{return val + v; } - inline T operator-(const T& v) volatile const{return val - v; } -}; - -typedef SAtomicVar TIntAtomic; -typedef SAtomicVar TUIntAtomic; -typedef SAtomicVar TFloatAtomic; - -#define __add_db16cycl__ NIntrinsics::YieldFor16Cycles(); void CrySpinLock(volatile int* pLock, int checkVal, int setVal); void CryReleaseSpinLock (volatile int*, int); @@ -208,37 +143,6 @@ ILINE void CryReleaseSpinLock(volatile int* pLock, int setVal) } ////////////////////////////////////////////////////////////////////////// -#if defined(APPLE) || defined(LINUX64) -// Fixes undefined reference to CryInterlockedAdd(unsigned long volatile*, long) on -// Mac and linux. -ILINE void CryInterLockedAdd(volatile LONG* pVal, LONG iAdd) -{ - (void) CryInterlockedExchangeAdd(pVal, iAdd); -} - - -/* -ILINE void CryInterLockedAdd(volatile unsigned long *pVal, long iAdd) -{ - long r; - __asm__ __volatile__ ( - #if defined(LINUX64) || defined(MAC) // long is 64 bits on amd64. - "lock ; xaddq %0, (%1) \n\t" - #else - "lock ; xaddl %0, (%1) \n\t" - #endif - : "=r" (r) - : "r" (pVal), "0" (iAdd) - : "memory" - ); - (void) r; -}*/ -/*ILINE void CryInterlockedAdd(volatile size_t *pVal, ptrdiff_t iAdd) { - //(void)CryInterlockedExchangeAdd((volatile long*)pVal,(long)iAdd); - (void) __sync_fetch_and_add(pVal,iAdd); -}*/ - -#endif ILINE void CryInterlockedAdd(volatile int* pVal, int iAdd) { #ifdef _CPU_X86 @@ -311,123 +215,6 @@ ILINE void CryInterlockedAddSize(volatile size_t* pVal, ptrdiff_t iAdd) ////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -// CryInterlocked*SList Function, these are specialized C-A-S -// functions for single-linked lists which prevent the A-B-A problem there -// there are implemented in the platform specific CryThread_*.h files -// TODO clean up the interlocked function the same was the CryThread_* header are - -//TODO somehow get their real size on WIN (without including windows.h...) -//NOTE: The sizes are verifyed at compile-time in the implementation functions, but this is still ugly -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_MSALIGN_16 -_MS_ALIGN(16) -#elif defined(WIN32) -_MS_ALIGN(8) -#endif -struct SLockFreeSingleLinkedListEntry -{ - SLockFreeSingleLinkedListEntry* volatile pNext; -} -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_ATTRIBUTE_ALIGN_16 -__attribute__ ((aligned(16))) -#elif defined(LINUX32) -_ALIGN(8) -#elif defined(APPLE) || defined(LINUX64) -_ALIGN(16) -#endif -; - -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_MSALIGN_16 -_MS_ALIGN(16) -#elif defined(WIN32) -_MS_ALIGN(8) -#endif -struct SLockFreeSingleLinkedListHeader -{ - SLockFreeSingleLinkedListEntry* volatile pNext; -#if defined(INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED) - // arm64 processors do not provide a cmpxchg16b (or equivalent) instruction, - // so _InterlockedCompareExchange128 is not implemented on arm64 platforms, - // and we have to use a mutex to ensure thread safety. - AZStd::mutex mutex; -#elif MULTITHREAD_H_TRAIT_USE_SALTED_LINKEDLISTHEADER - // If pointers 32bit, salt should be as well. Otherwise we get 4 bytes of padding between pNext and salt and CAS operations fail -#if defined(PLATFORM_64BIT) - volatile uint64 salt; -#else - volatile uint32 salt; -#endif -#endif -} -#if MULTITHREAD_H_TRAIT_SLOCKFREESINGLELINKEDLISTENTRY_ATTRIBUTE_ALIGN_16 -__attribute__ ((aligned(16))) -#elif defined(LINUX32) -_ALIGN(8) -#elif defined(APPLE) || defined(LINUX64) -_ALIGN(16) -#endif -; - - -// push a element atomically onto a single linked list -void CryInterlockedPushEntrySList(SLockFreeSingleLinkedListHeader& list, SLockFreeSingleLinkedListEntry& element); - -// push a element atomically from a single linked list -void* CryInterlockedPopEntrySList(SLockFreeSingleLinkedListHeader& list); - -// initialzied the lock-free single linked list -void CryInitializeSListHead(SLockFreeSingleLinkedListHeader& list); - -// flush the whole list -void* CryInterlockedFlushSList(SLockFreeSingleLinkedListHeader& list); - -ILINE void CryReadLock(volatile int* rw, bool yield) -{ - CryInterlockedAdd(rw, 1); -#ifdef NEED_ENDIAN_SWAP - volatile char* pw = (volatile char*)rw + 1; -#else - volatile char* pw = (volatile char*)rw + 2; -#endif - - uint64 loops = 0; - for (; *pw; ) - { - if (yield) - { -# if !defined(ANDROID) && !defined(IOS) && !defined(MULTITHREAD_H_TRAIT_NO_MM_PAUSE) - _mm_pause(); -# endif - - if (!(++loops & 0x7F)) - { - // give other threads with other prio right to run -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT1 - #include AZ_RESTRICTED_FILE(MultiThread_h) -#elif defined (LINUX) - usleep(1); -#endif - } - else if (!(loops & 0x3F)) - { - // give threads with same prio chance to run -#if defined(AZ_RESTRICTED_PLATFORM) - #define AZ_RESTRICTED_SECTION MULTITHREAD_H_SECTION_CRYINTERLOCKEDFLUSHSLIST_PT2 - #include AZ_RESTRICTED_FILE(MultiThread_h) -#elif defined (LINUX) - sched_yield(); -#endif - } - } - } -} - -ILINE void CryReleaseReadLock(volatile int* rw) -{ - CryInterlockedAdd(rw, -1); -} - ILINE void CryWriteLock(volatile int* rw) { CrySpinLock(rw, 0, WRITE_LOCK_VAL); @@ -438,78 +225,6 @@ ILINE void CryReleaseWriteLock(volatile int* rw) CryInterlockedAdd(rw, -WRITE_LOCK_VAL); } -////////////////////////////////////////////////////////////////////////// -struct ReadLock -{ - ILINE ReadLock(volatile int& rw) - { - CryInterlockedAdd(prw = &rw, 1); -#ifdef NEED_ENDIAN_SWAP - volatile char* pw = (volatile char*)&rw + 1; - for (; * pw; ) - { - ; - } -#else - volatile char* pw = (volatile char*)&rw + 2; - for (; * pw; ) - { - ; - } -#endif - } - ILINE ReadLock(volatile int& rw, bool yield) - { - CryReadLock(prw = &rw, yield); - } - ~ReadLock() - { - CryReleaseReadLock(prw); - } -private: - volatile int* prw; -}; - -struct ReadLockCond -{ - ILINE ReadLockCond(volatile int& rw, int bActive) - { - if (bActive) - { - CryInterlockedAdd(&rw, 1); - bActivated = 1; -#ifdef NEED_ENDIAN_SWAP - volatile char* pw = (volatile char*)&rw + 1; - for (; * pw; ) - { - ; - } -#else - volatile char* pw = (volatile char*)&rw + 2; - for (; * pw; ) - { - ; - } -#endif - } - else - { - bActivated = 0; - } - prw = &rw; - } - void SetActive(int bActive = 1) { bActivated = bActive; } - void Release() { CryInterlockedAdd(prw, -bActivated); } - ~ReadLockCond() - { - CryInterlockedAdd(prw, -bActivated); - } - -private: - volatile int* prw; - int bActivated; -}; - ////////////////////////////////////////////////////////////////////////// struct WriteLock { @@ -519,15 +234,6 @@ private: volatile int* prw; }; -////////////////////////////////////////////////////////////////////////// -struct WriteAfterReadLock -{ - ILINE WriteAfterReadLock(volatile int& rw) { CrySpinLock(&rw, 1, WRITE_LOCK_VAL + 1); prw = &rw; } - ~WriteAfterReadLock() { CryInterlockedAdd(prw, -WRITE_LOCK_VAL); } -private: - volatile int* prw; -}; - ////////////////////////////////////////////////////////////////////////// struct WriteLockCond { @@ -562,12 +268,6 @@ ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange // This is OK, because long is signed int64 on Linux x86_64 //return CryInterlockedCompareExchange((volatile long*)addr, (long)exchange, (long)comperand); } - -ILINE int64 CryInterlockedExchange64(volatile int64* addr, int64 exchange) -{ - __sync_synchronize(); - return __sync_lock_test_and_set(addr, exchange); -} #else ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange, int64 compare) { @@ -583,21 +283,3 @@ ILINE int64 CryInterlockedCompareExchange64(volatile int64* addr, int64 exchange #endif } #endif - -////////////////////////////////////////////////////////////////////////// -#if defined(EXCLUDE_PHYSICS_THREAD) -ILINE void SpinLock(volatile int* pLock, int checkVal, int setVal) { *(int*)pLock = setVal; } -ILINE void AtomicAdd(volatile int* pVal, int iAdd) { *(int*)pVal += iAdd; } -ILINE void AtomicAdd(volatile unsigned int* pVal, int iAdd) { *(unsigned int*)pVal += iAdd; } - -ILINE void JobSpinLock(volatile int* pLock, int checkVal, int setVal) { CrySpinLock(pLock, checkVal, setVal); } -#else -ILINE void SpinLock(volatile int* pLock, int checkVal, int setVal) { CrySpinLock(pLock, checkVal, setVal); } -ILINE void AtomicAdd(volatile int* pVal, int iAdd) { CryInterlockedAdd(pVal, iAdd); } -ILINE void AtomicAdd(volatile unsigned int* pVal, int iAdd) { CryInterlockedAdd((volatile int*)pVal, iAdd); } - -ILINE void JobSpinLock(volatile int* pLock, int checkVal, int setVal) { SpinLock(pLock, checkVal, setVal); } -#endif - -ILINE void JobAtomicAdd(volatile int* pVal, int iAdd) { CryInterlockedAdd(pVal, iAdd); } -ILINE void JobAtomicAdd(volatile unsigned int* pVal, int iAdd) { CryInterlockedAdd((volatile int*)pVal, iAdd); } diff --git a/Code/Legacy/CryCommon/MultiThread_Containers.h b/Code/Legacy/CryCommon/MultiThread_Containers.h index 7c5af2a5d0..23f7cd1e0c 100644 --- a/Code/Legacy/CryCommon/MultiThread_Containers.h +++ b/Code/Legacy/CryCommon/MultiThread_Containers.h @@ -94,325 +94,10 @@ namespace CryMT container_type v; mutable CryCriticalSection m_cs; }; - - ////////////////////////////////////////////////////////////////////////// - // Multi-Thread safe vector container, can be used instead of std::vector. - ////////////////////////////////////////////////////////////////////////// - template - class vector - { - public: - typedef T value_type; - typedef CryAutoCriticalSection AutoLock; - - CryCriticalSection& get_lock() const { return m_cs; } - - void free_memory() { AutoLock lock(m_cs); stl::free_container(v); } - - ////////////////////////////////////////////////////////////////////////// - // std::vector interface - ////////////////////////////////////////////////////////////////////////// - bool empty() const { AutoLock lock(m_cs); return v.empty(); } - int size() const { AutoLock lock(m_cs); return v.size(); } - void resize(int sz) { AutoLock lock(m_cs); v.resize(sz); } - void reserve(int sz) { AutoLock lock(m_cs); v.reserve(sz); } - size_t capacity() const { AutoLock lock(m_cs); return v.size(); } - void clear() { AutoLock lock(m_cs); v.clear(); } - T& operator[](size_t pos) { AutoLock lock(m_cs); return v[pos]; } - const T& operator[](size_t pos) const { AutoLock lock(m_cs); return v[pos]; } - const T& front() const { AutoLock lock(m_cs); return v.front(); } - const T& back() const { AutoLock lock(m_cs); return v.back(); } - T& back() { AutoLock lock(m_cs); return v.back(); } - - void push_back(const T& x) { AutoLock lock(m_cs); return v.push_back(x); } - void pop_back() { AutoLock lock(m_cs); return v.pop_back(); } - ////////////////////////////////////////////////////////////////////////// - - template - void sort(const Func& compare_less) { AutoLock lock(m_cs); std::sort(v.begin(), v.end(), compare_less); } - - template - void append(const Iter& startRange, const Iter& endRange) { AutoLock lock(m_cs); v.insert(v.end(), startRange, endRange); } - - void swap(std::vector& vec) { AutoLock lock(m_cs); v.swap(vec); } - - ////////////////////////////////////////////////////////////////////////// - bool try_pop_front(T& returnValue) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - returnValue = v.front(); - v.erase(v.begin()); - return true; - } - return false; - }; - bool try_pop_back(T& returnValue) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - returnValue = v.back(); - v.pop_back(); - return true; - } - return false; - }; - - ////////////////////////////////////////////////////////////////////////// - template - bool find_and_copy(FindFunction findFunc, const KeyType& key, T& foundValue) const - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector::const_iterator it; - for (it = v.begin(); it != v.end(); ++it) - { - if (findFunc(key, *it)) - { - foundValue = *it; - return true; - } - } - } - return false; - } - - ////////////////////////////////////////////////////////////////////////// - bool try_remove(const T& value) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector::iterator it = std::find(v.begin(), v.end(), value); - if (it != v.end()) - { - v.erase(it); - return true; - } - } - return false; - }; - - ////////////////////////////////////////////////////////////////////////// - template - bool try_remove_and_erase_if(Predicate predicateFunction) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector::iterator it = std::remove_if(v.begin(), v.end(), predicateFunction); - if (it != v.end()) - { - v.erase(it, v.end()); - return true; - } - } - return false; - }; - - - ////////////////////////////////////////////////////////////////////////// - bool try_remove_at(size_t idx) - { - AutoLock lock(m_cs); - if (idx < v.size()) - { - v.erase(v.begin() + idx); - return true; - } - return false; - } - - - ////////////////////////////////////////////////////////////////////////// - //Fast remove - just move last elem over deleted element - order is not preserved - bool try_remove_unordered(const T& value) - { - AutoLock lock(m_cs); - if (!v.empty()) - { - typename std::vector::iterator it = std::find(v.begin(), v.end(), value); - if (it != v.end()) - { - if (v.size() > 1) - { - typename std::vector::iterator it_back = v.end() - 1; - - if (it != it_back) - { - *it = *it_back; - } - - v.erase(it_back); - } - else - { - v.erase(it); - } - return true; - } - } - return false; - }; - - vector() {} - - vector(const vector& rOther) - { - AutoLock lock1(m_cs); - AutoLock lock2(rOther.m_cs); - - v = rOther.v; - } - - vector& operator=(const vector& rOther) - { - if (this == &rOther) - { - return *this; - } - - AutoLock lock1(m_cs); - AutoLock lock2(rOther.m_cs); - - v = rOther.v; - - return *this; - } - private: - std::vector v; - mutable CryCriticalSection m_cs; - }; - - - ////////////////////////////////////////////////////////////////////////// - // Multi-Thread safe set container, can be used instead of std::set. - // It has limited functionality, but most of it is there. - ////////////////////////////////////////////////////////////////////////// - template - class set - { - public: - typedef T value_type; - typedef T Key; - typedef typename std::set::size_type size_type; - typedef CryAutoCriticalSection AutoLock; - - ////////////////////////////////////////////////////////////////////////// - // Methods - ////////////////////////////////////////////////////////////////////////// - void clear() { AutoLock lock(m_cs); s.clear(); } - size_type count(const Key& _Key) const { AutoLock lock(m_cs); return s.count(_Key); } - bool empty() const { AutoLock lock(m_cs); return s.empty(); } - size_type erase(const Key& _Key) { AutoLock lock(m_cs); return s.erase(_Key); } - - bool find(const Key& _Key) { AutoLock lock(m_cs); return (s.find(_Key) != s.end()); } - - bool pop_front(value_type& rFrontElement) - { - AutoLock lock(m_cs); - if (s.empty()) - { - return false; - } - rFrontElement = *s.begin(); - s.erase(s.begin()); - return true; - } - bool pop_front() - { - AutoLock lock(m_cs); - if (s.empty()) - { - return false; - } - s.erase(s.begin()); - return true; - } - - bool front(value_type& rFrontElement) - { - AutoLock lock(m_cs); - if (s.empty()) - { - return false; - } - rFrontElement = *s.begin(); - return true; - } - - bool insert(const value_type& _Val) { AutoLock lock(m_cs); return s.insert(_Val).second; } - size_type max_size() const { AutoLock lock(m_cs); return s.max_size(); } - size_type size() const { AutoLock lock(m_cs); return s.size(); } - void swap(set& _Right) { AutoLock lock(m_cs); s.swap(_Right); } - - CryCriticalSection& get_lock() { return m_cs; } - - private: - std::set s; - mutable CryCriticalSection m_cs; - }; - - - /////////////////////////////////////////////////////////////////////////////// - // - // Multi-thread safe lock-less FIFO queue container for passing pointers between threads. - // The queue only stores pointers to T, it does not copy the contents of T. - // - ////////////////////////////////////////////////////////////////////////// - template > - class CLocklessPointerQueue - { - public: - explicit CLocklessPointerQueue(size_t reserve = 32) { m_lockFreeQueue.reserve(reserve); }; - ~CLocklessPointerQueue() {}; - - // Check's if queue is empty. - bool empty() const; - - // Pushes item to the queue, only pointer is stored, T contents are not copied. - void push(T* ptr); - // pop can return NULL, always check for it before use. - T* pop(); - - private: - queue::template rebind_alloc> m_lockFreeQueue; - }; - - ////////////////////////////////////////////////////////////////////////// - template - inline bool CLocklessPointerQueue::empty() const - { - return m_lockFreeQueue.empty(); - } - - ////////////////////////////////////////////////////////////////////////// - template - inline void CLocklessPointerQueue::push(T* ptr) - { - m_lockFreeQueue.push(ptr); - } - - ////////////////////////////////////////////////////////////////////////// - template - inline T* CLocklessPointerQueue::pop() - { - T* val = NULL; - m_lockFreeQueue.try_pop(val); - return val; - } }; // namespace CryMT namespace stl { - template - void free_container(CryMT::vector& v) - { - v.free_memory(); - } template void free_container(CryMT::queue& v) { diff --git a/Code/Legacy/CryCommon/WinBase.cpp b/Code/Legacy/CryCommon/WinBase.cpp index 3208da9d68..15146fbac1 100644 --- a/Code/Legacy/CryCommon/WinBase.cpp +++ b/Code/Legacy/CryCommon/WinBase.cpp @@ -1377,25 +1377,6 @@ DLL_EXPORT void* CryInterlockedExchangePointer(void* volatile* dst, void* ex //return (void*)CryInterlockedCompareExchange((long volatile*)dst, (long)exchange, (long)comperand); } -#if (defined(LINUX64) && !defined(ANDROID)) || defined(MAC) || defined(IOS_SIMULATOR) -DLL_EXPORT unsigned char _InterlockedCompareExchange128(int64 volatile* dst, int64 exchangehigh, int64 exchangelow, int64* comperand) -{ - bool bEquals; - __asm__ __volatile__ - ( - "lock cmpxchg16b %1\n\t" - "setz %0" - : "=q" (bEquals), "+m" (*dst), "+d" (comperand[1]), "+a" (comperand[0]) - : "c" (exchangehigh), "b" (exchangelow) - : "cc" - ); - return (char)bEquals; -} -#elif defined(INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED) - // arm64 processors do not provide a cmpxchg16b (or equivalent) instruction, - // so _InterlockedCompareExchange128 is not implemented on arm64 platforms. -#endif - threadID CryGetCurrentThreadId() { return GetCurrentThreadId(); diff --git a/Code/Legacy/CryCommon/iOSSpecific.h b/Code/Legacy/CryCommon/iOSSpecific.h index 36b50f0e3e..d2503a7441 100644 --- a/Code/Legacy/CryCommon/iOSSpecific.h +++ b/Code/Legacy/CryCommon/iOSSpecific.h @@ -34,10 +34,6 @@ #define PLATFORM_64BIT #endif -#if defined(_CPU_ARM) && defined(PLATFORM_64BIT) -# define INTERLOCKED_COMPARE_EXCHANGE_128_NOT_SUPPORTED -#endif // defined(_CPU_ARM) && defined(PLATFORM_64BIT) - #ifndef MOBILE #define MOBILE #endif diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index ffaf0e7210..e2ddc324bb 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -618,12 +618,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) } } - // Reset the camera to (1,1,1) (not (0,0,0) which is the invalid/uninitialised state, - // to avoid the hack in the renderer to not show anything if the camera is at the origin). - CCamera defaultCam; - defaultCam.SetPosition(Vec3(1.0f)); - m_pSystem->SetViewCamera(defaultCam); - m_pLoadingLevelInfo = pLevelInfo; OnLoadingStart(levelName); @@ -952,10 +946,6 @@ void CLevelSystem::UnloadLevel() oAudioRequestData.pData = &oAMData3; Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - // Reset the camera to (0,0,0) which is the invalid/uninitialised state - CCamera defaultCam; - m_pSystem->SetViewCamera(defaultCam); - OnUnloadComplete(m_lastLevelName.c_str()); // -- kenzo: this will close all pack files for this level diff --git a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 103d5999f7..f541ad1cec 100644 --- a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -268,12 +268,6 @@ namespace LegacyLevelSystem // This is a workaround until the replacement for GameEntityContext is done AzFramework::GameEntityContextEventBus::Broadcast(&AzFramework::GameEntityContextEventBus::Events::OnPreGameEntitiesStarted); - // Reset the camera to (1,1,1) (not (0,0,0) which is the invalid/uninitialised state, - // to avoid the hack in the renderer to not show anything if the camera is at the origin). - CCamera defaultCam; - defaultCam.SetPosition(Vec3(1.0f)); - m_pSystem->SetViewCamera(defaultCam); - OnLoadingStart(levelName); auto pPak = gEnv->pCryPak; @@ -587,10 +581,6 @@ namespace LegacyLevelSystem oAudioRequestData.pData = &oAMData3; Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); - // Reset the camera to (0,0,0) which is the invalid/uninitialised state - CCamera defaultCam; - m_pSystem->SetViewCamera(defaultCam); - OnUnloadComplete(m_lastLevelName.c_str()); AzFramework::RootSpawnableInterface::Get()->ReleaseRootSpawnable(); diff --git a/Code/Legacy/CrySystem/System.h b/Code/Legacy/CrySystem/System.h index c66b2aab60..db20dd8f1b 100644 --- a/Code/Legacy/CrySystem/System.h +++ b/Code/Legacy/CrySystem/System.h @@ -353,9 +353,6 @@ public: virtual IXmlUtils* GetXmlUtils(); ////////////////////////////////////////////////////////////////////////// - void SetViewCamera(CCamera& Camera){ m_ViewCamera = Camera; } - CCamera& GetViewCamera() { return m_ViewCamera; } - void IgnoreUpdates(bool bIgnore) { m_bIgnoreUpdates = bIgnore; }; void SetIProcess(IProcess* process); @@ -494,7 +491,6 @@ private: // ------------------------------------------------------ SSystemGlobalEnvironment m_env; CTimer m_Time; //!< - CCamera m_ViewCamera; //!< bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch) int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading) diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp index cce3cf4aec..f24bcd2d41 100644 --- a/Code/Legacy/CrySystem/SystemInit.cpp +++ b/Code/Legacy/CrySystem/SystemInit.cpp @@ -896,16 +896,14 @@ void CSystem::InitLocalization() if (auto console = AZ::Interface::Get(); console != nullptr) { AZ::CVarFixedString languageAudio; - if (auto result = console->GetCvarValue("g_languageAudio", languageAudio); result == AZ::GetValueResult::Success) + console->GetCvarValue("g_languageAudio", languageAudio); + if (languageAudio.empty()) { - if (languageAudio.size() == 0) - { - console->PerformCommand(AZStd::string::format("g_languageAudio %s", language.c_str()).c_str()); - } - else - { - language.assign(languageAudio.data(), languageAudio.size()); - } + console->PerformCommand(AZStd::string::format("g_languageAudio %s", language.c_str()).c_str()); + } + else + { + language.assign(languageAudio.data(), languageAudio.size()); } } OpenLanguageAudioPak(language); diff --git a/Code/Legacy/CrySystem/ViewSystem/DebugCamera.cpp b/Code/Legacy/CrySystem/ViewSystem/DebugCamera.cpp index e8d21c961f..1616816844 100644 --- a/Code/Legacy/CrySystem/ViewSystem/DebugCamera.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/DebugCamera.cpp @@ -58,10 +58,10 @@ DebugCamera::~DebugCamera() /////////////////////////////////////////////////////////////////////////////// void DebugCamera::OnEnable() { - m_position = gEnv->pSystem->GetViewCamera().GetPosition(); + m_position = Vec3_Zero; m_moveInput = Vec3_Zero; - Ang3 cameraAngles = Ang3(gEnv->pSystem->GetViewCamera().GetMatrix()); + Ang3 cameraAngles = Ang3(ZERO); m_cameraYaw = RAD2DEG(cameraAngles.z); m_cameraPitch = RAD2DEG(cameraAngles.x); m_view = Matrix33(Ang3(DEG2RAD(m_cameraPitch), 0.0f, DEG2RAD(m_cameraYaw))); @@ -126,13 +126,6 @@ void DebugCamera::Update() /////////////////////////////////////////////////////////////////////////////// void DebugCamera::PostUpdate() { - if (m_cameraMode == DebugCamera::ModeOff) - { - return; - } - - CCamera& camera = gEnv->pSystem->GetViewCamera(); - camera.SetMatrix(Matrix34(m_view, m_position)); } /////////////////////////////////////////////////////////////////////////////// diff --git a/Code/Legacy/CrySystem/ViewSystem/View.cpp b/Code/Legacy/CrySystem/ViewSystem/View.cpp index e6e9f7a984..d8dc24123c 100644 --- a/Code/Legacy/CrySystem/ViewSystem/View.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/View.cpp @@ -55,79 +55,9 @@ void CView::Release() } //------------------------------------------------------------------------ -void CView::Update(float frameTime, bool isActive) +void CView::Update([[maybe_unused]] float frameTime, [[maybe_unused]] bool isActive) { - //FIXME:some cameras may need to be updated always - if (!isActive) - { - return; - } - - if (m_azEntity) - { - m_viewParams.SaveLast(); - - CCamera* pSysCam = &m_pSystem->GetViewCamera(); - - //process screen shaking - ProcessShaking(frameTime); - - //FIXME:to let the updateView implementation use the correct shakeVector - m_viewParams.currentShakeShift = m_viewParams.rotation * m_viewParams.currentShakeShift; - - m_viewParams.frameTime = frameTime; - //update view position/rotation - if (m_azEntity != nullptr) - { - auto entityTransform = m_azEntity->GetTransform(); - if (entityTransform != nullptr) - { - AZ::Transform transform = entityTransform->GetWorldTM(); - m_viewParams.position = AZVec3ToLYVec3(transform.GetTranslation()); - m_viewParams.rotation = AZQuaternionToLYQuaternion(transform.GetRotation()); - } - } - - ApplyFrameAdditiveAngles(m_viewParams.rotation); - - const float fNearZ = gEnv->pSystem->GetIViewSystem()->GetDefaultZNear(); - - //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 : DEFAULT_FAR; - float fov = (m_viewParams.fov < 0.001f) ? DEFAULT_FOV : m_viewParams.fov; - - m_camera.SetFrustum(pSysCam->GetViewSurfaceX(), pSysCam->GetViewSurfaceZ(), fov, nearPlane, farPlane, pSysCam->GetPixelAspectRatio()); - - //apply shake & set the view matrix - m_viewParams.rotation *= m_viewParams.currentShakeQuat; - m_viewParams.rotation.NormalizeSafe(); - m_viewParams.position += m_viewParams.currentShakeShift; - - // Blending between cameras needs to happen after Camera space rendering calculations have been applied - // so that the m_viewParams.position is in World Space again - m_viewParams.UpdateBlending(frameTime); - - // [VR] specific - // Add HMD's pose tracking on top of current camera pose - // Each game-title can decide whether to keep this functionality here or (most likely) - // move it somewhere else. - - Quat q = m_viewParams.rotation; - Vec3 pos = m_viewParams.position; - Vec3 p = Vec3(ZERO); - - Matrix34 viewMtx(q); - viewMtx.SetTranslation(pos + p); - m_camera.SetMatrix(viewMtx); - - m_camera.SetEntityRotation(m_viewParams.rotation); - m_camera.SetEntityPos(pos); - } - else - { - m_linkedTo = AZ::EntityId(0); - } + AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CView::Update)"); } //----------------------------------------------------------------------- diff --git a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp index a82e78c08c..28cf0eb07a 100644 --- a/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/Legacy/CrySystem/ViewSystem/ViewSystem.cpp @@ -253,7 +253,7 @@ void CViewSystem::Update(float frameTime) } } - m_pSystem->SetViewCamera(rCamera); + AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CViewSystem::Update)"); } } @@ -557,23 +557,7 @@ void CViewSystem::SetOverrideCameraRotation(bool bOverride, Quat rotation) ////////////////////////////////////////////////////////////////////////// void CViewSystem::UpdateSoundListeners() { - assert(gEnv->IsEditor() && !gEnv->IsEditorGameMode()); - - // In Editor we may want to control global listeners outside of the game view. - if (m_bControlsAudioListeners) - { - IView* const pActiveView = static_cast(GetActiveView()); - TViewMap::const_iterator Iter(m_views.begin()); - TViewMap::const_iterator const IterEnd(m_views.end()); - - for (; Iter != IterEnd; ++Iter) - { - IView* const pView = Iter->second; - bool const bIsActive = (pView == pActiveView); - CCamera const& rCamera = bIsActive ? gEnv->pSystem->GetViewCamera() : pView->GetCamera(); - pView->UpdateAudioListener(rCamera.GetMatrix()); - } - } + AZ_ErrorOnce("CryLegacy", false, "CryLegacy view system no longer available (CViewSystem::UpdateSoundListeners)"); } ////////////////////////////////////////////////////////////////// diff --git a/Code/Tools/AssetProcessor/Platform/Mac/assetprocessor_mac.cmake b/Code/Tools/AssetProcessor/Platform/Mac/assetprocessor_mac.cmake index 54ed70c496..e34ce9d341 100644 --- a/Code/Tools/AssetProcessor/Platform/Mac/assetprocessor_mac.cmake +++ b/Code/Tools/AssetProcessor/Platform/Mac/assetprocessor_mac.cmake @@ -13,3 +13,27 @@ set_target_properties(AssetProcessor PROPERTIES RESOURCE ${CMAKE_CURRENT_SOURCE_DIR}/Platform/Mac/Images.xcassets XCODE_ATTRIBUTE_ASSETCATALOG_COMPILER_APPICON_NAME AssetProcessorAppIcon ) + +# We cannot use ly_add_target here because we're already including this file from inside ly_add_target +# So we need to setup target, dependencies and install logic manually. +add_executable(AssetProcessorDummy Platform/Mac/main_dummy.cpp) +add_executable(AZ::AssetProcessorDummy ALIAS AssetProcessorDummy) + +ly_target_link_libraries(AssetProcessorDummy + PRIVATE + AZ::AzCore + AZ::AzFramework) + +ly_add_dependencies(AssetProcessor AssetProcessorDummy) + +# Store the aliased target into a DIRECTORY property +set_property(DIRECTORY APPEND PROPERTY LY_DIRECTORY_TARGETS AZ::AssetProcessorDummy) + +# Store the directory path in a GLOBAL property so that it can be accessed +# in the layout install logic. Skip if the directory has already been added +get_property(ly_all_target_directories GLOBAL PROPERTY LY_ALL_TARGET_DIRECTORIES) +if(NOT CMAKE_CURRENT_SOURCE_DIR IN_LIST ly_all_target_directories) + set_property(GLOBAL APPEND PROPERTY LY_ALL_TARGET_DIRECTORIES ${CMAKE_CURRENT_SOURCE_DIR}) +endif() + +ly_install_add_install_path_setreg(AssetProcessor) \ No newline at end of file diff --git a/Code/Tools/AssetProcessor/Platform/Mac/gui_info.plist b/Code/Tools/AssetProcessor/Platform/Mac/gui_info.plist index 665abea1d3..301f0c5cee 100644 --- a/Code/Tools/AssetProcessor/Platform/Mac/gui_info.plist +++ b/Code/Tools/AssetProcessor/Platform/Mac/gui_info.plist @@ -11,7 +11,7 @@ CFBundleSignature ASPR CFBundleExecutable - AssetProcessor + AssetProcessorDummy CFBundleIdentifier com.Amazon.AssetProcessor
diff --git a/Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp b/Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp new file mode 100644 index 0000000000..12832cc488 --- /dev/null +++ b/Code/Tools/AssetProcessor/Platform/Mac/main_dummy.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include + +#include + +int main(int argc, char* argv[]) +{ + // Create a ComponentApplication to initialize the AZ::SystemAllocator and initialize the SettingsRegistry + AZ::ComponentApplication::Descriptor desc; + AZ::ComponentApplication application; + application.Create(desc); + + AZStd::vector envVars; + + const char* homePath = std::getenv("HOME"); + envVars.push_back(AZStd::string::format("HOME=%s", homePath)); + + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + const char* dyldLibPathOrig = std::getenv("DYLD_LIBRARY_PATH"); + AZStd::string dyldSearchPath = AZStd::string::format("DYLD_LIBRARY_PATH=%s", dyldLibPathOrig); + if (AZ::IO::FixedMaxPath projectModulePath; + settingsRegistry->Get(projectModulePath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectConfigurationBinPath)) + { + dyldSearchPath.append(":"); + dyldSearchPath.append(projectModulePath.c_str()); + } + + if (AZ::IO::FixedMaxPath installedBinariesFolder; + settingsRegistry->Get(installedBinariesFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_InstalledBinaryFolder)) + { + if (AZ::IO::FixedMaxPath engineRootFolder; + settingsRegistry->Get(engineRootFolder.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder)) + { + installedBinariesFolder = engineRootFolder / installedBinariesFolder; + dyldSearchPath.append(":"); + dyldSearchPath.append(installedBinariesFolder.c_str()); + } + } + envVars.push_back(dyldSearchPath); + } + + AZStd::string commandArgs; + for (int i = 1; i < argc; i++) + { + commandArgs.append(argv[i]); + commandArgs.append(" "); + } + + AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; + AZ::IO::Path processPath{ AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()) }; + processPath /= "AssetProcessor"; + processLaunchInfo.m_processExecutableString = AZStd::move(processPath.Native()); + processLaunchInfo.m_commandlineParameters = commandArgs; + processLaunchInfo.m_environmentVariables = &envVars; + processLaunchInfo.m_showWindow = true; + + AzFramework::ProcessWatcher* processWatcher = AzFramework::ProcessWatcher::LaunchProcess(processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE); + + application.Destroy(); + + return 0; +} + diff --git a/Code/Tools/AssetProcessor/native/utilities/BuilderManager.cpp b/Code/Tools/AssetProcessor/native/utilities/BuilderManager.cpp index 5ef2ebd2f4..751afc1a5d 100644 --- a/Code/Tools/AssetProcessor/native/utilities/BuilderManager.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/BuilderManager.cpp @@ -28,7 +28,7 @@ namespace AssetProcessor //! Amount of time in seconds to wait for a builder to start up and connect // sometimes, builders take a long time to start because of things like virus scanners scanning each // builder DLL, so we give them a large margin. - static const int s_StartupConnectionWaitTimeS = 120; + static const int s_StartupConnectionWaitTimeS = 300; static const int s_MillisecondsInASecond = 1000; diff --git a/Code/Tools/ProjectManager/Source/Application.cpp b/Code/Tools/ProjectManager/Source/Application.cpp index bdcb59897b..c977698152 100644 --- a/Code/Tools/ProjectManager/Source/Application.cpp +++ b/Code/Tools/ProjectManager/Source/Application.cpp @@ -56,8 +56,6 @@ namespace O3DE::ProjectManager QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QCoreApplication::setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); - QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); - QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware); diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp index eeddf4a0b3..a42870c426 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpBoneImporter.cpp @@ -103,10 +103,6 @@ namespace AZ } } - if(!isBone) - { - return Events::ProcessingResult::Ignored; - } // If the current scene node (our eventual parent) contains bone data, we are not a root bone AZStd::shared_ptr createdBoneData; diff --git a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp index 861d6dd85c..c61ab147a8 100644 --- a/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp +++ b/Code/Tools/SceneAPI/SceneBuilder/Importers/AssImpImporterUtilities.cpp @@ -135,18 +135,13 @@ namespace AZ const aiBone* bone = FindFirstBoneByNodeName(node, boneByNameMap); if (bone) { - const DataTypes::MatrixType inverseOffsetMatrix = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(bone->mOffsetMatrix).GetInverseFull(); - const aiBone* parentBone = FindFirstBoneByNodeName(node->mParent, boneByNameMap); if (parentBone) { + DataTypes::MatrixType inverseOffsetMatrix = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(bone->mOffsetMatrix).GetInverseFull(); const DataTypes::MatrixType parentBoneOffsetMatrix = AssImpSDKWrapper::AssImpTypeConverter::ToTransform(parentBone->mOffsetMatrix); return parentBoneOffsetMatrix * inverseOffsetMatrix; } - else - { - return inverseOffsetMatrix; - } } return AssImpSDKWrapper::AssImpTypeConverter::ToTransform(GetConcatenatedLocalTransform(node)); diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.cpp index cbe587cf1a..0d1f352f21 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.cpp @@ -6,6 +6,8 @@ * */ +#include + #include #include @@ -19,8 +21,9 @@ namespace TestImpact { // Options ConfigKey, + DataFileKey, ChangeListKey, - OutputChangeListKey, + SequenceReportKey, SequenceKey, TestPrioritizationPolicyKey, ExecutionFailurePolicyKey, @@ -55,8 +58,9 @@ namespace TestImpact { // Options "config", + "datafile", "changelist", - "ochangelist", + "report", "sequence", "ppolicy", "epolicy", @@ -92,14 +96,19 @@ namespace TestImpact return ParsePathOption(OptionKeys[ConfigKey], cmd).value_or(LY_TEST_IMPACT_DEFAULT_CONFIG_FILE); } + AZStd::optional ParseDataFile(const AZ::CommandLine& cmd) + { + return ParsePathOption(OptionKeys[DataFileKey], cmd); + } + AZStd::optional ParseChangeListFile(const AZ::CommandLine& cmd) { return ParsePathOption(OptionKeys[ChangeListKey], cmd); } - bool ParseOutputChangeList(const AZ::CommandLine& cmd) + AZStd::optional ParseSequenceReportFile(const AZ::CommandLine& cmd) { - return ParseOnOffOption(OptionKeys[OutputChangeListKey], BinaryStateValue{ false, true }, cmd).value_or(false); + return ParsePathOption(OptionKeys[SequenceReportKey], cmd); } TestSequenceType ParseTestSequenceType(const AZ::CommandLine& cmd) @@ -255,9 +264,9 @@ namespace TestImpact { const AZStd::vector> states = { - {GetSuiteTypeName(SuiteType::Main), SuiteType::Main}, - {GetSuiteTypeName(SuiteType::Periodic), SuiteType::Periodic}, - {GetSuiteTypeName(SuiteType::Sandbox), SuiteType::Sandbox} + { SuiteTypeAsString(SuiteType::Main), SuiteType::Main }, + { SuiteTypeAsString(SuiteType::Periodic), SuiteType::Periodic }, + { SuiteTypeAsString(SuiteType::Sandbox), SuiteType::Sandbox } }; return ParseMultiStateOption(OptionKeys[SuiteFilterKey], states, cmd).value_or(SuiteType::Main); @@ -270,8 +279,9 @@ namespace TestImpact cmd.Parse(argc, argv); m_configurationFile = ParseConfigurationFile(cmd); + m_dataFile = ParseDataFile(cmd); m_changeListFile = ParseChangeListFile(cmd); - m_outputChangeList = ParseOutputChangeList(cmd); + m_sequenceReportFile = ParseSequenceReportFile(cmd); m_testSequenceType = ParseTestSequenceType(cmd); m_testPrioritizationPolicy = ParseTestPrioritizationPolicy(cmd); m_executionFailurePolicy = ParseExecutionFailurePolicy(cmd); @@ -286,28 +296,43 @@ namespace TestImpact m_safeMode = ParseSafeMode(cmd); m_suiteFilter = ParseSuiteFilter(cmd); } + + bool CommandLineOptions::HasDataFilePath() const + { + return m_dataFile.has_value(); + } - bool CommandLineOptions::HasChangeListFile() const + bool CommandLineOptions::HasChangeListFilePath() const { return m_changeListFile.has_value(); } + bool CommandLineOptions::HasSequenceReportFilePath() const + { + return m_sequenceReportFile.has_value(); + } + bool CommandLineOptions::HasSafeMode() const { return m_safeMode; } - const AZStd::optional& CommandLineOptions::GetChangeListFile() const + const AZStd::optional& CommandLineOptions::GetDataFilePath() const + { + return m_dataFile; + } + + const AZStd::optional& CommandLineOptions::GetChangeListFilePath() const { return m_changeListFile; } - bool CommandLineOptions::HasOutputChangeList() const + const AZStd::optional& CommandLineOptions::GetSequenceReportFilePath() const { - return m_outputChangeList; + return m_sequenceReportFile; } - const RepoPath& CommandLineOptions::GetConfigurationFile() const + const RepoPath& CommandLineOptions::GetConfigurationFilePath() const { return m_configurationFile; } @@ -379,8 +404,12 @@ namespace TestImpact " options:\n" " -config= Path to the configuration file for the TIAF runtime (default: \n" " ..json).\n" + " -datafile= Optional path to a test impact data file that will used instead of that\n" + " specified in the config file.\n" " -changelist= Path to the JSON of source file changes to perform test impact \n" " analysis on.\n" + " -report= Path to where the sequence report file will be written (if this option \n" + " is not specified, no report will be written).\n" " -gtimeout= Global timeout value to terminate the entire test sequence should it \n" " be exceeded.\n" " -ttimeout= Timeout value to terminate individual test targets should it be \n" @@ -443,7 +472,6 @@ namespace TestImpact " available, no prioritization will occur).\n" " -maxconcurrency= The maximum number of concurrent test targets/shards to be in flight at \n" " any given moment.\n" - " -ochangelist= Outputs the change list used for test selection.\n" " -suite= The test suite to select from for this test sequence."; return help; diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.h b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.h index ea58305afb..36ca4231b9 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.h +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactCommandLineOptions.h @@ -36,20 +36,29 @@ namespace TestImpact CommandLineOptions(int argc, char** argv); static AZStd::string GetCommandLineUsageString(); + //! Returns true if a test impact data file path has been supplied, otherwise false. + bool HasDataFilePath() const; + //! Returns true if a change list file path has been supplied, otherwise false. - bool HasChangeListFile() const; + bool HasChangeListFilePath() const; + + //! Returns true if a sequence report file path has been supplied, otherwise false. + bool HasSequenceReportFilePath() const; //! Returns true if the safe mode option has been enabled, otherwise false. bool HasSafeMode() const; - //! Returns true if the output change list option has been enabled, otherwise false. - bool HasOutputChangeList() const; - //! Returns the path to the runtime configuration file. - const RepoPath& GetConfigurationFile() const; + const RepoPath& GetConfigurationFilePath() const; + + //! Returns the path to the data file (if any). + const AZStd::optional& GetDataFilePath() const; //! Returns the path to the change list file (if any). - const AZStd::optional& GetChangeListFile() const; + const AZStd::optional& GetChangeListFilePath() const; + + //! Returns the path to the sequence report file (if any). + const AZStd::optional& GetSequenceReportFilePath() const; //! Returns the test sequence type to run. TestSequenceType GetTestSequenceType() const; @@ -89,8 +98,9 @@ namespace TestImpact private: RepoPath m_configurationFile; + AZStd::optional m_dataFile; AZStd::optional m_changeListFile; - bool m_outputChangeList = false; + AZStd::optional m_sequenceReportFile; TestSequenceType m_testSequenceType; Policy::TestPrioritization m_testPrioritizationPolicy = Policy::TestPrioritization::None; Policy::ExecutionFailure m_executionFailurePolicy = Policy::ExecutionFailure::Continue; diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp index 5788da5b2b..bbb4765ad4 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleMain.cpp @@ -9,14 +9,16 @@ #include #include #include +#include #include #include #include #include #include -#include +#include #include #include +#include #include #include @@ -33,31 +35,6 @@ namespace TestImpact { namespace Console { - //! Generates a string to be used for printing to the console for the specified change list. - AZStd::string GenerateChangeListString(const ChangeList& changeList) - { - AZStd::string output; - - const auto& outputFiles = [&output](const AZStd::vector& files) - { - for (const auto& file : files) - { - output += AZStd::string::format("\t%s\n", file.c_str()); - } - }; - - output += AZStd::string::format("Created files (%u):\n", changeList.m_createdFiles.size()); - outputFiles(changeList.m_createdFiles); - - output += AZStd::string::format("Updated files (%u):\n", changeList.m_updatedFiles.size()); - outputFiles(changeList.m_updatedFiles); - - output += AZStd::string::format("Deleted files (%u):\n", changeList.m_deletedFiles.size()); - outputFiles(changeList.m_deletedFiles); - - return output; - } - //! Gets the appropriate console return code for the specified test sequence result. ReturnCode GetReturnCodeForTestSequenceResult(TestSequenceResult result) { @@ -75,9 +52,22 @@ namespace TestImpact } } + //! Wrapper around sequence reports to optionally serialize them and transform the result into a return code. + template + ReturnCode ConsumeSequenceReportAndGetReturnCode(const SequenceReportType& sequenceReport, const CommandLineOptions& options) + { + if (options.HasSequenceReportFilePath()) + { + std::cout << "Exporting sequence report '" << options.GetSequenceReportFilePath().value().c_str() << "'" << std::endl; + const auto sequenceReportJson = SerializeSequenceReport(sequenceReport); + WriteFileContents(sequenceReportJson, options.GetSequenceReportFilePath().value()); + } + + return GetReturnCodeForTestSequenceResult(sequenceReport.GetResult()); + } + //! Wrapper around impact analysis sequences to handle the case where the safe mode option is active. ReturnCode WrappedImpactAnalysisTestSequence( - TestSequenceEventHandler& sequenceEventHandler, const CommandLineOptions& options, Runtime& runtime, const AZStd::optional& changeList) @@ -89,49 +79,34 @@ namespace TestImpact CommandLineOptionsException, "Expected a change list for impact analysis but none was provided"); - TestSequenceResult result = TestSequenceResult::Failure; if (options.HasSafeMode()) { if (options.GetTestSequenceType() == TestSequenceType::ImpactAnalysis) { - auto [selectedResult, discardedResult] = runtime.SafeImpactAnalysisTestSequence( - changeList.value(), - options.GetTestPrioritizationPolicy(), - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); - - // Handling the possible timeout and failure permutations of the selected and discarded test results is splitting hairs - // so apply the following, admittedly arbitrary, rules to determine what the composite test sequence result should be - if (selectedResult == TestSequenceResult::Success && discardedResult == TestSequenceResult::Success) - { - // Trivial case: both sequences succeeded - result = TestSequenceResult::Success; - } - else if (selectedResult == TestSequenceResult::Failure || discardedResult == TestSequenceResult::Failure) - { - // One sequence failed whilst the other sequence either succeeded or timed out - result = TestSequenceResult::Failure; - } - else - { - // One or both sequences timed out or failed - result = TestSequenceResult::Timeout; - } + return ConsumeSequenceReportAndGetReturnCode( + runtime.SafeImpactAnalysisTestSequence( + changeList.value(), + options.GetTestPrioritizationPolicy(), + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + SafeImpactAnalysisTestSequenceStartCallback, + SafeImpactAnalysisTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } else if (options.GetTestSequenceType() == TestSequenceType::ImpactAnalysisNoWrite) { // A no-write impact analysis sequence with safe mode enabled is functionally identical to a regular sequence type // due to a) the selected tests being run without instrumentation and b) the discarded tests also being run without // instrumentation - result = runtime.RegularTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); + return ConsumeSequenceReportAndGetReturnCode( + runtime.RegularTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + RegularTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } else { @@ -153,19 +128,19 @@ namespace TestImpact { throw(Exception("Unexpected sequence type")); } - - result = runtime.ImpactAnalysisTestSequence( - changeList.value(), - options.GetTestPrioritizationPolicy(), - dynamicDependencyMapPolicy, - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); + + return ConsumeSequenceReportAndGetReturnCode( + runtime.ImpactAnalysisTestSequence( + changeList.value(), + options.GetTestPrioritizationPolicy(), + dynamicDependencyMapPolicy, + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + ImpactAnalysisTestSequenceStartCallback, + ImpactAnalysisTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } - - return GetReturnCodeForTestSequenceResult(result); }; //! Entry point for the test impact analysis framework console front end application. @@ -177,28 +152,22 @@ namespace TestImpact AZStd::optional changeList; // If we have a change list, check to see whether or not the client has requested the printing of said change list - if (options.HasChangeListFile()) + if (options.HasChangeListFilePath()) { - changeList = DeserializeChangeList(ReadFileContents(*options.GetChangeListFile())); - if (options.HasOutputChangeList()) - { - std::cout << "Change List:\n"; - std::cout << GenerateChangeListString(*changeList).c_str(); - - if (options.GetTestSequenceType() == TestSequenceType::None) - { - return ReturnCode::Success; - } - } + changeList = DeserializeChangeList(ReadFileContents(*options.GetChangeListFilePath())); } - // As of now, there are no other non-test operations other than printing a change list so getting this far is considered an error - AZ_TestImpact_Eval(options.GetTestSequenceType() != TestSequenceType::None, CommandLineOptionsException, "No action specified"); + // As of now, there are no non-test operations but leave this door open for the future + if (options.GetTestSequenceType() == TestSequenceType::None) + { + return ReturnCode::Success; + } std::cout << "Constructing in-memory model of source tree and test coverage for test suite "; - std::cout << GetSuiteTypeName(options.GetSuiteFilter()).c_str() << ", this may take a moment...\n"; + std::cout << SuiteTypeAsString(options.GetSuiteFilter()).c_str() << ", this may take a moment...\n"; Runtime runtime( - RuntimeConfigurationFactory(ReadFileContents(options.GetConfigurationFile())), + RuntimeConfigurationFactory(ReadFileContents(options.GetConfigurationFilePath())), + options.GetDataFilePath(), options.GetSuiteFilter(), options.GetExecutionFailurePolicy(), options.GetFailedTestCoveragePolicy(), @@ -217,53 +186,51 @@ namespace TestImpact std::cout << "Test impact analysis data for this repository was not found, seed or regular sequence fallbacks will be used.\n"; } - TestSequenceEventHandler sequenceEventHandler(options.GetSuiteFilter()); - switch (const auto type = options.GetTestSequenceType()) { case TestSequenceType::Regular: { - const auto result = runtime.RegularTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); - - return GetReturnCodeForTestSequenceResult(result); + return ConsumeSequenceReportAndGetReturnCode( + runtime.RegularTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + RegularTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } case TestSequenceType::Seed: { - const auto result = runtime.SeededTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); - - return GetReturnCodeForTestSequenceResult(result); + return ConsumeSequenceReportAndGetReturnCode( + runtime.SeededTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + SeedTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } case TestSequenceType::ImpactAnalysisNoWrite: case TestSequenceType::ImpactAnalysis: { - return WrappedImpactAnalysisTestSequence(sequenceEventHandler, options, runtime, changeList); + return WrappedImpactAnalysisTestSequence(options, runtime, changeList); } case TestSequenceType::ImpactAnalysisOrSeed: { if (runtime.HasImpactAnalysisData()) { - return WrappedImpactAnalysisTestSequence(sequenceEventHandler, options, runtime, changeList); + return WrappedImpactAnalysisTestSequence(options, runtime, changeList); } else { - const auto result = runtime.SeededTestSequence( - options.GetTestTargetTimeout(), - options.GetGlobalTimeout(), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler), - AZStd::ref(sequenceEventHandler)); - - return GetReturnCodeForTestSequenceResult(result); + return ConsumeSequenceReportAndGetReturnCode( + runtime.SeededTestSequence( + options.GetTestTargetTimeout(), + options.GetGlobalTimeout(), + TestSequenceStartCallback, + SeedTestSequenceCompleteCallback, + TestRunCompleteCallback), + options); } } default: diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp index dc29b2580c..e7430fe90b 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp @@ -6,8 +6,9 @@ * */ -#include +#include +#include #include #include @@ -20,7 +21,7 @@ namespace TestImpact { void TestSuiteFilter(SuiteType filter) { - std::cout << "Test suite filter: " << GetSuiteTypeName(filter).c_str() << "\n"; + std::cout << "Test suite filter: " << SuiteTypeAsString(filter).c_str() << "\n"; } void ImpactAnalysisTestSelection(size_t numSelectedTests, size_t numDiscardedTests, size_t numExcludedTests, size_t numDraftedTests) @@ -32,72 +33,70 @@ namespace TestImpact std::cout << "Of which " << numExcludedTests << " tests have been excluded and " << numDraftedTests << " tests have been drafted.\n"; } - void FailureReport(const Client::SequenceFailure& failureReport, AZStd::chrono::milliseconds duration) + void FailureReport(const Client::TestRunReport& testRunReport) { - std::cout << "Sequence completed in " << (duration.count() / 1000.f) << "s with"; + std::cout << "Sequence completed in " << (testRunReport.GetDuration().count() / 1000.f) << "s with"; - if (!failureReport.GetExecutionFailures().empty() || - !failureReport.GetTestRunFailures().empty() || - !failureReport.GetTimedOutTests().empty() || - !failureReport.GetUnexecutedTests().empty()) + if (!testRunReport.GetExecutionFailureTestRuns().empty() || + !testRunReport.GetFailingTestRuns().empty() || + !testRunReport.GetTimedOutTestRuns().empty() || + !testRunReport.GetUnexecutedTestRuns().empty()) { std::cout << ":\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetTestRunFailures().size() + << testRunReport.GetFailingTestRuns().size() << ResetColor().c_str() << " test failures\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetExecutionFailures().size() + << testRunReport.GetExecutionFailureTestRuns().size() << ResetColor().c_str() << " execution failures\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetTimedOutTests().size() + << testRunReport.GetTimedOutTestRuns().size() << ResetColor().c_str() << " test timeouts\n"; std::cout << SetColor(Foreground::White, Background::Red).c_str() - << failureReport.GetUnexecutedTests().size() + << testRunReport.GetUnexecutedTestRuns().size() << ResetColor().c_str() << " unexecuted tests\n"; - if (!failureReport.GetTestRunFailures().empty()) + if (!testRunReport.GetFailingTestRuns().empty()) { std::cout << "\nTest failures:\n"; - for (const auto& testRunFailure : failureReport.GetTestRunFailures()) + for (const auto& testRunFailure : testRunReport.GetFailingTestRuns()) { - std::cout << " " << testRunFailure.GetTargetName().c_str(); - for (const auto& testCaseFailure : testRunFailure.GetTestCaseFailures()) + for (const auto& test : testRunFailure.GetTests()) { - std::cout << "." << testCaseFailure.GetName().c_str(); - for (const auto& testFailure : testCaseFailure.GetTestFailures()) + if (test.GetResult() == Client::TestResult::Failed) { - std::cout << "." << testFailure.GetName().c_str() << "\n"; + std::cout << " " << test.GetName().c_str() << "\n"; } } } } - if (!failureReport.GetExecutionFailures().empty()) + if (!testRunReport.GetExecutionFailureTestRuns().empty()) { std::cout << "\nExecution failures:\n"; - for (const auto& executionFailure : failureReport.GetExecutionFailures()) + for (const auto& executionFailure : testRunReport.GetExecutionFailureTestRuns()) { std::cout << " " << executionFailure.GetTargetName().c_str() << "\n"; std::cout << executionFailure.GetCommandString().c_str() << "\n"; } } - if (!failureReport.GetTimedOutTests().empty()) + if (!testRunReport.GetTimedOutTestRuns().empty()) { std::cout << "\nTimed out tests:\n"; - for (const auto& testTimeout : failureReport.GetTimedOutTests()) + for (const auto& testTimeout : testRunReport.GetTimedOutTestRuns()) { std::cout << " " << testTimeout.GetTargetName().c_str() << "\n"; } } - if (!failureReport.GetUnexecutedTests().empty()) + if (!testRunReport.GetUnexecutedTestRuns().empty()) { std::cout << "\nUnexecuted tests:\n"; - for (const auto& unexecutedTest : failureReport.GetUnexecutedTests()) + for (const auto& unexecutedTest : testRunReport.GetUnexecutedTestRuns()) { std::cout << " " << unexecutedTest.GetTargetName().c_str() << "\n"; } @@ -105,50 +104,42 @@ namespace TestImpact } else { - std::cout << SetColor(Foreground::White, Background::Green).c_str() << " \100% passes!\n" << ResetColor().c_str(); + std::cout << " " << SetColor(Foreground::White, Background::Green).c_str() << "100% passes!\n" << ResetColor().c_str() << "\n"; } } } - TestSequenceEventHandler::TestSequenceEventHandler(SuiteType suiteFilter) - : m_suiteFilter(suiteFilter) + void TestSequenceStartCallback(SuiteType suiteType, const Client::TestRunSelection& selectedTests) { + Output::TestSuiteFilter(suiteType); + std::cout << selectedTests.GetNumIncludedTestRuns() << " tests selected, " << selectedTests.GetNumExcludedTestRuns() + << " excluded.\n"; } - // TestSequenceStartCallback - void TestSequenceEventHandler::operator()(Client::TestRunSelection&& selectedTests) + void TestSequenceCompleteCallback(SuiteType suiteType, const Client::TestRunSelection& selectedTests) { - ClearState(); - m_numTests = selectedTests.GetNumIncludedTestRuns(); - - Output::TestSuiteFilter(m_suiteFilter); + Output::TestSuiteFilter(suiteType); std::cout << selectedTests.GetNumIncludedTestRuns() << " tests selected, " << selectedTests.GetNumExcludedTestRuns() << " excluded.\n"; } - // ImpactAnalysisTestSequenceStartCallback - void TestSequenceEventHandler::operator()( - Client::TestRunSelection&& selectedTests, - AZStd::vector&& discardedTests, - AZStd::vector&& draftedTests) + void ImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests) { - ClearState(); - m_numTests = selectedTests.GetNumIncludedTestRuns() + draftedTests.size(); - - Output::TestSuiteFilter(m_suiteFilter); + Output::TestSuiteFilter(suiteType); Output::ImpactAnalysisTestSelection( selectedTests.GetTotalNumTests(), discardedTests.size(), selectedTests.GetNumExcludedTestRuns(), draftedTests.size()); } - // SafeImpactAnalysisTestSequenceStartCallback - void TestSequenceEventHandler::operator()( - Client::TestRunSelection&& selectedTests, - Client::TestRunSelection&& discardedTests, - AZStd::vector&& draftedTests) + void SafeImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const Client::TestRunSelection& discardedTests, + const AZStd::vector& draftedTests) { - ClearState(); - m_numTests = selectedTests.GetNumIncludedTestRuns() + draftedTests.size(); - - Output::TestSuiteFilter(m_suiteFilter); + Output::TestSuiteFilter(suiteType); Output::ImpactAnalysisTestSelection( selectedTests.GetTotalNumTests(), discardedTests.GetTotalNumTests(), @@ -156,40 +147,49 @@ namespace TestImpact draftedTests.size()); } - // TestSequenceCompleteCallback - void TestSequenceEventHandler::operator()( - Client::SequenceFailure&& failureReport, - AZStd::chrono::milliseconds duration) + void RegularTestSequenceCompleteCallback(const Client::RegularSequenceReport& sequenceReport) { - - Output::FailureReport(failureReport, duration); + Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); std::cout << "Updating and serializing the test impact analysis data, this may take a moment...\n"; } - // SafeTestSequenceCompleteCallback - void TestSequenceEventHandler::operator()( - Client::SequenceFailure&& selectedFailureReport, - Client::SequenceFailure&& discardedFailureReport, - AZStd::chrono::milliseconds selectedDuration, - AZStd::chrono::milliseconds discaredDuration) + void SeedTestSequenceCompleteCallback(const Client::SeedSequenceReport& sequenceReport) + { + Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); + } + + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport) { std::cout << "Selected test run:\n"; - Output::FailureReport(selectedFailureReport, selectedDuration); + Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); + + std::cout << "Drafted test run:\n"; + Output::FailureReport(sequenceReport.GetDraftedTestRunReport()); + + std::cout << "Updating and serializing the test impact analysis data, this may take a moment...\n"; + } + + void SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport) + { + std::cout << "Selected test run:\n"; + Output::FailureReport(sequenceReport.GetSelectedTestRunReport()); std::cout << "Discarded test run:\n"; - Output::FailureReport(discardedFailureReport, discaredDuration); + Output::FailureReport(sequenceReport.GetDiscardedTestRunReport()); + + std::cout << "Drafted test run:\n"; + Output::FailureReport(sequenceReport.GetDraftedTestRunReport()); std::cout << "Updating and serializing the test impact analysis data, this may take a moment...\n"; } - // TestRunCompleteCallback - void TestSequenceEventHandler::operator()([[maybe_unused]] Client::TestRun&& test) + void TestRunCompleteCallback(const Client::TestRunBase& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns) { - m_numTestsComplete++; - const auto progress = AZStd::string::format("(%03u/%03u)", m_numTestsComplete, m_numTests, test.GetTargetName().c_str()); + const auto progress = + AZStd::string::format("(%03u/%03u)", numTestRunsCompleted, totalNumTestRuns, testRun.GetTargetName().c_str()); AZStd::string result; - switch (test.GetResult()) + switch (testRun.GetResult()) { case Client::TestRunResult::AllTestsPass: { @@ -216,15 +216,14 @@ namespace TestImpact result = SetColorForString(Foreground::White, Background::Magenta, "TIME"); break; } + default: + { + AZ_Error("TestRunCompleteCallback", false, "Unexpected test result to handle: %u", aznumeric_cast(testRun.GetResult())); + } } - std::cout << progress.c_str() << " " << result.c_str() << " " << test.GetTargetName().c_str() << " (" << (test.GetDuration().count() / 1000.f) << "s)\n"; - } - - void TestSequenceEventHandler::ClearState() - { - m_numTests = 0; - m_numTestsComplete = 0; + std::cout << progress.c_str() << " " << result.c_str() << " " << testRun.GetTargetName().c_str() << " (" + << (testRun.GetDuration().count() / 1000.f) << "s)\n"; } } // namespace Console } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h index ea570f6fc8..8f28d60617 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.h @@ -8,7 +8,7 @@ #include #include -#include +#include #include #include @@ -21,48 +21,36 @@ namespace TestImpact { namespace Console { - //! Event handler for all test sequence types. - class TestSequenceEventHandler - { - public: - explicit TestSequenceEventHandler(SuiteType suiteFilter); + //! Handler for TestSequenceStartCallback event. + void TestSequenceStartCallback(SuiteType suiteType, const Client::TestRunSelection& selectedTests); - //! TestSequenceStartCallback. - void operator()(Client::TestRunSelection&& selectedTests); + //! Handler for TestSequenceStartCallback event. + void ImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests); - //! ImpactAnalysisTestSequenceStartCallback. - void operator()( - Client::TestRunSelection&& selectedTests, - AZStd::vector&& discardedTests, - AZStd::vector&& draftedTests); + //! Handler for SafeImpactAnalysisTestSequenceStartCallback event. + void SafeImpactAnalysisTestSequenceStartCallback( + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const Client::TestRunSelection& discardedTests, + const AZStd::vector& draftedTests); - //! SafeImpactAnalysisTestSequenceStartCallback. - void operator()( - Client::TestRunSelection&& selectedTests, - Client::TestRunSelection&& discardedTests, - AZStd::vector&& draftedTests); + //! Handler for RegularTestSequenceCompleteCallback event. + void RegularTestSequenceCompleteCallback(const Client::RegularSequenceReport& sequenceReport); - //! TestSequenceCompleteCallback. - void operator()( - Client::SequenceFailure&& failureReport, - AZStd::chrono::milliseconds duration); + //! Handler for SeedTestSequenceCompleteCallback event. + void SeedTestSequenceCompleteCallback(const Client::SeedSequenceReport& sequenceReport); - //! SafeTestSequenceCompleteCallback. - void operator()( - Client::SequenceFailure&& selectedFailureReport, - Client::SequenceFailure&& discardedFailureReport, - AZStd::chrono::milliseconds selectedDuration, - AZStd::chrono::milliseconds discaredDuration); + //! Handler for ImpactAnalysisTestSequenceCompleteCallback event. + void ImpactAnalysisTestSequenceCompleteCallback(const Client::ImpactAnalysisSequenceReport& sequenceReport); - //! TestRunCompleteCallback. - void operator()(Client::TestRun&& test); + //! Handler for SafeImpactAnalysisTestSequenceCompleteCallback event. + void SafeImpactAnalysisTestSequenceCompleteCallback(const Client::SafeImpactAnalysisSequenceReport& sequenceReport); - private: - void ClearState(); - - SuiteType m_suiteFilter; - size_t m_numTests = 0; - size_t m_numTestsComplete = 0; - }; + //! Handler for TestRunCompleteCallback event. + void TestRunCompleteCallback(const Client::TestRunBase& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns); } // namespace Console } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp index 0d54cf417d..8ea32d6447 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactRuntimeConfigurationFactory.cpp @@ -7,6 +7,7 @@ */ #include +#include #include @@ -140,17 +141,17 @@ namespace TestImpact return tempWorkspaceConfig; } - AZStd::array ParseTestImpactAnalysisDataFiles(const RepoPath& root, const rapidjson::Value& sparTIAFile) + AZStd::array ParseTestImpactAnalysisDataFiles(const RepoPath& root, const rapidjson::Value& sparTiaFile) { - AZStd::array sparTIAFiles; - sparTIAFiles[static_cast(SuiteType::Main)] = - GetAbsPathFromRelPath(root, sparTIAFile[GetSuiteTypeName(SuiteType::Main).c_str()].GetString()); - sparTIAFiles[static_cast(SuiteType::Periodic)] = - GetAbsPathFromRelPath(root, sparTIAFile[GetSuiteTypeName(SuiteType::Periodic).c_str()].GetString()); - sparTIAFiles[static_cast(SuiteType::Sandbox)] = - GetAbsPathFromRelPath(root, sparTIAFile[GetSuiteTypeName(SuiteType::Sandbox).c_str()].GetString()); + AZStd::array sparTiaFiles; + sparTiaFiles[static_cast(SuiteType::Main)] = + GetAbsPathFromRelPath(root, sparTiaFile[SuiteTypeAsString(SuiteType::Main).c_str()].GetString()); + sparTiaFiles[static_cast(SuiteType::Periodic)] = + GetAbsPathFromRelPath(root, sparTiaFile[SuiteTypeAsString(SuiteType::Periodic).c_str()].GetString()); + sparTiaFiles[static_cast(SuiteType::Sandbox)] = + GetAbsPathFromRelPath(root, sparTiaFile[SuiteTypeAsString(SuiteType::Sandbox).c_str()].GetString()); - return sparTIAFiles; + return sparTiaFiles; } WorkspaceConfig::Active ParseActiveWorkspaceConfig(const rapidjson::Value& activeWorkspace) @@ -160,7 +161,7 @@ namespace TestImpact activeWorkspaceConfig.m_root = activeWorkspace[Config::Keys[Config::Root]].GetString(); activeWorkspaceConfig.m_enumerationCacheDirectory = GetAbsPathFromRelPath(activeWorkspaceConfig.m_root, relativePaths[Config::Keys[Config::EnumerationCacheDir]].GetString()); - activeWorkspaceConfig.m_sparTIAFiles = + activeWorkspaceConfig.m_sparTiaFiles = ParseTestImpactAnalysisDataFiles(activeWorkspaceConfig.m_root, relativePaths[Config::Keys[Config::TestImpactDataFiles]]); return activeWorkspaceConfig; } diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientFailureReport.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientFailureReport.h deleted file mode 100644 index 063a3fa642..0000000000 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientFailureReport.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include - -namespace TestImpact -{ - namespace Client - { - //! Represents a test target that failed, either due to failing to execute, completing in an abnormal state or completing with failing tests. - class TargetFailure - { - public: - TargetFailure(const AZStd::string& targetName); - - //! Returns the name of the test target this failure pertains to. - const AZStd::string& GetTargetName() const; - private: - AZStd::string m_targetName; - }; - - //! Represents a test target that failed to execute. - class ExecutionFailure - : public TargetFailure - { - public: - ExecutionFailure(const AZStd::string& targetName, const AZStd::string& command); - - //! Returns the command string used to execute this test target. - const AZStd::string& GetCommandString() const; - private: - AZStd::string m_commandString; - }; - - //! Represents an individual test of a test target that failed. - class TestFailure - { - public: - TestFailure(const AZStd::string& testName, const AZStd::string& errorMessage); - - //! Returns the name of the test that failed. - const AZStd::string& GetName() const; - - //! Returns the error message of the test that failed. - const AZStd::string& GetErrorMessage() const; - - private: - AZStd::string m_name; - AZStd::string m_errorMessage; - }; - - //! Represents a collection of tests that failed. - //! @note Only the failing tests are included in the collection. - class TestCaseFailure - { - public: - TestCaseFailure(const AZStd::string& testCaseName, AZStd::vector&& testFailures); - - //! Returns the name of the test case containing the failing tests. - const AZStd::string& GetName() const; - - //! Returns the collection of tests in this test case that failed. - const AZStd::vector& GetTestFailures() const; - - private: - AZStd::string m_name; - AZStd::vector m_testFailures; - }; - - //! Represents a test target that launched successfully but contains failing tests. - class TestRunFailure - : public TargetFailure - { - public: - TestRunFailure(const AZStd::string& targetName, AZStd::vector&& testFailures); - - //! Returns the total number of failing tests in this run. - size_t GetNumTestFailures() const; - - //! Returns the test cases in this run containing failing tests. - const AZStd::vector& GetTestCaseFailures() const; - - private: - AZStd::vector m_testCaseFailures; - size_t m_numTestFailures = 0; - }; - - //! Base class for reporting failing test sequences. - class SequenceFailure - { - public: - SequenceFailure( - AZStd::vector&& executionFailures, - AZStd::vector&& testRunFailures, - AZStd::vector&& timedOutTests, - AZStd::vector&& unexecutedTests); - - //! Returns the test targets in this sequence that failed to execute. - const AZStd::vector& GetExecutionFailures() const; - - //! Returns the test targets that contain failing tests. - const AZStd::vector& GetTestRunFailures() const; - - //! Returns the test targets in this sequence that were terminated for exceeding their allotted runtime. - const AZStd::vector& GetTimedOutTests() const; - - //! Returns the test targets in this sequence that were not executed due to the sequence terminating prematurely. - const AZStd::vector& GetUnexecutedTests() const; - - private: - AZStd::vector m_executionFailures; - AZStd::vector m_testRunFailures; - AZStd::vector m_timedOutTests; - AZStd::vector m_unexecutedTests; - }; - } // namespace Client -} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h new file mode 100644 index 0000000000..e86123ddc7 --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h @@ -0,0 +1,544 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include +#include + +#include +#include + +namespace TestImpact +{ + namespace Client + { + //! The report types generated by each sequence. + enum class SequenceReportType : AZ::u8 + { + RegularSequence, + SeedSequence, + ImpactAnalysisSequence, + SafeImpactAnalysisSequence + }; + + //! Calculates the final sequence result for a composite of multiple sequences. + TestSequenceResult CalculateMultiTestSequenceResult(const AZStd::vector& results); + + //! Report detailing the result and duration of a given set of test runs along with the details of each individual test run. + class TestRunReport + { + public: + //! Constructs the report for the given set of test runs that were run together in the same set. + //! @param result The result of this set of test runs. + //! @param startTime The time point his set of test runs started. + //! @param duration The duration this set of test runs took to complete. + //! @param passingTestRuns The set of test runs that executed successfully with no failing test runs. + //! @param failingTestRuns The set of test runs that executed successfully but had one or more failing tests. + //! @param executionFailureTestRuns The set of test runs that failed to execute. + //! @param timedOutTestRuns The set of test runs that executed successfully but were terminated prematurely due to timing out. + //! @param unexecutedTestRuns The set of test runs that were queued up for execution but did not get the opportunity to execute. + TestRunReport( + TestSequenceResult result, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + AZStd::vector&& passingTestRuns, + AZStd::vector&& failingTestRuns, + AZStd::vector&& executionFailureTestRuns, + AZStd::vector&& timedOutTestRuns, + AZStd::vector&& unexecutedTestRuns); + + //! Returns the result of this sequence of test runs. + TestSequenceResult GetResult() const; + + //! Returns the time this sequence of test runs started relative to T0. + AZStd::chrono::high_resolution_clock::time_point GetStartTime() const; + + //! Returns the time this sequence of test runs ended relative to T0. + AZStd::chrono::high_resolution_clock::time_point GetEndTime() const; + + //! Returns the duration this sequence of test runs took to complete. + AZStd::chrono::milliseconds GetDuration() const; + + //! Returns the total number of test runs. + size_t GetTotalNumTestRuns() const; + + //! Returns the number of passing test runs. + size_t GetNumPassingTestRuns() const; + + //! Returns the number of failing test runs. + size_t GetNumFailingTestRuns() const; + + //! Returns the number of test runs that failed to execute. + size_t GetNumExecutionFailureTestRuns() const; + + //! Returns the number of timed out test runs. + size_t GetNumTimedOutTestRuns() const; + + //! Returns the number of unexecuted test runs. + size_t GetNumUnexecutedTestRuns() const; + + //! Returns the total number of passing tests across all test runs in the report. + size_t GetTotalNumPassingTests() const; + + //! Returns the total number of failing tests across all test runs in the report. + size_t GetTotalNumFailingTests() const; + + //! Returns the total number of disabled tests across all test runs in the report. + size_t GetTotalNumDisabledTests() const; + + //! Returns the set of test runs that executed successfully with no failing tests. + const AZStd::vector& GetPassingTestRuns() const; + + //! Returns the set of test runs that executed successfully but had one or more failing tests. + const AZStd::vector& GetFailingTestRuns() const; + + //! Returns the set of test runs that failed to execute. + const AZStd::vector& GetExecutionFailureTestRuns() const; + + //! Returns the set of test runs that executed successfully but were terminated prematurely due to timing out. + const AZStd::vector& GetTimedOutTestRuns() const; + + //! Returns the set of test runs that were queued up for execution but did not get the opportunity to execute. + const AZStd::vector& GetUnexecutedTestRuns() const; + private: + TestSequenceResult m_result = TestSequenceResult::Success; + AZStd::chrono::high_resolution_clock::time_point m_startTime; + AZStd::chrono::milliseconds m_duration = AZStd::chrono::milliseconds{ 0 }; + AZStd::vector m_passingTestRuns; + AZStd::vector m_failingTestRuns; + AZStd::vector m_executionFailureTestRuns; + AZStd::vector m_timedOutTestRuns; + AZStd::vector m_unexecutedTestRuns; + size_t m_totalNumPassingTests = 0; + size_t m_totalNumFailingTests = 0; + size_t m_totalNumDisabledTests = 0; + }; + + //! Base class for all sequence report types. + template + class SequenceReportBase + { + public: + //! Constructs the report for a sequence of selected tests. + //! @param type The type of sequence this report is generated for. + //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. + //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param policyState The policy state this sequence was executed under. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTestRuns The target names of the selected test runs. + //! @param selectedTestRunReport The report for the set of selected test runs. + SequenceReportBase( + SequenceReportType type, + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const PolicyStateType& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + TestRunReport&& selectedTestRunReport) + : m_type(type) + , m_maxConcurrency(maxConcurrency) + , m_testTargetTimeout(testTargetTimeout) + , m_globalTimeout(globalTimeout) + , m_policyState(policyState) + , m_suite(suiteType) + , m_selectedTestRuns(selectedTestRuns) + , m_selectedTestRunReport(AZStd::move(selectedTestRunReport)) + { + } + + virtual ~SequenceReportBase() = default; + + //! Returns the identifying type for this sequence report. + SequenceReportType GetType() const + { + return m_type; + } + + //! Returns the maximum concurrency for this sequence. + size_t GetMaxConcurrency() const + { + return m_maxConcurrency; + } + + //! Returns the global timeout for this sequence. + const AZStd::optional& GetGlobalTimeout() const + { + return m_globalTimeout; + } + + //! Returns the test target timeout for this sequence. + const AZStd::optional& GetTestTargetTimeout() const + { + return m_testTargetTimeout; + } + + //! Returns the policy state for this sequence. + const PolicyStateType& GetPolicyState() const + { + return m_policyState; + } + + //! Returns the suite for this sequence. + SuiteType GetSuite() const + { + return m_suite; + } + + //! Returns the result of the sequence. + virtual TestSequenceResult GetResult() const + { + return m_selectedTestRunReport.GetResult(); + } + + //! Returns the tests selected for running in the sequence. + TestRunSelection GetSelectedTestRuns() const + { + return m_selectedTestRuns; + } + + //! Returns the report for the selected test runs. + TestRunReport GetSelectedTestRunReport() const + { + return m_selectedTestRunReport; + } + + //! Returns the start time of the sequence. + AZStd::chrono::high_resolution_clock::time_point GetStartTime() const + { + return m_selectedTestRunReport.GetStartTime(); + } + + //! Returns the end time of the sequence. + AZStd::chrono::high_resolution_clock::time_point GetEndTime() const + { + return GetStartTime() + GetDuration(); + } + + //! Returns the entire duration the sequence took from start to finish. + virtual AZStd::chrono::milliseconds GetDuration() const + { + return m_selectedTestRunReport.GetDuration(); + } + + //! Returns the total number of test runs across all test run reports. + virtual size_t GetTotalNumTestRuns() const + { + return m_selectedTestRunReport.GetTotalNumTestRuns(); + } + + //! Returns the total number of passing tests across all test targets in all test run reports. + virtual size_t GetTotalNumPassingTests() const + { + return m_selectedTestRunReport.GetTotalNumPassingTests(); + } + + //! Returns the total number of failing tests across all test targets in all test run reports. + virtual size_t GetTotalNumFailingTests() const + { + return m_selectedTestRunReport.GetTotalNumFailingTests(); + } + + //! Returns the total number of unexecuted tests across all test targets in all test run reports. + virtual size_t GetTotalNumDisabledTests() const + { + return m_selectedTestRunReport.GetTotalNumDisabledTests(); + } + + //! Get the total number of test runs in the sequence that passed. + virtual size_t GetTotalNumPassingTestRuns() const + { + return m_selectedTestRunReport.GetNumPassingTestRuns(); + } + + //! Get the total number of test runs in the sequence that contain one or more test failures. + virtual size_t GetTotalNumFailingTestRuns() const + { + return m_selectedTestRunReport.GetNumFailingTestRuns(); + } + + //! Returns the total number of test runs that failed to execute. + virtual size_t GetTotalNumExecutionFailureTestRuns() const + { + return m_selectedTestRunReport.GetNumExecutionFailureTestRuns(); + } + + //! Get the total number of test runs in the sequence that timed out whilst in flight. + virtual size_t GetTotalNumTimedOutTestRuns() const + { + return m_selectedTestRunReport.GetNumTimedOutTestRuns(); + } + + //! Get the total number of test runs in the sequence that were queued for execution but did not get the opportunity to execute. + virtual size_t GetTotalNumUnexecutedTestRuns() const + { + return m_selectedTestRunReport.GetNumUnexecutedTestRuns(); + } + + private: + SequenceReportType m_type; + size_t m_maxConcurrency = 0; + AZStd::optional m_testTargetTimeout; + AZStd::optional m_globalTimeout; + PolicyStateType m_policyState; + SuiteType m_suite = SuiteType::Main; + TestRunSelection m_selectedTestRuns; + TestRunReport m_selectedTestRunReport; + }; + + //! Report type for regular test sequences. + class RegularSequenceReport + : public SequenceReportBase + { + public: + //! Constructs the report for a regular sequence. + //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. + //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param policyState The policy state this sequence was executed under. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTestRuns The target names of the selected test runs. + //! @param selectedTestRunReport The report for the set of selected test runs. + RegularSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const SequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + TestRunReport&& selectedTestRunReport); + }; + + //! Report type for seed test sequences. + class SeedSequenceReport + : public SequenceReportBase + { + public: + //! Constructs the report for a seed sequence. + //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. + //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param policyState The policy state this sequence was executed under. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTestRuns The target names of the selected test runs. + //! @param selectedTestRunReport The report for the set of selected test runs. + SeedSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const SequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + TestRunReport&& selectedTestRunReport); + }; + + //! Report detailing a test run sequence of selected and drafted tests. + template + class DraftingSequenceReportBase + : public SequenceReportBase + { + public: + //! Constructs the report for sequences that draft in previously failed/newly added test targets. + //! @param type The type of sequence this report is generated for. + //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. + //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param policyState The policy state this sequence was executed under. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTestRuns The target names of the selected test runs. + //! @param draftedTestRuns The target names of the drafted test runs. + //! @param selectedTestRunReport The report for the set of selected test runs. + //! @param draftedTestRunReport The report for the set of drafted test runs. + DraftingSequenceReportBase( + SequenceReportType type, + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const PolicyStateType& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + const AZStd::vector& draftedTestRuns, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport) + : SequenceReportBase( + type, + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTestRuns, + AZStd::move(selectedTestRunReport)) + , m_draftedTestRuns(draftedTestRuns) + , m_draftedTestRunReport(AZStd::move(draftedTestRunReport)) + { + } + + //! Returns the tests drafted for running in the sequence. + const AZStd::vector& GetDraftedTestRuns() const + { + return m_draftedTestRuns; + } + + //! Returns the report for the drafted test runs. + TestRunReport GetDraftedTestRunReport() const + { + return m_draftedTestRunReport; + } + + // SequenceReport overrides ... + AZStd::chrono::milliseconds GetDuration() const override + { + return SequenceReportBase::GetDuration() + m_draftedTestRunReport.GetDuration(); + } + + TestSequenceResult GetResult() const override + { + return CalculateMultiTestSequenceResult({ SequenceReportBase::GetResult(), m_draftedTestRunReport.GetResult() }); + } + + size_t GetTotalNumTestRuns() const override + { + return SequenceReportBase::GetTotalNumTestRuns() + m_draftedTestRunReport.GetTotalNumTestRuns(); + } + + size_t GetTotalNumPassingTests() const override + { + return SequenceReportBase::GetTotalNumPassingTests() + m_draftedTestRunReport.GetTotalNumPassingTests(); + } + + size_t GetTotalNumFailingTests() const override + { + return SequenceReportBase::GetTotalNumFailingTests() + m_draftedTestRunReport.GetTotalNumFailingTests(); + } + + size_t GetTotalNumDisabledTests() const override + { + return SequenceReportBase::GetTotalNumDisabledTests() + m_draftedTestRunReport.GetTotalNumDisabledTests(); + } + + size_t GetTotalNumPassingTestRuns() const override + { + return SequenceReportBase::GetTotalNumPassingTestRuns() + m_draftedTestRunReport.GetNumPassingTestRuns(); + } + + size_t GetTotalNumFailingTestRuns() const override + { + return SequenceReportBase::GetTotalNumFailingTestRuns() + m_draftedTestRunReport.GetNumFailingTestRuns(); + } + + size_t GetTotalNumExecutionFailureTestRuns() const override + { + return SequenceReportBase::GetTotalNumExecutionFailureTestRuns() + m_draftedTestRunReport.GetNumExecutionFailureTestRuns(); + } + + size_t GetTotalNumTimedOutTestRuns() const override + { + return SequenceReportBase::GetTotalNumTimedOutTestRuns() + m_draftedTestRunReport.GetNumTimedOutTestRuns(); + } + + size_t GetTotalNumUnexecutedTestRuns() const override + { + return SequenceReportBase::GetTotalNumUnexecutedTestRuns() + m_draftedTestRunReport.GetNumUnexecutedTestRuns(); + } + private: + AZStd::vector m_draftedTestRuns; + TestRunReport m_draftedTestRunReport; + }; + + //! Report detailing an impact analysis sequence of selected, discarded and drafted tests. + class ImpactAnalysisSequenceReport + : public DraftingSequenceReportBase + { + public: + //! Constructs the report for an impact analysis sequence. + //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. + //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param policyState The policy state this sequence was executed under. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTestRuns The target names of the selected test runs. + //! @param draftedTestRuns The target names of the drafted test runs. + //! @param selectedTestRunReport The report for the set of selected test runs. + //! @param draftedTestRunReport The report for the set of drafted test runs. + ImpactAnalysisSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const ImpactAnalysisSequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + const AZStd::vector& discardedTestRuns, + const AZStd::vector& draftedTestRuns, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport); + + //! Returns the test runs discarded from running in the sequence. + const AZStd::vector& GetDiscardedTestRuns() const; + private: + AZStd::vector m_discardedTestRuns; + }; + + //! Report detailing an impact analysis sequence of selected, discarded and drafted test runs. + class SafeImpactAnalysisSequenceReport + : public DraftingSequenceReportBase + { + public: + //! Constructs the report for a sequence of selected, discarded and drafted test runs. + //! @param maxConcurrency The maximum number of concurrent test targets in flight at any given time. + //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param policyState The policy state this sequence was executed under. + //! @param suiteType The suite from which the tests have been selected from. + //! @param selectedTestRuns The target names of the selected test runs. + //! @param discardedTestRuns The target names of the discarded test runs. + //! @param draftedTestRuns The target names of the drafted test runs. + //! @param selectedTestRunReport The report for the set of selected test runs. + //! @param discardedTestRunReport The report for the set of discarded test runs. + //! @param draftedTestRunReport The report for the set of drafted test runs. + SafeImpactAnalysisSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const SafeImpactAnalysisSequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + const TestRunSelection& discardedTestRuns, + const AZStd::vector& draftedTestRuns, + TestRunReport&& selectedTestRunReport, + TestRunReport&& discardedTestRunReport, + TestRunReport&& draftedTestRunReport); + + // SequenceReport overrides ... + AZStd::chrono::milliseconds GetDuration() const override; + TestSequenceResult GetResult() const override; + size_t GetTotalNumTestRuns() const override; + size_t GetTotalNumPassingTests() const override; + size_t GetTotalNumFailingTests() const override; + size_t GetTotalNumDisabledTests() const override; + size_t GetTotalNumPassingTestRuns() const override; + size_t GetTotalNumFailingTestRuns() const override; + size_t GetTotalNumExecutionFailureTestRuns() const override; + size_t GetTotalNumTimedOutTestRuns() const override; + size_t GetTotalNumUnexecutedTestRuns() const override; + + //! Returns the report for the discarded test runs. + const TestRunSelection GetDiscardedTestRuns() const; + + //! Returns the report for the discarded test runs. + TestRunReport GetDiscardedTestRunReport() const; + + private: + TestRunSelection m_discardedTestRuns; + TestRunReport m_discardedTestRunReport; + }; + } // namespace Client +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h new file mode 100644 index 0000000000..fc226588e7 --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +#include + +namespace TestImpact +{ + //! Serializes a regular sequence report to JSON format. + AZStd::string SerializeSequenceReport(const Client::RegularSequenceReport& sequenceReport); + + //! Serializes a seed sequence report to JSON format. + AZStd::string SerializeSequenceReport(const Client::SeedSequenceReport& sequenceReport); + + //! Serializes an impact analysis sequence report to JSON format. + AZStd::string SerializeSequenceReport(const Client::ImpactAnalysisSequenceReport& sequenceReport); + + //! Serializes a safe impact analysis sequence report to JSON format. + AZStd::string SerializeSequenceReport(const Client::SafeImpactAnalysisSequenceReport& sequenceReport); +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestRun.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestRun.h index f8a2707b96..f22963b5e6 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestRun.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestRun.h @@ -6,8 +6,9 @@ * */ -#include #include +#include +#include #pragma once @@ -25,18 +26,165 @@ namespace TestImpact AllTestsPass //!< The test run completed its run and all tests passed. }; - class TestRun + //! Representation of a test run. + class TestRunBase { public: - TestRun(const AZStd::string& name, TestRunResult result, AZStd::chrono::milliseconds duration); + //! Constructs the client facing representation of a given test target's run. + //! @param name The name of the test target. + //! @param commandString The command string used to execute this test target. + //! @param startTime The start time, relative to the sequence start, that this run started. + //! @param duration The duration that this test run took to complete. + //! @param result The result of the run. + TestRunBase( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result); + + virtual ~TestRunBase() = default; + + //! Returns the test target name. const AZStd::string& GetTargetName() const; + + //! Returns the test run result. TestRunResult GetResult() const; + + //! Returns the test run start time. + AZStd::chrono::high_resolution_clock::time_point GetStartTime() const; + + //! Returns the end time, relative to the sequence start, that this run ended. + AZStd::chrono::high_resolution_clock::time_point GetEndTime() const; + + //! Returns the duration that this test run took to complete. AZStd::chrono::milliseconds GetDuration() const; + //! Returns the command string used to execute this test target. + const AZStd::string& GetCommandString() const; + private: AZStd::string m_targetName; + AZStd::string m_commandString; TestRunResult m_result; + AZStd::chrono::high_resolution_clock::time_point m_startTime; AZStd::chrono::milliseconds m_duration; }; + + //! Representation of a test run that failed to execute. + class TestRunWithExecutionFailure + : public TestRunBase + { + public: + using TestRunBase::TestRunBase; + TestRunWithExecutionFailure(TestRunBase&& testRun); + }; + + //! Representation of a test run that was terminated in-flight due to timing out. + class TimedOutTestRun + : public TestRunBase + { + public: + using TestRunBase::TestRunBase; + TimedOutTestRun(TestRunBase&& testRun); + }; + + //! Representation of a test run that was not executed. + class UnexecutedTestRun + : public TestRunBase + { + public: + using TestRunBase::TestRunBase; + UnexecutedTestRun(TestRunBase&& testRun); + }; + + // Result of a test executed during a test run. + enum class TestResult : AZ::u8 + { + Passed, + Failed, + NotRun + }; + + //! Representation of a single test in a test target. + class Test + { + public: + //! Constructs the test with the specified name and result. + Test(const AZStd::string& testName, TestResult result); + + //! Returns the name of this test. + const AZStd::string& GetName() const; + + //! Returns the result of executing this test. + TestResult GetResult() const; + + private: + AZStd::string m_name; + TestResult m_result; + }; + + //! Representation of a test run that completed with or without test failures. + class CompletedTestRun + : public TestRunBase + { + public: + //! Constructs the test run from the specified test target executaion data. + //! @param name The name of the test target for this run. + //! @param commandString The command string used to execute the test target for this run. + //! @param startTime The start time, offset from the sequence start time, that this test run started. + //! @param duration The duration that this test run took to complete. + //! @param result The result of this test run. + //! @param tests The tests contained in the test target for this test run. + CompletedTestRun( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result, + AZStd::vector&& tests); + + //! Constructs the test run from the specified test target executaion data. + CompletedTestRun(TestRunBase&& testRun, AZStd::vector&& tests); + + //! Returns the total number of tests in the run. + size_t GetTotalNumTests() const; + + //! Returns the total number of passing tests in the run. + size_t GetTotalNumPassingTests() const; + + //! Returns the total number of failing tests in the run. + size_t GetTotalNumFailingTests() const; + + //! Returns the total number of disabled tests in the run. + size_t GetTotalNumDisabledTests() const; + + //! Returns the tests in the run. + const AZStd::vector& GetTests() const; + + private: + AZStd::vector m_tests; + size_t m_totalNumPassingTests = 0; + size_t m_totalNumFailingTests = 0; + size_t m_totalNumDisabledTests = 0; + }; + + //! Representation of a test run that completed with no test failures. + class PassingTestRun + : public CompletedTestRun + { + public: + using CompletedTestRun::CompletedTestRun; + PassingTestRun(TestRunBase&& testRun, AZStd::vector&& tests); + }; + + //! Representation of a test run that completed with one or more test failures. + class FailingTestRun + : public CompletedTestRun + { + public: + using CompletedTestRun::CompletedTestRun; + FailingTestRun(TestRunBase&& testRun, AZStd::vector&& tests); + }; } // namespace Client } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestSelection.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestSelection.h index af084ee57b..7d2169e680 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestSelection.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientTestSelection.h @@ -21,6 +21,7 @@ namespace TestImpact class TestRunSelection { public: + TestRunSelection() = default; TestRunSelection(const AZStd::vector& includedTests, const AZStd::vector& excludedTests); TestRunSelection(AZStd::vector&& includedTests, AZStd::vector&& excludedTests); diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h index c10c27c643..fcacd90e71 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactConfiguration.h @@ -44,7 +44,7 @@ namespace TestImpact { RepoPath m_root; //!< Path to the persistent workspace tracked by the repository. RepoPath m_enumerationCacheDirectory; //!< Path to the test enumerations cache. - AZStd::array m_sparTIAFiles; //!< Paths to the test impact analysis data files for each test suite. + AZStd::array m_sparTiaFiles; //!< Paths to the test impact analysis data files for each test suite. }; Temp m_temp; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactPolicy.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactPolicy.h new file mode 100644 index 0000000000..b400af018a --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactPolicy.h @@ -0,0 +1,81 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace TestImpact +{ + namespace Policy + { + //! Policy for handling of test targets that fail to execute (e.g. due to the binary not being found). + //! @note Test targets that fail to execute will be tagged such that their execution can be attempted at a later date. This is + //! important as otherwise it would be erroneously assumed that they cover no sources due to having no entries in the dynamic + //! dependency map. + enum class ExecutionFailure : AZ::u8 + { + Abort, //!< Abort the test sequence and report a failure. + Continue, //!< Continue the test sequence but treat the execution failures as test failures after the run. + Ignore //!< Continue the test sequence and ignore the execution failures. + }; + + //! Policy for handling the coverage data of failed tests targets (both tests that failed to execute and tests that ran but failed). + enum class FailedTestCoverage : AZ::u8 + { + Discard, //!< Discard the coverage data produced by the failing tests, causing them to be drafted into future test runs. + Keep //!< Keep any existing coverage data and update the coverage data for failed test targets that produce coverage. + }; + + //! Policy for prioritizing selected tests. + enum class TestPrioritization : AZ::u8 + { + None, //!< Do not attempt any test prioritization. + DependencyLocality //!< Prioritize test targets according to the locality of the production targets they cover in the build + //!< dependency graph. + }; + + //! Policy for handling test targets that report failing tests. + enum class TestFailure : AZ::u8 + { + Abort, //!< Abort the test sequence and report the test failure. + Continue //!< Continue the test sequence and report the test failures after the run. + }; + + //! Policy for handling integrity failures of the dynamic dependency map and the source to target mappings. + enum class IntegrityFailure : AZ::u8 + { + Abort, //!< Abort the test sequence and report the test failure. + Continue //!< Continue the test sequence and report the test failures after the run. + }; + + //! Policy for updating the dynamic dependency map with the coverage data of produced by test sequences. + enum class DynamicDependencyMap : AZ::u8 + { + Discard, //!< Discard the coverage data produced by test sequences. + Update //!< Update the dynamic dependency map with the coverage data produced by test sequences. + }; + + //! Policy for sharding test targets that have been marked for test sharding. + enum class TestSharding : AZ::u8 + { + Never, //!< Do not shard any test targets. + Always //!< Shard all test targets that have been marked for test sharding. + }; + + //! Standard output capture of test target runs. + enum class TargetOutputCapture : AZ::u8 + { + None, //!< Do not capture any output. + StdOut, //!< Send captured output to standard output + File, //!< Write captured output to file. + StdOutAndFile //!< Send captured output to standard output and write to file. + }; + + } // namespace Policy +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h index 506aeef53e..ec8d88eaad 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRuntime.h @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include @@ -34,10 +34,12 @@ namespace TestImpact class TestEngineInstrumentedRun; //! Callback for a test sequence that isn't using test impact analysis to determine selected tests. + //! @parm suiteType The test suite to select tests from. //! @param tests The tests that will be run for this sequence. - using TestSequenceStartCallback = AZStd::function; + using TestSequenceStartCallback = AZStd::function; //! Callback for a test sequence using test impact analysis. + //! @parm suiteType The test suite to select tests from. //! @param selectedTests The tests that have been selected for this run by test impact analysis. //! @param discardedTests The tests that have been rejected for this run by test impact analysis. //! @param draftedTests The tests that have been drafted in for this run due to requirements outside of test impact analysis @@ -46,11 +48,13 @@ namespace TestImpact //! These tests will be run with coverage instrumentation. //! @note discardedTests and draftedTests may contain overlapping tests. using ImpactAnalysisTestSequenceStartCallback = AZStd::function&& discardedTests, - AZStd::vector&& draftedTests)>; + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const AZStd::vector& discardedTests, + const AZStd::vector& draftedTests)>; //! Callback for a test sequence using test impact analysis. + //! @parm suiteType The test suite to select tests from. //! @param selectedTests The tests that have been selected for this run by test impact analysis. //! @param discardedTests The tests that have been rejected for this run by test impact analysis. //! These tests will not be run without coverage instrumentation unless there is an entry in the draftedTests list. @@ -59,30 +63,22 @@ namespace TestImpact //! to execute previously). //! @note discardedTests and draftedTests may contain overlapping tests. using SafeImpactAnalysisTestSequenceStartCallback = AZStd::function&& draftedTests)>; + SuiteType suiteType, + const Client::TestRunSelection& selectedTests, + const Client::TestRunSelection& discardedTests, + const AZStd::vector& draftedTests)>; //! Callback for end of a test sequence. - //! @param failureReport The test runs that failed for any reason during this sequence. - //! @param duration The total duration of this test sequence. - using TestSequenceCompleteCallback = AZStd::function; - - //! Callback for end of a test impact analysis test sequence. - //! @param selectedFailureReport The selected test runs that failed for any reason during this sequence. - //! @param discardedFailureReport The discarded test runs that failed for any reason during this sequence. - //! @param duration The total duration of this test sequence. - using SafeTestSequenceCompleteCallback = AZStd::function; + //! @tparam SequenceReportType The report type to be used for the sequence. + //! @param sequenceReport The completed sequence report. + template + using TestSequenceCompleteCallback = AZStd::function; //! Callback for test runs that have completed for any reason. - //! @param selectedTests The test that has completed. - using TestRunCompleteCallback = AZStd::function; + //! @param testRunMeta The test that has completed. + //! @param numTestRunsCompleted The number of test runs that have completed. + //! @param totalNumTestRuns The total number of test runs in the sequence. + using TestRunCompleteCallback = AZStd::function; //! The API exposed to the client responsible for all test runs and persistent data management. class Runtime @@ -90,6 +86,7 @@ namespace TestImpact public: //! Constructs a runtime with the specified configuration and policies. //! @param config The configuration used for this runtime instance. + //! @param dataFile The optional data file to be used instead of that specified in the config file. //! @param suiteFilter The test suite for which the coverage data and test selection will draw from. //! @param executionFailurePolicy Determines how to handle test targets that fail to execute. //! @param executionFailureDraftingPolicy Determines how test targets that previously failed to execute are drafted into subsequent test sequences. @@ -98,6 +95,7 @@ namespace TestImpact //! @param testShardingPolicy Determines how to handle test targets that have opted in to test sharding. Runtime( RuntimeConfig&& config, + AZStd::optional dataFile, SuiteType suiteFilter, Policy::ExecutionFailure executionFailurePolicy, Policy::FailedTestCoverage failedTestCoveragePolicy, @@ -108,19 +106,19 @@ namespace TestImpact AZStd::optional maxConcurrency = AZStd::nullopt); ~Runtime(); - + //! Runs a test sequence where all tests with a matching suite in the suite filter and also not on the excluded list are selected. //! @param testTargetTimeout The maximum duration individual test targets may be in flight for (infinite if empty). //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). //! @param testSequenceStartCallback The client function to be called after the test targets have been selected but prior to running the tests. //! @param testSequenceCompleteCallback The client function to be called after the test sequence has completed. //! @param testRunCompleteCallback The client function to be called after an individual test run has completed. - //! @returns - TestSequenceResult RegularTestSequence( + //! @returns The test run and sequence report for the selected test sequence. + Client::RegularSequenceReport RegularTestSequence( AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceCompleteCallback, + AZStd::optional> testSequenceCompleteCallback, AZStd::optional testRunCompleteCallback); //! Runs a test sequence where tests are selected according to test impact analysis so long as they are not on the excluded list. @@ -132,15 +130,15 @@ namespace TestImpact //! @param testSequenceStartCallback The client function to be called after the test targets have been selected but prior to running the tests. //! @param testSequenceCompleteCallback The client function to be called after the test sequence has completed. //! @param testRunCompleteCallback The client function to be called after an individual test run has completed. - //! @returns - TestSequenceResult ImpactAnalysisTestSequence( + //! @returns The test run and sequence report for the selected and drafted test sequences. + Client::ImpactAnalysisSequenceReport ImpactAnalysisTestSequence( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy, Policy::DynamicDependencyMap dynamicDependencyMapPolicy, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceCompleteCallback, + AZStd::optional> testSequenceCompleteCallback, AZStd::optional testRunCompleteCallback); //! Runs a test sequence as per the ImpactAnalysisTestSequence where the tests not selected are also run (albeit without instrumentation). @@ -151,14 +149,14 @@ namespace TestImpact //! @param testSequenceStartCallback The client function to be called after the test targets have been selected but prior to running the tests. //! @param testSequenceCompleteCallback The client function to be called after the test sequence has completed. //! @param testRunCompleteCallback The client function to be called after an individual test run has completed. - //! @returns - AZStd::pair SafeImpactAnalysisTestSequence( + //! @returns The test run and sequence report for the selected, discarded and drafted test sequences. + Client::SafeImpactAnalysisSequenceReport SafeImpactAnalysisTestSequence( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceCompleteCallback, + AZStd::optional> testSequenceCompleteCallback, AZStd::optional testRunCompleteCallback); //! Runs all tests not on the excluded list and uses their coverage data to seed the test impact analysis data (ant existing data will be overwritten). @@ -167,12 +165,12 @@ namespace TestImpact //! @param testSequenceStartCallback The client function to be called after the test targets have been selected but prior to running the tests. //! @param testSequenceCompleteCallback The client function to be called after the test sequence has completed. //! @param testRunCompleteCallback The client function to be called after an individual test run has completed. - //! - TestSequenceResult SeededTestSequence( + //! @returns The test run and sequence report for the selected test sequence. + Client::SeedSequenceReport SeededTestSequence( AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceCompleteCallback, + AZStd::optional> testSequenceCompleteCallback, AZStd::optional testRunCompleteCallback); //! Returns true if the runtime has test impact analysis data (either preexisting or generated). @@ -188,7 +186,7 @@ namespace TestImpact //! @param changeList The change list for which the covering tests and enumeration cache updates will be generated for. //! @param testPrioritizationPolicy The test prioritization strategy to use for the selected test targets. //! @returns The pair of selected test targets and discarded test targets. - AZStd::pair, AZStd::vector> SelectCoveringTestTargetsAndUpdateEnumerationCache( + AZStd::pair, AZStd::vector> SelectCoveringTestTargets( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy); @@ -208,9 +206,23 @@ namespace TestImpact //! Updates the dynamic dependency map and serializes the entire map to disk. void UpdateAndSerializeDynamicDependencyMap(const AZStd::vector& jobs); + //! Generates a base policy state for the current runtime policy runtime configuration. + PolicyStateBase GeneratePolicyStateBase() const; + + //! Generates a regular/seed sequence policy state for the current runtime policy runtime configuration. + SequencePolicyState GenerateSequencePolicyState() const; + + //! Generates a safe impact analysis sequence policy state for the current runtime policy runtime configuration. + SafeImpactAnalysisSequencePolicyState GenerateSafeImpactAnalysisSequencePolicyState( + Policy::TestPrioritization testPrioritizationPolicy) const; + + //! Generates an impact analysis sequence policy state for the current runtime policy runtime configuration. + ImpactAnalysisSequencePolicyState GenerateImpactAnalysisSequencePolicyState( + Policy::TestPrioritization testPrioritizationPolicy, Policy::DynamicDependencyMap dynamicDependencyMapPolicy) const; + RuntimeConfig m_config; + RepoPath m_sparTiaFile; SuiteType m_suiteFilter; - RepoPath m_sparTIAFile; Policy::ExecutionFailure m_executionFailurePolicy; Policy::FailedTestCoverage m_failedTestCoveragePolicy; Policy::TestFailure m_testFailurePolicy; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactSequenceReportException.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactSequenceReportException.h new file mode 100644 index 0000000000..72c2d0c530 --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactSequenceReportException.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace TestImpact +{ + //! Exception for sequence report operations. + class SequenceReportException + : public Exception + { + public: + using Exception::Exception; + }; +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactTestSequence.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactTestSequence.h index 8841c29644..38b716398c 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactTestSequence.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactTestSequence.h @@ -9,76 +9,12 @@ #pragma once #include +#include #include namespace TestImpact { - namespace Policy - { - //! Policy for handling of test targets that fail to execute (e.g. due to the binary not being found). - //! @note Test targets that fail to execute will be tagged such that their execution can be attempted at a later date. This is - //! important as otherwise it would be erroneously assumed that they cover no sources due to having no entries in the dynamic - //! dependency map. - enum class ExecutionFailure - { - Abort, //!< Abort the test sequence and report a failure. - Continue, //!< Continue the test sequence but treat the execution failures as test failures after the run. - Ignore //!< Continue the test sequence and ignore the execution failures. - }; - - //! Policy for handling the coverage data of failed tests targets (both test that failed to execute and tests that ran but failed). - enum class FailedTestCoverage - { - Discard, //!< Discard the coverage data produced by the failing tests, causing them to be drafted into future test runs. - Keep //!< Keep any existing coverage data and update the coverage data for failed test targetss that produce coverage. - }; - - //! Policy for prioritizing selected tests. - enum class TestPrioritization - { - None, //!< Do not attempt any test prioritization. - DependencyLocality //!< Prioritize test targets according to the locality of the production targets they cover in the build dependency graph. - }; - - //! Policy for handling test targets that report failing tests. - enum class TestFailure - { - Abort, //!< Abort the test sequence and report the test failure. - Continue //!< Continue the test sequence and report the test failures after the run. - }; - - //! Policy for handling integrity failures of the dynamic dependency map and the source to target mappings. - enum class IntegrityFailure - { - Abort, //!< Abort the test sequence and report the test failure. - Continue //!< Continue the test sequence and report the test failures after the run. - }; - - //! Policy for updating the dynamic dependency map with the coverage data of produced by test sequences. - enum class DynamicDependencyMap - { - Discard, //!< Discard the coverage data produced by test sequences. - Update //!< Update the dynamic dependency map with the coverage data produced by test sequences. - }; - - //! Policy for sharding test targets that have been marked for test sharding. - enum class TestSharding - { - Never, //!< Do not shard any test targets. - Always //!< Shard all test targets that have been marked for test sharding. - }; - - //! Standard output capture of test target runs. - enum class TargetOutputCapture - { - None, //!< Do not capture any output. - StdOut, //!< Send captured output to standard output - File, //!< Write captured output to file. - StdOutAndFile //!< Send captured output to standard output and write to file. - }; - } - //! Configuration for test targets that opt in to test sharding. enum class ShardConfiguration { @@ -97,22 +33,6 @@ namespace TestImpact Sandbox }; - //! User-friendly names for the test suite types. - inline AZStd::string GetSuiteTypeName(SuiteType suiteType) - { - switch (suiteType) - { - case SuiteType::Main: - return "main"; - case SuiteType::Periodic: - return "periodic"; - case SuiteType::Sandbox: - return "sandbox"; - default: - throw(RuntimeException("Unexpected suite type")); - } - } - //! Result of a test sequence that was run. enum class TestSequenceResult { @@ -120,4 +40,36 @@ namespace TestImpact Failure, //!< One or more tests failed and/or timed out and/or failed to launch and/or an integrity failure was encountered. Timeout //!< The global timeout for the sequence was exceeded. }; + + //! Base representation of runtime policies. + struct PolicyStateBase + { + Policy::ExecutionFailure m_executionFailurePolicy = Policy::ExecutionFailure::Continue; + Policy::FailedTestCoverage m_failedTestCoveragePolicy = Policy::FailedTestCoverage::Keep; + Policy::TestFailure m_testFailurePolicy = Policy::TestFailure::Abort; + Policy::IntegrityFailure m_integrityFailurePolicy = Policy::IntegrityFailure::Abort; + Policy::TestSharding m_testShardingPolicy = Policy::TestSharding::Never; + Policy::TargetOutputCapture m_targetOutputCapture = Policy::TargetOutputCapture::None; + }; + + //! Representation of regular and seed sequence policies. + struct SequencePolicyState + { + PolicyStateBase m_basePolicies; + }; + + //! Representation of impact analysis sequence policies. + struct ImpactAnalysisSequencePolicyState + { + PolicyStateBase m_basePolicies; + Policy::TestPrioritization m_testPrioritizationPolicy = Policy::TestPrioritization::None; + Policy::DynamicDependencyMap m_dynamicDependencyMap = Policy::DynamicDependencyMap::Update; + }; + + //! Representation of safe impact analysis sequence policies. + struct SafeImpactAnalysisSequencePolicyState + { + PolicyStateBase m_basePolicies; + Policy::TestPrioritization m_testPrioritizationPolicy = Policy::TestPrioritization::None; + }; } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactFileUtils.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h similarity index 51% rename from Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactFileUtils.h rename to Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h index f77008ffa7..c4625e9d2c 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactFileUtils.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactUtils.h @@ -6,12 +6,12 @@ * */ -#include -#include +#include +#include +#include #include #include -#include #pragma once @@ -59,23 +59,48 @@ namespace TestImpact //! Delete the files that match the pattern from the specified directory. //! @param path The path to the directory to pattern match the files for deletion. //! @param pattern The pattern to match files for deletion. - inline void DeleteFiles(const RepoPath& path, const AZStd::string& pattern) - { - AZ::IO::SystemFile::FindFiles(AZStd::string::format("%s/%s", path.c_str(), pattern.c_str()).c_str(), - [&path](const char* file, bool isFile) - { - if (isFile) - { - AZ::IO::SystemFile::Delete(AZStd::string::format("%s/%s", path.c_str(), file).c_str()); - } - - return true; - }); - } + //! @return The number of files that were deleted. + size_t DeleteFiles(const RepoPath& path, const AZStd::string& pattern); //! Deletes the specified file. - inline void DeleteFile(const RepoPath& file) - { - DeleteFiles(file.ParentPath(), file.Filename().Native()); - } + void DeleteFile(const RepoPath& file); + + //! User-friendly names for the test suite types. + AZStd::string SuiteTypeAsString(SuiteType suiteType); + + //! User-friendly names for the sequence report types. + AZStd::string SequenceReportTypeAsString(Client::SequenceReportType type); + + //! User-friendly names for the sequence result types. + AZStd::string TestSequenceResultAsString(TestSequenceResult result); + + //! User-friendly names for the test run result types. + AZStd::string TestRunResultAsString(Client::TestRunResult result); + + //! User-friendly names for the execution failure policy types. + AZStd::string ExecutionFailurePolicyAsString(Policy::ExecutionFailure executionFailurePolicy); + + //! User-friendly names for the failed test coverage policy types. + AZStd::string FailedTestCoveragePolicyAsString(Policy::FailedTestCoverage failedTestCoveragePolicy); + + //! User-friendly names for the test prioritization policy types. + AZStd::string TestPrioritizationPolicyAsString(Policy::TestPrioritization testPrioritizationPolicy); + + //! User-friendly names for the test failure policy types. + AZStd::string TestFailurePolicyAsString(Policy::TestFailure testFailurePolicy); + + //! User-friendly names for the integrity failure policy types. + AZStd::string IntegrityFailurePolicyAsString(Policy::IntegrityFailure integrityFailurePolicy); + + //! User-friendly names for the dynamic dependency map policy types. + AZStd::string DynamicDependencyMapPolicyAsString(Policy::DynamicDependencyMap dynamicDependencyMapPolicy); + + //! User-friendly names for the test sharding policy types. + AZStd::string TestShardingPolicyAsString(Policy::TestSharding testShardingPolicy); + + //! User-friendly names for the target output capture policy types. + AZStd::string TargetOutputCapturePolicyAsString(Policy::TargetOutputCapture targetOutputCapturePolicy); + + //! User-friendly names for the client test result types. + AZStd::string ClientTestResultAsString(Client::TestResult result); } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestTargetMetaMapFactory.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestTargetMetaMapFactory.cpp index d69177814f..4c8d71bba1 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestTargetMetaMapFactory.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestTargetMetaMapFactory.cpp @@ -6,6 +6,8 @@ * */ +#include + #include #include @@ -67,7 +69,7 @@ namespace TestImpact { // Check to see if this test target has the suite we're looking for if (const auto suiteName = suite[Keys[SuiteKey]].GetString(); - strcmp(GetSuiteTypeName(suiteType).c_str(), suiteName) == 0) + strcmp(SuiteTypeAsString(suiteType).c_str(), suiteName) == 0) { testMeta.m_suite = suiteName; testMeta.m_customArgs = suite[Keys[CommandKey]].GetString(); diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.cpp index 1c79494c30..af32171b2b 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.cpp @@ -156,8 +156,6 @@ namespace TestImpact { coveringTestTargetIt->second.erase(source); } - - } // 2. diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.h index 5309a00894..d63938930f 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactDynamicDependencyMap.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include #include #include diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactTestSelectorAndPrioritizer.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactTestSelectorAndPrioritizer.h index 4f266af8d2..bcfd8d24d5 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactTestSelectorAndPrioritizer.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Dependency/TestImpactTestSelectorAndPrioritizer.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp index c2ba00835a..e564b93f6c 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Enumeration/TestImpactTestEnumerator.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactInstrumentedTestRunner.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactInstrumentedTestRunner.cpp index cad8df1449..bf7e4d2c34 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactInstrumentedTestRunner.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactInstrumentedTestRunner.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunner.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunner.cpp index a138e329b6..a480f4aa4a 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunner.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/Run/TestImpactTestRunner.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp index 61634a8bd3..c84700065f 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include @@ -262,7 +262,7 @@ namespace TestImpact Policy::TestFailure testFailurePolicy, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, - AZStd::optional callback) + AZStd::optional callback) const { TestEngineJobMap engineJobs; const auto jobInfos = m_testJobInfoGenerator->GenerateTestEnumerationJobInfos(testTargets, TestEnumerator::JobInfo::CachePolicy::Write); @@ -285,7 +285,7 @@ namespace TestImpact [[maybe_unused]]Policy::TargetOutputCapture targetOutputCapture, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, - AZStd::optional callback) + AZStd::optional callback) const { DeleteArtifactXmls(); @@ -312,7 +312,7 @@ namespace TestImpact [[maybe_unused]]Policy::TargetOutputCapture targetOutputCapture, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, - AZStd::optional callback) + AZStd::optional callback) const { DeleteArtifactXmls(); diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h index f1bb77f06f..6b097f241f 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h @@ -69,7 +69,7 @@ namespace TestImpact Policy::TestFailure testFailurePolicy, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, - AZStd::optional callback); + AZStd::optional callback) const; //! Performs a test run without any instrumentation and, for each test target, returns the test run results and metrics about the run. //! @param testTargets The test targets to run. @@ -89,7 +89,7 @@ namespace TestImpact Policy::TargetOutputCapture targetOutputCapture, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, - AZStd::optional callback); + AZStd::optional callback) const; //! Performs a test run with instrumentation and, for each test target, returns the test run results, coverage data and metrics about the run. //! @param testTargets The test targets to run. @@ -111,7 +111,7 @@ namespace TestImpact Policy::TargetOutputCapture targetOutputCapture, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, - AZStd::optional callback); + AZStd::optional callback) const; private: //! Cleans up the artifacts directory of any artifacts from previous runs. diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientFailureReport.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientFailureReport.cpp deleted file mode 100644 index 000ded2aa8..0000000000 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientFailureReport.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include - -namespace TestImpact -{ - namespace Client - { - TargetFailure::TargetFailure(const AZStd::string& targetName) - : m_targetName(targetName) - { - } - - const AZStd::string& TargetFailure::GetTargetName() const - { - return m_targetName; - } - - ExecutionFailure::ExecutionFailure(const AZStd::string& targetName, const AZStd::string& command) - : TargetFailure(targetName) - , m_commandString(command) - { - } - - const AZStd::string& ExecutionFailure::GetCommandString() const - { - return m_commandString; - } - - TestFailure::TestFailure(const AZStd::string& testName, const AZStd::string& errorMessage) - : m_name(testName) - , m_errorMessage(errorMessage) - { - } - - const AZStd::string& TestFailure::GetName() const - { - return m_name; - } - - const AZStd::string& TestFailure::GetErrorMessage() const - { - return m_errorMessage; - } - - TestCaseFailure::TestCaseFailure(const AZStd::string& testCaseName, AZStd::vector&& testFailures) - : m_name(testCaseName) - , m_testFailures(AZStd::move(testFailures)) - { - } - - const AZStd::string& TestCaseFailure::GetName() const - { - return m_name; - } - - const AZStd::vector& TestCaseFailure::GetTestFailures() const - { - return m_testFailures; - } - - TestRunFailure::TestRunFailure(const AZStd::string& targetName, AZStd::vector&& testFailures) - : TargetFailure(targetName) - , m_testCaseFailures(AZStd::move(testFailures)) - { - for (const auto& testCase : m_testCaseFailures) - { - m_numTestFailures += testCase.GetTestFailures().size(); - } - } - - size_t TestRunFailure::GetNumTestFailures() const - { - return m_numTestFailures; - } - - const AZStd::vector& TestRunFailure::GetTestCaseFailures() const - { - return m_testCaseFailures; - } - - SequenceFailure::SequenceFailure( - AZStd::vector&& executionFailures, - AZStd::vector&& testRunFailures, - AZStd::vector&& timedOutTests, - AZStd::vector&& unexecutionTests) - : m_executionFailures(AZStd::move(executionFailures)) - , m_testRunFailures(testRunFailures) - , m_timedOutTests(AZStd::move(timedOutTests)) - , m_unexecutedTests(AZStd::move(unexecutionTests)) - { - } - - const AZStd::vector& SequenceFailure::GetExecutionFailures() const - { - return m_executionFailures; - } - - const AZStd::vector& SequenceFailure::GetTestRunFailures() const - { - return m_testRunFailures; - } - - const AZStd::vector& SequenceFailure::GetTimedOutTests() const - { - return m_timedOutTests; - } - - const AZStd::vector& SequenceFailure::GetUnexecutedTests() const - { - return m_unexecutedTests; - } - } // namespace Client -} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp new file mode 100644 index 0000000000..3f4656758a --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReport.cpp @@ -0,0 +1,326 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +namespace TestImpact +{ + namespace Client + { + TestSequenceResult CalculateMultiTestSequenceResult(const AZStd::vector& results) + { + // Order of precedence: + // 1. TestSequenceResult::Failure + // 2. TestSequenceResult::Timeout + // 3. TestSequenceResult::Success + + if (const auto it = AZStd::find(results.begin(), results.end(), TestSequenceResult::Failure); it != results.end()) + { + return TestSequenceResult::Failure; + } + + if (const auto it = AZStd::find(results.begin(), results.end(), TestSequenceResult::Timeout); it != results.end()) + { + return TestSequenceResult::Timeout; + } + + return TestSequenceResult::Success; + } + + TestRunReport::TestRunReport( + TestSequenceResult result, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + AZStd::vector&& passingTestRuns, + AZStd::vector&& failingTestRuns, + AZStd::vector&& executionFailureTestRuns, + AZStd::vector&& timedOutTestRuns, + AZStd::vector&& unexecutedTestRuns) + : m_startTime(startTime) + , m_result(result) + , m_duration(duration) + , m_passingTestRuns(AZStd::move(passingTestRuns)) + , m_failingTestRuns(AZStd::move(failingTestRuns)) + , m_executionFailureTestRuns(AZStd::move(executionFailureTestRuns)) + , m_timedOutTestRuns(AZStd::move(timedOutTestRuns)) + , m_unexecutedTestRuns(AZStd::move(unexecutedTestRuns)) + { + for (const auto& failingTestRun : m_failingTestRuns) + { + m_totalNumPassingTests += failingTestRun.GetTotalNumPassingTests(); + m_totalNumFailingTests += failingTestRun.GetTotalNumFailingTests(); + m_totalNumDisabledTests += failingTestRun.GetTotalNumDisabledTests(); + } + + for (const auto& passingTestRun : m_passingTestRuns) + { + m_totalNumPassingTests += passingTestRun.GetTotalNumPassingTests(); + m_totalNumDisabledTests += passingTestRun.GetTotalNumDisabledTests(); + } + } + + TestSequenceResult TestRunReport::GetResult() const + { + return m_result; + } + + AZStd::chrono::high_resolution_clock::time_point TestRunReport::GetStartTime() const + { + return m_startTime; + } + + AZStd::chrono::high_resolution_clock::time_point TestRunReport::GetEndTime() const + { + return m_startTime + m_duration; + } + + AZStd::chrono::milliseconds TestRunReport::GetDuration() const + { + return m_duration; + } + + size_t TestRunReport::GetTotalNumTestRuns() const + { + return + GetNumPassingTestRuns() + + GetNumFailingTestRuns() + + GetNumExecutionFailureTestRuns() + + GetNumTimedOutTestRuns() + + GetNumUnexecutedTestRuns(); + } + + size_t TestRunReport::GetNumPassingTestRuns() const + { + return m_passingTestRuns.size(); + } + + size_t TestRunReport::GetNumFailingTestRuns() const + { + return m_failingTestRuns.size(); + } + + size_t TestRunReport::GetNumExecutionFailureTestRuns() const + { + return m_executionFailureTestRuns.size(); + } + + size_t TestRunReport::TestRunReport::GetNumTimedOutTestRuns() const + { + return m_timedOutTestRuns.size(); + } + + size_t TestRunReport::GetNumUnexecutedTestRuns() const + { + return m_unexecutedTestRuns.size(); + } + + const AZStd::vector& TestRunReport::GetPassingTestRuns() const + { + return m_passingTestRuns; + } + + const AZStd::vector& TestRunReport::GetFailingTestRuns() const + { + return m_failingTestRuns; + } + + const AZStd::vector& TestRunReport::GetExecutionFailureTestRuns() const + { + return m_executionFailureTestRuns; + } + + const AZStd::vector& TestRunReport::GetTimedOutTestRuns() const + { + return m_timedOutTestRuns; + } + + const AZStd::vector& TestRunReport::GetUnexecutedTestRuns() const + { + return m_unexecutedTestRuns; + } + + size_t TestRunReport::GetTotalNumPassingTests() const + { + return m_totalNumPassingTests; + } + + size_t TestRunReport::GetTotalNumFailingTests() const + { + return m_totalNumFailingTests; + } + + size_t TestRunReport::GetTotalNumDisabledTests() const + { + return m_totalNumDisabledTests; + } + + RegularSequenceReport::RegularSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const SequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + TestRunReport&& selectedTestRunReport) + : SequenceReportBase( + SequenceReportType::RegularSequence, + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTestRuns, + AZStd::move(selectedTestRunReport)) + { + } + + SeedSequenceReport::SeedSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const SequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + TestRunReport&& selectedTestRunReport) + : SequenceReportBase( + SequenceReportType::SeedSequence, + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTestRuns, + AZStd::move(selectedTestRunReport)) + { + } + + ImpactAnalysisSequenceReport::ImpactAnalysisSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const ImpactAnalysisSequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + const AZStd::vector& discardedTestRuns, + const AZStd::vector& draftedTestRuns, + TestRunReport&& selectedTestRunReport, + TestRunReport&& draftedTestRunReport) + : DraftingSequenceReportBase( + SequenceReportType::ImpactAnalysisSequence, + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTestRuns, + draftedTestRuns, + AZStd::move(selectedTestRunReport), + AZStd::move(draftedTestRunReport)) + , m_discardedTestRuns(discardedTestRuns) + { + } + + const AZStd::vector& ImpactAnalysisSequenceReport::GetDiscardedTestRuns() const + { + return m_discardedTestRuns; + } + + SafeImpactAnalysisSequenceReport::SafeImpactAnalysisSequenceReport( + size_t maxConcurrency, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + const SafeImpactAnalysisSequencePolicyState& policyState, + SuiteType suiteType, + const TestRunSelection& selectedTestRuns, + const TestRunSelection& discardedTestRuns, + const AZStd::vector& draftedTestRuns, + TestRunReport&& selectedTestRunReport, + TestRunReport&& discardedTestRunReport, + TestRunReport&& draftedTestRunReport) + : DraftingSequenceReportBase( + SequenceReportType::SafeImpactAnalysisSequence, + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTestRuns, + draftedTestRuns, + AZStd::move(selectedTestRunReport), + AZStd::move(draftedTestRunReport)) + , m_discardedTestRuns(discardedTestRuns) + , m_discardedTestRunReport(AZStd::move(discardedTestRunReport)) + { + } + + TestSequenceResult SafeImpactAnalysisSequenceReport::GetResult() const + { + return CalculateMultiTestSequenceResult({ DraftingSequenceReportBase::GetResult(), m_discardedTestRunReport.GetResult() }); + } + + AZStd::chrono::milliseconds SafeImpactAnalysisSequenceReport::GetDuration() const + { + return DraftingSequenceReportBase::GetDuration() + m_discardedTestRunReport.GetDuration(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumTestRuns() const + { + return DraftingSequenceReportBase::GetTotalNumTestRuns() + m_discardedTestRunReport.GetTotalNumTestRuns(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumPassingTests() const + { + return DraftingSequenceReportBase::GetTotalNumPassingTests() + m_discardedTestRunReport.GetTotalNumPassingTests(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumFailingTests() const + { + return DraftingSequenceReportBase::GetTotalNumFailingTests() + m_discardedTestRunReport.GetTotalNumFailingTests(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumDisabledTests() const + { + return DraftingSequenceReportBase::GetTotalNumDisabledTests() + m_discardedTestRunReport.GetTotalNumDisabledTests(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumPassingTestRuns() const + { + return DraftingSequenceReportBase::GetTotalNumPassingTestRuns() + m_discardedTestRunReport.GetNumPassingTestRuns(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumFailingTestRuns() const + { + return DraftingSequenceReportBase::GetTotalNumFailingTestRuns() + m_discardedTestRunReport.GetNumFailingTestRuns(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumExecutionFailureTestRuns() const + { + return DraftingSequenceReportBase::GetTotalNumExecutionFailureTestRuns() + m_discardedTestRunReport.GetNumExecutionFailureTestRuns(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumTimedOutTestRuns() const + { + return DraftingSequenceReportBase::GetTotalNumTimedOutTestRuns() + m_discardedTestRunReport.GetNumTimedOutTestRuns(); + } + + size_t SafeImpactAnalysisSequenceReport::GetTotalNumUnexecutedTestRuns() const + { + return DraftingSequenceReportBase::GetTotalNumUnexecutedTestRuns() + m_discardedTestRunReport.GetNumUnexecutedTestRuns(); + } + + const TestRunSelection SafeImpactAnalysisSequenceReport::GetDiscardedTestRuns() const + { + return m_discardedTestRuns; + } + + TestRunReport SafeImpactAnalysisSequenceReport::GetDiscardedTestRunReport() const + { + return m_discardedTestRunReport; + } + } // namespace Client +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp new file mode 100644 index 0000000000..99a187fe16 --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp @@ -0,0 +1,606 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +#include +#include +#include +#include + +namespace TestImpact +{ + namespace + { + namespace SequenceReportFields + { + // Keys for pertinent JSON node and attribute names + constexpr const char* Keys[] = + { + "name", + "command_args", + "start_time", + "end_time", + "duration", + "result", + "num_passing_tests", + "num_failing_tests", + "num_disabled_tests", + "tests", + "num_passing_test_runs", + "num_failing_test_runs", + "num_execution_failure_test_runs", + "num_timed_out_test_runs", + "num_unexecuted_test_runs", + "passing_test_runs", + "failing_test_runs", + "execution_failure_test_runs", + "timed_out_test_runs", + "unexecuted_test_runs", + "total_num_passing_tests", + "total_num_failing_tests", + "total_num_disabled_tests", + "total_num_test_runs", + "num_included_test_runs", + "num_excluded_test_runs", + "included_test_runs", + "excluded_test_runs", + "execution_failure", + "coverage_failure", + "test_failure", + "integrity_failure", + "test_sharding", + "target_output_capture", + "test_prioritization", + "dynamic_dependency_map", + "type", + "test_target_timeout", + "global_timeout", + "max_concurrency", + "policy", + "suite", + "selected_test_runs", + "selected_test_run_report", + "total_num_passing_test_runs", + "total_num_failing_test_runs", + "total_num_execution_failure_test_runs", + "total_num_timed_out_test_runs", + "total_num_unexecuted_test_runs", + "drafted_test_runs", + "drafted_test_run_report", + "discarded_test_runs", + "discarded_test_run_report" + }; + + enum + { + Name, + CommandArgs, + StartTime, + EndTime, + Duration, + Result, + NumPassingTests, + NumFailingTests, + NumDisabledTests, + Tests, + NumPassingTestRuns, + NumFailingTestRuns, + NumExecutionFailureTestRuns, + NumTimedOutTestRuns, + NumUnexecutedTestRuns, + PassingTestRuns, + FailingTestRuns, + ExecutionFailureTestRuns, + TimedOutTestRuns, + UnexecutedTestRuns, + TotalNumPassingTests, + TotalNumFailingTests, + TotalNumDisabledTests, + TotalNumTestRuns, + NumIncludedTestRuns, + NumExcludedTestRuns, + IncludedTestRuns, + ExcludedTestRuns, + ExecutionFailure, + CoverageFailure, + TestFailure, + IntegrityFailure, + TestSharding, + TargetOutputCapture, + TestPrioritization, + DynamicDependencyMap, + Type, + TestTargetTimeout, + GlobalTimeout, + MaxConcurrency, + Policy, + Suite, + SelectedTestRuns, + SelectedTestRunReport, + TotalNumPassingTestRuns, + TotalNumFailingTestRuns, + TotalNumExecutionFailureTestRuns, + TotalNumTimedOutTestRuns, + TotalNumUnexecutedTestRuns, + DraftedTestRuns, + DraftedTestRunReport, + DiscardedTestRuns, + DiscardedTestRunReport + }; + } // namespace SequenceReportFields + + AZ::u64 TimePointInMsAsInt64(AZStd::chrono::high_resolution_clock::time_point timePoint) + { + return AZStd::chrono::duration_cast(timePoint.time_since_epoch()).count(); + } + + void SerializeTestRunMembers(const Client::TestRunBase& testRun, rapidjson::PrettyWriter& writer) + { + // Name + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Name]); + writer.String(testRun.GetTargetName().c_str()); + + // Command string + writer.Key(SequenceReportFields::Keys[SequenceReportFields::CommandArgs]); + writer.String(testRun.GetCommandString().c_str()); + + // Start time + writer.Key(SequenceReportFields::Keys[SequenceReportFields::StartTime]); + writer.Int64(TimePointInMsAsInt64(testRun.GetStartTime())); + + // End time + writer.Key(SequenceReportFields::Keys[SequenceReportFields::EndTime]); + writer.Int64(TimePointInMsAsInt64(testRun.GetEndTime())); + + // Duration + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Duration]); + writer.Uint64(testRun.GetDuration().count()); + + // Result + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Result]); + writer.String(TestRunResultAsString(testRun.GetResult()).c_str()); + } + + void SerializeTestRun(const Client::TestRunBase& testRun, rapidjson::PrettyWriter& writer) + { + writer.StartObject(); + { + SerializeTestRunMembers(testRun, writer); + } + writer.EndObject(); + } + + void SerializeCompletedTestRun(const Client::CompletedTestRun& testRun, rapidjson::PrettyWriter& writer) + { + writer.StartObject(); + { + SerializeTestRunMembers(testRun, writer); + + // Number of passing test cases + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumPassingTests]); + writer.Uint64(testRun.GetTotalNumPassingTests()); + + // Number of failing test cases + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumFailingTests]); + writer.Uint64(testRun.GetTotalNumFailingTests()); + + // Number of disabled test cases + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumDisabledTests]); + writer.Uint64(testRun.GetTotalNumDisabledTests()); + + // Tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Tests]); + writer.StartArray(); + + for (const auto& test : testRun.GetTests()) + { + // Test + writer.StartObject(); + + // Name + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Name]); + writer.String(test.GetName().c_str()); + + // Result + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Result]); + writer.String(ClientTestResultAsString(test.GetResult()).c_str()); + + writer.EndObject(); // Test + } + + writer.EndArray(); // Tests + } + writer.EndObject(); + } + + void SerializeTestRunReport( + const Client::TestRunReport& testRunReport, rapidjson::PrettyWriter& writer) + { + writer.StartObject(); + { + // Result + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Result]); + writer.String(TestSequenceResultAsString(testRunReport.GetResult()).c_str()); + + // Start time + writer.Key(SequenceReportFields::Keys[SequenceReportFields::StartTime]); + writer.Int64(TimePointInMsAsInt64(testRunReport.GetStartTime())); + + // End time + writer.Key(SequenceReportFields::Keys[SequenceReportFields::EndTime]); + writer.Int64(TimePointInMsAsInt64(testRunReport.GetEndTime())); + + // Duration + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Duration]); + writer.Uint64(testRunReport.GetDuration().count()); + + // Number of passing test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumPassingTestRuns]); + writer.Uint64(testRunReport.GetNumPassingTestRuns()); + + // Number of failing test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumFailingTestRuns]); + writer.Uint64(testRunReport.GetNumFailingTestRuns()); + + // Number of test runs that failed to execute + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumExecutionFailureTestRuns]); + writer.Uint64(testRunReport.GetNumExecutionFailureTestRuns()); + + // Number of timed out test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumTimedOutTestRuns]); + writer.Uint64(testRunReport.GetNumTimedOutTestRuns()); + + // Number of unexecuted test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumUnexecutedTestRuns]); + writer.Uint64(testRunReport.GetNumUnexecutedTestRuns()); + + // Passing test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::PassingTestRuns]); + writer.StartArray(); + for (const auto& testRun : testRunReport.GetPassingTestRuns()) + { + SerializeCompletedTestRun(testRun, writer); + } + writer.EndArray(); // Passing test runs + + // Failing test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::FailingTestRuns]); + writer.StartArray(); + for (const auto& testRun : testRunReport.GetFailingTestRuns()) + { + SerializeCompletedTestRun(testRun, writer); + } + writer.EndArray(); // Failing test runs + + // Execution failures + writer.Key(SequenceReportFields::Keys[SequenceReportFields::ExecutionFailureTestRuns]); + writer.StartArray(); + for (const auto& testRun : testRunReport.GetExecutionFailureTestRuns()) + { + SerializeTestRun(testRun, writer); + } + writer.EndArray(); // Execution failures + + // Timed out test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TimedOutTestRuns]); + writer.StartArray(); + for (const auto& testRun : testRunReport.GetTimedOutTestRuns()) + { + SerializeTestRun(testRun, writer); + } + writer.EndArray(); // Timed out test runs + + // Unexecuted test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::UnexecutedTestRuns]); + writer.StartArray(); + for (const auto& testRun : testRunReport.GetUnexecutedTestRuns()) + { + SerializeTestRun(testRun, writer); + } + writer.EndArray(); // Unexecuted test runs + + // Number of passing tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumPassingTests]); + writer.Uint64(testRunReport.GetTotalNumPassingTests()); + + // Number of failing tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumFailingTests]); + writer.Uint64(testRunReport.GetTotalNumFailingTests()); + + // Number of disabled tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumDisabledTests]); + writer.Uint64(testRunReport.GetTotalNumDisabledTests()); + } + writer.EndObject(); + } + + void SerializeTestSelection( + const Client::TestRunSelection& testSelection, rapidjson::PrettyWriter& writer) + { + writer.StartObject(); + { + // Total number of test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumTestRuns]); + writer.Uint64(testSelection.GetTotalNumTests()); + + // Number of included test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumIncludedTestRuns]); + writer.Uint64(testSelection.GetNumIncludedTestRuns()); + + // Number of excluded test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::NumExcludedTestRuns]); + writer.Uint64(testSelection.GetNumExcludedTestRuns()); + + // Included test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::IncludedTestRuns]); + writer.StartArray(); + for (const auto& testRun : testSelection.GetIncludededTestRuns()) + { + writer.String(testRun.c_str()); + } + writer.EndArray(); // Included test runs + + // Excluded test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::ExcludedTestRuns]); + writer.StartArray(); + for (const auto& testRun : testSelection.GetExcludedTestRuns()) + { + writer.String(testRun.c_str()); + } + writer.EndArray(); // Excluded test runs + } + writer.EndObject(); + } + + void SerializePolicyStateBaseMembers(const PolicyStateBase& policyState, rapidjson::PrettyWriter& writer) + { + // Execution failure + writer.Key(SequenceReportFields::Keys[SequenceReportFields::ExecutionFailure]); + writer.String(ExecutionFailurePolicyAsString(policyState.m_executionFailurePolicy).c_str()); + + // Failed test coverage + writer.Key(SequenceReportFields::Keys[SequenceReportFields::CoverageFailure]); + writer.String(FailedTestCoveragePolicyAsString(policyState.m_failedTestCoveragePolicy).c_str()); + + // Test failure + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TestFailure]); + writer.String(TestFailurePolicyAsString(policyState.m_testFailurePolicy).c_str()); + + // Integrity failure + writer.Key(SequenceReportFields::Keys[SequenceReportFields::IntegrityFailure]); + writer.String(IntegrityFailurePolicyAsString(policyState.m_integrityFailurePolicy).c_str()); + + // Test sharding + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TestSharding]); + writer.String(TestShardingPolicyAsString(policyState.m_testShardingPolicy).c_str()); + + // Target output capture + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TargetOutputCapture]); + writer.String(TargetOutputCapturePolicyAsString(policyState.m_targetOutputCapture).c_str()); + } + + void SerializePolicyStateMembers( + const SequencePolicyState& policyState, rapidjson::PrettyWriter& writer) + { + SerializePolicyStateBaseMembers(policyState.m_basePolicies, writer); + } + + void SerializePolicyStateMembers( + const SafeImpactAnalysisSequencePolicyState& policyState, rapidjson::PrettyWriter& writer) + { + SerializePolicyStateBaseMembers(policyState.m_basePolicies, writer); + + // Test prioritization + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TestPrioritization]); + writer.String(TestPrioritizationPolicyAsString(policyState.m_testPrioritizationPolicy).c_str()); + } + + void SerializePolicyStateMembers( + const ImpactAnalysisSequencePolicyState& policyState, rapidjson::PrettyWriter& writer) + { + SerializePolicyStateBaseMembers(policyState.m_basePolicies, writer); + + // Test prioritization + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TestPrioritization]); + writer.String(TestPrioritizationPolicyAsString(policyState.m_testPrioritizationPolicy).c_str()); + + // Dynamic dependency map + writer.Key(SequenceReportFields::Keys[SequenceReportFields::DynamicDependencyMap]); + writer.String(DynamicDependencyMapPolicyAsString(policyState.m_dynamicDependencyMap).c_str()); + } + + template + void SerializeSequenceReportBaseMembers( + const Client::SequenceReportBase& sequenceReport, rapidjson::PrettyWriter& writer) + { + // Type + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Type]); + writer.String(SequenceReportTypeAsString(sequenceReport.GetType()).c_str()); + + // Test target timeout + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TestTargetTimeout]); + writer.Uint64(sequenceReport.GetTestTargetTimeout().value_or(AZStd::chrono::milliseconds{0}).count()); + + // Global timeout + writer.Key(SequenceReportFields::Keys[SequenceReportFields::GlobalTimeout]); + writer.Uint64(sequenceReport.GetGlobalTimeout().value_or(AZStd::chrono::milliseconds{ 0 }).count()); + + // Maximum concurrency + writer.Key(SequenceReportFields::Keys[SequenceReportFields::MaxConcurrency]); + writer.Uint64(sequenceReport.GetMaxConcurrency()); + + // Policies + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Policy]); + writer.StartObject(); + { + SerializePolicyStateMembers(sequenceReport.GetPolicyState(), writer); + } + writer.EndObject(); // Policies + + // Suite + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Suite]); + writer.String(SuiteTypeAsString(sequenceReport.GetSuite()).c_str()); + + // Selected test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::SelectedTestRuns]); + SerializeTestSelection(sequenceReport.GetSelectedTestRuns(), writer); + + // Selected test run report + writer.Key(SequenceReportFields::Keys[SequenceReportFields::SelectedTestRunReport]); + SerializeTestRunReport(sequenceReport.GetSelectedTestRunReport(), writer); + + // Start time + writer.Key(SequenceReportFields::Keys[SequenceReportFields::StartTime]); + writer.Int64(TimePointInMsAsInt64(sequenceReport.GetStartTime())); + + // End time + writer.Key(SequenceReportFields::Keys[SequenceReportFields::EndTime]); + writer.Int64(TimePointInMsAsInt64(sequenceReport.GetEndTime())); + + // Duration + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Duration]); + writer.Uint64(sequenceReport.GetDuration().count()); + + // Result + writer.Key(SequenceReportFields::Keys[SequenceReportFields::Result]); + writer.String(TestSequenceResultAsString(sequenceReport.GetResult()).c_str()); + + // Total number of test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumTestRuns]); + writer.Uint64(sequenceReport.GetTotalNumTestRuns()); + + // Total number of passing test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumPassingTestRuns]); + writer.Uint64(sequenceReport.GetTotalNumPassingTestRuns()); + + // Total number of failing test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumFailingTestRuns]); + writer.Uint64(sequenceReport.GetTotalNumFailingTestRuns()); + + // Total number of test runs that failed to execute + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumExecutionFailureTestRuns]); + writer.Uint64(sequenceReport.GetTotalNumExecutionFailureTestRuns()); + + // Total number of timed out test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumTimedOutTestRuns]); + writer.Uint64(sequenceReport.GetTotalNumTimedOutTestRuns()); + + // Total number of unexecuted test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumUnexecutedTestRuns]); + writer.Uint64(sequenceReport.GetTotalNumUnexecutedTestRuns()); + + // Total number of passing tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumPassingTests]); + writer.Uint64(sequenceReport.GetTotalNumPassingTests()); + + // Total number of failing tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumFailingTests]); + writer.Uint64(sequenceReport.GetTotalNumFailingTests()); + + // Total number of disabled tests + writer.Key(SequenceReportFields::Keys[SequenceReportFields::TotalNumDisabledTests]); + writer.Uint64(sequenceReport.GetTotalNumDisabledTests()); + } + + template + void SerializeDraftingSequenceReportMembers( + const Client::DraftingSequenceReportBase& sequenceReport, rapidjson::PrettyWriter& writer) + { + SerializeSequenceReportBaseMembers(sequenceReport, writer); + + // Drafted test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::DraftedTestRuns]); + writer.StartArray(); + for (const auto& testRun : sequenceReport.GetDraftedTestRuns()) + { + writer.String(testRun.c_str()); + } + writer.EndArray(); // Drafted test runs + + // Drafted test run report + writer.Key(SequenceReportFields::Keys[SequenceReportFields::DraftedTestRunReport]); + SerializeTestRunReport(sequenceReport.GetDraftedTestRunReport(), writer); + } + } // namespace + + AZStd::string SerializeSequenceReport(const Client::RegularSequenceReport& sequenceReport) + { + rapidjson::StringBuffer stringBuffer; + rapidjson::PrettyWriter writer(stringBuffer); + + writer.StartObject(); + { + SerializeSequenceReportBaseMembers(sequenceReport, writer); + } + writer.EndObject(); + + return stringBuffer.GetString(); + } + + AZStd::string SerializeSequenceReport(const Client::SeedSequenceReport& sequenceReport) + { + rapidjson::StringBuffer stringBuffer; + rapidjson::PrettyWriter writer(stringBuffer); + + writer.StartObject(); + { + SerializeSequenceReportBaseMembers(sequenceReport, writer); + } + writer.EndObject(); + + return stringBuffer.GetString(); + } + + AZStd::string SerializeSequenceReport(const Client::ImpactAnalysisSequenceReport& sequenceReport) + { + rapidjson::StringBuffer stringBuffer; + rapidjson::PrettyWriter writer(stringBuffer); + + writer.StartObject(); + { + SerializeDraftingSequenceReportMembers(sequenceReport, writer); + + // Discarded test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRuns]); + writer.StartArray(); + for (const auto& testRun : sequenceReport.GetDiscardedTestRuns()) + { + writer.String(testRun.c_str()); + } + writer.EndArray(); // Discarded test runs + } + writer.EndObject(); + + return stringBuffer.GetString(); + } + + AZStd::string SerializeSequenceReport(const Client::SafeImpactAnalysisSequenceReport& sequenceReport) + { + rapidjson::StringBuffer stringBuffer; + rapidjson::PrettyWriter writer(stringBuffer); + + writer.StartObject(); + { + SerializeDraftingSequenceReportMembers(sequenceReport, writer); + + // Discarded test runs + writer.Key(SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRuns]); + SerializeTestSelection(sequenceReport.GetDiscardedTestRuns(), writer); + + // Discarded test run report + writer.Key(SequenceReportFields::Keys[SequenceReportFields::DiscardedTestRunReport]); + SerializeTestRunReport(sequenceReport.GetDiscardedTestRunReport(), writer); + } + writer.EndObject(); + + return stringBuffer.GetString(); + } +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp index 582927baa5..6f50145716 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientTestRun.cpp @@ -7,30 +7,166 @@ */ #include + +#include + namespace TestImpact { namespace Client { - TestRun::TestRun(const AZStd::string& name, TestRunResult result, AZStd::chrono::milliseconds duration) + TestRunBase::TestRunBase( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result) : m_targetName(name) - , m_result(result) + , m_commandString(commandString) + , m_startTime(startTime) , m_duration(duration) + , m_result(result) { } - const AZStd::string& TestRun::GetTargetName() const + const AZStd::string& TestRunBase::GetTargetName() const { return m_targetName; } - AZStd::chrono::milliseconds TestRun::GetDuration() const + const AZStd::string& TestRunBase::GetCommandString() const + { + return m_commandString; + } + + AZStd::chrono::high_resolution_clock::time_point TestRunBase::GetStartTime() const + { + return m_startTime; + } + + AZStd::chrono::high_resolution_clock::time_point TestRunBase::GetEndTime() const + { + return m_startTime + m_duration; + } + + AZStd::chrono::milliseconds TestRunBase::GetDuration() const { return m_duration; } - TestRunResult TestRun::GetResult() const + TestRunResult TestRunBase::GetResult() const + { + return m_result; + } + + TestRunWithExecutionFailure::TestRunWithExecutionFailure(TestRunBase&& testRun) + : TestRunBase(AZStd::move(testRun)) + { + } + + TimedOutTestRun::TimedOutTestRun(TestRunBase&& testRun) + : TestRunBase(AZStd::move(testRun)) + { + } + + UnexecutedTestRun::UnexecutedTestRun(TestRunBase&& testRun) + : TestRunBase(AZStd::move(testRun)) + { + } + + Test::Test(const AZStd::string& testName, TestResult result) + : m_name(testName) + , m_result(result) + { + } + + const AZStd::string& Test::GetName() const + { + return m_name; + } + + TestResult Test::GetResult() const { return m_result; } + + AZStd::tuple CalculateTestCaseMetrics(const AZStd::vector& tests) + { + size_t totalNumPassingTests = 0; + size_t totalNumFailingTests = 0; + size_t totalNumDisabledTests = 0; + + for (const auto& test : tests) + { + if (test.GetResult() == Client::TestResult::Passed) + { + totalNumPassingTests++; + } + else if (test.GetResult() == Client::TestResult::Failed) + { + totalNumFailingTests++; + } + else + { + totalNumDisabledTests++; + } + } + + return { totalNumPassingTests, totalNumFailingTests, totalNumDisabledTests }; + } + + CompletedTestRun::CompletedTestRun( + const AZStd::string& name, + const AZStd::string& commandString, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + TestRunResult result, + AZStd::vector&& tests) + : TestRunBase(name, commandString, startTime, duration, result) + , m_tests(AZStd::move(tests)) + { + AZStd::tie(m_totalNumPassingTests, m_totalNumFailingTests, m_totalNumDisabledTests) = CalculateTestCaseMetrics(m_tests); + } + + CompletedTestRun::CompletedTestRun(TestRunBase&& testRun, AZStd::vector&& tests) + : TestRunBase(AZStd::move(testRun)) + , m_tests(AZStd::move(tests)) + { + AZStd::tie(m_totalNumPassingTests, m_totalNumFailingTests, m_totalNumDisabledTests) = CalculateTestCaseMetrics(m_tests); + } + + size_t CompletedTestRun::GetTotalNumTests() const + { + return m_tests.size(); + } + + size_t CompletedTestRun::GetTotalNumPassingTests() const + { + return m_totalNumPassingTests; + } + + size_t CompletedTestRun::GetTotalNumFailingTests() const + { + return m_totalNumFailingTests; + } + + size_t CompletedTestRun::GetTotalNumDisabledTests() const + { + return m_totalNumDisabledTests; + } + + const AZStd::vector& CompletedTestRun::GetTests() const + { + return m_tests; + } + + PassingTestRun::PassingTestRun(TestRunBase&& testRun, AZStd::vector&& tests) + : CompletedTestRun(AZStd::move(testRun), AZStd::move(tests)) + { + } + + FailingTestRun::FailingTestRun(TestRunBase&& testRun, AZStd::vector&& tests) + : CompletedTestRun(AZStd::move(testRun), AZStd::move(tests)) + { + } } // namespace Client } // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp index 57b6db1e8e..8a9d96bca8 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntime.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include @@ -34,13 +34,33 @@ namespace TestImpact { } - //! Returns the time elapsed (in milliseconds) since the timer was instantiated - AZStd::chrono::milliseconds Elapsed() + //! Returns the time point that the timer was instantiated. + AZStd::chrono::high_resolution_clock::time_point GetStartTimePoint() const + { + return m_startTime; + } + + //! Returns the time point that the timer was instantiated relative to the specified starting time point. + AZStd::chrono::high_resolution_clock::time_point GetStartTimePointRelative(const Timer& start) const + { + return AZStd::chrono::high_resolution_clock::time_point() + + AZStd::chrono::duration_cast(m_startTime - start.GetStartTimePoint()); + } + + //! Returns the time elapsed (in milliseconds) since the timer was instantiated. + AZStd::chrono::milliseconds GetElapsedMs() const { const auto endTime = AZStd::chrono::high_resolution_clock::now(); return AZStd::chrono::duration_cast(endTime - m_startTime); } + //! Returns the current time point relative to the time point the timer was instantiated. + AZStd::chrono::high_resolution_clock::time_point GetElapsedTimepoint() const + { + const auto endTime = AZStd::chrono::high_resolution_clock::now(); + return m_startTime + AZStd::chrono::duration_cast(endTime - m_startTime); + } + private: AZStd::chrono::high_resolution_clock::time_point m_startTime; }; @@ -49,8 +69,11 @@ namespace TestImpact class TestRunCompleteCallbackHandler { public: - TestRunCompleteCallbackHandler(AZStd::optional testCompleteCallback) - : m_testCompleteCallback(testCompleteCallback) + TestRunCompleteCallbackHandler( + size_t totalTests, + AZStd::optional testCompleteCallback) + : m_totalTests(totalTests) + , m_testCompleteCallback(testCompleteCallback) { } @@ -58,19 +81,27 @@ namespace TestImpact { if (m_testCompleteCallback.has_value()) { - (*m_testCompleteCallback) - (Client::TestRun(testJob.GetTestTarget()->GetName(), testJob.GetTestResult(), testJob.GetDuration())); + Client::TestRunBase testRun( + testJob.GetTestTarget()->GetName(), + testJob.GetCommandString(), + testJob.GetStartTime(), + testJob.GetDuration(), + testJob.GetTestResult()); + + (*m_testCompleteCallback)(testRun, ++m_numTestsCompleted, m_totalTests); } } private: + const size_t m_totalTests; //!< The total number of tests to run for the entire sequence. + size_t m_numTestsCompleted = 0; //!< The running total of tests that have completed. AZStd::optional m_testCompleteCallback; }; } //! Utility for concatenating two vectors. template - AZStd::vector ConcatenateVectors(const AZStd::vector& v1, const AZStd::vector& v2) + static AZStd::vector ConcatenateVectors(const AZStd::vector& v1, const AZStd::vector& v2) { AZStd::vector result; result.reserve(v1.size() + v2.size()); @@ -79,8 +110,140 @@ namespace TestImpact return result; } + //! Utility structure for holding the pertinent data for test run reports. + template + struct TestRunData + { + TestSequenceResult m_result = TestSequenceResult::Success; + AZStd::vector m_jobs; + AZStd::chrono::high_resolution_clock::time_point m_relativeStartTime; + AZStd::chrono::milliseconds m_duration = AZStd::chrono::milliseconds{ 0 }; + }; + + //! Wrapper for the impact analysis test sequence to handle both the updating and non-updating policies through a common pathway. + //! @tparam TestRunnerFunctor The functor for running the specified tests. + //! @tparam TestJob The test engine job type returned by the functor. + //! @param maxConcurrency The maximum concurrency being used for this sequence. + //! @param policyState The policy state being used for the sequence. + //! @param suiteType The suite type used for this sequence. + //! @param timer The timer to use for the test run timings. + //! @param testRunner The test runner functor to use for each of the test runs. + //! @param includedSelectedTestTargets The subset of test targets that were selected to run and not also fully excluded from running. + //! @param excludedSelectedTestTargets The subset of test targets that were selected to run but were fully excluded running. + //! @param discardedTestTargets The subset of test targets that were discarded from the test selection and will not be run. + //! @param globalTimeout The maximum duration the entire test sequence may run for (infinite if empty). + //! @param testSequenceStartCallback The client function to be called after the test targets have been selected but prior to running the + //! tests. + //! @param testSequenceCompleteCallback The client function to be called after the test sequence has completed. + //! @param testRunCompleteCallback The client function to be called after an individual test run has completed. + //! @param updateCoverage The function to call to update the dynamic dependency map with test coverage (if any). + template + Client::ImpactAnalysisSequenceReport ImpactAnalysisTestSequenceWrapper( + size_t maxConcurrency, + const ImpactAnalysisSequencePolicyState& policyState, + SuiteType suiteType, + const Timer& sequenceTimer, + const TestRunnerFunctor& testRunner, + const AZStd::vector& includedSelectedTestTargets, + const AZStd::vector& excludedSelectedTestTargets, + const AZStd::vector& discardedTestTargets, + const AZStd::vector& draftedTestTargets, + const AZStd::optional& testTargetTimeout, + const AZStd::optional& globalTimeout, + AZStd::optional testSequenceStartCallback, + AZStd::optional> testSequenceEndCallback, + AZStd::optional testCompleteCallback, + AZStd::optional& jobs)>> updateCoverage) + { + TestRunData selectedTestRunData, draftedTestRunData; + AZStd::optional sequenceTimeout = globalTimeout; + + // Extract the client facing representation of selected, discarded and drafted test targets + const Client::TestRunSelection selectedTests( + ExtractTestTargetNames(includedSelectedTestTargets), ExtractTestTargetNames(excludedSelectedTestTargets)); + const auto discardedTests = ExtractTestTargetNames(discardedTestTargets); + const auto draftedTests = ExtractTestTargetNames(draftedTestTargets); + + // Inform the client that the sequence is about to start + if (testSequenceStartCallback.has_value()) + { + (*testSequenceStartCallback)(suiteType, selectedTests, discardedTests, draftedTests); + } + + // We share the test run complete handler between the selected and drafted test runs as to present them together as one + // continuous test sequence to the client rather than two discrete test runs + const size_t totalNumTestRuns = includedSelectedTestTargets.size() + draftedTestTargets.size(); + TestRunCompleteCallbackHandler testRunCompleteHandler(totalNumTestRuns, testCompleteCallback); + + const auto gatherTestRunData = [&sequenceTimer, &testRunner, &testRunCompleteHandler, &globalTimeout] + (const AZStd::vector& testsTargets, TestRunData& testRunData) + { + const Timer testRunTimer; + testRunData.m_relativeStartTime = testRunTimer.GetStartTimePointRelative(sequenceTimer); + auto [result, jobs] = testRunner(testsTargets, testRunCompleteHandler, globalTimeout); + testRunData.m_result = result; + testRunData.m_jobs = AZStd::move(jobs); + testRunData.m_duration = testRunTimer.GetElapsedMs(); + }; + + if (!includedSelectedTestTargets.empty()) + { + // Run the selected test targets and collect the test run results + gatherTestRunData(includedSelectedTestTargets, selectedTestRunData); + + // Carry the remaining global sequence time over to the drafted test run + if (globalTimeout.has_value()) + { + const auto elapsed = selectedTestRunData.m_duration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + } + } + + if (!draftedTestTargets.empty()) + { + // Run the drafted test targets and collect the test run results + gatherTestRunData(draftedTestTargets, draftedTestRunData); + } + + // Generate the sequence report for the client + const auto sequenceReport = Client::ImpactAnalysisSequenceReport( + maxConcurrency, + testTargetTimeout, + globalTimeout, + policyState, + suiteType, + selectedTests, + discardedTests, + draftedTests, + GenerateTestRunReport( + selectedTestRunData.m_result, + selectedTestRunData.m_relativeStartTime, + selectedTestRunData.m_duration, + selectedTestRunData.m_jobs), + GenerateTestRunReport( + draftedTestRunData.m_result, + draftedTestRunData.m_relativeStartTime, + draftedTestRunData.m_duration, + draftedTestRunData.m_jobs)); + + // Inform the client that the sequence has ended + if (testSequenceEndCallback.has_value()) + { + (*testSequenceEndCallback)(sequenceReport); + } + + // Update the dynamic dependency map with the latest coverage data (if any) + if (updateCoverage.has_value()) + { + (*updateCoverage)(ConcatenateVectors(selectedTestRunData.m_jobs, draftedTestRunData.m_jobs)); + } + + return sequenceReport; + } + Runtime::Runtime( RuntimeConfig&& config, + AZStd::optional dataFile, SuiteType suiteFilter, Policy::ExecutionFailure executionFailurePolicy, Policy::FailedTestCoverage failedTestCoveragePolicy, @@ -120,27 +283,22 @@ namespace TestImpact try { + if (dataFile.has_value()) + { + m_sparTiaFile = dataFile.value().String(); + } + else + { + m_sparTiaFile = m_config.m_workspace.m_active.m_sparTiaFiles[static_cast(m_suiteFilter)].String(); + } + // Populate the dynamic dependency map with the existing source coverage data (if any) - m_sparTIAFile = m_config.m_workspace.m_active.m_sparTIAFiles[static_cast(m_suiteFilter)].String(); - const auto tiaDataRaw = ReadFileContents(m_sparTIAFile); + const auto tiaDataRaw = ReadFileContents(m_sparTiaFile); const auto tiaData = DeserializeSourceCoveringTestsList(tiaDataRaw); if (tiaData.GetNumSources()) { m_dynamicDependencyMap->ReplaceSourceCoverage(tiaData); m_hasImpactAnalysisData = true; - - // Enumerate new test targets - const auto testTargetsWithNoEnumeration = m_dynamicDependencyMap->GetNotCoveringTests(); - if (!testTargetsWithNoEnumeration.empty()) - { - m_testEngine->UpdateEnumerationCache( - testTargetsWithNoEnumeration, - Policy::ExecutionFailure::Ignore, - Policy::TestFailure::Continue, - AZStd::nullopt, - AZStd::nullopt, - AZStd::nullopt); - } } } catch (const DependencyException& e) @@ -155,7 +313,7 @@ namespace TestImpact AZ_Printf( LogCallSite, AZStd::string::format( - "No test impact analysis data found for suite '%s' at %s\n", GetSuiteTypeName(m_suiteFilter).c_str(), m_sparTIAFile.c_str()).c_str()); + "No test impact analysis data found for suite '%s' at %s\n", SuiteTypeAsString(m_suiteFilter).c_str(), m_sparTiaFile.c_str()).c_str()); } } @@ -199,7 +357,7 @@ namespace TestImpact } } - AZStd::pair, AZStd::vector> Runtime::SelectCoveringTestTargetsAndUpdateEnumerationCache( + AZStd::pair, AZStd::vector> Runtime::SelectCoveringTestTargets( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy) { @@ -212,9 +370,6 @@ namespace TestImpact // Populate a set with the selected test targets so that we can infer the discarded test target not selected for this change list const AZStd::unordered_set selectedTestTargetSet(selectedTestTargets.begin(), selectedTestTargets.end()); - // Update the enumeration caches of mutated targets regardless of the current sharding policy - EnumerateMutatedTestTargets(changeDependencyList); - // The test targets in the main list not in the selected test target set are the test targets not selected for this change list for (const auto& testTarget : m_dynamicDependencyMap->GetTestTargetList().GetTargets()) { @@ -256,7 +411,7 @@ namespace TestImpact void Runtime::ClearDynamicDependencyMapAndRemoveExistingFile() { m_dynamicDependencyMap->ClearAllSourceCoverage(); - DeleteFile(m_sparTIAFile); + DeleteFile(m_sparTiaFile); } SourceCoveringTestsList Runtime::CreateSourceCoveringTestFromTestCoverages(const AZStd::vector& jobs) @@ -298,6 +453,7 @@ namespace TestImpact continue; } + // Add the sources covered by this test target to the coverage map for (const auto& source : job.GetTestCoverge().value().GetSourcesCovered()) { coverage[source.String()].insert(job.GetTestTarget()->GetName()); @@ -309,6 +465,7 @@ namespace TestImpact sourceCoveringTests.reserve(coverage.size()); for (auto&& [source, testTargets] : coverage) { + // Check to see whether this source is inside the repo or not (not a perfect check but weeds out the obvious non-repo sources) if (const auto sourcePath = RepoPath(source); sourcePath.IsRelativeTo(m_config.m_repo.m_root)) { @@ -335,9 +492,9 @@ namespace TestImpact } m_dynamicDependencyMap->ReplaceSourceCoverage(sourceCoverageTestsList); - const auto sparTIA = m_dynamicDependencyMap->ExportSourceCoverage(); - const auto sparTIAData = SerializeSourceCoveringTestsList(sparTIA); - WriteFileContents(sparTIAData, m_sparTIAFile); + const auto sparTia = m_dynamicDependencyMap->ExportSourceCoverage(); + const auto sparTiaData = SerializeSourceCoveringTestsList(sparTia); + WriteFileContents(sparTiaData, m_sparTiaFile); m_hasImpactAnalysisData = true; } catch(const RuntimeException& e) @@ -353,17 +510,48 @@ namespace TestImpact } } - TestSequenceResult Runtime::RegularTestSequence( + PolicyStateBase Runtime::GeneratePolicyStateBase() const + { + PolicyStateBase policyState; + + policyState.m_executionFailurePolicy = m_executionFailurePolicy; + policyState.m_failedTestCoveragePolicy = m_failedTestCoveragePolicy; + policyState.m_integrityFailurePolicy = m_integrationFailurePolicy; + policyState.m_targetOutputCapture = m_targetOutputCapture; + policyState.m_testFailurePolicy = m_testFailurePolicy; + policyState.m_testShardingPolicy = m_testShardingPolicy; + + return policyState; + } + + SequencePolicyState Runtime::GenerateSequencePolicyState() const + { + return { GeneratePolicyStateBase() }; + } + + SafeImpactAnalysisSequencePolicyState Runtime::GenerateSafeImpactAnalysisSequencePolicyState( + Policy::TestPrioritization testPrioritizationPolicy) const + { + return { GeneratePolicyStateBase(), testPrioritizationPolicy }; + } + + ImpactAnalysisSequencePolicyState Runtime::GenerateImpactAnalysisSequencePolicyState( + Policy::TestPrioritization testPrioritizationPolicy, Policy::DynamicDependencyMap dynamicDependencyMapPolicy) const + { + return { GeneratePolicyStateBase(), testPrioritizationPolicy, dynamicDependencyMapPolicy }; + } + + Client::RegularSequenceReport Runtime::RegularTestSequence( AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceEndCallback, + AZStd::optional> testSequenceEndCallback, AZStd::optional testCompleteCallback) { - Timer timer; + const Timer sequenceTimer; AZStd::vector includedTestTargets; AZStd::vector excludedTestTargets; - + // Separate the test targets into those that are excluded by either the test filter or exclusion list and those that are not for (const auto& testTarget : m_dynamicDependencyMap->GetTestTargetList().GetTargets()) { @@ -378,12 +566,17 @@ namespace TestImpact } } - // Sequence start callback + // Extract the client facing representation of selected test targets + const Client::TestRunSelection selectedTests(ExtractTestTargetNames(includedTestTargets), ExtractTestTargetNames(excludedTestTargets)); + + // Inform the client that the sequence is about to start if (testSequenceStartCallback.has_value()) { - (*testSequenceStartCallback)(Client::TestRunSelection(ExtractTestTargetNames(includedTestTargets), ExtractTestTargetNames(excludedTestTargets))); + (*testSequenceStartCallback)(m_suiteFilter, selectedTests); } + // Run the test targets and collect the test run results + const Timer testRunTimer; const auto [result, testJobs] = m_testEngine->RegularRun( includedTestTargets, m_testShardingPolicy, @@ -392,108 +585,171 @@ namespace TestImpact m_targetOutputCapture, testTargetTimeout, globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); + TestRunCompleteCallbackHandler(includedTestTargets.size(), testCompleteCallback)); + const auto testRunDuration = testRunTimer.GetElapsedMs(); + + // Generate the sequence report for the client + const auto sequenceReport = Client::RegularSequenceReport( + m_maxConcurrency, + testTargetTimeout, + globalTimeout, + GenerateSequencePolicyState(), + m_suiteFilter, + selectedTests, + GenerateTestRunReport(result, testRunTimer.GetStartTimePointRelative(sequenceTimer), testRunDuration, testJobs)); + // Inform the client that the sequence has ended if (testSequenceEndCallback.has_value()) { - (*testSequenceEndCallback)(GenerateSequenceFailureReport(testJobs), timer.Elapsed()); + (*testSequenceEndCallback)(sequenceReport); } - return result; + return sequenceReport; } - TestSequenceResult Runtime::ImpactAnalysisTestSequence( + Client::ImpactAnalysisSequenceReport Runtime::ImpactAnalysisTestSequence( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy, Policy::DynamicDependencyMap dynamicDependencyMapPolicy, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceEndCallback, + AZStd::optional> testSequenceEndCallback, AZStd::optional testCompleteCallback) { - Timer timer; + const Timer sequenceTimer; // Draft in the test targets that have no coverage entries in the dynamic dependency map - AZStd::vector draftedTestTargets = m_dynamicDependencyMap->GetNotCoveringTests(); + const AZStd::vector draftedTestTargets = m_dynamicDependencyMap->GetNotCoveringTests(); - // The test targets that were selected for the change list by the dynamic dependency map and the test targets that were not - auto [selectedTestTargets, discardedTestTargets] = SelectCoveringTestTargetsAndUpdateEnumerationCache(changeList, testPrioritizationPolicy); + const auto selectCoveringTestTargetsAndPruneDraftedFromDiscarded = + [this, &draftedTestTargets, &changeList, testPrioritizationPolicy]() + { + // The test targets that were selected for the change list by the dynamic dependency map and the test targets that were not + const auto [selectedTestTargets, discardedTestTargets] = + SelectCoveringTestTargets(changeList, testPrioritizationPolicy); - // The subset of selected test targets that are not on the configuration's exclude list and those that are - auto [includedSelectedTestTargets, excludedSelectedTestTargets] = SelectTestTargetsByExcludeList(selectedTestTargets); + const AZStd::unordered_set draftedTestTargetsSet(draftedTestTargets.begin(), draftedTestTargets.end()); - // We present to the client the included selected test targets and the drafted test targets as distinct sets but internally - // we consider the concatenated set of the two the actual set of tests to run - AZStd::vector testTargetsToRun = ConcatenateVectors(includedSelectedTestTargets, draftedTestTargets); + AZStd::vector discardedNotDraftedTestTargets; + for (const auto* testTarget : discardedTestTargets) + { + if (!draftedTestTargetsSet.count(testTarget)) + { + discardedNotDraftedTestTargets.push_back(testTarget); + } + } - if (testSequenceStartCallback.has_value()) - { - (*testSequenceStartCallback)( - Client::TestRunSelection(ExtractTestTargetNames(includedSelectedTestTargets), ExtractTestTargetNames(excludedSelectedTestTargets)), - ExtractTestTargetNames(discardedTestTargets), - ExtractTestTargetNames(draftedTestTargets)); - } + return AZStd::pair{ selectedTestTargets, discardedNotDraftedTestTargets }; + }; - if (dynamicDependencyMapPolicy == Policy::DynamicDependencyMap::Update) + const auto [selectedTestTargets, discardedTestTargets] = selectCoveringTestTargetsAndPruneDraftedFromDiscarded(); + + // The subset of selected test targets that are not on the configuration's exclude list and those that are + auto [includedSelectedTestTargets, excludedSelectedTestTargets] = SelectTestTargetsByExcludeList(selectedTestTargets); + + // Functor for running instrumented test targets + const auto instrumentedTestRun = + [this, &testTargetTimeout]( + const AZStd::vector& testsTargets, + TestRunCompleteCallbackHandler& testRunCompleteHandler, + AZStd::optional globalTimeout) { - const auto [result, testJobs] = m_testEngine->InstrumentedRun( - testTargetsToRun, + return m_testEngine->InstrumentedRun( + testsTargets, m_testShardingPolicy, m_executionFailurePolicy, - Policy::IntegrityFailure::Continue, + m_integrationFailurePolicy, m_testFailurePolicy, m_targetOutputCapture, testTargetTimeout, globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); - - UpdateAndSerializeDynamicDependencyMap(testJobs); - - if (testSequenceEndCallback.has_value()) - { - (*testSequenceEndCallback)(GenerateSequenceFailureReport(testJobs), timer.Elapsed()); - } + AZStd::ref(testRunCompleteHandler)); + }; - return result; - } - else + // Functor for running uninstrumented test targets + const auto regularTestRun = + [this, &testTargetTimeout]( + const AZStd::vector& testsTargets, + TestRunCompleteCallbackHandler& testRunCompleteHandler, + AZStd::optional globalTimeout) { - const auto [result, testJobs] = m_testEngine->RegularRun( - testTargetsToRun, + return m_testEngine->RegularRun( + testsTargets, m_testShardingPolicy, m_executionFailurePolicy, m_testFailurePolicy, m_targetOutputCapture, testTargetTimeout, globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); + AZStd::ref(testRunCompleteHandler)); + }; - if (testSequenceEndCallback.has_value()) + if (dynamicDependencyMapPolicy == Policy::DynamicDependencyMap::Update) + { + AZStd::optional& jobs)>> updateCoverage = + [this](const AZStd::vector& jobs) { - (*testSequenceEndCallback)(GenerateSequenceFailureReport(testJobs), timer.Elapsed()); - } - - return result; + UpdateAndSerializeDynamicDependencyMap(jobs); + }; + + return ImpactAnalysisTestSequenceWrapper( + m_maxConcurrency, + GenerateImpactAnalysisSequencePolicyState(testPrioritizationPolicy, dynamicDependencyMapPolicy), + m_suiteFilter, + sequenceTimer, + instrumentedTestRun, + includedSelectedTestTargets, + excludedSelectedTestTargets, + discardedTestTargets, + draftedTestTargets, + testTargetTimeout, + globalTimeout, + testSequenceStartCallback, + testSequenceEndCallback, + testCompleteCallback, + updateCoverage); + } + else + { + return ImpactAnalysisTestSequenceWrapper( + m_maxConcurrency, + GenerateImpactAnalysisSequencePolicyState(testPrioritizationPolicy, dynamicDependencyMapPolicy), + m_suiteFilter, + sequenceTimer, + regularTestRun, + includedSelectedTestTargets, + excludedSelectedTestTargets, + discardedTestTargets, + draftedTestTargets, + testTargetTimeout, + globalTimeout, + testSequenceStartCallback, + testSequenceEndCallback, + testCompleteCallback, + AZStd::optional& jobs)>>{ AZStd::nullopt }); } } - AZStd::pair Runtime::SafeImpactAnalysisTestSequence( + Client::SafeImpactAnalysisSequenceReport Runtime::SafeImpactAnalysisTestSequence( const ChangeList& changeList, Policy::TestPrioritization testPrioritizationPolicy, AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceEndCallback, + AZStd::optional> testSequenceEndCallback, AZStd::optional testCompleteCallback) { - Timer timer; + const Timer sequenceTimer; + TestRunData selectedTestRunData, draftedTestRunData; + TestRunData discardedTestRunData; + AZStd::optional sequenceTimeout = globalTimeout; // Draft in the test targets that have no coverage entries in the dynamic dependency map AZStd::vector draftedTestTargets = m_dynamicDependencyMap->GetNotCoveringTests(); // The test targets that were selected for the change list by the dynamic dependency map and the test targets that were not - auto [selectedTestTargets, discardedTestTargets] = SelectCoveringTestTargetsAndUpdateEnumerationCache(changeList, testPrioritizationPolicy); + const auto [selectedTestTargets, discardedTestTargets] = SelectCoveringTestTargets(changeList, testPrioritizationPolicy); // The subset of selected test targets that are not on the configuration's exclude list and those that are auto [includedSelectedTestTargets, excludedSelectedTestTargets] = SelectTestTargetsByExcludeList(selectedTestTargets); @@ -501,76 +757,146 @@ namespace TestImpact // The subset of discarded test targets that are not on the configuration's exclude list and those that are auto [includedDiscardedTestTargets, excludedDiscardedTestTargets] = SelectTestTargetsByExcludeList(discardedTestTargets); - // We present to the client the included selected test targets and the drafted test targets as distinct sets but internally - // we consider the concatenated set of the two the actual set of tests to run - AZStd::vector testTargetsToRun = ConcatenateVectors(includedSelectedTestTargets, draftedTestTargets); + // Extract the client facing representation of selected, discarded and drafted test targets + const Client::TestRunSelection selectedTests( + ExtractTestTargetNames(includedSelectedTestTargets), ExtractTestTargetNames(excludedSelectedTestTargets)); + const Client::TestRunSelection discardedTests(ExtractTestTargetNames(includedDiscardedTestTargets), ExtractTestTargetNames(excludedDiscardedTestTargets)); + const auto draftedTests = ExtractTestTargetNames(draftedTestTargets); + // Inform the client that the sequence is about to start if (testSequenceStartCallback.has_value()) { - (*testSequenceStartCallback)( - Client::TestRunSelection(ExtractTestTargetNames(includedSelectedTestTargets), ExtractTestTargetNames(excludedSelectedTestTargets)), - Client::TestRunSelection(ExtractTestTargetNames(includedDiscardedTestTargets), ExtractTestTargetNames(excludedDiscardedTestTargets)), - ExtractTestTargetNames(draftedTestTargets)); + (*testSequenceStartCallback)(m_suiteFilter, selectedTests, discardedTests, draftedTests); } - // Impact analysis run of the selected test targets - const auto [selectedResult, selectedTestJobs] = m_testEngine->InstrumentedRun( - testTargetsToRun, - m_testShardingPolicy, - m_executionFailurePolicy, - Policy::IntegrityFailure::Continue, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, - globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); + // We share the test run complete handler between the selected, discarded and drafted test runs as to present them together as one + // continuous test sequence to the client rather than three discrete test runs + const size_t totalNumTestRuns = includedSelectedTestTargets.size() + draftedTestTargets.size() + includedDiscardedTestTargets.size(); + TestRunCompleteCallbackHandler testRunCompleteHandler(totalNumTestRuns, testCompleteCallback); - const auto selectedDuraton = timer.Elapsed(); + // Functor for running instrumented test targets + const auto instrumentedTestRun = + [this, &testTargetTimeout, &sequenceTimeout, &testRunCompleteHandler](const AZStd::vector& testsTargets) + { + return m_testEngine->InstrumentedRun( + testsTargets, + m_testShardingPolicy, + m_executionFailurePolicy, + m_integrationFailurePolicy, + m_testFailurePolicy, + m_targetOutputCapture, + testTargetTimeout, + sequenceTimeout, + AZStd::ref(testRunCompleteHandler)); + }; + + // Functor for running uninstrumented test targets + const auto regularTestRun = + [this, &testTargetTimeout, &sequenceTimeout, &testRunCompleteHandler](const AZStd::vector& testsTargets) + { + return m_testEngine->RegularRun( + testsTargets, + m_testShardingPolicy, + m_executionFailurePolicy, + m_testFailurePolicy, + m_targetOutputCapture, + testTargetTimeout, + sequenceTimeout, + AZStd::ref(testRunCompleteHandler)); + }; - // Carry the remaining global sequence time over to the discarded test run - if (globalTimeout.has_value()) + // Functor for running instrumented test targets + const auto gatherTestRunData = [&sequenceTimer] + (const AZStd::vector& testsTargets, const auto& testRunner, auto& testRunData) { - const auto elapsed = timer.Elapsed(); - globalTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + const Timer testRunTimer; + testRunData.m_relativeStartTime = testRunTimer.GetStartTimePointRelative(sequenceTimer); + auto [result, jobs] = testRunner(testsTargets); + testRunData.m_result = result; + testRunData.m_jobs = AZStd::move(jobs); + testRunData.m_duration = testRunTimer.GetElapsedMs(); + }; + + if (!includedSelectedTestTargets.empty()) + { + // Run the selected test targets and collect the test run results + gatherTestRunData(includedSelectedTestTargets, instrumentedTestRun, selectedTestRunData); + + // Carry the remaining global sequence time over to the discarded test run + if (globalTimeout.has_value()) + { + const auto elapsed = selectedTestRunData.m_duration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + } } - // Regular run of the discarded test targets - const auto [discardedResult, discardedTestJobs] = m_testEngine->RegularRun( - includedDiscardedTestTargets, - m_testShardingPolicy, - m_executionFailurePolicy, - m_testFailurePolicy, - m_targetOutputCapture, - testTargetTimeout, - globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); + if (!includedDiscardedTestTargets.empty()) + { + // Run the discarded test targets and collect the test run results + gatherTestRunData(includedDiscardedTestTargets, regularTestRun, discardedTestRunData); + + // Carry the remaining global sequence time over to the drafted test run + if (globalTimeout.has_value()) + { + const auto elapsed = selectedTestRunData.m_duration + discardedTestRunData.m_duration; + sequenceTimeout = elapsed < globalTimeout.value() ? globalTimeout.value() - elapsed : AZStd::chrono::milliseconds(0); + } + } - const auto discardedDuraton = timer.Elapsed(); + if (!draftedTestTargets.empty()) + { + // Run the drafted test targets and collect the test run results + gatherTestRunData(draftedTestTargets, instrumentedTestRun, draftedTestRunData); + } + // Generate the sequence report for the client + const auto sequenceReport = Client::SafeImpactAnalysisSequenceReport( + m_maxConcurrency, + testTargetTimeout, + globalTimeout, + GenerateSafeImpactAnalysisSequencePolicyState(testPrioritizationPolicy), + m_suiteFilter, + selectedTests, + discardedTests, + draftedTests, + GenerateTestRunReport( + selectedTestRunData.m_result, + selectedTestRunData.m_relativeStartTime, + selectedTestRunData.m_duration, + selectedTestRunData.m_jobs), + GenerateTestRunReport( + discardedTestRunData.m_result, + discardedTestRunData.m_relativeStartTime, + discardedTestRunData.m_duration, + discardedTestRunData.m_jobs), + GenerateTestRunReport( + draftedTestRunData.m_result, + draftedTestRunData.m_relativeStartTime, + draftedTestRunData.m_duration, + draftedTestRunData.m_jobs)); + + // Inform the client that the sequence has ended if (testSequenceEndCallback.has_value()) { - (*testSequenceEndCallback)( - GenerateSequenceFailureReport(selectedTestJobs), - GenerateSequenceFailureReport(discardedTestJobs), - selectedDuraton, - discardedDuraton); + (*testSequenceEndCallback)(sequenceReport); } - UpdateAndSerializeDynamicDependencyMap(selectedTestJobs); - return { selectedResult, discardedResult }; + UpdateAndSerializeDynamicDependencyMap(ConcatenateVectors(selectedTestRunData.m_jobs, draftedTestRunData.m_jobs)); + return sequenceReport; } - TestSequenceResult Runtime::SeededTestSequence( + Client::SeedSequenceReport Runtime::SeededTestSequence( AZStd::optional testTargetTimeout, AZStd::optional globalTimeout, AZStd::optional testSequenceStartCallback, - AZStd::optional testSequenceEndCallback, + AZStd::optional> testSequenceEndCallback, AZStd::optional testCompleteCallback) { - Timer timer; + const Timer sequenceTimer; AZStd::vector includedTestTargets; AZStd::vector excludedTestTargets; + // Separate the test targets into those that are excluded by either the test filter or exclusion list and those that are not for (const auto& testTarget : m_dynamicDependencyMap->GetTestTargetList().GetTargets()) { if (!m_testTargetExcludeList.contains(&testTarget)) @@ -583,31 +909,48 @@ namespace TestImpact } } + // Extract the client facing representation of selected test targets + Client::TestRunSelection selectedTests(ExtractTestTargetNames(includedTestTargets), ExtractTestTargetNames(excludedTestTargets)); + + // Inform the client that the sequence is about to start if (testSequenceStartCallback.has_value()) { - (*testSequenceStartCallback)(Client::TestRunSelection(ExtractTestTargetNames(includedTestTargets), ExtractTestTargetNames(excludedTestTargets))); + (*testSequenceStartCallback)(m_suiteFilter, selectedTests); } + // Run the test targets and collect the test run results + const Timer testRunTimer; const auto [result, testJobs] = m_testEngine->InstrumentedRun( includedTestTargets, m_testShardingPolicy, m_executionFailurePolicy, - Policy::IntegrityFailure::Continue, + m_integrationFailurePolicy, m_testFailurePolicy, m_targetOutputCapture, testTargetTimeout, globalTimeout, - TestRunCompleteCallbackHandler(testCompleteCallback)); + TestRunCompleteCallbackHandler(includedTestTargets.size(), testCompleteCallback)); + const auto testRunDuration = testRunTimer.GetElapsedMs(); + // Generate the sequence report for the client + const auto sequenceReport = Client::SeedSequenceReport( + m_maxConcurrency, + testTargetTimeout, + globalTimeout, + GenerateSequencePolicyState(), + m_suiteFilter, + selectedTests, + GenerateTestRunReport(result, testRunTimer.GetStartTimePointRelative(sequenceTimer), testRunDuration, testJobs)); + + // Inform the client that the sequence has ended if (testSequenceEndCallback.has_value()) { - (*testSequenceEndCallback)(GenerateSequenceFailureReport(testJobs), timer.Elapsed()); + (*testSequenceEndCallback)(sequenceReport); } ClearDynamicDependencyMapAndRemoveExistingFile(); UpdateAndSerializeDynamicDependencyMap(testJobs); - - return result; + return sequenceReport; } bool Runtime::HasImpactAnalysisData() const diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp index 10a77a2e58..fec3d90471 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include @@ -24,13 +24,13 @@ namespace TestImpact return TestTargetMetaMapFactory(masterTestListData, suiteFilter); } - AZStd::vector ReadBuildTargetDescriptorFiles(const BuildTargetDescriptorConfig& buildTargetDescriptorConfig) + AZStd::vector ReadBuildTargetDescriptorFiles(const BuildTargetDescriptorConfig& buildTargetDescriptorConfig) { - AZStd::vector buildTargetDescriptors; + AZStd::vector buildTargetDescriptors; for (const auto& buildTargetDescriptorFile : std::filesystem::directory_iterator(buildTargetDescriptorConfig.m_mappingDirectory.c_str())) { const auto buildTargetDescriptorContents = ReadFileContents(buildTargetDescriptorFile.path().string().c_str()); - auto buildTargetDescriptor = TestImpact::BuildTargetDescriptorFactory( + auto buildTargetDescriptor = BuildTargetDescriptorFactory( buildTargetDescriptorContents, buildTargetDescriptorConfig.m_staticInclusionFilters, buildTargetDescriptorConfig.m_inputInclusionFilters, @@ -41,7 +41,7 @@ namespace TestImpact return buildTargetDescriptors; } - AZStd::unique_ptr ConstructDynamicDependencyMap( + AZStd::unique_ptr ConstructDynamicDependencyMap( SuiteType suiteFilter, const BuildTargetDescriptorConfig& buildTargetDescriptorConfig, const TestTargetMetaConfig& testTargetMetaConfig) @@ -50,7 +50,7 @@ namespace TestImpact auto buildTargetDescriptors = ReadBuildTargetDescriptorFiles(buildTargetDescriptorConfig); auto buildTargets = CompileTargetDescriptors(AZStd::move(buildTargetDescriptors), AZStd::move(testTargetmetaMap)); auto&& [productionTargets, testTargets] = buildTargets; - return AZStd::make_unique(AZStd::move(productionTargets), AZStd::move(testTargets)); + return AZStd::make_unique(AZStd::move(productionTargets), AZStd::move(testTargets)); } AZStd::unordered_set ConstructTestTargetExcludeList( @@ -68,7 +68,7 @@ namespace TestImpact return testTargetExcludeList; } - AZStd::vector ExtractTestTargetNames(const AZStd::vector testTargets) + AZStd::vector ExtractTestTargetNames(const AZStd::vector& testTargets) { AZStd::vector testNames; AZStd::transform(testTargets.begin(), testTargets.end(), AZStd::back_inserter(testNames), [](const TestTarget* testTarget) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h index 608888726e..23d78ee329 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactRuntimeUtils.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include @@ -25,7 +25,7 @@ namespace TestImpact { //! Construct a dynamic dependency map from the build target descriptors and test target metas. - AZStd::unique_ptr ConstructDynamicDependencyMap( + AZStd::unique_ptr ConstructDynamicDependencyMap( SuiteType suiteFilter, const BuildTargetDescriptorConfig& buildTargetDescriptorConfig, const TestTargetMetaConfig& testTargetMetaConfig); @@ -36,77 +36,97 @@ namespace TestImpact const AZStd::vector& excludedTestTargets); //! Extracts the name information from the specified test targets. - AZStd::vector ExtractTestTargetNames(const AZStd::vector testTargets); + AZStd::vector ExtractTestTargetNames(const AZStd::vector& testTargets); - //! Generates a test run failure report from the specified test engine job information. + //! Generates the test suites from the specified test engine job information. //! @tparam TestJob The test engine job type. template - Client::TestRunFailure GenerateTestRunFailure(const TestJob& testJob) + AZStd::vector GenerateClientTests(const TestJob& testJob) { + AZStd::vector tests; + if (testJob.GetTestRun().has_value()) { - AZStd::vector testCaseFailures; for (const auto& testSuite : testJob.GetTestRun()->GetTestSuites()) { - AZStd::vector testFailures; for (const auto& testCase : testSuite.m_tests) { - if (testCase.m_result.value_or(TestRunResult::Passed) == TestRunResult::Failed) + auto result = Client::TestResult::NotRun; + if (testCase.m_result.has_value()) { - testFailures.push_back(Client::TestFailure(testCase.m_name, "No error message retrieved")); + if (testCase.m_result.value() == TestRunResult::Passed) + { + result = Client::TestResult::Passed; + } + else if (testCase.m_result.value() == TestRunResult::Failed) + { + result = Client::TestResult::Failed; + } + else + { + throw RuntimeException(AZStd::string::format( + "Unexpected test run result: %u", aznumeric_cast(testCase.m_result.value()))); + } } - } - if (!testFailures.empty()) - { - testCaseFailures.push_back(Client::TestCaseFailure(testSuite.m_name, AZStd::move(testFailures))); + const auto name = AZStd::string::format("%s.%s", testSuite.m_name.c_str(), testCase.m_name.c_str()); + tests.push_back(Client::Test(name, result)); } } - - return Client::TestRunFailure(Client::TestRunFailure(testJob.GetTestTarget()->GetName(), AZStd::move(testCaseFailures))); - } - else - { - return Client::TestRunFailure(testJob.GetTestTarget()->GetName(), { }); } + + return tests; } - //! Generates a sequence failure report from the specified list of test engine jobs. - //! @tparam TestJob The test engine job type. template - Client::SequenceFailure GenerateSequenceFailureReport(const AZStd::vector& testJobs) + Client::TestRunReport GenerateTestRunReport( + TestSequenceResult result, + AZStd::chrono::high_resolution_clock::time_point startTime, + AZStd::chrono::milliseconds duration, + const AZStd::vector& testJobs) { - AZStd::vector executionFailures; - AZStd::vector testRunFailures; - AZStd::vector timedOutTestRuns; - AZStd::vector unexecutedTestRuns; - + AZStd::vector passingTests; + AZStd::vector failingTests; + AZStd::vector executionFailureTests; + AZStd::vector timedOutTests; + AZStd::vector unexecutedTests; + for (const auto& testJob : testJobs) { + // Test job start time relative to start time + const auto relativeStartTime = + AZStd::chrono::high_resolution_clock::time_point() + + AZStd::chrono::duration_cast(testJob.GetStartTime() - startTime); + + Client::TestRunBase clientTestRun( + testJob.GetTestTarget()->GetName(), testJob.GetCommandString(), relativeStartTime, testJob.GetDuration(), + testJob.GetTestResult()); + switch (testJob.GetTestResult()) { case Client::TestRunResult::FailedToExecute: { - executionFailures.push_back(Client::ExecutionFailure(testJob.GetTestTarget()->GetName(), testJob.GetCommandString())); + executionFailureTests.emplace_back(AZStd::move(clientTestRun)); break; } case Client::TestRunResult::NotRun: { - unexecutedTestRuns.push_back(testJob.GetTestTarget()->GetName()); + unexecutedTests.emplace_back(AZStd::move(clientTestRun)); break; } case Client::TestRunResult::Timeout: { - timedOutTestRuns.push_back(testJob.GetTestTarget()->GetName()); + timedOutTests.emplace_back(AZStd::move(clientTestRun)); break; } case Client::TestRunResult::AllTestsPass: { + passingTests.emplace_back(AZStd::move(clientTestRun), GenerateClientTests(testJob)); break; } case Client::TestRunResult::TestFailures: { - testRunFailures.push_back(GenerateTestRunFailure(testJob)); + failingTests.emplace_back(AZStd::move(clientTestRun), GenerateClientTests(testJob)); break; } default: @@ -116,11 +136,15 @@ namespace TestImpact } } } - - return Client::SequenceFailure( - AZStd::move(executionFailures), - AZStd::move(testRunFailures), - AZStd::move(timedOutTestRuns), - AZStd::move(unexecutedTestRuns)); + + return Client::TestRunReport( + result, + startTime, + duration, + AZStd::move(passingTests), + AZStd::move(failingTests), + AZStd::move(executionFailureTests), + AZStd::move(timedOutTests), + AZStd::move(unexecutedTests)); } -} +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp new file mode 100644 index 0000000000..993aee9af5 --- /dev/null +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactUtils.cpp @@ -0,0 +1,244 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include + +namespace TestImpact +{ + //! Delete the files that match the pattern from the specified directory. + //! @param path The path to the directory to pattern match the files for deletion. + //! @param pattern The pattern to match files for deletion. + size_t DeleteFiles(const RepoPath& path, const AZStd::string& pattern) + { + size_t numFilesDeleted = 0; + + AZ::IO::SystemFile::FindFiles( + AZStd::string::format("%s/%s", path.c_str(), pattern.c_str()).c_str(), + [&path, &numFilesDeleted](const char* file, bool isFile) + { + if (isFile) + { + AZ::IO::SystemFile::Delete(AZStd::string::format("%s/%s", path.c_str(), file).c_str()); + numFilesDeleted++; + } + + return true; + }); + + return numFilesDeleted; + } + + //! Deletes the specified file. + void DeleteFile(const RepoPath& file) + { + DeleteFiles(file.ParentPath(), file.Filename().Native()); + } + + //! User-friendly names for the test suite types. + AZStd::string SuiteTypeAsString(SuiteType suiteType) + { + switch (suiteType) + { + case SuiteType::Main: + return "main"; + case SuiteType::Periodic: + return "periodic"; + case SuiteType::Sandbox: + return "sandbox"; + default: + throw(Exception("Unexpected suite type")); + } + } + + AZStd::string SequenceReportTypeAsString(Client::SequenceReportType type) + { + switch (type) + { + case Client::SequenceReportType::RegularSequence: + return "regular"; + case Client::SequenceReportType::SeedSequence: + return "seed"; + case Client::SequenceReportType::ImpactAnalysisSequence: + return "impact_analysis"; + case Client::SequenceReportType::SafeImpactAnalysisSequence: + return "safe_impact_analysis"; + default: + throw(Exception(AZStd::string::format("Unexpected sequence report type: %u", aznumeric_cast(type)))); + } + } + + AZStd::string TestSequenceResultAsString(TestSequenceResult result) + { + switch (result) + { + case TestSequenceResult::Failure: + return "failure"; + case TestSequenceResult::Success: + return "success"; + case TestSequenceResult::Timeout: + return "timeout"; + default: + throw(Exception(AZStd::string::format("Unexpected test sequence result: %u", aznumeric_cast(result)))); + } + } + + AZStd::string TestRunResultAsString(Client::TestRunResult result) + { + switch (result) + { + case Client::TestRunResult::AllTestsPass: + return "all_tests_pass"; + case Client::TestRunResult::FailedToExecute: + return "failed_to_execute"; + case Client::TestRunResult::NotRun: + return "not_run"; + case Client::TestRunResult::TestFailures: + return "test_failures"; + case Client::TestRunResult::Timeout: + return "timeout"; + default: + throw(Exception(AZStd::string::format("Unexpected test run result: %u", aznumeric_cast(result)))); + } + } + + AZStd::string ExecutionFailurePolicyAsString(Policy::ExecutionFailure executionFailurePolicy) + { + switch (executionFailurePolicy) + { + case Policy::ExecutionFailure::Abort: + return "abort"; + case Policy::ExecutionFailure::Continue: + return "continue"; + case Policy::ExecutionFailure::Ignore: + return "ignore"; + default: + throw(Exception( + AZStd::string::format("Unexpected execution failure policy: %u", aznumeric_cast(executionFailurePolicy)))); + } + } + + AZStd::string FailedTestCoveragePolicyAsString(Policy::FailedTestCoverage failedTestCoveragePolicy) + { + switch (failedTestCoveragePolicy) + { + case Policy::FailedTestCoverage::Discard: + return "discard"; + case Policy::FailedTestCoverage::Keep: + return "keep"; + default: + throw(Exception( + AZStd::string::format("Unexpected failed test coverage policy: %u", aznumeric_cast(failedTestCoveragePolicy)))); + } + } + + AZStd::string TestPrioritizationPolicyAsString(Policy::TestPrioritization testPrioritizationPolicy) + { + switch (testPrioritizationPolicy) + { + case Policy::TestPrioritization::DependencyLocality: + return "dependency_locality"; + case Policy::TestPrioritization::None: + return "none"; + default: + throw(Exception( + AZStd::string::format("Unexpected test prioritization policy: %u", aznumeric_cast(testPrioritizationPolicy)))); + } + } + + AZStd::string TestFailurePolicyAsString(Policy::TestFailure testFailurePolicy) + { + switch (testFailurePolicy) + { + case Policy::TestFailure::Abort: + return "abort"; + case Policy::TestFailure::Continue: + return "continue"; + default: + throw( + Exception(AZStd::string::format("Unexpected test failure policy: %u", aznumeric_cast(testFailurePolicy)))); + } + } + + AZStd::string IntegrityFailurePolicyAsString(Policy::IntegrityFailure integrityFailurePolicy) + { + switch (integrityFailurePolicy) + { + case Policy::IntegrityFailure::Abort: + return "abort"; + case Policy::IntegrityFailure::Continue: + return "continue"; + default: + throw(Exception( + AZStd::string::format("Unexpected integration failure policy: %u", aznumeric_cast(integrityFailurePolicy)))); + } + } + + AZStd::string DynamicDependencyMapPolicyAsString(Policy::DynamicDependencyMap dynamicDependencyMapPolicy) + { + switch (dynamicDependencyMapPolicy) + { + case Policy::DynamicDependencyMap::Discard: + return "discard"; + case Policy::DynamicDependencyMap::Update: + return "update"; + default: + throw(Exception(AZStd::string::format( + "Unexpected dynamic dependency map policy: %u", aznumeric_cast(dynamicDependencyMapPolicy)))); + } + } + + AZStd::string TestShardingPolicyAsString(Policy::TestSharding testShardingPolicy) + { + switch (testShardingPolicy) + { + case Policy::TestSharding::Always: + return "always"; + case Policy::TestSharding::Never: + return "never"; + default: + throw(Exception( + AZStd::string::format("Unexpected test sharding policy: %u", aznumeric_cast(testShardingPolicy)))); + } + } + + AZStd::string TargetOutputCapturePolicyAsString(Policy::TargetOutputCapture targetOutputCapturePolicy) + { + switch (targetOutputCapturePolicy) + { + case Policy::TargetOutputCapture::File: + return "file"; + case Policy::TargetOutputCapture::None: + return "none"; + case Policy::TargetOutputCapture::StdOut: + return "stdout"; + case Policy::TargetOutputCapture::StdOutAndFile: + return "stdout_file"; + default: + throw(Exception( + AZStd::string::format("Unexpected target output capture policy: %u", aznumeric_cast(targetOutputCapturePolicy)))); + } + } + + AZStd::string ClientTestResultAsString(Client::TestResult result) + { + switch (result) + { + case Client::TestResult::Failed: + return "failed"; + case Client::TestResult::NotRun: + return "not_run"; + case Client::TestResult::Passed: + return "passed"; + default: + throw(Exception(AZStd::string::format("Unexpected client test case result: %u", aznumeric_cast(result)))); + } + } +} // namespace TestImpact diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake b/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake index 090bb68fcc..75f253ad27 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake +++ b/Code/Tools/TestImpactFramework/Runtime/Code/testimpactframework_runtime_files.cmake @@ -16,11 +16,14 @@ set(FILES Include/TestImpactFramework/TestImpactChangelist.h Include/TestImpactFramework/TestImpactChangelistSerializer.h Include/TestImpactFramework/TestImpactChangelistException.h + Include/TestImpactFramework/TestImpactPolicy.h Include/TestImpactFramework/TestImpactTestSequence.h Include/TestImpactFramework/TestImpactClientTestSelection.h Include/TestImpactFramework/TestImpactClientTestRun.h - Include/TestImpactFramework/TestImpactClientFailureReport.h - Include/TestImpactFramework/TestImpactFileUtils.h + Include/TestImpactFramework/TestImpactClientSequenceReport.h + Include/TestImpactFramework/TestImpactUtils.h + Include/TestImpactFramework/TestImpactClientSequenceReportSerializer.h + Include/TestImpactFramework/TestImpactSequenceReportException.h Source/Artifact/TestImpactArtifactException.h Source/Artifact/Factory/TestImpactBuildTargetDescriptorFactory.cpp Source/Artifact/Factory/TestImpactBuildTargetDescriptorFactory.h @@ -123,7 +126,9 @@ set(FILES Source/TestImpactRuntimeUtils.h Source/TestImpactClientTestSelection.cpp Source/TestImpactClientTestRun.cpp - Source/TestImpactClientFailureReport.cpp + Source/TestImpactClientSequenceReport.cpp Source/TestImpactChangeListSerializer.cpp + Source/TestImpactClientSequenceReportSerializer.cpp Source/TestImpactRepoPath.cpp + Source/TestImpactUtils.cpp ) diff --git a/Gems/AWSCore/Code/CMakeLists.txt b/Gems/AWSCore/Code/CMakeLists.txt index 71271eb7ee..8489e38550 100644 --- a/Gems/AWSCore/Code/CMakeLists.txt +++ b/Gems/AWSCore/Code/CMakeLists.txt @@ -166,3 +166,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ) endif() endif() + +install(DIRECTORY "Tools/ResourceMappingTool" + DESTINATION "Gems/AWSCore/Code/Tools" + COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} + PATTERN "__pycache__" EXCLUDE +) diff --git a/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h b/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h index 243d40c974..b24fe8f898 100644 --- a/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h +++ b/Gems/AWSCore/Code/Include/Private/AWSCoreInternalBus.h @@ -34,11 +34,6 @@ namespace AWSCore //! @return The path of AWS resource mapping config file virtual AZStd::string GetResourceMappingConfigFilePath() const = 0; - //! GetResourceMappingConfigFolderPath - //! Get the path of AWS resource mapping config folder - //! @return The path of AWS resource mapping config folder - virtual AZStd::string GetResourceMappingConfigFolderPath() const = 0; - //! ReloadConfiguration //! Reload AWSCore configuration without restarting application virtual void ReloadConfiguration() = 0; diff --git a/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h b/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h index 1c4bb84cad..9834f9ca38 100644 --- a/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h +++ b/Gems/AWSCore/Code/Include/Private/Configuration/AWSCoreConfiguration.h @@ -50,7 +50,6 @@ namespace AWSCore // AWSCoreInternalRequestBus interface implementation AZStd::string GetResourceMappingConfigFilePath() const override; - AZStd::string GetResourceMappingConfigFolderPath() const override; AZStd::string GetProfileName() const override; void ReloadConfiguration() override; diff --git a/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h b/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h index d462e2d435..1a4c428e68 100644 --- a/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h +++ b/Gems/AWSCore/Code/Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h @@ -7,9 +7,11 @@ */ #pragma once +#include #include #include +#include namespace AWSCore { @@ -17,22 +19,26 @@ namespace AWSCore : public QAction { public: + static constexpr const char AWSCoreResourceMappingToolActionName[] = "AWSCoreResourceMappingToolAction"; static constexpr const char ResourceMappingToolDirectoryPath[] = "Gems/AWSCore/Code/Tools/ResourceMappingTool"; + static constexpr const char ResourceMappingToolLogDirectoryPath[] = "user/log/"; static constexpr const char EngineWindowsPythonEntryScriptPath[] = "python/python.cmd"; - AWSCoreResourceMappingToolAction(const QString& text); + AWSCoreResourceMappingToolAction(const QString& text, QObject* parent = nullptr); + + void InitAWSCoreResourceMappingToolAction(); AZStd::string GetToolLaunchCommand() const; - AZStd::string GetToolLogPath() const; + AZStd::string GetToolLogFilePath() const; AZStd::string GetToolReadMePath() const; private: bool m_isDebug; - AZStd::string m_enginePythonEntryPath; - AZStd::string m_toolScriptPath; - AZStd::string m_toolQtBinDirectoryPath; - - AZStd::string m_toolLogPath; - AZStd::string m_toolReadMePath; + AZ::IO::Path m_enginePythonEntryPath; + AZ::IO::Path m_toolScriptPath; + AZ::IO::Path m_toolQtBinDirectoryPath; + AZ::IO::Path m_toolLogDirectoryPath; + AZ::IO::Path m_toolConfigDirectoryPath; + AZ::IO::Path m_toolReadMePath; }; } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp b/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp index 46bce001e1..4653975a52 100644 --- a/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp +++ b/Gems/AWSCore/Code/Source/Configuration/AWSCoreConfiguration.cpp @@ -56,19 +56,6 @@ namespace AWSCore return configFilePath; } - AZStd::string AWSCoreConfiguration::GetResourceMappingConfigFolderPath() const - { - if (m_sourceProjectFolder.empty()) - { - AZ_Warning(AWSCoreConfigurationName, false, ProjectSourceFolderNotFoundErrorMessage); - return ""; - } - AZStd::string configFolderPath = AZStd::string::format( - "%s/%s", m_sourceProjectFolder.c_str(), AWSCoreResourceMappingConfigFolderName); - AzFramework::StringFunc::Path::Normalize(configFolderPath); - return configFolderPath; - } - void AWSCoreConfiguration::InitConfig() { InitSourceProjectFolderPath(); diff --git a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp index 02dc30d887..a2c89a5af3 100644 --- a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp +++ b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreEditorMenu.cpp @@ -80,7 +80,7 @@ namespace AWSCore { #ifdef AWSCORE_EDITOR_RESOURCE_MAPPING_TOOL_ENABLED AWSCoreResourceMappingToolAction* resourceMappingTool = - new AWSCoreResourceMappingToolAction(QObject::tr(AWSResourceMappingToolActionText)); + new AWSCoreResourceMappingToolAction(QObject::tr(AWSResourceMappingToolActionText), this); QObject::connect(resourceMappingTool, &QAction::triggered, this, [resourceMappingTool, this]() { AZStd::string launchCommand = resourceMappingTool->GetToolLaunchCommand(); @@ -109,7 +109,7 @@ namespace AWSCore if (!m_resourceMappingToolWatcher || !m_resourceMappingToolWatcher->IsProcessRunning()) { - AZStd::string resourceMappingToolLogPath = resourceMappingTool->GetToolLogPath(); + AZStd::string resourceMappingToolLogPath = resourceMappingTool->GetToolLogFilePath(); AZStd::string message = AZStd::string::format(AWSResourceMappingToolLogWarningText, resourceMappingToolLogPath.c_str()); QMessageBox::warning(QApplication::activeWindow(), "Warning", message.c_str(), QMessageBox::Ok); } diff --git a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp index 2519ab87c3..858d30fa40 100644 --- a/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp +++ b/Gems/AWSCore/Code/Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp @@ -6,133 +6,89 @@ * */ -#include #include -#include #include +#include #include namespace AWSCore { - AWSCoreResourceMappingToolAction::AWSCoreResourceMappingToolAction(const QString& text) - : QAction(text) + AWSCoreResourceMappingToolAction::AWSCoreResourceMappingToolAction(const QString& text, QObject* parent) + : QAction(text, parent) , m_isDebug(false) - , m_enginePythonEntryPath("") - , m_toolScriptPath("") - , m_toolQtBinDirectoryPath("") - , m_toolLogPath("") - , m_toolReadMePath("") { - auto engineRootPath = AZ::IO::FileIOBase::GetInstance()->GetAlias("@engroot@"); - if (!engineRootPath) - { - AZ_Error("AWSCoreEditor", false, "Failed to determine engine root path."); - } - else - { - m_enginePythonEntryPath = AZStd::string::format("%s/%s", engineRootPath, EngineWindowsPythonEntryScriptPath); - AzFramework::StringFunc::Path::Normalize(m_enginePythonEntryPath); - if (!AZ::IO::SystemFile::Exists(m_enginePythonEntryPath.c_str())) - { - AZ_Error("AWSCoreEditor", false, "Failed to find engine python entry at %s.", m_enginePythonEntryPath.c_str()); - m_enginePythonEntryPath.clear(); - } - - m_toolScriptPath = AZStd::string::format("%s/%s/resource_mapping_tool.py", engineRootPath, ResourceMappingToolDirectoryPath); - AzFramework::StringFunc::Path::Normalize(m_toolScriptPath); - if (!AZ::IO::SystemFile::Exists(m_toolScriptPath.c_str())) - { - AZ_Error("AWSCoreEditor", false, "Failed to find ResourceMappingTool python script at %s.", m_toolScriptPath.c_str()); - m_toolScriptPath.clear(); - } - - m_toolLogPath = AZStd::string::format("%s/%s/resource_mapping_tool.log", engineRootPath, ResourceMappingToolDirectoryPath); - AzFramework::StringFunc::Path::Normalize(m_toolLogPath); - if (!AZ::IO::SystemFile::Exists(m_toolLogPath.c_str())) - { - AZ_Error("AWSCoreEditor", false, "Failed to find ResourceMappingTool log file at %s.", m_toolLogPath.c_str()); - m_toolLogPath.clear(); - } + InitAWSCoreResourceMappingToolAction(); + } - m_toolReadMePath = AZStd::string::format("%s/%s/README.md", engineRootPath, ResourceMappingToolDirectoryPath); - AzFramework::StringFunc::Path::Normalize(m_toolReadMePath); - if (!AZ::IO::SystemFile::Exists(m_toolReadMePath.c_str())) - { - AZ_Error("AWSCoreEditor", false, "Failed to find ResourceMappingTool README file at %s.", m_toolReadMePath.c_str()); - m_toolReadMePath.clear(); - } + void AWSCoreResourceMappingToolAction::InitAWSCoreResourceMappingToolAction() + { + AZ::IO::Path engineRootPath = AZ::IO::PathView(AZ::Utils::GetEnginePath()); + m_enginePythonEntryPath = (engineRootPath / EngineWindowsPythonEntryScriptPath).LexicallyNormal(); + m_toolScriptPath = (engineRootPath / ResourceMappingToolDirectoryPath / "resource_mapping_tool.py").LexicallyNormal(); + m_toolReadMePath = (engineRootPath / ResourceMappingToolDirectoryPath / "README.md").LexicallyNormal(); - char executablePath[AZ_MAX_PATH_LEN]; - auto result = AZ::Utils::GetExecutablePath(executablePath, AZ_MAX_PATH_LEN); - if (result.m_pathStored != AZ::Utils::ExecutablePathResult::Success) - { - AZ_Error("AWSCoreEditor", false, "Failed to find engine executable path."); - } - else - { - if (result.m_pathIncludesFilename) - { - // Remove the file name if it exists, and keep the parent folder only - char* lastSeparatorAddress = strrchr(executablePath, AZ_CORRECT_FILESYSTEM_SEPARATOR); - if (lastSeparatorAddress) - { - *lastSeparatorAddress = '\0'; - } - } - } + AZ::IO::Path projectPath = AZ::IO::PathView(AZ::Utils::GetProjectPath()); + m_toolLogDirectoryPath = (projectPath / ResourceMappingToolLogDirectoryPath).LexicallyNormal(); + m_toolConfigDirectoryPath = (projectPath / AWSCoreConfiguration::AWSCoreResourceMappingConfigFolderName).LexicallyNormal(); - AZStd::string binDirectoryPath(executablePath); - auto lastSeparator = binDirectoryPath.find_last_of(AZ_CORRECT_FILESYSTEM_SEPARATOR); - if (lastSeparator != AZStd::string::npos) - { - m_isDebug = binDirectoryPath.substr(lastSeparator).contains("debug"); - } + AZ::IO::Path executablePath = AZ::IO::PathView(AZ::Utils::GetExecutableDirectory()); + m_toolQtBinDirectoryPath = (executablePath / "AWSCoreEditorQtBin").LexicallyNormal(); - m_toolQtBinDirectoryPath = AZStd::string::format("%s/%s", binDirectoryPath.c_str(), "AWSCoreEditorQtBin"); - AzFramework::StringFunc::Path::Normalize(m_toolQtBinDirectoryPath); - if (!AZ::IO::SystemFile::Exists(m_toolQtBinDirectoryPath.c_str())) - { - AZ_Error("AWSCoreEditor", false, "Failed to find ResourceMappingTool Qt binaries at %s.", m_toolQtBinDirectoryPath.c_str()); - m_toolQtBinDirectoryPath.clear(); - } - } + m_isDebug = AZStd::string_view(AZ_BUILD_CONFIGURATION_TYPE) == "debug"; } AZStd::string AWSCoreResourceMappingToolAction::GetToolLaunchCommand() const { - if (m_enginePythonEntryPath.empty() || m_toolScriptPath.empty() || m_toolQtBinDirectoryPath.empty()) + if (!AZ::IO::SystemFile::Exists(m_enginePythonEntryPath.c_str()) || + !AZ::IO::SystemFile::Exists(m_toolScriptPath.c_str()) || + !AZ::IO::SystemFile::Exists(m_toolQtBinDirectoryPath.c_str()) || + !AZ::IO::SystemFile::Exists(m_toolConfigDirectoryPath.c_str()) || + !AZ::IO::SystemFile::Exists(m_toolLogDirectoryPath.c_str())) { + AZ_Error(AWSCoreResourceMappingToolActionName, false, + "Expected parameter for tool launch command is invalid, engine python path: %s, tool script path: %s, tool qt binaries path: %s, tool config path: %s, tool log path: %s", + m_enginePythonEntryPath.c_str(), m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), m_toolConfigDirectoryPath.c_str(), m_toolLogDirectoryPath.c_str()); return ""; } AZStd::string profileName = "default"; AWSCoreInternalRequestBus::BroadcastResult(profileName, &AWSCoreInternalRequests::GetProfileName); - AZStd::string configPath = ""; - AWSCoreInternalRequestBus::BroadcastResult(configPath, &AWSCoreInternalRequests::GetResourceMappingConfigFolderPath); - if (m_isDebug) { return AZStd::string::format( - "%s debug %s --binaries_path %s --debug --profile %s --config_path %s", m_enginePythonEntryPath.c_str(), - m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), profileName.c_str(), configPath.c_str()); + "\"%s\" debug -B \"%s\" --binaries-path \"%s\" --debug --profile \"%s\" --config-path \"%s\" --log-path \"%s\"", + m_enginePythonEntryPath.c_str(), m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), + profileName.c_str(), m_toolConfigDirectoryPath.c_str(), m_toolLogDirectoryPath.c_str()); } else { return AZStd::string::format( - "%s %s --binaries_path %s --profile %s --config_path %s", m_enginePythonEntryPath.c_str(), - m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), profileName.c_str(), configPath.c_str()); + "\"%s\" -B \"%s\" --binaries-path \"%s\" --profile \"%s\" --config-path \"%s\" --log-path \"%s\"", + m_enginePythonEntryPath.c_str(), m_toolScriptPath.c_str(), m_toolQtBinDirectoryPath.c_str(), + profileName.c_str(), m_toolConfigDirectoryPath.c_str(), m_toolLogDirectoryPath.c_str()); } } - AZStd::string AWSCoreResourceMappingToolAction::GetToolLogPath() const + AZStd::string AWSCoreResourceMappingToolAction::GetToolLogFilePath() const { - return m_toolLogPath; + AZ::IO::Path toolLogFilePath = (m_toolLogDirectoryPath / "resource_mapping_tool.log").LexicallyNormal(); + if (!AZ::IO::SystemFile::Exists(toolLogFilePath.c_str())) + { + AZ_Error(AWSCoreResourceMappingToolActionName, false, "Invalid tool log file path: %s", toolLogFilePath.c_str()); + return ""; + } + return toolLogFilePath.Native(); } AZStd::string AWSCoreResourceMappingToolAction::GetToolReadMePath() const { - return m_toolReadMePath; + if (!AZ::IO::SystemFile::Exists(m_toolReadMePath.c_str())) + { + AZ_Error(AWSCoreResourceMappingToolActionName, false, "Invalid tool readme path: %s", m_toolReadMePath.c_str()); + return ""; + } + return m_toolReadMePath.Native(); } } // namespace AWSCore diff --git a/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp b/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp index e1acd3e3d9..b3e2ec5738 100644 --- a/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp +++ b/Gems/AWSCore/Code/Tests/Credential/AWSDefaultCredentialHandlerTest.cpp @@ -73,7 +73,6 @@ public: // AWSCoreInternalRequestBus interface implementation AZStd::string GetProfileName() const override { return m_profileName; } AZStd::string GetResourceMappingConfigFilePath() const override { return ""; } - AZStd::string GetResourceMappingConfigFolderPath() const override { return ""; } void ReloadConfiguration() override {} std::shared_ptr m_environmentCredentialsProviderMock; diff --git a/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorManagerTest.cpp b/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorManagerTest.cpp index e2ace4212f..9a0063e5a9 100644 --- a/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorManagerTest.cpp +++ b/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorManagerTest.cpp @@ -34,8 +34,6 @@ class AWSCoreEditorManagerTest TEST_F(AWSCoreEditorManagerTest, AWSCoreEditorManager_Constructor_HaveExpectedUIResourcesCreated) { - AZ_TEST_START_TRACE_SUPPRESSION; AWSCoreEditorManager testManager; - AZ_TEST_STOP_TRACE_SUPPRESSION(1); // expect the above have thrown an AZ_Error EXPECT_TRUE(testManager.GetAWSCoreEditorMenu()); } diff --git a/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorSystemComponentTest.cpp b/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorSystemComponentTest.cpp index b722c83950..07a6c8ae08 100644 --- a/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorSystemComponentTest.cpp +++ b/Gems/AWSCore/Code/Tests/Editor/AWSCoreEditorSystemComponentTest.cpp @@ -41,9 +41,7 @@ class AWSCoreEditorSystemComponentTest m_entity = aznew AZ::Entity(); m_coreEditorSystemsComponent.reset(m_entity->CreateComponent()); - AZ_TEST_START_TRACE_SUPPRESSION; m_entity->Init(); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); // expect the above have thrown an AZ_Error m_entity->Activate(); } diff --git a/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp b/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp index 295818c44c..40ed5b53b5 100644 --- a/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp +++ b/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreEditorMenuTest.cpp @@ -42,18 +42,9 @@ class AWSCoreEditorMenuTest } }; -TEST_F(AWSCoreEditorMenuTest, AWSCoreEditorMenu_NoEngineRootFolder_ExpectOneError) -{ - AZ_TEST_START_TRACE_SUPPRESSION; - AWSCoreEditorMenu testMenu("dummy title"); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); // expect the above have thrown an AZ_Error -} - TEST_F(AWSCoreEditorMenuTest, AWSCoreEditorMenu_GetAllActions_GetExpectedNumberOfActions) { - AZ_TEST_START_TRACE_SUPPRESSION; AWSCoreEditorMenu testMenu("dummy title"); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); // expect the above have thrown an AZ_Error QList actualActions = testMenu.actions(); #ifdef AWSCORE_EDITOR_RESOURCE_MAPPING_TOOL_ENABLED @@ -65,9 +56,7 @@ TEST_F(AWSCoreEditorMenuTest, AWSCoreEditorMenu_GetAllActions_GetExpectedNumberO TEST_F(AWSCoreEditorMenuTest, AWSCoreEditorMenu_BroadcastFeatureGemsAreEnabled_CorrespondingActionsAreEnabled) { - AZ_TEST_START_TRACE_SUPPRESSION; AWSCoreEditorMenu testMenu("dummy title"); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); // expect the above have thrown an AZ_Error AWSCoreEditorRequestBus::Broadcast(&AWSCoreEditorRequests::SetAWSClientAuthEnabled); AWSCoreEditorRequestBus::Broadcast(&AWSCoreEditorRequests::SetAWSMetricsEnabled); diff --git a/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreResourceMappingToolActionTest.cpp b/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreResourceMappingToolActionTest.cpp index 4a027ec920..81e7eda21e 100644 --- a/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreResourceMappingToolActionTest.cpp +++ b/Gems/AWSCore/Code/Tests/Editor/UI/AWSCoreResourceMappingToolActionTest.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include @@ -24,7 +25,6 @@ class AWSCoreResourceMappingToolActionTest { AWSCoreEditorUIFixture::SetUp(); AWSCoreFixture::SetUp(); - m_localFileIO->SetAlias("@engroot@", "dummy engine root"); } void TearDown() override @@ -34,20 +34,12 @@ class AWSCoreResourceMappingToolActionTest } }; -TEST_F(AWSCoreResourceMappingToolActionTest, AWSCoreResourceMappingToolAction_NoEngineRootFolder_ExpectOneError) +TEST_F(AWSCoreResourceMappingToolActionTest, AWSCoreResourceMappingToolAction_NoEngineRootPath_ExpectErrorsAndResult) { - m_localFileIO->ClearAlias("@engroot@"); - AZ_TEST_START_TRACE_SUPPRESSION; AWSCoreResourceMappingToolAction testAction("dummy title"); - AZ_TEST_STOP_TRACE_SUPPRESSION(1); // expect the above have thrown an AZ_Error -} - -TEST_F(AWSCoreResourceMappingToolActionTest, AWSCoreResourceMappingToolAction_UnableToFindExpectedFileOrFolder_ExpectFiveErrorsAndEmptyResult) -{ AZ_TEST_START_TRACE_SUPPRESSION; - AWSCoreResourceMappingToolAction testAction("dummy title"); - AZ_TEST_STOP_TRACE_SUPPRESSION_NO_COUNT; EXPECT_TRUE(testAction.GetToolLaunchCommand() == ""); - EXPECT_TRUE(testAction.GetToolLogPath() == ""); + EXPECT_TRUE(testAction.GetToolLogFilePath() == ""); EXPECT_TRUE(testAction.GetToolReadMePath() == ""); + AZ_TEST_STOP_TRACE_SUPPRESSION(3); } diff --git a/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp b/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp index ebd13fbcb8..557fbc820c 100644 --- a/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp +++ b/Gems/AWSCore/Code/Tests/ResourceMapping/AWSResourceMappingManagerTest.cpp @@ -115,7 +115,6 @@ public: // AWSCoreInternalRequestBus interface implementation AZStd::string GetProfileName() const override { return ""; } AZStd::string GetResourceMappingConfigFilePath() const override { return m_normalizedConfigFilePath; } - AZStd::string GetResourceMappingConfigFolderPath() const override { return m_normalizedConfigFolderPath; } void ReloadConfiguration() override { m_reloadConfigurationCounter++; } AZStd::unique_ptr m_resourceMappingManager; diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/README.md b/Gems/AWSCore/Code/Tools/ResourceMappingTool/README.md index 78a8856288..e09ecc281f 100644 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/README.md +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/README.md @@ -89,3 +89,13 @@ you can create the virtualenv manually. ``` $ python3 resource_mapping_tool.py ``` +## Tool Arguments +* `--binaries-path` **[Optional]** Path to QT Binaries necessary for PySide, + required if launching tool with engine python environment. +* `--config-path` **[Optional]** Path to resource mapping config directory, + if not provided tool will use current directory. +* `--debug` **[Optional]** Execute on debug mode to enable DEBUG logging level. +* `--log-path` **[Optional]** Path to resource mapping tool logging directory, + if not provided tool will store logging under tool source code directory. +* `--profile` **[Optional]** Named AWS profile to use for querying AWS resources, + if not provided tool will use `default` aws profile. \ No newline at end of file diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py index ec27fb3cf7..2351fd001b 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/resource_mapping_tool.py @@ -9,15 +9,16 @@ from argparse import (ArgumentParser, Namespace) import logging import sys -from utils import aws_utils from utils import environment_utils from utils import file_utils # arguments setup argument_parser: ArgumentParser = ArgumentParser() -argument_parser.add_argument('--binaries_path', help='Path to QT Binaries necessary for PySide.') -argument_parser.add_argument('--config_path', help='Path to resource mapping config directory.') +argument_parser.add_argument('--binaries-path', help='Path to QT Binaries necessary for PySide.') +argument_parser.add_argument('--config-path', help='Path to resource mapping config directory.') argument_parser.add_argument('--debug', action='store_true', help='Execute on debug mode to enable DEBUG logging level') +argument_parser.add_argument('--log-path', help='Path to resource mapping tool logging directory ' + '(if not provided, logging file will be located at tool directory)') argument_parser.add_argument('--profile', default='default', help='Named AWS profile to use for querying AWS resources') arguments: Namespace = argument_parser.parse_args() @@ -25,8 +26,11 @@ arguments: Namespace = argument_parser.parse_args() logging_level: int = logging.INFO if arguments.debug: logging_level = logging.DEBUG -logging_path: str = file_utils.join_path(file_utils.get_parent_directory_path(__file__), - 'resource_mapping_tool.log') +logging_path: str = file_utils.join_path(file_utils.get_parent_directory_path(__file__), 'resource_mapping_tool.log') +if arguments.log_path: + normalized_logging_path: str = file_utils.normalize_file_path(arguments.log_path, False) + if normalized_logging_path and file_utils.create_directory(normalized_logging_path): + logging_path = file_utils.join_path(normalized_logging_path, 'resource_mapping_tool.log') logging.basicConfig(filename=logging_path, filemode='w', level=logging_level, format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S') logging.getLogger('boto3').setLevel(logging.CRITICAL) @@ -34,6 +38,7 @@ logging.getLogger('botocore').setLevel(logging.CRITICAL) logging.getLogger('s3transfer').setLevel(logging.CRITICAL) logging.getLogger('urllib3').setLevel(logging.CRITICAL) logger = logging.getLogger(__name__) +logger.info(f"Using {logging_path} for logging.") if __name__ == "__main__": if arguments.binaries_path and not environment_utils.is_qt_linked(): diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_aws_utils.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_aws_utils.py index 397472d252..9dd4fbd5be 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_aws_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_aws_utils.py @@ -98,16 +98,52 @@ class TestAWSUtils(TestCase): mocked_s3_client.list_buckets.assert_called_once() assert not actual_buckets - def test_list_s3_buckets_return_expected_buckets(self) -> None: + def test_list_s3_buckets_return_empty_list_with_no_matching_region(self) -> None: + expected_region: str = "us-east-1" mocked_s3_client: MagicMock = self._mock_client.return_value expected_buckets: List[str] = [f"{TestAWSUtils._expected_bucket}1", f"{TestAWSUtils._expected_bucket}2"] mocked_s3_client.list_buckets.return_value = {"Buckets": [{"Name": expected_buckets[0]}, {"Name": expected_buckets[1]}]} + mocked_s3_client.get_bucket_location.side_effect = [{"LocationConstraint": "us-east-2"}, + {"LocationConstraint": "us-west-1"}] - actual_buckets: List[str] = aws_utils.list_s3_buckets() - self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME) + actual_buckets: List[str] = aws_utils.list_s3_buckets(expected_region) + self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME, + region_name=expected_region) + mocked_s3_client.list_buckets.assert_called_once() + assert not actual_buckets + + def test_list_s3_buckets_return_expected_buckets_matching_region(self) -> None: + expected_region: str = "us-west-2" + mocked_s3_client: MagicMock = self._mock_client.return_value + expected_buckets: List[str] = [f"{TestAWSUtils._expected_bucket}1", f"{TestAWSUtils._expected_bucket}2"] + mocked_s3_client.list_buckets.return_value = {"Buckets": [{"Name": expected_buckets[0]}, + {"Name": expected_buckets[1]}]} + mocked_s3_client.get_bucket_location.side_effect = [{"LocationConstraint": "us-west-2"}, + {"LocationConstraint": "us-west-1"}] + + actual_buckets: List[str] = aws_utils.list_s3_buckets(expected_region) + self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME, + region_name=expected_region) + mocked_s3_client.list_buckets.assert_called_once() + assert len(actual_buckets) == 1 + assert actual_buckets[0] == expected_buckets[0] + + def test_list_s3_buckets_return_expected_iad_buckets(self) -> None: + expected_region: str = "us-east-1" + mocked_s3_client: MagicMock = self._mock_client.return_value + expected_buckets: List[str] = [f"{TestAWSUtils._expected_bucket}1", f"{TestAWSUtils._expected_bucket}2"] + mocked_s3_client.list_buckets.return_value = {"Buckets": [{"Name": expected_buckets[0]}, + {"Name": expected_buckets[1]}]} + mocked_s3_client.get_bucket_location.side_effect = [{"LocationConstraint": None}, + {"LocationConstraint": "us-west-1"}] + + actual_buckets: List[str] = aws_utils.list_s3_buckets(expected_region) + self._mock_client.assert_called_once_with(aws_utils.AWSConstants.S3_SERVICE_NAME, + region_name=expected_region) mocked_s3_client.list_buckets.assert_called_once() - assert actual_buckets == expected_buckets + assert len(actual_buckets) == 1 + assert actual_buckets[0] == expected_buckets[0] def test_list_lambda_functions_return_empty_list(self) -> None: mocked_lambda_client: MagicMock = self._mock_client.return_value diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_file_utils.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_file_utils.py index ea0630af49..fe0f1754f3 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_file_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/tests/unit/utils/test_file_utils.py @@ -44,6 +44,23 @@ class TestFileUtils(TestCase): mocked_path.exists.assert_called_once() assert not actual_result + def test_create_directory_return_true(self) -> None: + mocked_path: MagicMock = self._mock_path.return_value + + actual_result: bool = file_utils.create_directory("dummy") + self._mock_path.assert_called_once() + mocked_path.mkdir.assert_called_once() + assert actual_result + + def test_create_directory_return_false_when_exception_raised(self) -> None: + mocked_path: MagicMock = self._mock_path.return_value + mocked_path.mkdir.side_effect = FileExistsError() + + actual_result: bool = file_utils.create_directory("dummy") + self._mock_path.assert_called_once() + mocked_path.mkdir.assert_called_once() + assert not actual_result + def test_get_current_directory_path_return_expected_path_name(self) -> None: self._mock_path.cwd.return_value = TestFileUtils._expected_path_name diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py index dded35efed..0344834298 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/aws_utils.py @@ -103,7 +103,17 @@ def list_s3_buckets(region: str = "") -> List[str]: bucket_names: List[str] = [] bucket: Dict[str, any] for bucket in response["Buckets"]: - bucket_names.append(bucket["Name"]) + try: + bucket_name: str = bucket["Name"] + location_response: Dict[str, any] = s3_client.get_bucket_location(Bucket=bucket_name) + # Buckets in Region us-east-1 have a LocationConstraint of null . + # https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.get_bucket_location + if ((location_response["LocationConstraint"] == region) or + (not location_response["LocationConstraint"] and region == "us-east-1")): + bucket_names.append(bucket_name) + except ClientError as error: + raise RuntimeError(error_messages.AWS_SERVICE_REQUEST_CLIENT_ERROR_MESSAGE.format( + "get_bucket_location", error.response['Error']['Code'], error.response['Error']['Message'])) return bucket_names diff --git a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/file_utils.py b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/file_utils.py index 024c620948..9e5dd9617b 100755 --- a/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/file_utils.py +++ b/Gems/AWSCore/Code/Tools/ResourceMappingTool/utils/file_utils.py @@ -20,6 +20,15 @@ def check_path_exists(file_path: str) -> bool: return pathlib.Path(file_path).exists() +def create_directory(dir_path: str) -> bool: + try: + pathlib.Path(dir_path).mkdir(parents=True, exist_ok=True) + return True + except FileExistsError: + logger.warning(f"Failed to create directory at {dir_path}") + return False + + def get_current_directory_path() -> str: return str(pathlib.Path.cwd()) @@ -40,10 +49,10 @@ def find_files_with_suffix_under_directory(dir_path: str, suffix: str) -> List[s return results -def normalize_file_path(file_path: str) -> str: +def normalize_file_path(file_path: str, strict: bool = True) -> str: if file_path: try: - return str(pathlib.Path(file_path).resolve(True)) + return str(pathlib.Path(file_path).resolve(strict)) except (FileNotFoundError, RuntimeError): logger.warning(f"Failed to normalize file path {file_path}, return empty string instead") return "" diff --git a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraComponent.h b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraComponent.h index d5c84c7441..fb9c543bca 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraComponent.h +++ b/Gems/Atom/Component/DebugCamera/Code/Include/Atom/Component/DebugCamera/CameraComponent.h @@ -103,6 +103,7 @@ namespace AZ void SetOrthographic(bool orthographic) override; void SetOrthographicHalfWidth(float halfWidth) override; void MakeActiveView() override; + bool IsActiveView() override; // RPI::WindowContextNotificationBus overrides... void OnViewportResized(uint32_t width, uint32_t height) override; diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp index 330b6571f3..217cf0f061 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp @@ -250,6 +250,11 @@ namespace AZ // do nothing } + bool CameraComponent::IsActiveView() + { + return false; + } + void CameraComponent::OnViewportResized(uint32_t width, uint32_t height) { AZ_UNUSED(width) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ProfilingCaptureBus.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ProfilingCaptureBus.h index 15f15705c8..b22e82f456 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ProfilingCaptureBus.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/ProfilingCaptureBus.h @@ -22,12 +22,21 @@ namespace AZ //! Dump the Timestamp from passes to a json file. virtual bool CapturePassTimestamp(const AZStd::string& outputFilePath) = 0; + //! Dump the Cpu frame time statistics to a json file. + virtual bool CaptureCpuFrameTime(const AZStd::string& outputFilePath) = 0; + //! Dump the PipelineStatistics from passes to a json file. virtual bool CapturePassPipelineStatistics(const AZStd::string& outputFilePath) = 0; - //! Dump the Cpu Profiling Statistics to a json file. + //! Dump a single frame of Cpu profiling data virtual bool CaptureCpuProfilingStatistics(const AZStd::string& outputFilePath) = 0; + //! Start a multiframe capture of CPU profiling data. + virtual bool BeginContinuousCpuProfilingCapture() = 0; + + //! End and dump an in-progress continuous capture. + virtual bool EndContinuousCpuProfilingCapture(const AZStd::string& outputFilePath) = 0; + //! Dump the benchmark metadata to a json file. virtual bool CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath) = 0; }; @@ -44,6 +53,11 @@ namespace AZ //! @param info The output file path or error information which depends on the return. virtual void OnCaptureQueryTimestampFinished(bool result, const AZStd::string& info) = 0; + //! Notify when the current CpuFrameTimeStatistics capture is finished + //! @param result Set to true if it's finished successfully + //! @param info The output file path or error information which depends on the return. + virtual void OnCaptureCpuFrameTimeFinished(bool result, const AZStd::string& info) = 0; + //! Notify when the current PipelineStatistics query capture is finished //! @param result Set to true if it's finished successfully //! @param info The output file path or error information which depends on the return. diff --git a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp index 0c4c4d9689..add6d0e098 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.cpp @@ -10,6 +10,9 @@ #include #include +#include +#include +#include #include #include @@ -22,6 +25,7 @@ #include #include #include +#include namespace AZ { @@ -34,6 +38,7 @@ namespace AZ public: AZ_EBUS_BEHAVIOR_BINDER(ProfilingCaptureNotificationBusHandler, "{E45E4F37-EC1F-4010-994B-4F80998BEF15}", AZ::SystemAllocator, OnCaptureQueryTimestampFinished, + OnCaptureCpuFrameTimeFinished, OnCaptureQueryPipelineStatisticsFinished, OnCaptureCpuProfilingStatisticsFinished, OnCaptureBenchmarkMetadataFinished @@ -44,6 +49,11 @@ namespace AZ Call(FN_OnCaptureQueryTimestampFinished, result, info); } + void OnCaptureCpuFrameTimeFinished(bool result, const AZStd::string& info) override + { + Call(FN_OnCaptureCpuFrameTimeFinished, result, info); + } + void OnCaptureQueryPipelineStatisticsFinished(bool result, const AZStd::string& info) override { Call(FN_OnCaptureQueryPipelineStatisticsFinished, result, info); @@ -95,6 +105,19 @@ namespace AZ AZStd::vector m_timestampEntries; }; + // Intermediate class to serialize CPU frame time statistics. + class CpuFrameTimeSerializer + { + public: + AZ_TYPE_INFO(Render::CpuFrameTimeSerializer, "{584B415E-8769-4757-AC64-EA57EDBCBC3E}"); + static void Reflect(AZ::ReflectContext* context); + + CpuFrameTimeSerializer() = default; + CpuFrameTimeSerializer(double frameTime); + + double m_frameTime; + }; + // Intermediate class to serialize pass' PipelineStatistics data. class PipelineStatisticsSerializer { @@ -135,14 +158,15 @@ namespace AZ Name m_groupName; Name m_regionName; uint16_t m_stackDepth; - AZStd::sys_time_t m_elapsedInNanoseconds; + AZStd::sys_time_t m_startTick; + AZStd::sys_time_t m_endTick; }; AZ_TYPE_INFO(CpuProfilingStatisticsSerializer, "{D5B02946-0D27-474F-9A44-364C2706DD41}"); static void Reflect(AZ::ReflectContext* context); CpuProfilingStatisticsSerializer() = default; - CpuProfilingStatisticsSerializer(const RHI::CpuProfiler::TimeRegionMap& timeRegionMap); + CpuProfilingStatisticsSerializer(const AZStd::ring_buffer& continuousData); AZStd::vector m_cpuProfilingStatisticsSerializerEntries; }; @@ -248,6 +272,24 @@ namespace AZ } } + // --- CpuFrameTimeSerializer --- + + CpuFrameTimeSerializer::CpuFrameTimeSerializer(double frameTime) + { + m_frameTime = frameTime; + } + + void CpuFrameTimeSerializer::Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("frameTime", &CpuFrameTimeSerializer::m_frameTime) + ; + } + } + // --- PipelineStatisticsSerializer --- PipelineStatisticsSerializer::PipelineStatisticsSerializer(AZStd::vector&& passes) @@ -287,17 +329,20 @@ namespace AZ // --- CpuProfilingStatisticsSerializer --- - CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializer(const RHI::CpuProfiler::TimeRegionMap& timeRegionMap) + CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializer(const AZStd::ring_buffer& continuousData) { // Create serializable entries - for (auto& threadEntry : timeRegionMap) + for (const auto& timeRegionMap : continuousData) { - for (auto& cachedRegionEntry : threadEntry.second) + for (const auto& threadEntry : timeRegionMap) { - m_cpuProfilingStatisticsSerializerEntries.insert( - m_cpuProfilingStatisticsSerializerEntries.end(), - cachedRegionEntry.second.begin(), - cachedRegionEntry.second.end()); + for (const auto& cachedRegionEntry : threadEntry.second) + { + m_cpuProfilingStatisticsSerializerEntries.insert( + m_cpuProfilingStatisticsSerializerEntries.end(), + cachedRegionEntry.second.begin(), + cachedRegionEntry.second.end()); + } } } } @@ -319,19 +364,11 @@ namespace AZ CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::CpuProfilingStatisticsSerializerEntry(const RHI::CachedTimeRegion& cachedTimeRegion) { - // Converts ticks to Nanoseconds - static const auto ticksToNanoSeconds = [](AZStd::sys_time_t elapsedInTicks) -> AZStd::sys_time_t - { - const AZStd::sys_time_t ticksPerSecond = AZStd::GetTimeTicksPerSecond(); - - const AZStd::sys_time_t timeInNanoseconds = (elapsedInTicks * 1000000) / (ticksPerSecond / 1000); - return timeInNanoseconds; - }; - m_groupName = cachedTimeRegion.m_groupRegionName->m_groupName; m_regionName = cachedTimeRegion.m_groupRegionName->m_regionName; m_stackDepth = cachedTimeRegion.m_stackDepth; - m_elapsedInNanoseconds = ticksToNanoSeconds(cachedTimeRegion.m_endTick - cachedTimeRegion.m_startTick); + m_startTick = cachedTimeRegion.m_startTick; + m_endTick = cachedTimeRegion.m_endTick; } void CpuProfilingStatisticsSerializer::CpuProfilingStatisticsSerializerEntry::Reflect(AZ::ReflectContext* context) @@ -343,7 +380,8 @@ namespace AZ ->Field("groupName", &CpuProfilingStatisticsSerializerEntry::m_groupName) ->Field("regionName", &CpuProfilingStatisticsSerializerEntry::m_regionName) ->Field("stackDepth", &CpuProfilingStatisticsSerializerEntry::m_stackDepth) - ->Field("elapsedInNanoseconds", &CpuProfilingStatisticsSerializerEntry::m_elapsedInNanoseconds) + ->Field("startTick", &CpuProfilingStatisticsSerializerEntry::m_startTick) + ->Field("endTick", &CpuProfilingStatisticsSerializerEntry::m_endTick) ; } } @@ -408,6 +446,7 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Module, "atom") ->Event("CapturePassTimestamp", &ProfilingCaptureRequestBus::Events::CapturePassTimestamp) + ->Event("CaptureCpuFrameTime", &ProfilingCaptureRequestBus::Events::CaptureCpuFrameTime) ->Event("CapturePassPipelineStatistics", &ProfilingCaptureRequestBus::Events::CapturePassPipelineStatistics) ->Event("CaptureCpuProfilingStatistics", &ProfilingCaptureRequestBus::Events::CaptureCpuProfilingStatistics) ->Event("CaptureBenchmarkMetadata", &ProfilingCaptureRequestBus::Events::CaptureBenchmarkMetadata) @@ -417,6 +456,7 @@ namespace AZ } TimestampSerializer::Reflect(context); + CpuFrameTimeSerializer::Reflect(context); PipelineStatisticsSerializer::Reflect(context); CpuProfilingStatisticsSerializer::Reflect(context); BenchmarkMetadataSerializer::Reflect(context); @@ -432,6 +472,12 @@ namespace AZ TickBus::Handler::BusDisconnect(); ProfilingCaptureRequestBus::Handler::BusDisconnect(); + + // Block deactivation until the IO thread has finished serializing the CPU data + if (m_cpuDataSerializationThread.joinable()) + { + m_cpuDataSerializationThread.join(); + } } bool ProfilingCaptureSystemComponent::CapturePassTimestamp(const AZStd::string& outputFilePath) @@ -484,6 +530,71 @@ namespace AZ return captureStarted; } + bool ProfilingCaptureSystemComponent::CaptureCpuFrameTime(const AZStd::string& outputFilePath) + { + AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags( + AZ::RHI::FrameSchedulerStatisticsFlags::GatherCpuTimingStatistics, true + ); + bool wasEnabled = RHI::CpuProfiler::Get()->IsProfilerEnabled(); + if (!wasEnabled) + { + RHI::CpuProfiler::Get()->SetProfilerEnabled(true); + } + + const bool captureStarted = m_cpuFrameTimeStatisticsCapture.StartCapture([this, outputFilePath, wasEnabled]() + { + JsonSerializerSettings serializationSettings; + serializationSettings.m_keepDefaults = true; + + double frameTime = 0.0; + const AZ::RHI::CpuTimingStatistics* stats = AZ::RHI::RHISystemInterface::Get()->GetCpuTimingStatistics(); + if (stats) + { + frameTime = stats->GetFrameToFrameTimeMilliseconds(); + } + else + { + AZStd::string warning = AZStd::string::format("Failed to get Cpu frame time"); + AZ_Warning("ProfilingCaptureSystemComponent", false, warning.c_str()); + } + + CpuFrameTimeSerializer serializer(frameTime); + const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer, + outputFilePath, (CpuFrameTimeSerializer*)nullptr, &serializationSettings); + + AZStd::string captureInfo = outputFilePath; + if (!saveResult.IsSuccess()) + { + captureInfo = AZStd::string::format("Failed to save Cpu frame time to file '%s'. Error: %s", + outputFilePath.c_str(), + saveResult.GetError().c_str()); + AZ_Warning("ProfilingCaptureSystemComponent", false, captureInfo.c_str()); + } + + // Disable the profiler again + if (!wasEnabled) + { + RHI::CpuProfiler::Get()->SetProfilerEnabled(false); + } + AZ::RHI::RHISystemInterface::Get()->ModifyFrameSchedulerStatisticsFlags( + AZ::RHI::FrameSchedulerStatisticsFlags::GatherCpuTimingStatistics, false + ); + + // Notify listeners that the Cpu frame time statistics capture has finished. + ProfilingCaptureNotificationBus::Broadcast(&ProfilingCaptureNotificationBus::Events::OnCaptureCpuFrameTimeFinished, + saveResult.IsSuccess(), + captureInfo); + }); + + // Start the TickBus. + if (captureStarted) + { + TickBus::Handler::BusConnect(); + } + + return captureStarted; + } + bool ProfilingCaptureSystemComponent::CapturePassPipelineStatistics(const AZStd::string& outputFilePath) { // Find the root pass. @@ -534,6 +645,43 @@ namespace AZ return captureStarted; } + bool SerializeCpuProfilingData(const AZStd::ring_buffer& data, AZStd::string outputFilePath, bool wasEnabled) + { + AZ_TracePrintf("ProfilingCaptureSystemComponent", "Beginning serialization of %zu frames of profiling data\n", data.size()); + JsonSerializerSettings serializationSettings; + serializationSettings.m_keepDefaults = true; + + CpuProfilingStatisticsSerializer serializer(data); + + const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer, + outputFilePath, (CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings); + + AZStd::string captureInfo = outputFilePath; + if (!saveResult.IsSuccess()) + { + captureInfo = AZStd::string::format("Failed to save Cpu Profiling Statistics data to file '%s'. Error: %s", + outputFilePath.c_str(), + saveResult.GetError().c_str()); + AZ_Warning("ProfilingCaptureSystemComponent", false, captureInfo.c_str()); + } + else + { + AZ_Printf("ProfilingCaptureSystemComponent", "Cpu profiling statistics was saved to file [%s]\n", outputFilePath.c_str()); + } + + // Disable the profiler again + if (!wasEnabled) + { + RHI::CpuProfiler::Get()->SetProfilerEnabled(false); + } + + // Notify listeners that the pass' PipelineStatistics queries capture has finished. + ProfilingCaptureNotificationBus::Broadcast(&ProfilingCaptureNotificationBus::Events::OnCaptureCpuProfilingStatisticsFinished, + saveResult.IsSuccess(), + captureInfo); + return saveResult.IsSuccess(); + } + bool ProfilingCaptureSystemComponent::CaptureCpuProfilingStatistics(const AZStd::string& outputFilePath) { // Start the cpu profiling @@ -545,49 +693,66 @@ namespace AZ const bool captureStarted = m_cpuProfilingStatisticsCapture.StartCapture([this, outputFilePath, wasEnabled]() { - JsonSerializerSettings serializationSettings; - serializationSettings.m_keepDefaults = true; + // Blocking call for a single frame of data, avoid thread overhead + AZStd::ring_buffer singleFrameData; + singleFrameData.push_back(RHI::CpuProfiler::Get()->GetTimeRegionMap()); + SerializeCpuProfilingData(singleFrameData, outputFilePath, wasEnabled); + }); - // Get time Cpu profiled time regions - const RHI::CpuProfiler::TimeRegionMap& timeRegionMap = RHI::CpuProfiler::Get()->GetTimeRegionMap(); + // Start the TickBus. + if (captureStarted) + { + TickBus::Handler::BusConnect(); + } - CpuProfilingStatisticsSerializer serializer(timeRegionMap); - const auto saveResult = JsonSerializationUtils::SaveObjectToFile(&serializer, - outputFilePath, (CpuProfilingStatisticsSerializer*)nullptr, &serializationSettings); + return captureStarted; + } - AZStd::string captureInfo = outputFilePath; - if (!saveResult.IsSuccess()) - { - captureInfo = AZStd::string::format("Failed to save Cpu Profiling Statistics data to file '%s'. Error: %s", - outputFilePath.c_str(), - saveResult.GetError().c_str()); - AZ_Warning("ProfilingCaptureSystemComponent", false, captureInfo.c_str()); - } - else + bool ProfilingCaptureSystemComponent::BeginContinuousCpuProfilingCapture() + { + return AZ::RHI::CpuProfiler::Get()->BeginContinuousCapture(); + } + + bool ProfilingCaptureSystemComponent::EndContinuousCpuProfilingCapture(const AZStd::string& outputFilePath) + { + bool expected = false; + if (m_cpuDataSerializationInProgress.compare_exchange_strong(expected, true)) + { + AZStd::ring_buffer captureResult; + const bool captureEnded = AZ::RHI::CpuProfiler::Get()->EndContinuousCapture(captureResult); + if (!captureEnded) { - AZ_Printf("ProfilingCaptureSystemComponent", "Cpu profiling statistics was saved to file [%s]\n", outputFilePath.c_str()); + AZ_TracePrintf("ProfilingCaptureSystemComponent", "Could not end the continuous capture, is one in progress?\n"); + m_cpuDataSerializationInProgress.store(false); + return false; } - // Disable the profiler again - if (!wasEnabled) + // cpuProfilingData could be 1GB+ once saved, so use an IO thread to write it to disk. + auto threadIoFunction = + [data = AZStd::move(captureResult), filePath = AZStd::string(outputFilePath), &flag = m_cpuDataSerializationInProgress]() { - RHI::CpuProfiler::Get()->SetProfilerEnabled(false); + SerializeCpuProfilingData(data, filePath, true); + flag.store(false); + }; + + // If the thread object already exists (ex. we have already serialized data), join. This will not block since + // m_cpuDataSerializationInProgress was false, meaning the IO thread has already completed execution. + // TODO Use a reusable thread implementation over repeated creation + destruction of threads [ATOM-16214] + if (m_cpuDataSerializationThread.joinable()) + { + m_cpuDataSerializationThread.join(); } - // Notify listeners that the pass' PipelineStatistics queries capture has finished. - ProfilingCaptureNotificationBus::Broadcast(&ProfilingCaptureNotificationBus::Events::OnCaptureCpuProfilingStatisticsFinished, - saveResult.IsSuccess(), - captureInfo); - - }); + auto thread = AZStd::thread(threadIoFunction); + m_cpuDataSerializationThread = AZStd::move(thread); - // Start the TickBus. - if (captureStarted) - { - TickBus::Handler::BusConnect(); + return true; } - return captureStarted; + AZ_TracePrintf( + "ProfilingSystemCaptureComponent", + "Cannot end a continuous capture - another serialization is currently in progress\n"); + return false; } bool ProfilingCaptureSystemComponent::CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath) @@ -666,12 +831,13 @@ namespace AZ { // Update the delayed captures m_timestampCapture.UpdateCapture(); + m_cpuFrameTimeStatisticsCapture.UpdateCapture(); m_pipelineStatisticsCapture.UpdateCapture(); m_cpuProfilingStatisticsCapture.UpdateCapture(); m_benchmarkMetadataCapture.UpdateCapture(); // Disconnect from the TickBus if all capture states are set to idle. - if (m_timestampCapture.IsIdle() && m_pipelineStatisticsCapture.IsIdle() && m_cpuProfilingStatisticsCapture.IsIdle() && m_benchmarkMetadataCapture.IsIdle()) + if (m_timestampCapture.IsIdle() && m_pipelineStatisticsCapture.IsIdle() && m_cpuProfilingStatisticsCapture.IsIdle() && m_benchmarkMetadataCapture.IsIdle() && m_cpuFrameTimeStatisticsCapture.IsIdle()) { TickBus::Handler::BusDisconnect(); } diff --git a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h index 6703076c6e..1846767139 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h +++ b/Gems/Atom/Feature/Common/Code/Source/ProfilingCaptureSystemComponent.h @@ -12,6 +12,7 @@ #include #include +#include namespace AZ { @@ -68,8 +69,11 @@ namespace AZ // ProfilingCaptureRequestBus overrides... bool CapturePassTimestamp(const AZStd::string& outputFilePath) override; + bool CaptureCpuFrameTime(const AZStd::string& outputFilePath) override; bool CapturePassPipelineStatistics(const AZStd::string& outputFilePath) override; bool CaptureCpuProfilingStatistics(const AZStd::string& outputFilePath) override; + bool BeginContinuousCpuProfilingCapture() override; + bool EndContinuousCpuProfilingCapture(const AZStd::string& outputFilePath) override; bool CaptureBenchmarkMetadata(const AZStd::string& benchmarkName, const AZStd::string& outputFilePath) override; private: @@ -81,9 +85,15 @@ namespace AZ AZStd::vector FindPasses(AZStd::vector&& passHierarchy) const; DelayedQueryCaptureHelper m_timestampCapture; + DelayedQueryCaptureHelper m_cpuFrameTimeStatisticsCapture; DelayedQueryCaptureHelper m_pipelineStatisticsCapture; DelayedQueryCaptureHelper m_cpuProfilingStatisticsCapture; DelayedQueryCaptureHelper m_benchmarkMetadataCapture; + + // Flag passed by reference to the CPU profiling data serialization job, blocks new continuous capture requests when set. + AZStd::atomic_bool m_cpuDataSerializationInProgress = false; + + AZStd::thread m_cpuDataSerializationThread; }; } } diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h index 1c10b8829f..2248474820 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfiler.h @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -82,6 +83,14 @@ namespace AZ //! Get the last frame's TimeRegionMap virtual const TimeRegionMap& GetTimeRegionMap() const = 0; + //! Begin a continuous capture. Blocks the profiler from being toggled off until EndContinuousCapture is called. + [[nodiscard]] virtual bool BeginContinuousCapture() = 0; + + //! Flush the CPU Profiler's saved data into the passed ring buffer . + [[nodiscard]] virtual bool EndContinuousCapture(AZStd::ring_buffer& flushTarget) = 0; + + virtual bool IsContinuousCaptureInProgress() const = 0; + //! Enable/Disable the CpuProfiler virtual void SetProfilerEnabled(bool enabled) = 0; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h index 640c67858b..7d3b0c5b81 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/CpuProfilerImpl.h @@ -106,13 +106,18 @@ namespace AZ void OnSystemTick() final override; //! CpuProfiler overrides... - void BeginTimeRegion(TimeRegion& timeRegion) final; - void EndTimeRegion() final; - const TimeRegionMap& GetTimeRegionMap() const final; - void SetProfilerEnabled(bool enabled) final; - bool IsProfilerEnabled() const final; + void BeginTimeRegion(TimeRegion& timeRegion) final override; + void EndTimeRegion() final override; + const TimeRegionMap& GetTimeRegionMap() const final override; + bool BeginContinuousCapture() final override; + bool EndContinuousCapture(AZStd::ring_buffer& flushTarget) final override; + bool IsContinuousCaptureInProgress() const final override; + void SetProfilerEnabled(bool enabled) final override; + bool IsProfilerEnabled() const final override; private: + static constexpr AZStd::size_t MaxFramesToSave = 2 * 60 * 120; // 2 minutes of 120fps + // Lazily create and register the local thread data void RegisterThreadStorage(); @@ -134,6 +139,14 @@ namespace AZ AZStd::shared_mutex m_shutdownMutex; bool m_initialized = false; + + AZStd::mutex m_continuousCaptureEndingMutex; + + AZStd::atomic_bool m_continuousCaptureInProgress; + + // Stores multiple frames of profiling data, size is controlled by MaxFramesToSave. Flushed when EndContinuousCapture is called. + // Ring buffer so that we can have fast append of new data + removal of old profiling data with good cache locality. + AZStd::ring_buffer m_continuousCaptureData; }; }; // namespace RPI diff --git a/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp b/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp index 5cc69bc9a1..8c64f1611f 100644 --- a/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI.Edit/Utils.cpp @@ -304,7 +304,7 @@ namespace AZ uint32_t exitCode = 0; bool timedOut = false; - const AZStd::sys_time_t maxWaitTimeSeconds = 120; + const AZStd::sys_time_t maxWaitTimeSeconds = 300; const AZStd::sys_time_t startTimeSeconds = AZStd::GetTimeNowSecond(); const AZStd::sys_time_t startTime = AZStd::GetTimeNowTicks(); diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index 73a1881ead..cdfd4ac469 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -81,6 +81,7 @@ namespace AZ Interface::Register(this); m_initialized = true; SystemTickBus::Handler::BusConnect(); + m_continuousCaptureData.set_capacity(10); } void CpuProfilerImpl::Shutdown() @@ -101,6 +102,8 @@ namespace AZ m_registeredThreads.clear(); m_timeRegionMap.clear(); m_initialized = false; + m_continuousCaptureInProgress.store(false); + m_continuousCaptureData.clear(); SystemTickBus::Handler::BusDisconnect(); } @@ -141,12 +144,54 @@ namespace AZ return m_timeRegionMap; } + bool CpuProfilerImpl::BeginContinuousCapture() + { + bool expected = false; + if (m_continuousCaptureInProgress.compare_exchange_strong(expected, true)) + { + m_enabled = true; + AZ_TracePrintf("Profiler", "Continuous capture started\n"); + return true; + } + + AZ_TracePrintf("Profiler", "Attempting to start a continuous capture while one already in progress"); + return false; + } + + bool CpuProfilerImpl::EndContinuousCapture(AZStd::ring_buffer& flushTarget) + { + if (!m_continuousCaptureInProgress.load()) + { + AZ_TracePrintf("Profiler", "Attempting to end a continuous capture while one not in progress"); + return false; + } + + if (m_continuousCaptureEndingMutex.try_lock()) + { + m_enabled = false; + flushTarget = AZStd::move(m_continuousCaptureData); + m_continuousCaptureData.clear(); + AZ_TracePrintf("Profiler", "Continuous capture ended\n"); + m_continuousCaptureInProgress.store(false); + + m_continuousCaptureEndingMutex.unlock(); + return true; + } + + return false; + } + + bool CpuProfilerImpl::IsContinuousCaptureInProgress() const + { + return m_continuousCaptureInProgress.load(); + } + void CpuProfilerImpl::SetProfilerEnabled(bool enabled) { AZStd::unique_lock lock(m_threadRegisterMutex); - // Early out if the state is already the same - if (m_enabled == enabled) + // Early out if the state is already the same or a continuous capture is in progress + if (m_enabled == enabled || m_continuousCaptureInProgress.load()) { return; } @@ -179,6 +224,20 @@ namespace AZ { return; } + + if (m_continuousCaptureInProgress.load() && m_continuousCaptureEndingMutex.try_lock()) + { + if (m_continuousCaptureData.full() && m_continuousCaptureData.size() != MaxFramesToSave) + { + const AZStd::size_t size = m_continuousCaptureData.size(); + m_continuousCaptureData.set_capacity(AZStd::min(MaxFramesToSave, size + size / 2)); + } + + m_continuousCaptureData.push_back(AZStd::move(m_timeRegionMap)); + m_timeRegionMap.clear(); + m_continuousCaptureEndingMutex.unlock(); + } + AZStd::unique_lock lock(m_threadRegisterMutex); // Iterate through all the threads, and collect the thread's cached time regions diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h index c654952cf4..cdaf59ff75 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/View.h @@ -110,9 +110,6 @@ namespace AZ //! Value returned is 1.0f when an area equal to the viewport height squared is covered. Useful for accurate LOD decisions. float CalculateSphereAreaInClipSpace(const AZ::Vector3& sphereWorldPosition, float sphereRadius) const; - //! Invalidate the view srg to rebuild the srg. - void InvalidateSrg(); - const AZ::Name& GetName() const { return m_name; } const UsageFlags GetUsageFlags() { return m_usageFlags; } @@ -192,9 +189,6 @@ namespace AZ // Clip space offset for camera jitter with taa Vector2 m_clipSpaceOffset = Vector2(0.0f, 0.0f); - // Flags whether view matrices are dirty which requires rebuild srg - bool m_needBuildSrg = true; - MatrixChangedEvent m_onWorldToClipMatrixChange; MatrixChangedEvent m_onWorldToViewMatrixChange; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index 4984186b4e..1937afc240 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -126,8 +126,6 @@ namespace AZ m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix); m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix); - - InvalidateSrg(); } AZ::Transform View::GetCameraTransform() const @@ -170,8 +168,6 @@ namespace AZ m_onWorldToViewMatrixChange.Signal(m_worldToViewMatrix); } m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix); - - InvalidateSrg(); } void View::SetViewToClipMatrix(const AZ::Matrix4x4& viewToClip) @@ -202,14 +198,11 @@ namespace AZ m_unprojectionConstants.SetW(float(tanHalfFovY)); m_onWorldToClipMatrixChange.Signal(m_worldToClipMatrix); - - InvalidateSrg(); } void View::SetClipSpaceOffset(float xOffset, float yOffset) { m_clipSpaceOffset.Set(xOffset, yOffset); - InvalidateSrg(); } const AZ::Matrix4x4& View::GetWorldToViewMatrix() const @@ -362,58 +355,49 @@ namespace AZ return -0.25f * cotHalfFovYSq * AZ::Constants::Pi * radiusSq * sqrt(fabsf((distanceSq - radiusSq)/radiusSqSubDepthSq))/radiusSqSubDepthSq; } - void View::InvalidateSrg() - { - m_needBuildSrg = true; - } - void View::UpdateSrg() { - if (m_needBuildSrg) + if (m_clipSpaceOffset.IsZero()) { - if (m_clipSpaceOffset.IsZero()) - { - Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix; - m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix); - m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix); - m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull()); - } - else - { - // Offset the current and previous frame clip matricies - Matrix4x4 offsetViewToClipMatrix = m_viewToClipMatrix; - offsetViewToClipMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); - offsetViewToClipMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); - - Matrix4x4 offsetViewToClipPrevMatrix = m_viewToClipPrevMatrix; - offsetViewToClipPrevMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); - offsetViewToClipPrevMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); - - // Build other matricies dependent on the view to clip matricies - Matrix4x4 offsetWorldToClipMatrix = offsetViewToClipMatrix * m_worldToViewMatrix; - Matrix4x4 offsetWorldToClipPrevMatrix = offsetViewToClipPrevMatrix * m_worldToViewPrevMatrix; + Matrix4x4 worldToClipPrevMatrix = m_viewToClipPrevMatrix * m_worldToViewPrevMatrix; + m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, worldToClipPrevMatrix); + m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, m_worldToClipMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, m_viewToClipMatrix); + m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, m_clipToWorldMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, m_viewToClipMatrix.GetInverseFull()); + } + else + { + // Offset the current and previous frame clip matricies + Matrix4x4 offsetViewToClipMatrix = m_viewToClipMatrix; + offsetViewToClipMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); + offsetViewToClipMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); + + Matrix4x4 offsetViewToClipPrevMatrix = m_viewToClipPrevMatrix; + offsetViewToClipPrevMatrix.SetElement(0, 2, m_clipSpaceOffset.GetX()); + offsetViewToClipPrevMatrix.SetElement(1, 2, m_clipSpaceOffset.GetY()); + + // Build other matricies dependent on the view to clip matricies + Matrix4x4 offsetWorldToClipMatrix = offsetViewToClipMatrix * m_worldToViewMatrix; + Matrix4x4 offsetWorldToClipPrevMatrix = offsetViewToClipPrevMatrix * m_worldToViewPrevMatrix; - Matrix4x4 offsetClipToViewMatrix = offsetViewToClipMatrix.GetInverseFull(); - Matrix4x4 offsetClipToWorldMatrix = m_viewToWorldMatrix * offsetClipToViewMatrix; + Matrix4x4 offsetClipToViewMatrix = offsetViewToClipMatrix.GetInverseFull(); + Matrix4x4 offsetClipToWorldMatrix = m_viewToWorldMatrix * offsetClipToViewMatrix; - m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix); - m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix); - m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix); - m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull()); - } + m_shaderResourceGroup->SetConstant(m_worldToClipPrevMatrixConstantIndex, offsetWorldToClipPrevMatrix); + m_shaderResourceGroup->SetConstant(m_viewProjectionMatrixConstantIndex, offsetWorldToClipMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixConstantIndex, offsetViewToClipMatrix); + m_shaderResourceGroup->SetConstant(m_clipToWorldMatrixConstantIndex, offsetClipToWorldMatrix); + m_shaderResourceGroup->SetConstant(m_projectionMatrixInverseConstantIndex, offsetViewToClipMatrix.GetInverseFull()); + } - m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position); - m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix); - m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull()); - m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ); - m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants); + m_shaderResourceGroup->SetConstant(m_worldPositionConstantIndex, m_position); + m_shaderResourceGroup->SetConstant(m_viewMatrixConstantIndex, m_worldToViewMatrix); + m_shaderResourceGroup->SetConstant(m_viewMatrixInverseConstantIndex, m_worldToViewMatrix.GetInverseFull()); + m_shaderResourceGroup->SetConstant(m_zConstantsConstantIndex, m_nearZ_farZ_farZTimesNearZ_farZMinusNearZ); + m_shaderResourceGroup->SetConstant(m_unprojectionConstantsIndex, m_unprojectionConstants); - m_shaderResourceGroup->Compile(); - m_needBuildSrg = false; - } + m_shaderResourceGroup->Compile(); m_viewToClipPrevMatrix = m_viewToClipMatrix; m_worldToViewPrevMatrix = m_worldToViewMatrix; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h index dc57179fcc..3639606f03 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h @@ -9,12 +9,17 @@ #include #include +#include + #include #include #include + #include #include + #include + #include #include #include @@ -31,6 +36,7 @@ namespace AtomToolsFramework , protected AzFramework::AssetSystemStatusBus::Handler , protected AzToolsFramework::EditorPythonConsoleNotificationBus::Handler , protected AZ::UserSettingsOwnerRequestBus::Handler + , protected AtomToolsMainWindowNotificationBus::Handler { public: AZ_TYPE_INFO(AtomTools::AtomToolsApplication, "{A0DF25BA-6F74-4F11-9F85-0F99278D5986}"); @@ -38,6 +44,7 @@ namespace AtomToolsFramework using Base = AzFramework::Application; AtomToolsApplication(int* argc, char*** argv); + ~AtomToolsApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application @@ -52,6 +59,11 @@ namespace AtomToolsFramework void Stop() override; protected: + ////////////////////////////////////////////////////////////////////////// + // AtomsToolMainWindowNotificationBus::Handler overrides... + void OnMainWindowClosing() override; + ////////////////////////////////////////////////////////////////////////// + ////////////////////////////////////////////////////////////////////////// // AssetDatabaseRequestsBus::Handler overrides... bool GetAssetDatabaseLocation(AZStd::string& result) override; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h new file mode 100644 index 0000000000..82444246fd --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -0,0 +1,63 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once +#include + +#include + +#include +#include +#include +#include + +#include +#include +#include + +namespace AtomToolsFramework +{ + class AtomToolsMainWindow + : public AzQtComponents::DockMainWindow + , protected AtomToolsMainWindowRequestBus::Handler + { + public: + AtomToolsMainWindow(QWidget* parent = 0); + ~AtomToolsMainWindow(); + + protected: + 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; + bool IsDockWidgetVisible(const AZStd::string& name) const override; + AZStd::vector GetDockWidgetNames() const override; + + virtual void CreateMenu(); + virtual void CreateTabBar(); + + virtual void AddTabForDocumentId( + const AZ::Uuid& documentId, const AZStd::string& label, const AZStd::string& toolTip, AZStd::function widgetCreator); + virtual void RemoveTabForDocumentId(const AZ::Uuid& documentId); + virtual void UpdateTabForDocumentId( + const AZ::Uuid& documentId, const AZStd::string& label, const AZStd::string& toolTip, bool isModified); + virtual AZ::Uuid GetDocumentIdFromTab(const int tabIndex) const; + + virtual void OpenTabContextMenu(); + virtual void SelectPreviousTab(); + virtual void SelectNextTab(); + + AzQtComponents::FancyDocking* m_advancedDockManager = nullptr; + QWidget* m_centralWidget = nullptr; + QMenuBar* m_menuBar = nullptr; + AzQtComponents::TabWidget* m_tabWidget = nullptr; + QStatusBar* m_statusBar = nullptr; + + AZStd::unordered_map m_dockWidgets; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h new file mode 100644 index 0000000000..c93b4ba4b9 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace AtomToolsFramework +{ + //! AtomToolsMainWindowFactoryRequestBus provides + class AtomToolsMainWindowFactoryRequests : public AZ::EBusTraits + { + public: + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + + /// Creates and shows main window + virtual void CreateMainWindow() = 0; + + //! Destroys main window and releases all cached assets + virtual void DestroyMainWindow() = 0; + }; + using AtomToolsMainWindowFactoryRequestBus = AZ::EBus; + +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowNotificationBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h similarity index 62% rename from Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowNotificationBus.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h index 38f77e8bf5..cadd3440d9 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowNotificationBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h @@ -10,17 +10,16 @@ #include -namespace MaterialEditor +namespace AtomToolsFramework { - class MaterialEditorWindowNotifications - : public AZ::EBusTraits + class AtomToolsMainWindowNotifications : public AZ::EBusTraits { public: static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - virtual void OnMaterialEditorWindowClosing() {}; + virtual void OnMainWindowClosing(){}; }; - using MaterialEditorWindowNotificationBus = AZ::EBus; + using AtomToolsMainWindowNotificationBus = AZ::EBus; -} // namespace MaterialEditor +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h similarity index 80% rename from Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h index 6b62549684..6edb44bc5c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h @@ -8,17 +8,19 @@ #pragma once +//! Disables "unreferenced formal parameter" warning +#pragma warning(disable : 4100) + #include #include #include class QWidget; -namespace MaterialEditor +namespace AtomToolsFramework { - //! MaterialEditorWindowRequestBus provides - class MaterialEditorWindowRequests - : public AZ::EBusTraits + //! AtomToolsMainWindowRequestBus provides + class AtomToolsMainWindowRequests : public AZ::EBusTraits { public: static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; @@ -49,16 +51,16 @@ namespace MaterialEditor //! Get a list of registered docked widget names virtual AZStd::vector GetDockWidgetNames() const = 0; - //! Resizes the Material Editor window to achieve a requested size for the viewport render target. + //! Resizes the main window to achieve a requested size for the viewport render target. //! (This indicates the size of the render target, not the desktop-scaled QT widget size). - virtual void ResizeViewportRenderTarget(uint32_t width, uint32_t height) = 0; + virtual void ResizeViewportRenderTarget(uint32_t width, uint32_t height) {}; //! Forces the viewport's render target to use the given resolution, ignoring the size of the viewport widget. - virtual void LockViewportRenderTargetSize(uint32_t width, uint32_t height) = 0; + virtual void LockViewportRenderTargetSize(uint32_t width, uint32_t height) {}; //! Releases the viewport's render target resolution lock, allowing it to match the viewport widget again. - virtual void UnlockViewportRenderTargetSize() = 0; + virtual void UnlockViewportRenderTargetSize() {}; }; - using MaterialEditorWindowRequestBus = AZ::EBus; + using AtomToolsMainWindowRequestBus = AZ::EBus; -} // namespace MaterialEditor +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index 3d9219edc5..aedad7706b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -10,6 +10,8 @@ #include #include +#include +#include #include #include @@ -66,6 +68,13 @@ namespace AtomToolsFramework }); } + AtomToolsApplication ::~AtomToolsApplication() + { + AtomToolsMainWindowNotificationBus::Handler::BusDisconnect(); + AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); + AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); + } + void AtomToolsApplication::CreateReflectionManager() { Base::CreateReflectionManager(); @@ -145,12 +154,21 @@ namespace AtomToolsFramework m_timer.start(); } + void AtomToolsApplication::OnMainWindowClosing() + { + ExitMainLoop(); + } + void AtomToolsApplication::Destroy() { + // before modules are unloaded, destroy UI to free up any assets it cached + AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::DestroyMainWindow); + AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); - + AtomToolsMainWindowNotificationBus::Handler::BusDisconnect(); AzFramework::AssetSystemRequestBus::Broadcast(&AzFramework::AssetSystem::AssetSystemRequests::StartDisconnectingAssetProcessor); + Base::Destroy(); } @@ -271,6 +289,13 @@ namespace AtomToolsFramework void AtomToolsApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { + const AZStd::string activateWindowSwitchName = "activatewindow"; + if (commandLine.HasSwitch(activateWindowSwitchName)) + { + AtomToolsFramework::AtomToolsMainWindowRequestBus::Broadcast( + &AtomToolsFramework::AtomToolsMainWindowRequestBus::Handler::ActivateWindow); + } + const AZStd::string timeoputSwitchName = "timeout"; if (commandLine.HasSwitch(timeoputSwitchName)) { @@ -389,6 +414,10 @@ namespace AtomToolsFramework LoadSettings(); + AtomToolsMainWindowNotificationBus::Handler::BusConnect(); + + AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::CreateMainWindow); + auto editorPythonEventsInterface = AZ::Interface::Get(); if (editorPythonEventsInterface) { @@ -436,6 +465,8 @@ namespace AtomToolsFramework void AtomToolsApplication::Stop() { + AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::DestroyMainWindow); + UnloadSettings(); Base::Stop(); } @@ -445,7 +476,7 @@ namespace AtomToolsFramework appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Game; } - void AtomToolsApplication::OnTraceMessage([[maybe_unused]] AZStd::string_view message) + void AtomToolsApplication::OnTraceMessage([[maybe_unused]] AZStd::string_view message) { #if defined(AZ_ENABLE_TRACING) AZStd::vector lines; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp new file mode 100644 index 0000000000..f6e56b1ff6 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -0,0 +1,239 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include + +namespace AtomToolsFramework +{ + AtomToolsMainWindow::AtomToolsMainWindow(QWidget* parent) + : AzQtComponents::DockMainWindow(parent) + { + m_advancedDockManager = new AzQtComponents::FancyDocking(this); + + setDockNestingEnabled(true); + setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + + m_statusBar = new QStatusBar(this); + m_statusBar->setObjectName("StatusBar"); + statusBar()->addPermanentWidget(m_statusBar, 1); + + m_centralWidget = new QWidget(this); + + AtomToolsMainWindowRequestBus::Handler::BusConnect(); + } + + AtomToolsMainWindow::~AtomToolsMainWindow() + { + AtomToolsMainWindowRequestBus::Handler::BusDisconnect(); + } + + void AtomToolsMainWindow::ActivateWindow() + { + activateWindow(); + raise(); + } + + bool AtomToolsMainWindow::AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) + { + auto dockWidgetItr = m_dockWidgets.find(name); + if (dockWidgetItr != m_dockWidgets.end() || !widget) + { + return false; + } + + auto dockWidget = new AzQtComponents::StyledDockWidget(name.c_str()); + dockWidget->setObjectName(QString("%1_DockWidget").arg(name.c_str())); + dockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); + widget->setObjectName(name.c_str()); + widget->setParent(dockWidget); + widget->setMinimumSize(QSize(300, 300)); + dockWidget->setWidget(widget); + addDockWidget(aznumeric_cast(area), dockWidget); + resizeDocks({ dockWidget }, { 400 }, aznumeric_cast(orientation)); + m_dockWidgets[name] = dockWidget; + return true; + } + + void AtomToolsMainWindow::RemoveDockWidget(const AZStd::string& name) + { + auto dockWidgetItr = m_dockWidgets.find(name); + if (dockWidgetItr != m_dockWidgets.end()) + { + delete dockWidgetItr->second; + m_dockWidgets.erase(dockWidgetItr); + } + } + + void AtomToolsMainWindow::SetDockWidgetVisible(const AZStd::string& name, bool visible) + { + auto dockWidgetItr = m_dockWidgets.find(name); + if (dockWidgetItr != m_dockWidgets.end()) + { + dockWidgetItr->second->setVisible(visible); + } + } + + bool AtomToolsMainWindow::IsDockWidgetVisible(const AZStd::string& name) const + { + auto dockWidgetItr = m_dockWidgets.find(name); + if (dockWidgetItr != m_dockWidgets.end()) + { + return dockWidgetItr->second->isVisible(); + } + return false; + } + + AZStd::vector AtomToolsMainWindow::GetDockWidgetNames() const + { + AZStd::vector names; + names.reserve(m_dockWidgets.size()); + for (const auto& dockWidgetPair : m_dockWidgets) + { + names.push_back(dockWidgetPair.first); + } + return names; + } + + void AtomToolsMainWindow::CreateMenu() + { + m_menuBar = new QMenuBar(this); + m_menuBar->setObjectName("MenuBar"); + setMenuBar(m_menuBar); + } + + void AtomToolsMainWindow::CreateTabBar() + { + m_tabWidget = new AzQtComponents::TabWidget(m_centralWidget); + m_tabWidget->setObjectName("TabWidget"); + m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); + m_tabWidget->setContentsMargins(0, 0, 0, 0); + + // The tab bar should only be visible if it has active documents + m_tabWidget->setVisible(false); + m_tabWidget->setTabBarAutoHide(false); + m_tabWidget->setMovable(true); + m_tabWidget->setTabsClosable(true); + m_tabWidget->setUsesScrollButtons(true); + + // Add context menu for right-clicking on tabs + m_tabWidget->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); + connect( + m_tabWidget, &QWidget::customContextMenuRequested, this, + [this]() + { + OpenTabContextMenu(); + }); + } + + void AtomToolsMainWindow::AddTabForDocumentId( + const AZ::Uuid& documentId, const AZStd::string& label, const AZStd::string& toolTip, AZStd::function widgetCreator) + { + // Blocking signals from the tab bar so the currentChanged signal is not sent while a document is already being opened. + // This prevents the OnDocumentOpened notification from being sent recursively. + const QSignalBlocker blocker(m_tabWidget); + + // If a tab for this document already exists then select it instead of creating a new one + for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) + { + if (documentId == GetDocumentIdFromTab(tabIndex)) + { + m_tabWidget->setCurrentIndex(tabIndex); + m_tabWidget->repaint(); + return; + } + } + + const int tabIndex = m_tabWidget->addTab(widgetCreator(), label.c_str()); + + // The user can manually reorder tabs which will invalidate any association by index. + // We need to store the document ID with the tab using the tab instead of a separate mapping. + m_tabWidget->tabBar()->setTabData(tabIndex, QVariant(documentId.ToString())); + m_tabWidget->setTabToolTip(tabIndex, toolTip.c_str()); + m_tabWidget->setCurrentIndex(tabIndex); + m_tabWidget->setVisible(true); + m_tabWidget->repaint(); + } + + void AtomToolsMainWindow::RemoveTabForDocumentId(const AZ::Uuid& documentId) + { + // We are not blocking signals here because we want closing tabs to close the associated document + // and automatically select the next document. + for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) + { + if (documentId == GetDocumentIdFromTab(tabIndex)) + { + m_tabWidget->removeTab(tabIndex); + m_tabWidget->setVisible(m_tabWidget->count() > 0); + m_tabWidget->repaint(); + break; + } + } + } + + void AtomToolsMainWindow::UpdateTabForDocumentId( + const AZ::Uuid& documentId, const AZStd::string& label, const AZStd::string& toolTip, bool isModified) + { + // Whenever a document is opened, saved, or modified we need to update the tab label + if (!documentId.IsNull()) + { + // Because tab order and indexes can change from user interactions, we cannot store a map + // between a tab index and document ID. + // We must iterate over all of the tabs to find the one associated with this document. + for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) + { + if (documentId == GetDocumentIdFromTab(tabIndex)) + { + // We use an asterisk appended to the file name to denote modified document + const AZStd::string modifiedLabel = isModified ? label + " *" : label; + m_tabWidget->setTabText(tabIndex, modifiedLabel.c_str()); + m_tabWidget->setTabToolTip(tabIndex, toolTip.c_str()); + m_tabWidget->repaint(); + break; + } + } + } + } + + AZ::Uuid AtomToolsMainWindow::GetDocumentIdFromTab(const int tabIndex) const + { + const QVariant tabData = m_tabWidget->tabBar()->tabData(tabIndex); + if (!tabData.isNull()) + { + // We need to be able to convert between a UUID and a string to store and retrieve a document ID from the tab bar + const QString documentIdString = tabData.toString(); + const QByteArray documentIdBytes = documentIdString.toUtf8(); + const AZ::Uuid documentId(documentIdBytes.data(), documentIdBytes.size()); + return documentId; + } + return AZ::Uuid::CreateNull(); + } + + void AtomToolsMainWindow::OpenTabContextMenu() + { + } + + void AtomToolsMainWindow::SelectPreviousTab() + { + if (m_tabWidget->count() > 1) + { + // Adding count to wrap around when index <= 0 + m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + m_tabWidget->count() - 1) % m_tabWidget->count()); + } + } + + void AtomToolsMainWindow::SelectNextTab() + { + if (m_tabWidget->count() > 1) + { + m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + 1) % m_tabWidget->count()); + } + } +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 86fc3f5f5e..49e641eb9c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -24,6 +24,10 @@ set(FILES Include/AtomToolsFramework/Viewport/RenderViewportWidget.h Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h + Include/AtomToolsFramework/Window/AtomToolsMainWindow.h + Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h + Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h + Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h Source/Application/AtomToolsApplication.cpp Source/Communication/LocalServer.cpp Source/Communication/LocalSocket.cpp @@ -40,4 +44,5 @@ set(FILES Source/Util/Util.cpp Source/Viewport/RenderViewportWidget.cpp Source/Viewport/ModularViewportCameraController.cpp -) + Source/Window/AtomToolsMainWindow.cpp +) \ No newline at end of file diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h deleted file mode 100644 index 58eb662bd8..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace MaterialEditor -{ - //! MaterialEditorWindowFactoryRequestBus provides - class MaterialEditorWindowFactoryRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - /// Creates and shows the MaterialEditorWindow - virtual void CreateMaterialEditorWindow() = 0; - - //! Destroys material editor window and releases all cached assets - virtual void DestroyMaterialEditorWindow() = 0; - }; - using MaterialEditorWindowFactoryRequestBus = AZ::EBus; - -} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 6f1bdfb083..bdd9e6fbaf 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -6,48 +6,17 @@ * */ -#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 -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -AZ_POP_DISABLE_WARNING - namespace MaterialEditor { - //! This function returns the build system target name of "MaterialEditor + //! This function returns the build system target name of "MaterialEditor" AZStd::string MaterialEditorApplication::GetBuildTargetName() const { #if !defined(LY_CMAKE_TARGET) @@ -77,11 +46,6 @@ namespace MaterialEditor *AZ::SettingsRegistry::Get(), GetBuildTargetName()); } - MaterialEditorApplication::~MaterialEditorApplication() - { - MaterialEditorWindowNotificationBus::Handler::BusDisconnect(); - } - void MaterialEditorApplication::CreateStaticModules(AZStd::vector& outModules) { Base::CreateStaticModules(outModules); @@ -90,37 +54,14 @@ namespace MaterialEditor outModules.push_back(aznew MaterialEditorWindowModule); } - void MaterialEditorApplication::OnMaterialEditorWindowClosing() - { - ExitMainLoop(); - } - - void MaterialEditorApplication::Destroy() - { - // before modules are unloaded, destroy UI to free up any assets it cached - MaterialEditor::MaterialEditorWindowFactoryRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowFactoryRequestBus::Handler::DestroyMaterialEditorWindow); - - MaterialEditorWindowNotificationBus::Handler::BusDisconnect(); - - Base::Destroy(); - } - AZStd::vector MaterialEditorApplication::GetCriticalAssetFilters() const { - return AZStd::vector({ "passes/", "config/", "MaterialEditor" }); + return AZStd::vector({ "passes/", "config/", "MaterialEditor/" }); } void MaterialEditorApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { - const AZStd::string activateWindowSwitchName = "activatewindow"; - if (commandLine.HasSwitch(activateWindowSwitchName)) - { - MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); - } - - // Process command line options for opening one or more documents on startup + // Process command line options for opening one or more material documents on startup size_t openDocumentCount = commandLine.GetNumMiscValues(); for (size_t openDocumentIndex = 0; openDocumentIndex < openDocumentCount; ++openDocumentIndex) { @@ -132,22 +73,4 @@ namespace MaterialEditor Base::ProcessCommandLine(commandLine); } - - void MaterialEditorApplication::StartInternal() - { - Base::StartInternal(); - - MaterialEditorWindowNotificationBus::Handler::BusConnect(); - - MaterialEditor::MaterialEditorWindowFactoryRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowFactoryRequestBus::Handler::CreateMaterialEditorWindow); - } - - void MaterialEditorApplication::Stop() - { - MaterialEditor::MaterialEditorWindowFactoryRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowFactoryRequestBus::Handler::DestroyMaterialEditorWindow); - - Base::Stop(); - } } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index ec2a48288c..da691feff7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -9,18 +9,14 @@ #pragma once #include -#include #include -#include - namespace MaterialEditor { class MaterialThumbnailRenderer; class MaterialEditorApplication : public AtomToolsFramework::AtomToolsApplication - , private MaterialEditorWindowNotificationBus::Handler { public: AZ_TYPE_INFO(MaterialEditor::MaterialEditorApplication, "{30F90CA5-1253-49B5-8143-19CEE37E22BB}"); @@ -28,28 +24,15 @@ namespace MaterialEditor using Base = AtomToolsFramework::AtomToolsApplication; MaterialEditorApplication(int* argc, char*** argv); - virtual ~MaterialEditorApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application void CreateStaticModules(AZStd::vector& outModules) override; const char* GetCurrentConfigurationName() const override; - void Stop() override; private: - ////////////////////////////////////////////////////////////////////////// - // MaterialEditorWindowNotificationBus::Handler overrides... - void OnMaterialEditorWindowClosing() override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // AzFramework::Application overrides... - void Destroy() override; - ////////////////////////////////////////////////////////////////////////// - void ProcessCommandLine(const AZ::CommandLine& commandLine) override; - void StartInternal() override; AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; - }; + }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 47f2127405..f4dfa3df1b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -7,39 +7,27 @@ */ #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 AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT @@ -56,7 +44,7 @@ AZ_POP_DISABLE_WARNING namespace MaterialEditor { MaterialEditorWindow::MaterialEditorWindow(QWidget* parent /* = 0 */) - : AzQtComponents::DockMainWindow(parent) + : AtomToolsFramework::AtomToolsMainWindow(parent) { resize(1280, 1024); @@ -83,33 +71,19 @@ namespace MaterialEditor setWindowTitle(QApplication::applicationName()); } - m_advancedDockManager = new AzQtComponents::FancyDocking(this); - setObjectName("MaterialEditorWindow"); - setDockNestingEnabled(true); - setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); - setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); - - m_menuBar = new QMenuBar(this); - m_menuBar->setObjectName("MenuBar"); - setMenuBar(m_menuBar); m_toolBar = new MaterialEditorToolBar(this); m_toolBar->setObjectName("ToolBar"); addToolBar(m_toolBar); - m_centralWidget = new QWidget(this); - m_tabWidget = new AzQtComponents::TabWidget(m_centralWidget); - m_tabWidget->setObjectName("TabWidget"); - m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); - m_tabWidget->setContentsMargins(0, 0, 0, 0); - m_materialViewport = new MaterialViewportWidget(m_centralWidget); m_materialViewport->setObjectName("Viewport"); m_materialViewport->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + CreateMenu(); + CreateTabBar(); + QVBoxLayout* vl = new QVBoxLayout(m_centralWidget); vl->setMargin(0); vl->setContentsMargins(0, 0, 0, 0); @@ -118,13 +92,6 @@ namespace MaterialEditor m_centralWidget->setLayout(vl); setCentralWidget(m_centralWidget); - m_statusBar = new StatusBarWidget(this); - m_statusBar->setObjectName("StatusBar"); - statusBar()->addPermanentWidget(m_statusBar, 1); - - SetupMenu(); - SetupTabs(); - AddDockWidget("Asset Browser", new MaterialBrowserWidget, Qt::BottomDockWidgetArea, Qt::Vertical); AddDockWidget("Inspector", new MaterialInspector, Qt::RightDockWidgetArea, Qt::Horizontal); AddDockWidget("Viewport Settings", new ViewportSettingsInspector, Qt::LeftDockWidgetArea, Qt::Horizontal); @@ -148,7 +115,6 @@ namespace MaterialEditor m_advancedDockManager->restoreState(windowState); } - MaterialEditorWindowRequestBus::Handler::BusConnect(); MaterialDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); } @@ -156,76 +122,9 @@ namespace MaterialEditor MaterialEditorWindow::~MaterialEditorWindow() { MaterialDocumentNotificationBus::Handler::BusDisconnect(); - 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); - if (dockWidgetItr != m_dockWidgets.end() || !widget) - { - return false; - } - - auto dockWidget = new AzQtComponents::StyledDockWidget(name.c_str()); - dockWidget->setObjectName(QString("%1_DockWidget").arg(name.c_str())); - dockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); - widget->setObjectName(name.c_str()); - widget->setParent(dockWidget); - widget->setMinimumSize(QSize(300, 300)); - dockWidget->setWidget(widget); - addDockWidget(aznumeric_cast(area), dockWidget); - resizeDocks({ dockWidget }, { 400 }, aznumeric_cast(orientation)); - m_dockWidgets[name] = dockWidget; - return true; - } - - void MaterialEditorWindow::RemoveDockWidget(const AZStd::string& name) - { - auto dockWidgetItr = m_dockWidgets.find(name); - if (dockWidgetItr != m_dockWidgets.end()) - { - delete dockWidgetItr->second; - m_dockWidgets.erase(dockWidgetItr); - } - } - - void MaterialEditorWindow::SetDockWidgetVisible(const AZStd::string& name, bool visible) - { - auto dockWidgetItr = m_dockWidgets.find(name); - if (dockWidgetItr != m_dockWidgets.end()) - { - dockWidgetItr->second->setVisible(visible); - } - } - - bool MaterialEditorWindow::IsDockWidgetVisible(const AZStd::string& name) const - { - auto dockWidgetItr = m_dockWidgets.find(name); - if (dockWidgetItr != m_dockWidgets.end()) - { - return dockWidgetItr->second->isVisible(); - } - return false; - } - - AZStd::vector MaterialEditorWindow::GetDockWidgetNames() const - { - AZStd::vector names; - names.reserve(m_dockWidgets.size()); - for (const auto& dockWidgetPair : m_dockWidgets) - { - names.push_back(dockWidgetPair.first); - } - return names; } + void MaterialEditorWindow::ResizeViewportRenderTarget(uint32_t width, uint32_t height) { QSize requestedViewportSize = QSize(width, height) / devicePixelRatioF(); @@ -274,7 +173,8 @@ namespace MaterialEditor QByteArray windowState = m_advancedDockManager->saveState(); windowSettings->m_mainWindowState.assign(windowState.begin(), windowState.end()); - MaterialEditorWindowNotificationBus::Broadcast(&MaterialEditorWindowNotifications::OnMaterialEditorWindowClosing); + AtomToolsFramework::AtomToolsMainWindowNotificationBus::Broadcast( + &AtomToolsFramework::AtomToolsMainWindowNotifications::OnMainWindowClosing); } void MaterialEditorWindow::OnDocumentOpened(const AZ::Uuid& documentId) @@ -283,14 +183,31 @@ namespace MaterialEditor MaterialDocumentRequestBus::EventResult(isOpen, documentId, &MaterialDocumentRequestBus::Events::IsOpen); bool isSavable = false; MaterialDocumentRequestBus::EventResult(isSavable, documentId, &MaterialDocumentRequestBus::Events::IsSavable); + bool isModified = false; + MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); bool canUndo = false; MaterialDocumentRequestBus::EventResult(canUndo, documentId, &MaterialDocumentRequestBus::Events::CanUndo); bool canRedo = false; MaterialDocumentRequestBus::EventResult(canRedo, documentId, &MaterialDocumentRequestBus::Events::CanRedo); + AZStd::string absolutePath; + MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AZStd::string filename; + AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); // Update UI to display the new document - AddTabForDocumentId(documentId); - UpdateTabForDocumentId(documentId); + if (!documentId.IsNull() && isOpen) + { + // Create a new tab for the document ID and assign it's label to the file name of the document. + AddTabForDocumentId(documentId, filename, absolutePath, [this]{ + // The tab widget requires a dummy page per tab + auto contentWidget = new QWidget(m_centralWidget); + contentWidget->setContentsMargins(0, 0, 0, 0); + contentWidget->setFixedSize(0, 0); + return contentWidget; + }); + } + + UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); const bool hasTabs = m_tabWidget->count() > 0; @@ -330,7 +247,8 @@ namespace MaterialEditor const QString documentPath = GetDocumentPath(documentId); if (!documentPath.isEmpty()) { - m_statusBar->UpdateStatusInfo(QString("Material opened: %1").arg(documentPath)); + const QString status = QString("Material closed: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } } @@ -339,12 +257,19 @@ namespace MaterialEditor RemoveTabForDocumentId(documentId); const QString documentPath = GetDocumentPath(documentId); - m_statusBar->UpdateStatusInfo(QString("Material closed: %1").arg(documentPath)); + const QString status = QString("Material closed: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } void MaterialEditorWindow::OnDocumentModified(const AZ::Uuid& documentId) { - UpdateTabForDocumentId(documentId); + bool isModified = false; + MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); + AZStd::string absolutePath; + MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AZStd::string filename; + AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); + UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); } void MaterialEditorWindow::OnDocumentUndoStateChanged(const AZ::Uuid& documentId) @@ -362,14 +287,23 @@ namespace MaterialEditor void MaterialEditorWindow::OnDocumentSaved(const AZ::Uuid& documentId) { - UpdateTabForDocumentId(documentId); + bool isModified = false; + MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); + AZStd::string absolutePath; + MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); + AZStd::string filename; + AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); + UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); const QString documentPath = GetDocumentPath(documentId); - m_statusBar->UpdateStatusInfo(QString("Material saved: %1").arg(documentPath)); + const QString status = QString("Material closed: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } - void MaterialEditorWindow::SetupMenu() + void MaterialEditorWindow::CreateMenu() { + Base::CreateMenu(); + // Generating the main menu manually because it's easier and we will have some dynamic or data driven entries m_menuFile = m_menuBar->addMenu("&File"); @@ -407,7 +341,8 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - m_statusBar->UpdateStatusError(QString("Failed to save material: %1").arg(documentPath)); + const QString status = QString("Failed to save material: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } }, QKeySequence::Save); @@ -420,7 +355,8 @@ namespace MaterialEditor documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - m_statusBar->UpdateStatusError(QString("Failed to save material: %1").arg(documentPath)); + const QString status = QString("Failed to save material: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } }, QKeySequence::SaveAs); @@ -433,7 +369,8 @@ namespace MaterialEditor documentId, AtomToolsFramework::GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { - m_statusBar->UpdateStatusError(QString("Failed to save material: %1").arg(documentPath)); + const QString status = QString("Failed to save material: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } }); @@ -442,7 +379,8 @@ namespace MaterialEditor MaterialDocumentSystemRequestBus::BroadcastResult(result, &MaterialDocumentSystemRequestBus::Events::SaveAllDocuments); if (!result) { - m_statusBar->UpdateStatusError(QString("Failed to save materials.")); + const QString status = QString("Failed to save materials."); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } }); @@ -487,7 +425,8 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - m_statusBar->UpdateStatusError(QString("Failed to perform Undo in material: %1").arg(documentPath)); + const QString status = QString("Failed to perform Undo in material: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } }, QKeySequence::Undo); @@ -498,7 +437,8 @@ namespace MaterialEditor if (!result) { const QString documentPath = GetDocumentPath(documentId); - m_statusBar->UpdateStatusError(QString("Failed to perform Undo in material: %1").arg(documentPath)); + const QString status = QString("Failed to perform Undo in material: %1").arg(documentPath); + m_statusBar->setWindowIconText(QString("%1").arg(status)); } }, QKeySequence::Redo); @@ -561,20 +501,9 @@ namespace MaterialEditor }); } - void MaterialEditorWindow::SetupTabs() + void MaterialEditorWindow::CreateTabBar() { - // The tab bar should only be visible if it has active documents - m_tabWidget->setVisible(false); - m_tabWidget->setTabBarAutoHide(false); - m_tabWidget->setMovable(true); - m_tabWidget->setTabsClosable(true); - m_tabWidget->setUsesScrollButtons(true); - - // Add context menu for right-clicking on tabs - m_tabWidget->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); - connect(m_tabWidget, &QWidget::customContextMenuRequested, this, [this]() { - OpenTabContextMenu(); - }); + Base::CreateTabBar(); // This signal will be triggered whenever a tab is added, removed, selected, clicked, dragged // When the last tab is removed tabIndex will be -1 and the document ID will be null @@ -590,107 +519,6 @@ namespace MaterialEditor }); } - void MaterialEditorWindow::AddTabForDocumentId(const AZ::Uuid& documentId) - { - bool isOpen = false; - MaterialDocumentRequestBus::EventResult(isOpen, documentId, &MaterialDocumentRequestBus::Events::IsOpen); - - if (documentId.IsNull() || !isOpen) - { - return; - } - - // Blocking signals from the tab bar so the currentChanged signal is not sent while a document is already being opened. - // This prevents the OnDocumentOpened notification from being sent recursively. - const QSignalBlocker blocker(m_tabWidget); - - // If a tab for this document already exists then select it instead of creating a new one - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) - { - if (documentId == GetDocumentIdFromTab(tabIndex)) - { - m_tabWidget->setCurrentIndex(tabIndex); - m_tabWidget->repaint(); - return; - } - } - - // Create a new tab for the document ID and assign it's label to the file name of the document. - AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - - AZStd::string filename; - AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); - - // The tab widget requires a dummy page per tab - QWidget* placeHolderWidget = new QWidget(m_centralWidget); - placeHolderWidget->setContentsMargins(0, 0, 0, 0); - placeHolderWidget->resize(0, 0); - placeHolderWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - - const int tabIndex = m_tabWidget->addTab(placeHolderWidget, filename.c_str()); - - // The user can manually reorder tabs which will invalidate any association by index. - // We need to store the document ID with the tab using the tab instead of a separate mapping. - m_tabWidget->tabBar()->setTabData(tabIndex, QVariant(documentId.ToString())); - m_tabWidget->setTabToolTip(tabIndex, absolutePath.c_str()); - m_tabWidget->setCurrentIndex(tabIndex); - m_tabWidget->setVisible(true); - m_tabWidget->repaint(); - } - - void MaterialEditorWindow::RemoveTabForDocumentId(const AZ::Uuid& documentId) - { - // We are not blocking signals here because we want closing tabs to close the associated document - // and automatically select the next document. - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) - { - if (documentId == GetDocumentIdFromTab(tabIndex)) - { - m_tabWidget->removeTab(tabIndex); - m_tabWidget->setVisible(m_tabWidget->count() > 0); - m_tabWidget->repaint(); - break; - } - } - } - - void MaterialEditorWindow::UpdateTabForDocumentId(const AZ::Uuid& documentId) - { - // Whenever a document is opened, saved, or modified we need to update the tab label - if (!documentId.IsNull()) - { - // Because tab order and indexes can change from user interactions, we cannot store a map - // between a tab index and document ID. - // We must iterate over all of the tabs to find the one associated with this document. - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) - { - if (documentId == GetDocumentIdFromTab(tabIndex)) - { - AZStd::string absolutePath; - MaterialDocumentRequestBus::EventResult(absolutePath, documentId, &MaterialDocumentRequestBus::Events::GetAbsolutePath); - - AZStd::string filename; - AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); - - bool isModified = false; - MaterialDocumentRequestBus::EventResult(isModified, documentId, &MaterialDocumentRequestBus::Events::IsModified); - - // We use an asterisk appended to the file name to denote modified document - if (isModified) - { - filename += " *"; - } - - m_tabWidget->setTabText(tabIndex, filename.c_str()); - m_tabWidget->setTabToolTip(tabIndex, absolutePath.c_str()); - m_tabWidget->repaint(); - break; - } - } - } - } - QString MaterialEditorWindow::GetDocumentPath(const AZ::Uuid& documentId) const { AZStd::string absolutePath; @@ -698,20 +526,6 @@ namespace MaterialEditor return absolutePath.c_str(); } - AZ::Uuid MaterialEditorWindow::GetDocumentIdFromTab(const int tabIndex) const - { - const QVariant tabData = m_tabWidget->tabBar()->tabData(tabIndex); - if (!tabData.isNull()) - { - // We need to be able to convert between a UUID and a string to store and retrieve a document ID from the tab bar - const QString documentIdString = tabData.toString(); - const QByteArray documentIdBytes = documentIdString.toUtf8(); - const AZ::Uuid documentId(documentIdBytes.data(), documentIdBytes.size()); - return documentId; - } - return AZ::Uuid::CreateNull(); - } - void MaterialEditorWindow::OpenTabContextMenu() { const QTabBar* tabBar = m_tabWidget->tabBar(); @@ -738,23 +552,6 @@ namespace MaterialEditor tabMenu.exec(QCursor::pos()); } } - - void MaterialEditorWindow::SelectPreviousTab() - { - if (m_tabWidget->count() > 1) - { - // Adding count to wrap around when index <= 0 - m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + m_tabWidget->count() - 1) % m_tabWidget->count()); - } - } - - void MaterialEditorWindow::SelectNextTab() - { - if (m_tabWidget->count() > 1) - { - m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + 1) % m_tabWidget->count()); - } - } } // namespace MaterialEditor #include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index dac420ab21..43151b9c03 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -9,31 +9,16 @@ #pragma once #if !defined(Q_MOC_RUN) -#include #include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -#include -#include - -#include #include #include -#include - -#include -#include -#include AZ_POP_DISABLE_WARNING #endif -namespace AzToolsFramework -{ - class CScriptTermDialog; -} - namespace MaterialEditor { /** @@ -44,26 +29,19 @@ namespace MaterialEditor * 3) MaterialPropertyInspector - The user edits the properties of the selected Material. */ class MaterialEditorWindow - : public AzQtComponents::DockMainWindow - , private MaterialEditorWindowRequestBus::Handler + : public AtomToolsFramework::AtomToolsMainWindow , private MaterialDocumentNotificationBus::Handler { Q_OBJECT public: AZ_CLASS_ALLOCATOR(MaterialEditorWindow, AZ::SystemAllocator, 0); + using Base = AtomToolsFramework::AtomToolsMainWindow; + MaterialEditorWindow(QWidget* parent = 0); ~MaterialEditorWindow(); 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; - bool IsDockWidgetVisible(const AZStd::string& name) const override; - AZStd::vector GetDockWidgetNames() const override; - void ResizeViewportRenderTarget(uint32_t width, uint32_t height) override; void LockViewportRenderTargetSize(uint32_t width, uint32_t height) override; void UnlockViewportRenderTargetSize() override; @@ -75,30 +53,18 @@ namespace MaterialEditor void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override; void OnDocumentSaved(const AZ::Uuid& documentId) override; - void SetupMenu(); + void CreateMenu() override; + void CreateTabBar() override; - void SetupTabs(); - void AddTabForDocumentId(const AZ::Uuid& documentId); - void RemoveTabForDocumentId(const AZ::Uuid& documentId); - void UpdateTabForDocumentId(const AZ::Uuid& documentId); QString GetDocumentPath(const AZ::Uuid& documentId) const; - AZ::Uuid GetDocumentIdFromTab(const int tabIndex) const; - void OpenTabContextMenu(); - void SelectPreviousTab(); - void SelectNextTab(); + void OpenTabContextMenu() override; void closeEvent(QCloseEvent* closeEvent) override; - AzQtComponents::FancyDocking* m_advancedDockManager = nullptr; - QWidget* m_centralWidget = nullptr; - QMenuBar* m_menuBar = nullptr; - AzQtComponents::TabWidget* m_tabWidget = nullptr; MaterialViewportWidget* m_materialViewport = nullptr; MaterialEditorToolBar* m_toolBar = nullptr; - AZStd::unordered_map m_dockWidgets; - QMenu* m_menuFile = {}; QAction* m_actionNew = {}; QAction* m_actionOpen = {}; @@ -130,7 +96,5 @@ namespace MaterialEditor QMenu* m_menuHelp = {}; QAction* m_actionHelp = {}; QAction* m_actionAbout = {}; - - StatusBarWidget* m_statusBar = {}; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index 05641e8e55..8406ae891f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -6,8 +6,8 @@ * */ -#include -#include +#include +#include #include #include #include @@ -33,25 +33,25 @@ namespace MaterialEditor if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("MaterialEditorWindowFactoryRequestBus") + behaviorContext->EBus("MaterialEditorWindowAtomRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "materialeditor") - ->Event("CreateMaterialEditorWindow", &MaterialEditorWindowFactoryRequestBus::Events::CreateMaterialEditorWindow) - ->Event("DestroyMaterialEditorWindow", &MaterialEditorWindowFactoryRequestBus::Events::DestroyMaterialEditorWindow) + ->Event("CreateMaterialEditorWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) + ->Event("DestroyMaterialEditorWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) ; - behaviorContext->EBus("MaterialEditorWindowRequestBus") + behaviorContext->EBus("MaterialEditorWindowRequestBus") ->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) - ->Event("ResizeViewportRenderTarget", &MaterialEditorWindowRequestBus::Events::ResizeViewportRenderTarget) - ->Event("LockViewportRenderTargetSize", &MaterialEditorWindowRequestBus::Events::LockViewportRenderTargetSize) - ->Event("UnlockViewportRenderTargetSize", &MaterialEditorWindowRequestBus::Events::UnlockViewportRenderTargetSize) + ->Event("ActivateWindow", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::ActivateWindow) + ->Event("SetDockWidgetVisible", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::SetDockWidgetVisible) + ->Event("IsDockWidgetVisible", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::IsDockWidgetVisible) + ->Event("GetDockWidgetNames", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::GetDockWidgetNames) + ->Event("ResizeViewportRenderTarget", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::ResizeViewportRenderTarget) + ->Event("LockViewportRenderTargetSize", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::LockViewportRenderTargetSize) + ->Event("UnlockViewportRenderTargetSize", &AtomToolsFramework::AtomToolsMainWindowRequestBus::Events::UnlockViewportRenderTargetSize) ; } } @@ -80,26 +80,26 @@ namespace MaterialEditor void MaterialEditorWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - MaterialEditorWindowFactoryRequestBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusConnect(); AzToolsFramework::SourceControlConnectionRequestBus::Broadcast(&AzToolsFramework::SourceControlConnectionRequests::EnableSourceControl, true); } void MaterialEditorWindowComponent::Deactivate() { - MaterialEditorWindowFactoryRequestBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); m_window.reset(); } - void MaterialEditorWindowComponent::CreateMaterialEditorWindow() + void MaterialEditorWindowComponent::CreateMainWindow() { m_materialEditorBrowserInteractions.reset(aznew MaterialEditorBrowserInteractions); m_window.reset(aznew MaterialEditorWindow); } - void MaterialEditorWindowComponent::DestroyMaterialEditorWindow() + void MaterialEditorWindowComponent::DestroyMainWindow() { m_window.reset(); } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.h index c62e399236..87f6160089 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.h @@ -11,7 +11,7 @@ #include #include -#include +#include #include #include @@ -22,7 +22,7 @@ namespace MaterialEditor class MaterialEditorWindowComponent : public AZ::Component , private AzToolsFramework::EditorWindowRequestBus::Handler - , private MaterialEditorWindowFactoryRequestBus::Handler + , private AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler { public: AZ_COMPONENT(MaterialEditorWindowComponent, "{03976F19-3C74-49FE-A15F-7D3CADBA616C}"); @@ -35,9 +35,9 @@ namespace MaterialEditor private: //////////////////////////////////////////////////////////////////////// - // MaterialEditorWindowFactoryRequestBus::Handler overrides... - void CreateMaterialEditorWindow() override; - void DestroyMaterialEditorWindow() override; + // AtomToolsMainWindowFactoryRequestBus::Handler overrides... + void CreateMainWindow() override; + void DestroyMainWindow() override; //////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.cpp deleted file mode 100644 index 4f037ccc58..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.cpp +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include - -namespace MaterialEditor -{ - StatusBarWidget::StatusBarWidget(QWidget* parent) - : QWidget(parent) - , m_ui(new Ui::StatusBarWidget) - { - m_ui->setupUi(this); - } - - StatusBarWidget::~StatusBarWidget() = default; - - void StatusBarWidget::UpdateStatusInfo(const QString& status) - { - m_ui->m_statusLabel->setText(QString("%1").arg(status)); - } - void StatusBarWidget::UpdateStatusWarning(const QString& status) - { - m_ui->m_statusLabel->setText(QString("%1").arg(status)); - } - void StatusBarWidget::UpdateStatusError(const QString& status) - { - m_ui->m_statusLabel->setText(QString("%1").arg(status)); - } -} // namespace MaterialEditor - -#include diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.h deleted file mode 100644 index b637f41add..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#if !defined(Q_MOC_RUN) -#include - -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -AZ_POP_DISABLE_WARNING -#endif - -namespace Ui -{ - class StatusBarWidget; -} - -namespace MaterialEditor -{ - //! Status bar for MaterialEditor. - class StatusBarWidget - : public QWidget - { - Q_OBJECT - public: - StatusBarWidget(QWidget* parent = nullptr); - ~StatusBarWidget(); - - void UpdateStatusInfo(const QString& status); - void UpdateStatusWarning(const QString& status); - void UpdateStatusError(const QString& status); - - private: - QScopedPointer m_ui; - }; -} // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.ui b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.ui deleted file mode 100644 index e4f1d7a4b7..0000000000 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/StatusBar/StatusBarWidget.ui +++ /dev/null @@ -1,82 +0,0 @@ - - - StatusBarWidget - - - - 0 - 0 - 691 - 165 - - - - - 0 - 0 - - - - - 0 - 0 - - - - Status Bar - - - - 2 - - - 5 - - - 0 - - - 5 - - - 0 - - - - - - 0 - 0 - - - - - - - - - - - - - - Qt::Horizontal - - - QSizePolicy::MinimumExpanding - - - - 40 - 20 - - - - - - - - - - - diff --git a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake index f5891a5c2b..b814ad3f47 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake +++ b/Gems/Atom/Tools/MaterialEditor/Code/materialeditorwindow_files.cmake @@ -9,9 +9,6 @@ set(FILES Include/Atom/Window/MaterialEditorWindowModule.h Include/Atom/Window/MaterialEditorWindowSettings.h - Include/Atom/Window/MaterialEditorWindowNotificationBus.h - Include/Atom/Window/MaterialEditorWindowRequestBus.h - Include/Atom/Window/MaterialEditorWindowFactoryRequestBus.h Source/Window/MaterialEditorBrowserInteractions.h Source/Window/MaterialEditorBrowserInteractions.cpp Source/Window/MaterialEditorWindow.h @@ -48,9 +45,6 @@ set(FILES Source/Window/ToolBar/ModelPresetComboBox.cpp Source/Window/ToolBar/LightingPresetComboBox.h Source/Window/ToolBar/LightingPresetComboBox.cpp - Source/Window/StatusBar/StatusBarWidget.cpp - Source/Window/StatusBar/StatusBarWidget.h - Source/Window/StatusBar/StatusBarWidget.ui Source/Window/MaterialInspector/MaterialInspector.h Source/Window/MaterialInspector/MaterialInspector.cpp Source/Window/ViewportSettingsInspector/ViewportSettingsInspector.h diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowNotificationBus.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowNotificationBus.h deleted file mode 100644 index e74e81cf4b..0000000000 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowNotificationBus.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace ShaderManagementConsole -{ - class ShaderManagementConsoleWindowNotifications - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - virtual void OnShaderManagementConsoleWindowClosing() {}; - }; - using ShaderManagementConsoleWindowNotificationBus = AZ::EBus; - -} // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowRequestBus.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowRequestBus.h deleted file mode 100644 index a60b2c0e4c..0000000000 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Include/Atom/Window/ShaderManagementConsoleWindowRequestBus.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include - -namespace ShaderManagementConsole -{ - //! ShaderManagementConsoleWindowRequestBus provides - class ShaderManagementConsoleWindowRequests - : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - /// Creates and shows main window - virtual void CreateShaderManagementConsoleWindow() = 0; - - //! Destroys main window - virtual void DestroyShaderManagementConsoleWindow() = 0; - }; - using ShaderManagementConsoleWindowRequestBus = AZ::EBus; - -} // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index 947cf55050..313522a256 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -6,46 +6,16 @@ * */ -#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 -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -AZ_POP_DISABLE_WARNING - namespace ShaderManagementConsole { - //! This function returns the build system target name of "ShaderManagementConsole + //! This function returns the build system target name of "ShaderManagementConsole" AZStd::string ShaderManagementConsoleApplication::GetBuildTargetName() const { #if !defined(LY_CMAKE_TARGET) @@ -75,11 +45,6 @@ namespace ShaderManagementConsole *AZ::SettingsRegistry::Get(), GetBuildTargetName()); } - ShaderManagementConsoleApplication::~ShaderManagementConsoleApplication() - { - ShaderManagementConsoleWindowNotificationBus::Handler::BusDisconnect(); - } - void ShaderManagementConsoleApplication::CreateStaticModules(AZStd::vector& outModules) { Base::CreateStaticModules(outModules); @@ -87,22 +52,6 @@ namespace ShaderManagementConsole outModules.push_back(aznew ShaderManagementConsoleWindowModule); } - void ShaderManagementConsoleApplication::OnShaderManagementConsoleWindowClosing() - { - ExitMainLoop(); - } - - void ShaderManagementConsoleApplication::Destroy() - { - // before modules are unloaded, destroy UI to free up any assets it cached - ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Broadcast( - &ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Handler::DestroyShaderManagementConsoleWindow); - - ShaderManagementConsoleWindowNotificationBus::Handler::BusDisconnect(); - - Base::Destroy(); - } - AZStd::vector ShaderManagementConsoleApplication::GetCriticalAssetFilters() const { return AZStd::vector({ "passes/", "config/" }); @@ -117,27 +66,10 @@ namespace ShaderManagementConsole const AZStd::string openDocumentPath = commandLine.GetMiscValue(openDocumentIndex); AZ_Printf(GetBuildTargetName().c_str(), "Opening document: %s", openDocumentPath.c_str()); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); + ShaderManagementConsoleDocumentSystemRequestBus::Broadcast( + &ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } Base::ProcessCommandLine(commandLine); } - - void ShaderManagementConsoleApplication::StartInternal() - { - Base::StartInternal(); - - ShaderManagementConsoleWindowNotificationBus::Handler::BusConnect(); - - ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Broadcast( - &ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Handler::CreateShaderManagementConsoleWindow); - } - - void ShaderManagementConsoleApplication::Stop() - { - ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Broadcast( - &ShaderManagementConsole::ShaderManagementConsoleWindowRequestBus::Handler::DestroyShaderManagementConsoleWindow); - - Base::Stop(); - } } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index d0a2b800b2..24b2020dad 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -9,16 +9,12 @@ #pragma once #include -#include #include -#include - namespace ShaderManagementConsole { class ShaderManagementConsoleApplication : public AtomToolsFramework::AtomToolsApplication - , private ShaderManagementConsoleWindowNotificationBus::Handler { public: AZ_TYPE_INFO(ShaderManagementConsole::ShaderManagementConsoleApplication, "{A31B1AEB-4DA3-49CD-884A-CC998FF7546F}"); @@ -26,28 +22,15 @@ namespace ShaderManagementConsole using Base = AtomToolsFramework::AtomToolsApplication; ShaderManagementConsoleApplication(int* argc, char*** argv); - virtual ~ShaderManagementConsoleApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application void CreateStaticModules(AZStd::vector& outModules) override; const char* GetCurrentConfigurationName() const override; - void Stop() override; private: - ////////////////////////////////////////////////////////////////////////// - // ShaderManagementConsoleWindowNotificationBus::Handler overrides... - void OnShaderManagementConsoleWindowClosing() override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // AzFramework::Application overrides... - void Destroy() override; - ////////////////////////////////////////////////////////////////////////// - - void ProcessCommandLine(const AZ::CommandLine& commandLine) override; - void StartInternal() override; + void ProcessCommandLine(const AZ::CommandLine& commandLine); AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; - }; + }; } // namespace ShaderManagementConsole diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 3900720bf6..0a082f3c33 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -5,61 +5,47 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ - + #include - #include -#include - -#include #include #include #include + #include +#include #include #include -#include - -#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include -#include #include -#include -#include -#include -#include #include +#include #include +#include +#include +#include +#include AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole { ShaderManagementConsoleWindow::ShaderManagementConsoleWindow(QWidget* parent /* = 0 */) - : AzQtComponents::DockMainWindow(parent) + : AtomToolsFramework::AtomToolsMainWindow(parent) { setWindowTitle("Shader Management Console"); - m_advancedDockManager = new AzQtComponents::FancyDocking(this); - - setDockNestingEnabled(true); - setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); - setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); - setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); - - m_menuBar = new QMenuBar(this); - setMenuBar(m_menuBar); + setObjectName("ShaderManagementConsoleWindow"); m_toolBar = new ShaderManagementConsoleToolBar(this); + m_toolBar->setObjectName("ToolBar"); addToolBar(m_toolBar); - m_centralWidget = new QWidget(this); - m_tabWidget = new AzQtComponents::TabWidget(m_centralWidget); - m_tabWidget->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); - m_tabWidget->setContentsMargins(0, 0, 0, 0); + CreateMenu(); + CreateTabBar(); QVBoxLayout* vl = new QVBoxLayout(m_centralWidget); vl->setMargin(0); @@ -68,27 +54,8 @@ namespace ShaderManagementConsole m_centralWidget->setLayout(vl); setCentralWidget(m_centralWidget); - SetupMenu(); - SetupTabs(); - - m_assetBrowserDockWidget = new AzQtComponents::StyledDockWidget("Asset Browser"); - m_assetBrowserDockWidget->setObjectName(m_assetBrowserDockWidget->windowTitle()); - m_assetBrowserDockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); - m_assetBrowser = new ShaderManagementConsoleBrowserWidget(m_assetBrowserDockWidget); - m_assetBrowser->setMinimumSize(QSize(300, 300)); - m_assetBrowserDockWidget->setWidget(m_assetBrowser); - addDockWidget(Qt::BottomDockWidgetArea, m_assetBrowserDockWidget); - resizeDocks({ m_assetBrowserDockWidget }, { 400 }, Qt::Vertical); - - m_pythonTerminalDockWidget = new AzQtComponents::StyledDockWidget("Python Terminal"); - m_pythonTerminalDockWidget->setObjectName(m_pythonTerminalDockWidget->windowTitle()); - m_pythonTerminalDockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); - m_pythonTerminal = new AzToolsFramework::CScriptTermDialog(m_pythonTerminalDockWidget); - m_pythonTerminal->setMinimumSize(QSize(300, 300)); - m_pythonTerminalDockWidget->setWidget(m_pythonTerminal); - addDockWidget(Qt::BottomDockWidgetArea, m_pythonTerminalDockWidget); - resizeDocks({ m_pythonTerminalDockWidget }, { 400 }, Qt::Vertical); - m_pythonTerminalDockWidget->setVisible(false); + AddDockWidget("Asset Browser", new ShaderManagementConsoleBrowserWidget, Qt::BottomDockWidgetArea, Qt::Vertical); + AddDockWidget("Python Terminal", new AzToolsFramework::CScriptTermDialog, Qt::BottomDockWidgetArea, Qt::Horizontal); ShaderManagementConsoleDocumentNotificationBus::Handler::BusConnect(); OnDocumentOpened(AZ::Uuid::CreateNull()); @@ -109,7 +76,8 @@ namespace ShaderManagementConsole return; } - ShaderManagementConsoleWindowNotificationBus::Broadcast(&ShaderManagementConsoleWindowNotifications::OnShaderManagementConsoleWindowClosing); + AtomToolsFramework::AtomToolsMainWindowNotificationBus::Broadcast( + &AtomToolsFramework::AtomToolsMainWindowNotifications::OnMainWindowClosing); } void ShaderManagementConsoleWindow::OnDocumentOpened(const AZ::Uuid& documentId) @@ -118,14 +86,32 @@ namespace ShaderManagementConsole ShaderManagementConsoleDocumentRequestBus::EventResult(isOpen, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsOpen); bool isSavable = false; ShaderManagementConsoleDocumentRequestBus::EventResult(isSavable, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsSavable); + bool isModified = false; + ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); bool canUndo = false; ShaderManagementConsoleDocumentRequestBus::EventResult(canUndo, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::CanUndo); bool canRedo = false; ShaderManagementConsoleDocumentRequestBus::EventResult(canRedo, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::CanRedo); + AZStd::string absolutePath; + ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AZStd::string filename; + AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); // Update UI to display the new document - AddTabForDocumentId(documentId); - UpdateTabForDocumentId(documentId); + if (!documentId.IsNull() && isOpen) + { + // Create a new tab for the document ID and assign it's label to the file name of the document. + AddTabForDocumentId(documentId, filename, absolutePath, [this, documentId]{ + // The document tab contains a table view. + auto contentWidget = new QTableView(m_centralWidget); + contentWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + contentWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + contentWidget->setModel(CreateDocumentContent(documentId)); + return contentWidget; + }); + } + + UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); const bool hasTabs = m_tabWidget->count() > 0; @@ -144,7 +130,7 @@ namespace ShaderManagementConsole m_actionUndo->setEnabled(canUndo); m_actionRedo->setEnabled(canRedo); - m_actionPreferences->setEnabled(false); + m_actionSettings->setEnabled(false); m_actionAssetBrowser->setEnabled(true); m_actionPythonTerminal->setEnabled(true); @@ -165,7 +151,13 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::OnDocumentModified(const AZ::Uuid& documentId) { - UpdateTabForDocumentId(documentId); + bool isModified = false; + ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); + AZStd::string absolutePath; + ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AZStd::string filename; + AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); + UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); } void ShaderManagementConsoleWindow::OnDocumentUndoStateChanged(const AZ::Uuid& documentId) @@ -183,11 +175,19 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindow::OnDocumentSaved(const AZ::Uuid& documentId) { - UpdateTabForDocumentId(documentId); + bool isModified = false; + ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); + AZStd::string absolutePath; + ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); + AZStd::string filename; + AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); + UpdateTabForDocumentId(documentId, filename, absolutePath, isModified); } - void ShaderManagementConsoleWindow::SetupMenu() + void ShaderManagementConsoleWindow::CreateMenu() { + Base::CreateMenu(); + // Generating the main menu manually because it's easier and we will have some dynamic or data driven entries m_menuFile = m_menuBar->addMenu("&File"); @@ -264,23 +264,26 @@ namespace ShaderManagementConsole m_menuEdit->addSeparator(); - m_actionPreferences = m_menuEdit->addAction("&Preferences...", [this]() { + m_actionSettings = m_menuEdit->addAction("&Preferences...", [this]() { }, QKeySequence::Preferences); - m_actionPreferences->setEnabled(false); + m_actionSettings->setEnabled(false); m_menuView = m_menuBar->addMenu("&View"); - m_actionAssetBrowser = m_menuView->addAction("&Asset Browser", [this]() { - m_assetBrowserDockWidget->setVisible(!m_assetBrowserDockWidget->isVisible()); - }); + m_actionAssetBrowser = m_menuView->addAction( + "&Asset Browser", + [this]() + { + const AZStd::string label = "Asset Browser"; + SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); + }); - m_actionPythonTerminal = m_menuView->addAction("Python &Terminal", [this]() { - m_pythonTerminalDockWidget->setVisible(!m_pythonTerminalDockWidget->isVisible()); - if (m_pythonTerminalDockWidget->isVisible()) + m_actionPythonTerminal = m_menuView->addAction( + "Python &Terminal", + [this]() { - // reposition console window on the bottom, otherwise it gets docked in some weird spot... - addDockWidget(Qt::BottomDockWidgetArea, m_pythonTerminalDockWidget); - } + const AZStd::string label = "Python Terminal"; + SetDockWidgetVisible(label, !IsDockWidgetVisible(label)); }); m_menuView->addSeparator(); @@ -302,20 +305,9 @@ namespace ShaderManagementConsole }); } - void ShaderManagementConsoleWindow::SetupTabs() + void ShaderManagementConsoleWindow::CreateTabBar() { - // The tab bar should only be visible if it has active documents - m_tabWidget->setVisible(false); - m_tabWidget->setTabBarAutoHide(false); - m_tabWidget->setMovable(true); - m_tabWidget->setTabsClosable(true); - m_tabWidget->setUsesScrollButtons(true); - - // Add context menu for right-clicking on tabs - m_tabWidget->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); - connect(m_tabWidget, &QWidget::customContextMenuRequested, this, [this]() { - OpenTabContextMenu(); - }); + Base::CreateTabBar(); // This signal will be triggered whenever a tab is added, removed, selected, clicked, dragged // When the last tab is removed tabIndex will be -1 and the document ID will be null @@ -329,125 +321,6 @@ namespace ShaderManagementConsole }); } - void ShaderManagementConsoleWindow::AddTabForDocumentId(const AZ::Uuid& documentId) - { - bool isOpen = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isOpen, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsOpen); - - if (documentId.IsNull() || !isOpen) - { - return; - } - - // Blocking signals from the tab bar so the currentChanged signal is not sent while a document is already being opened. - // This prevents the OnDocumentOpened notification from being sent recursively. - const QSignalBlocker blocker(m_tabWidget); - - // If a tab for this document already exists then select it instead of creating a new one - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) - { - if (documentId == GetDocumentIdFromTab(tabIndex)) - { - m_tabWidget->setCurrentIndex(tabIndex); - m_tabWidget->repaint(); - return; - } - } - - // Create a new tab for the document ID and assign it's label to the file name of the document. - AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); - - AZStd::string filename; - AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); - - // The document tab contains a table view. - auto tableView = new QTableView(m_centralWidget); - tableView->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - tableView->setSelectionBehavior(QAbstractItemView::SelectRows); - - auto model = new QStandardItemModel(); - tableView->setModel(model); - - const int tabIndex = m_tabWidget->addTab(tableView, filename.c_str()); - - // The user can manually reorder tabs which will invalidate any association by index. - // We need to store the document ID with the tab using the tab instead of a separate mapping. - m_tabWidget->tabBar()->setTabData(tabIndex, QVariant(documentId.ToString())); - m_tabWidget->setTabToolTip(tabIndex, absolutePath.c_str()); - m_tabWidget->setCurrentIndex(tabIndex); - m_tabWidget->setVisible(true); - m_tabWidget->repaint(); - - CreateDocumentContent(documentId, model); - } - - void ShaderManagementConsoleWindow::RemoveTabForDocumentId(const AZ::Uuid& documentId) - { - // We are not blocking signals here because we want closing tabs to close the associated document - // and automatically select the next document. - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) - { - if (documentId == GetDocumentIdFromTab(tabIndex)) - { - m_tabWidget->removeTab(tabIndex); - m_tabWidget->setVisible(m_tabWidget->count() > 0); - m_tabWidget->repaint(); - break; - } - } - } - - void ShaderManagementConsoleWindow::UpdateTabForDocumentId(const AZ::Uuid& documentId) - { - // Whenever a document is opened, saved, or modified we need to update the tab label - if (!documentId.IsNull()) - { - // Because tab order and indexes can change from user interactions, we cannot store a map - // between a tab index and document ID. - // We must iterate over all of the tabs to find the one associated with this document. - for (int tabIndex = 0; tabIndex < m_tabWidget->count(); ++tabIndex) - { - if (documentId == GetDocumentIdFromTab(tabIndex)) - { - AZStd::string absolutePath; - ShaderManagementConsoleDocumentRequestBus::EventResult(absolutePath, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetAbsolutePath); - - AZStd::string filename; - AzFramework::StringFunc::Path::GetFullFileName(absolutePath.c_str(), filename); - - bool isModified = false; - ShaderManagementConsoleDocumentRequestBus::EventResult(isModified, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::IsModified); - - // We use an asterisk appended to the file name to denote modified document - if (isModified) - { - filename += " *"; - } - - m_tabWidget->setTabText(tabIndex, filename.c_str()); - m_tabWidget->setTabToolTip(tabIndex, absolutePath.c_str()); - m_tabWidget->repaint(); - break; - } - } - } - } - - AZ::Uuid ShaderManagementConsoleWindow::GetDocumentIdFromTab(const int tabIndex) const - { - const QVariant tabData = m_tabWidget->tabBar()->tabData(tabIndex); - if (!tabData.isNull()) - { - // We need to be able to convert between a UUID and a string to store and retrieve a document ID from the tab bar - const QString documentIdString = tabData.toString(); - const QByteArray documentIdBytes = documentIdString.toUtf8(); - const AZ::Uuid documentId(documentIdBytes.data(), documentIdBytes.size()); - return documentId; - } - return AZ::Uuid::CreateNull(); - } - void ShaderManagementConsoleWindow::OpenTabContextMenu() { const QTabBar* tabBar = m_tabWidget->tabBar(); @@ -472,23 +345,6 @@ namespace ShaderManagementConsole } } - void ShaderManagementConsoleWindow::SelectPreviousTab() - { - if (m_tabWidget->count() > 1) - { - // Adding count to wrap around when index <= 0 - m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + m_tabWidget->count() - 1) % m_tabWidget->count()); - } - } - - void ShaderManagementConsoleWindow::SelectNextTab() - { - if (m_tabWidget->count() > 1) - { - m_tabWidget->setCurrentIndex((m_tabWidget->currentIndex() + 1) % m_tabWidget->count()); - } - } - void ShaderManagementConsoleWindow::SelectDocumentForTab(const int tabIndex) { const AZ::Uuid documentId = GetDocumentIdFromTab(tabIndex); @@ -521,7 +377,7 @@ namespace ShaderManagementConsole } } - void ShaderManagementConsoleWindow::CreateDocumentContent(const AZ::Uuid& documentId, QStandardItemModel* model) + QStandardItemModel* ShaderManagementConsoleWindow::CreateDocumentContent(const AZ::Uuid& documentId) { AZStd::unordered_set optionNames; @@ -540,6 +396,7 @@ namespace ShaderManagementConsole size_t shaderVariantCount = 0; ShaderManagementConsoleDocumentRequestBus::EventResult(shaderVariantCount, documentId, &ShaderManagementConsoleDocumentRequestBus::Events::GetShaderVariantCount); + auto model = new QStandardItemModel(); model->setRowCount(static_cast(shaderVariantCount)); model->setColumnCount(static_cast(optionNames.size())); @@ -568,7 +425,9 @@ namespace ShaderManagementConsole model->setItem(variantIndex, optionIndex, item); } } + + return model; } } // namespace ShaderManagementConsole -#include +#include diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index 5ab94aa34e..aae31d1000 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -9,32 +9,20 @@ #pragma once #if !defined(Q_MOC_RUN) -#include #include - -#include #include +#include +#include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -#include -#include - #include #include -#include -#include #include AZ_POP_DISABLE_WARNING #endif -namespace AzToolsFramework -{ - class CScriptTermDialog; -} - namespace ShaderManagementConsole { /** @@ -42,13 +30,15 @@ namespace ShaderManagementConsole * its panels, managing selection of assets, and performing high-level actions like saving. It contains... */ class ShaderManagementConsoleWindow - : public AzQtComponents::DockMainWindow + : public AtomToolsFramework::AtomToolsMainWindow , private ShaderManagementConsoleDocumentNotificationBus::Handler { Q_OBJECT public: AZ_CLASS_ALLOCATOR(ShaderManagementConsoleWindow, AZ::SystemAllocator, 0); + using Base = AtomToolsFramework::AtomToolsMainWindow; + ShaderManagementConsoleWindow(QWidget* parent = 0); ~ShaderManagementConsoleWindow(); @@ -60,17 +50,9 @@ namespace ShaderManagementConsole void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override; void OnDocumentSaved(const AZ::Uuid& documentId) override; - void SetupMenu(); - - void SetupTabs(); - void AddTabForDocumentId(const AZ::Uuid& documentId); - void RemoveTabForDocumentId(const AZ::Uuid& documentId); - void UpdateTabForDocumentId(const AZ::Uuid& documentId); - AZ::Uuid GetDocumentIdFromTab(const int tabIndex) const; - - void OpenTabContextMenu(); - void SelectPreviousTab(); - void SelectNextTab(); + void CreateMenu() override; + void CreateTabBar() override; + void OpenTabContextMenu() override; void SelectDocumentForTab(const int tabIndex); void CloseDocumentForTab(const int tabIndex); @@ -78,18 +60,9 @@ namespace ShaderManagementConsole void closeEvent(QCloseEvent* closeEvent) override; - void CreateDocumentContent(const AZ::Uuid& documentId, QStandardItemModel* model); + QStandardItemModel* CreateDocumentContent(const AZ::Uuid& documentId); - AzQtComponents::FancyDocking* m_advancedDockManager = nullptr; - QMenuBar* m_menuBar = nullptr; - QWidget* m_centralWidget = nullptr; - AzQtComponents::TabWidget* m_tabWidget = nullptr; - ShaderManagementConsoleBrowserWidget* m_assetBrowser = nullptr; ShaderManagementConsoleToolBar* m_toolBar = nullptr; - AzToolsFramework::CScriptTermDialog* m_pythonTerminal = nullptr; - - AzQtComponents::StyledDockWidget* m_assetBrowserDockWidget = nullptr; - AzQtComponents::StyledDockWidget* m_pythonTerminalDockWidget = nullptr; QMenu* m_menuFile = {}; QMenu* m_menuNew = {}; @@ -106,7 +79,7 @@ namespace ShaderManagementConsole QMenu* m_menuEdit = {}; QAction* m_actionUndo = {}; QAction* m_actionRedo = {}; - QAction* m_actionPreferences = {}; + QAction* m_actionSettings = {}; QMenu* m_menuView = {}; QAction* m_actionAssetBrowser = {}; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp index 06c219f1cc..44715ef64f 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.cpp @@ -44,12 +44,12 @@ namespace ShaderManagementConsole if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("ShaderManagementConsoleWindowRequestBus") + behaviorContext->EBus("ShaderManagementConsoleWindowRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "shadermanagementconsole") - ->Event("CreateShaderManagementConsoleWindow", &ShaderManagementConsoleWindowRequestBus::Events::CreateShaderManagementConsoleWindow) - ->Event("DestroyShaderManagementConsoleWindow", &ShaderManagementConsoleWindowRequestBus::Events::DestroyShaderManagementConsoleWindow) + ->Event("CreateShaderManagementConsoleWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) + ->Event("DestroyShaderManagementConsoleWindow", &AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) ; behaviorContext->EBus("ShaderManagementConsoleRequestBus") @@ -87,7 +87,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Activate() { AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - ShaderManagementConsoleWindowRequestBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusConnect(); ShaderManagementConsoleRequestBus::Handler::BusConnect(); AzToolsFramework::SourceControlConnectionRequestBus::Broadcast(&AzToolsFramework::SourceControlConnectionRequests::EnableSourceControl, true); } @@ -95,7 +95,7 @@ namespace ShaderManagementConsole void ShaderManagementConsoleWindowComponent::Deactivate() { ShaderManagementConsoleRequestBus::Handler::BusDisconnect(); - ShaderManagementConsoleWindowRequestBus::Handler::BusDisconnect(); + AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); m_window.reset(); @@ -106,7 +106,7 @@ namespace ShaderManagementConsole return m_window.get(); } - void ShaderManagementConsoleWindowComponent::CreateShaderManagementConsoleWindow() + void ShaderManagementConsoleWindowComponent::CreateMainWindow() { m_assetBrowserInteractions.reset(aznew ShaderManagementConsoleBrowserInteractions); @@ -114,7 +114,7 @@ namespace ShaderManagementConsole m_window->show(); } - void ShaderManagementConsoleWindowComponent::DestroyShaderManagementConsoleWindow() + void ShaderManagementConsoleWindowComponent::DestroyMainWindow() { m_window.reset(); } diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.h index 472fc14efb..9b43babd9a 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindowComponent.h @@ -13,7 +13,7 @@ #include -#include +#include #include #include #include @@ -24,7 +24,7 @@ namespace ShaderManagementConsole //! used for initialization and registration of other classes, including ShaderManagementConsoleWindow. class ShaderManagementConsoleWindowComponent : public AZ::Component - , private ShaderManagementConsoleWindowRequestBus::Handler + , private AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler , private ShaderManagementConsoleRequestBus::Handler , private AzToolsFramework::EditorWindowRequestBus::Handler { @@ -51,9 +51,9 @@ namespace ShaderManagementConsole ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// - // ShaderManagementConsoleWindowRequestBus::Handler overrides... - void CreateShaderManagementConsoleWindow() override; - void DestroyShaderManagementConsoleWindow() override; + // AtomToolsMainWindowFactoryRequestBus::Handler overrides... + void CreateMainWindow() override; + void DestroyMainWindow() override; //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake index dad4f759d7..0d33d990a4 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/shadermanagementconsolewindow_files.cmake @@ -8,8 +8,6 @@ set(FILES Include/Atom/Window/ShaderManagementConsoleWindowModule.h - Include/Atom/Window/ShaderManagementConsoleWindowNotificationBus.h - Include/Atom/Window/ShaderManagementConsoleWindowRequestBus.h Include/Atom/Core/ShaderManagementConsoleRequestBus.h Source/Window/ShaderManagementConsoleBrowserInteractions.h Source/Window/ShaderManagementConsoleBrowserInteractions.cpp diff --git a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl index ae707a10a7..ffc9a60c00 100644 --- a/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl +++ b/Gems/Atom/Utils/Code/Include/Atom/Utils/ImGuiCpuProfiler.inl @@ -129,6 +129,34 @@ namespace AZ m_captureToFile = true; } + ImGui::SameLine(); + bool isInProgress = RHI::CpuProfiler::Get()->IsContinuousCaptureInProgress(); + if (ImGui::Button(isInProgress ? "End" : "Begin")) + { + if (isInProgress) + { + AZStd::sys_time_t timeNow = AZStd::GetTimeNowSecond(); + AZStd::string timeString; + AZStd::to_string(timeString, timeNow); + u64 currentTick = AZ::RPI::RPISystemInterface::Get()->GetCurrentTick(); + const AZStd::string frameDataFilePath = AZStd::string::format( + "@user@/CpuProfiler/%s_%llu.json", + timeString.c_str(), + currentTick); + char resolvedPath[AZ::IO::MaxPathLength]; + AZ::IO::FileIOBase::GetInstance()->ResolvePath(frameDataFilePath.c_str(), resolvedPath, AZ::IO::MaxPathLength); + m_lastCapturedFilePath = resolvedPath; + AZ::Render::ProfilingCaptureRequestBus::Broadcast( + &AZ::Render::ProfilingCaptureRequestBus::Events::EndContinuousCpuProfilingCapture, frameDataFilePath); + } + + else + { + AZ::Render::ProfilingCaptureRequestBus::Broadcast( + &AZ::Render::ProfilingCaptureRequestBus::Events::BeginContinuousCpuProfilingCapture); + } + } + if (!m_lastCapturedFilePath.empty()) { ImGui::SameLine(); diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp index 608635b395..8d247eaf45 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp @@ -58,8 +58,8 @@ namespace const AZ::RHI::Format BoneIndexFormat = AZ::RHI::Format::R32G32B32A32_UINT; const AZ::RHI::Format BoneWeightFormat = AZ::RHI::Format::R32G32B32A32_FLOAT; - const size_t LinearSkinningFloatsPerBone = 12; - const size_t DualQuaternionSkinningFloatsPerBone = 8; + const uint32_t LinearSkinningFloatsPerBone = 12; + const uint32_t DualQuaternionSkinningFloatsPerBone = 8; const uint32_t MaxSupportedSkinInfluences = 4; } @@ -266,7 +266,7 @@ namespace AZ } } - static void ProcessMorphsForLod(const EMotionFX::Actor* actor, const Data::Asset& morphBufferAsset, uint32_t lodIndex, const AZStd::string& fullFileName, SkinnedMeshInputLod& skinnedMeshLod) + static void ProcessMorphsForLod(const EMotionFX::Actor* actor, const Data::Asset& morphBufferAsset, size_t lodIndex, const AZStd::string& fullFileName, SkinnedMeshInputLod& skinnedMeshLod) { EMotionFX::MorphSetup* morphSetup = actor->GetMorphSetup(lodIndex); if (morphSetup) @@ -275,8 +275,8 @@ namespace AZ const AZStd::vector& metaDatas = actor->GetMorphTargetMetaAsset()->GetMorphTargets(); // Loop over all the EMotionFX morph targets - const AZ::u32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (AZ::u32 morphTargetIndex = 0; morphTargetIndex < numMorphTargets; ++morphTargetIndex) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t morphTargetIndex = 0; morphTargetIndex < numMorphTargets; ++morphTargetIndex) { EMotionFX::MorphTargetStandard* morphTarget = static_cast(morphSetup->GetMorphTarget(morphTargetIndex)); for (const auto& metaData : metaDatas) @@ -288,7 +288,7 @@ namespace AZ if (metaData.m_morphTargetName == morphTarget->GetNameString() && metaData.m_numVertices > 0) { // The skinned mesh lod gets a unique morph for each meta, since each one has unique min/max delta values to use for decompression - AZStd::string morphString = AZStd::string::format("%s_Lod%u_Morph_%s", fullFileName.c_str(), lodIndex, metaData.m_meshNodeName.c_str()); + const AZStd::string morphString = AZStd::string::format("%s_Lod%zu_Morph_%s", fullFileName.c_str(), lodIndex, metaData.m_meshNodeName.c_str()); float minWeight = morphTarget->GetRangeMin(); float maxWeight = morphTarget->GetRangeMax(); @@ -562,8 +562,8 @@ namespace AZ for (size_t i = 0; i < numBoneTransforms; ++i) { MCore::DualQuaternion dualQuat = MCore::DualQuaternion::ConvertFromTransform(AZ::Transform::CreateFromMatrix3x4(skinningMatrices[i])); - dualQuat.mReal.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone]); - dualQuat.mDual.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone + 4]); + dualQuat.m_real.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone]); + dualQuat.m_dual.StoreToFloat4(&boneTransforms[i * DualQuaternionSkinningFloatsPerBone + 4]); } } } @@ -574,7 +574,7 @@ namespace AZ AZStd::vector boneTransforms; GetBoneTransformsFromActorInstance(actorInstance, boneTransforms, skinningMethod); - size_t floatsPerBone = 0; + uint32_t floatsPerBone = 0; if (skinningMethod == EMotionFX::Integration::SkinningMethod::Linear) { floatsPerBone = LinearSkinningFloatsPerBone; diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp index 0cb8cf5ccd..d5a48b900d 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -83,10 +83,10 @@ namespace AZ // Update RenderActorInstance world bounding box // The bounding box is moving with the actor instance. // The entity and actor transforms are kept in sync already. - m_worldAABB = AZ::Aabb::CreateFromMinMax(m_actorInstance->GetAABB().GetMin(), m_actorInstance->GetAABB().GetMax()); + m_worldAABB = m_actorInstance->GetAabb(); // Update RenderActorInstance local bounding box - // NB: computing the local bbox from the world bbox makes the local bbox artifically larger than it should be + // NB: computing the local bbox from the world bbox makes the local bbox artificially larger than it should be // instead EMFX should support getting the local bbox from the actor instance directly m_localAABB = m_worldAABB.GetTransformedAabb(m_transformInterface->GetWorldTM().GetInverse()); @@ -107,9 +107,8 @@ namespace AZ { if (debugOptions.m_drawAABB) { - const MCore::AABB emfxAabb = m_actorInstance->GetAABB(); - const AZ::Aabb azAabb = AZ::Aabb::CreateFromMinMax(emfxAabb.GetMin(), emfxAabb.GetMax()); - auxGeom->DrawAabb(azAabb, AZ::Color(0.0f, 1.0f, 1.0f, 1.0f), RPI::AuxGeomDraw::DrawStyle::Line); + const AZ::Aabb& aabb = m_actorInstance->GetAabb(); + auxGeom->DrawAabb(aabb, AZ::Color(0.0f, 1.0f, 1.0f, 1.0f), RPI::AuxGeomDraw::DrawStyle::Line); } if (debugOptions.m_drawSkeleton) @@ -132,14 +131,13 @@ namespace AZ const EMotionFX::Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton(); const EMotionFX::Pose* pose = transformData->GetCurrentPose(); - const AZ::u32 transformCount = transformData->GetNumTransforms(); - const AZ::u32 lodLevel = m_actorInstance->GetLODLevel(); - const AZ::u32 numJoints = skeleton->GetNumNodes(); + const size_t lodLevel = m_actorInstance->GetLODLevel(); + const size_t numJoints = skeleton->GetNumNodes(); m_auxVertices.clear(); m_auxVertices.reserve(numJoints * 2); - for (AZ::u32 jointIndex = 0; jointIndex < numJoints; ++jointIndex) + for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { const EMotionFX::Node* joint = skeleton->GetNode(jointIndex); if (!joint->GetSkeletalLODStatus(lodLevel)) @@ -147,23 +145,23 @@ namespace AZ continue; } - const AZ::u32 parentIndex = joint->GetParentIndex(); - if (parentIndex == InvalidIndex32) + const size_t parentIndex = joint->GetParentIndex(); + if (parentIndex == InvalidIndex) { continue; } - const AZ::Vector3 parentPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; + const AZ::Vector3 parentPos = pose->GetWorldSpaceTransform(parentIndex).m_position; m_auxVertices.emplace_back(parentPos); - const AZ::Vector3 bonePos = pose->GetWorldSpaceTransform(jointIndex).mPosition; + const AZ::Vector3 bonePos = pose->GetWorldSpaceTransform(jointIndex).m_position; m_auxVertices.emplace_back(bonePos); } const AZ::Color skeletonColor(0.604f, 0.804f, 0.196f, 1.0f); RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments lineArgs; lineArgs.m_verts = m_auxVertices.data(); - lineArgs.m_vertCount = static_cast(m_auxVertices.size()); + lineArgs.m_vertCount = aznumeric_caster(m_auxVertices.size()); lineArgs.m_colors = &skeletonColor; lineArgs.m_colorCount = 1; lineArgs.m_depthTest = RPI::AuxGeomDraw::DepthTest::Off; @@ -204,9 +202,9 @@ namespace AZ RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments lineArgs; lineArgs.m_verts = m_auxVertices.data(); - lineArgs.m_vertCount = static_cast(m_auxVertices.size()); + lineArgs.m_vertCount = aznumeric_caster(m_auxVertices.size()); lineArgs.m_colors = m_auxColors.data(); - lineArgs.m_colorCount = static_cast(m_auxColors.size()); + lineArgs.m_colorCount = aznumeric_caster(m_auxColors.size()); lineArgs.m_depthTest = RPI::AuxGeomDraw::DepthTest::Off; auxGeom->DrawLines(lineArgs); } @@ -451,13 +449,13 @@ namespace AZ AZ::u32 AtomActorInstance::GetJointCount() { - return m_actorInstance->GetActor()->GetSkeleton()->GetNumNodes(); + return aznumeric_caster(m_actorInstance->GetActor()->GetSkeleton()->GetNumNodes()); } const char* AtomActorInstance::GetJointNameByIndex(AZ::u32 jointIndex) { EMotionFX::Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton(); - const AZ::u32 numNodes = skeleton->GetNumNodes(); + const size_t numNodes = skeleton->GetNumNodes(); if (jointIndex < numNodes) { return skeleton->GetNode(jointIndex)->GetName(); @@ -471,12 +469,12 @@ namespace AZ if (jointName) { EMotionFX::Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton(); - const AZ::u32 numNodes = skeleton->GetNumNodes(); - for (AZ::u32 nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) { if (0 == azstricmp(jointName, skeleton->GetNode(nodeIndex)->GetName())) { - return nodeIndex; + return aznumeric_caster(nodeIndex); } } } @@ -585,7 +583,8 @@ namespace AZ // Update the morph weights for every lod. This does not mean they will all be dispatched, but they will all have up to date weights // TODO: once culling is hooked up such that EMotionFX and Atom are always in sync about which lod to update, only update the currently visible lods [ATOM-13564] - for (uint32_t lodIndex = 0; lodIndex < m_actorInstance->GetActor()->GetNumLODLevels(); ++lodIndex) + const auto lodCount = aznumeric_cast(m_actorInstance->GetActor()->GetNumLODLevels()); + for (uint32_t lodIndex = 0; lodIndex < lodCount; ++lodIndex) { EMotionFX::MorphSetup* morphSetup = m_actorInstance->GetActor()->GetMorphSetup(lodIndex); if (morphSetup) @@ -594,9 +593,9 @@ namespace AZ m_wrinkleMasks.clear(); m_wrinkleMaskWeights.clear(); - uint32_t morphTargetCount = morphSetup->GetNumMorphTargets(); + size_t morphTargetCount = morphSetup->GetNumMorphTargets(); m_morphTargetWeights.clear(); - for (uint32_t morphTargetIndex = 0; morphTargetIndex < morphTargetCount; ++morphTargetIndex) + for (size_t morphTargetIndex = 0; morphTargetIndex < morphTargetCount; ++morphTargetIndex) { EMotionFX::MorphTarget* morphTarget = morphSetup->GetMorphTarget(morphTargetIndex); // check if we are dealing with a standard morph target @@ -612,11 +611,11 @@ namespace AZ // Each morph target is split into several deform datas, all of which share the same weight but have unique min/max delta values // and thus correspond with unique dispatches in the morph target pass - for (uint32_t deformDataIndex = 0; deformDataIndex < morphTargetStandard->GetNumDeformDatas(); ++deformDataIndex) + for (size_t deformDataIndex = 0; deformDataIndex < morphTargetStandard->GetNumDeformDatas(); ++deformDataIndex) { // Morph targets that don't deform any vertices (e.g. joint-based morph targets) are not registered in the render proxy. Skip adding their weights. const EMotionFX::MorphTargetStandard::DeformData* deformData = morphTargetStandard->GetDeformData(deformDataIndex); - if (deformData->mNumVerts > 0) + if (deformData->m_numVerts > 0) { float weight = morphTargetSetupInstance->GetWeight(); m_morphTargetWeights.push_back(weight); @@ -817,8 +816,8 @@ namespace AZ { const AZStd::vector& metaDatas = actor->GetMorphTargetMetaAsset()->GetMorphTargets(); // Loop over all the EMotionFX morph targets - uint32_t numMorphTargets = morphSetup->GetNumMorphTargets(); - for (uint32_t morphTargetIndex = 0; morphTargetIndex < numMorphTargets; ++morphTargetIndex) + size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t morphTargetIndex = 0; morphTargetIndex < numMorphTargets; ++morphTargetIndex) { EMotionFX::MorphTargetStandard* morphTarget = static_cast(morphSetup->GetMorphTarget(morphTargetIndex)); for (const RPI::MorphTargetMetaAsset::MorphTarget& metaData : metaDatas) @@ -862,7 +861,7 @@ namespace AZ // Set the weights for any active masks for (size_t i = 0; i < m_wrinkleMaskWeights.size(); ++i) { - wrinkleMaskObjectSrg->SetConstant(wrinkleMaskWeightsIndex, m_wrinkleMaskWeights[i], static_cast(i)); + wrinkleMaskObjectSrg->SetConstant(wrinkleMaskWeightsIndex, m_wrinkleMaskWeights[i], aznumeric_caster(i)); } AZ_Error("AtomActorInstance", m_wrinkleMaskWeights.size() <= s_maxActiveWrinkleMasks, "The skinning shader supports no more than %d active morph targets with wrinkle masks.", s_maxActiveWrinkleMasks); } diff --git a/Gems/AudioEngineWwise/Code/Source/Editor/AudioWwiseLoader.cpp b/Gems/AudioEngineWwise/Code/Source/Editor/AudioWwiseLoader.cpp index 616a30994c..19038dc54c 100644 --- a/Gems/AudioEngineWwise/Code/Source/Editor/AudioWwiseLoader.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Editor/AudioWwiseLoader.cpp @@ -54,7 +54,9 @@ namespace AudioControls //-------------------------------------------------------------------------------------------// void CAudioWwiseLoader::LoadSoundBanks(const AZStd::string_view rootFolder, const AZStd::string_view subPath, bool isLocalized) { - auto foundFiles = Audio::FindFilesInPath(rootFolder, "*"); + AZ::IO::FixedMaxPath searchPath(rootFolder); + searchPath /= subPath; + auto foundFiles = Audio::FindFilesInPath(searchPath.Native(), "*"); bool isLocalizedLoaded = isLocalized; for (const auto& filePath : foundFiles) @@ -71,7 +73,7 @@ namespace AudioControls // same content (in the future we want to have a // consistency report to highlight if this is not the case) m_localizationFolder.assign(fileName.Native().data(), fileName.Native().size()); - LoadSoundBanks(rootFolder, m_localizationFolder, true); + LoadSoundBanks(searchPath.Native(), m_localizationFolder, true); isLocalizedLoaded = true; } } diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp index 4095e3bf84..e4933728d4 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp @@ -2173,16 +2173,7 @@ namespace Audio { if (language) { - AZStd::string languageSubfolder; - - if (azstricmp(language, "english") == 0) - { - languageSubfolder = "english(us)"; - } - else - { - languageSubfolder = language; - } + AZStd::string languageSubfolder(language); languageSubfolder += "/"; diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp index 9571dd86a9..30084565d6 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/FileIOHandler_wwise.cpp @@ -69,7 +69,7 @@ namespace Audio AkDeviceSettings deviceSettings; AK::StreamMgr::GetDefaultDeviceSettings(deviceSettings); - deviceSettings.uIOMemorySize = poolSize; + deviceSettings.uIOMemorySize = aznumeric_cast(poolSize); deviceSettings.uSchedulerTypeFlags = AK_SCHEDULER_BLOCKING; Platform::SetThreadProperties(deviceSettings.threadProperties); @@ -198,7 +198,7 @@ namespace Audio deviceDesc.bCanWrite = true; deviceDesc.deviceID = m_deviceID; AK_CHAR_TO_UTF16(deviceDesc.szDeviceName, "IO::IArchive", AZ_ARRAY_SIZE(deviceDesc.szDeviceName)); - deviceDesc.uStringSize = AKPLATFORM::AkUtf16StrLen(deviceDesc.szDeviceName); + deviceDesc.uStringSize = aznumeric_cast(AKPLATFORM::AkUtf16StrLen(deviceDesc.szDeviceName)); } AkUInt32 CBlockingDevice_wwise::GetDeviceData() @@ -219,7 +219,7 @@ namespace Audio AkDeviceSettings deviceSettings; AK::StreamMgr::GetDefaultDeviceSettings(deviceSettings); - deviceSettings.uIOMemorySize = poolSize; + deviceSettings.uIOMemorySize = aznumeric_cast(poolSize); deviceSettings.uSchedulerTypeFlags = AK_SCHEDULER_DEFERRED_LINED_UP; Platform::SetThreadProperties(deviceSettings.threadProperties); @@ -336,7 +336,7 @@ namespace Audio deviceDesc.bCanWrite = false; deviceDesc.deviceID = m_deviceID; AK_CHAR_TO_UTF16(deviceDesc.szDeviceName, "IO::IStreamer", AZ_ARRAY_SIZE(deviceDesc.szDeviceName)); - deviceDesc.uStringSize = AKPLATFORM::AkUtf16StrLen(deviceDesc.szDeviceName); + deviceDesc.uStringSize = aznumeric_cast(AKPLATFORM::AkUtf16StrLen(deviceDesc.szDeviceName)); } AkUInt32 CStreamingDevice_wwise::GetDeviceData() diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControl.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControl.cpp index ce268022a8..c0a8fb8dde 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControl.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControl.cpp @@ -345,7 +345,7 @@ namespace AudioControls { for (auto& connectionNode : m_connectionNodes) { - if (TConnectionPtr connection = audioSystemImpl->CreateConnectionFromXMLNode(connectionNode.m_xmlNode.get(), m_type)) + if (TConnectionPtr connection = audioSystemImpl->CreateConnectionFromXMLNode(connectionNode.m_xmlNode, m_type)) { AddConnection(connection); connectionNode.m_isValid = true; diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControl.h b/Gems/AudioSystem/Code/Source/Editor/AudioControl.h index 37e67c815c..024e8eb6df 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControl.h +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControl.h @@ -25,46 +25,48 @@ namespace AudioControls { SRawConnectionData(AZ::rapidxml::xml_node* node, bool isValid) { - m_xmlNode = AZStd::move(DeepCopyNode(node)); + m_xmlNode = DeepCopyNode(node); m_isValid = isValid; } - AZStd::unique_ptr> m_xmlNode{}; + AZ::rapidxml::xml_node* m_xmlNode = nullptr; // indicates if the connection is valid for the currently loaded middleware bool m_isValid{ false }; + private: // Rapid XML provides a 'clone_node' utility that will copy an entire node tree, // but it only copies pointers of any strings in the node names and values. - // This causes problems with storing raw xml nodes as this class does because strings - // will be pointing into the memory pool of an xml document that has gone out of scope. + // This causes problems with storage of xml trees, as this class does, because strings + // will be pointing into an xml document's file buffer that has gone out of scope. // This function is a rewritten version of 'clone_node' that does the deep copy of strings // into the new destination tree. - [[nodiscard]] static AZStd::unique_ptr> DeepCopyNode(AZ::rapidxml::xml_node* srcNode) + [[nodiscard]] AZ::rapidxml::xml_node* DeepCopyNode(AZ::rapidxml::xml_node* srcNode) { - AZStd::unique_ptr> destNode; - if (srcNode) + if (!srcNode) + { + return nullptr; + } + + XmlAllocator& xmlAlloc(AudioControls::s_xmlAllocator); + AZ::rapidxml::xml_node* destNode = xmlAlloc.allocate_node(srcNode->type()); + + destNode->name(xmlAlloc.allocate_string(srcNode->name(), srcNode->name_size()), srcNode->name_size()); + destNode->value(xmlAlloc.allocate_string(srcNode->value(), srcNode->value_size()), srcNode->value_size()); + + for (AZ::rapidxml::xml_node* child = srcNode->first_node(); child != nullptr; child = child->next_sibling()) + { + destNode->append_node(DeepCopyNode(child)); + } + + for (AZ::rapidxml::xml_attribute* attr = srcNode->first_attribute(); attr != nullptr; attr = attr->next_attribute()) { - XmlAllocator& xmlAlloc(AudioControls::s_xmlAllocator); - destNode.reset(xmlAlloc.allocate_node(srcNode->type())); - - destNode->name(xmlAlloc.allocate_string(srcNode->name(), srcNode->name_size()), srcNode->name_size()); - destNode->value(xmlAlloc.allocate_string(srcNode->value(), srcNode->value_size()), srcNode->value_size()); - - for (AZ::rapidxml::xml_node* child = srcNode->first_node(); child != nullptr; child = child->next_sibling()) - { - destNode->append_node(DeepCopyNode(child).release()); - } - - for (AZ::rapidxml::xml_attribute* attr = srcNode->first_attribute(); attr != nullptr; attr = attr->next_attribute()) - { - destNode->append_attribute(xmlAlloc.allocate_attribute( - xmlAlloc.allocate_string(attr->name(), attr->name_size()), - xmlAlloc.allocate_string(attr->value(), attr->value_size()), - attr->name_size(), - attr->value_size() - )); - } + destNode->append_attribute(xmlAlloc.allocate_attribute( + xmlAlloc.allocate_string(attr->name(), attr->name_size()), + xmlAlloc.allocate_string(attr->value(), attr->value_size()), + attr->name_size(), + attr->value_size() + )); } return destNode; diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp index b318cea128..2b7023df61 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControlsEditorPlugin.cpp @@ -23,6 +23,8 @@ #include #include +#include + using namespace AudioControls; @@ -148,18 +150,24 @@ void CAudioControlsEditorPlugin::ExecuteTrigger(const AZStd::string_view sTrigge Audio::AudioSystemRequestBus::BroadcastResult(ms_nAudioTriggerID, &Audio::AudioSystemRequestBus::Events::GetAudioTriggerID, sTriggerName.data()); if (ms_nAudioTriggerID != INVALID_AUDIO_CONTROL_ID) { + AZ::Transform activeCameraTm = AZ::Transform::CreateIdentity(); + Camera::ActiveCameraRequestBus::BroadcastResult( + activeCameraTm, + &Camera::ActiveCameraRequestBus::Events::GetActiveCameraTransform + ); + const AZ::Matrix3x4 cameraMatrix = AZ::Matrix3x4::CreateFromTransform(activeCameraTm); + Audio::SAudioRequest request; request.nFlags = Audio::eARF_PRIORITY_NORMAL; - const AZ::Matrix3x4 listenerTxfm = AZ::Matrix3x4::CreateIdentity(); - Audio::SAudioListenerRequestData requestData(listenerTxfm); + Audio::SAudioListenerRequestData requestData(cameraMatrix); requestData.oNewPosition.NormalizeForwardVec(); requestData.oNewPosition.NormalizeUpVec(); request.pData = &requestData; Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequest, request); - ms_pIAudioProxy->SetPosition(listenerTxfm); + ms_pIAudioProxy->SetPosition(cameraMatrix); ms_pIAudioProxy->ExecuteTrigger(ms_nAudioTriggerID); } } diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControlsLoader.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControlsLoader.cpp index 220cd32b5c..30889e33f0 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControlsLoader.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControlsLoader.cpp @@ -475,7 +475,7 @@ namespace AudioControls control->AddConnection(connection); } - control->m_connectionNodes.push_back(SRawConnectionData(childNode, connection != nullptr)); + control->m_connectionNodes.emplace_back(childNode, connection != nullptr); childNode = childNode->next_sibling(); } @@ -517,7 +517,7 @@ namespace AudioControls { control->AddConnection(connection); } - control->m_connectionNodes.push_back(SRawConnectionData(connectionNode, connection != nullptr)); + control->m_connectionNodes.emplace_back(connectionNode, connection != nullptr); connectionNode = connectionNode->next_sibling(); } configGroupNode = configGroupNode->next_sibling(); @@ -534,7 +534,7 @@ namespace AudioControls { control->AddConnection(connection); } - control->m_connectionNodes.push_back(SRawConnectionData(connectionNode, connection != nullptr)); + control->m_connectionNodes.emplace_back(connectionNode, connection != nullptr); connectionNode = connectionNode->next_sibling(); } } @@ -576,7 +576,7 @@ namespace AudioControls requestNode->append_node(valueNode); - childControl->m_connectionNodes.push_back(SRawConnectionData(requestNode, false)); + childControl->m_connectionNodes.emplace_back(requestNode, false); return childControl; } diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControlsWriter.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioControlsWriter.cpp index 91f9aa5138..eb022b706f 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControlsWriter.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControlsWriter.cpp @@ -356,8 +356,8 @@ namespace AudioControls { if (!connectionNode.m_isValid) { - auto nodeCopy = SRawConnectionData::DeepCopyNode(connectionNode.m_xmlNode.get()); - node->append_node(nodeCopy.release()); + XmlAllocator& xmlAlloc(AudioControls::s_xmlAllocator); + node->append_node(xmlAlloc.clone_node(connectionNode.m_xmlNode)); } } @@ -371,7 +371,7 @@ namespace AudioControls childNode != nullptr) { node->append_node(childNode); - control->m_connectionNodes.push_back(SRawConnectionData(childNode, true)); + control->m_connectionNodes.emplace_back(childNode, true); } } } diff --git a/Gems/Camera/Code/Source/CameraComponent.cpp b/Gems/Camera/Code/Source/CameraComponent.cpp index 04c245bc95..0b892b0367 100644 --- a/Gems/Camera/Code/Source/CameraComponent.cpp +++ b/Gems/Camera/Code/Source/CameraComponent.cpp @@ -103,6 +103,7 @@ namespace Camera ->Event("SetNearClipDistance", &CameraRequestBus::Events::SetNearClipDistance) ->Event("SetFarClipDistance", &CameraRequestBus::Events::SetFarClipDistance) ->Event("MakeActiveView", &CameraRequestBus::Events::MakeActiveView) + ->Event("IsActiveView", &CameraRequestBus::Events::IsActiveView) ->Event("IsOrthographic", &CameraRequestBus::Events::IsOrthographic) ->Event("SetOrthographic", &CameraRequestBus::Events::SetOrthographic) ->Event("GetOrthographicHalfWidth", &CameraRequestBus::Events::GetOrthographicHalfWidth) diff --git a/Gems/Camera/Code/Source/CameraComponentController.cpp b/Gems/Camera/Code/Source/CameraComponentController.cpp index bbe8235449..a8b5b8992e 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.cpp +++ b/Gems/Camera/Code/Source/CameraComponentController.cpp @@ -24,7 +24,7 @@ namespace Camera if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(3) + ->Version(4) ->Field("Orthographic", &CameraComponentConfig::m_orthographic) ->Field("Orthographic Half Width", &CameraComponentConfig::m_orthographicHalfWidth) ->Field("Field of View", &CameraComponentConfig::m_fov) @@ -51,6 +51,7 @@ namespace Camera ->Attribute(AZ::Edit::Attributes::Visibility, &CameraComponentConfig::GetOrthographicParameterVisibility) ->Attribute(AZ::Edit::Attributes::Min, 0.001f) ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::ValuesOnly) + ->DataElement(AZ::Edit::UIHandlers::Default, &CameraComponentConfig::m_fov, "Field of view", "Vertical field of view in degrees") ->Attribute(AZ::Edit::Attributes::Min, MIN_FOV) ->Attribute(AZ::Edit::Attributes::Suffix, " degrees") @@ -114,6 +115,13 @@ namespace Camera AZ_Assert(m_atomCamera, "Attempted to activate Atom camera before component activation"); const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); + + // Connect to the bus the first time we activate the view + if (!AZ::RPI::ViewportContextNotificationBus::Handler::BusIsConnectedId(contextName)) + { + AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect(contextName); + } + // Ensure the Atom camera is updated with our current transform state AZ::Transform localTransform; AZ::TransformBus::EventResult(localTransform, m_entityId, &AZ::TransformBus::Events::GetLocalTM); @@ -124,17 +132,20 @@ namespace Camera // Push the Atom camera after we make sure we're up-to-date with our component's transform to ensure the viewport reads the correct state UpdateCamera(); atomViewportRequests->PushView(contextName, m_atomCamera); - AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect(contextName); } } void CameraComponentController::DeactivateAtomView() { + if (!IsActiveView()) + { + return; + } + auto atomViewportRequests = AZ::Interface::Get(); if (atomViewportRequests) { const AZ::Name contextName = atomViewportRequests->GetDefaultViewportContextName(); - AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(contextName); atomViewportRequests->PopView(contextName, m_atomCamera); } } @@ -413,6 +424,11 @@ namespace Camera void CameraComponentController::MakeActiveView() { + if (IsActiveView()) + { + return; + } + // Set Legacy Cry view, if it exists if (m_viewSystem) { @@ -433,6 +449,11 @@ namespace Camera CameraNotificationBus::Broadcast(&CameraNotificationBus::Events::OnActiveViewChanged, m_entityId); } + bool CameraComponentController::IsActiveView() + { + return m_isActiveView; + } + void CameraComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) { if (m_updatingTransformFromEntity) @@ -456,7 +477,15 @@ namespace Camera void CameraComponentController::OnViewportSizeChanged([[maybe_unused]] AzFramework::WindowSize size) { - UpdateCamera(); + if (IsActiveView()) + { + UpdateCamera(); + } + } + + void CameraComponentController::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) + { + m_isActiveView = m_atomCamera == view; } AZ::RPI::ViewPtr CameraComponentController::GetView() const diff --git a/Gems/Camera/Code/Source/CameraComponentController.h b/Gems/Camera/Code/Source/CameraComponentController.h index c004dbe6ec..923da65618 100644 --- a/Gems/Camera/Code/Source/CameraComponentController.h +++ b/Gems/Camera/Code/Source/CameraComponentController.h @@ -69,9 +69,6 @@ namespace Camera CameraComponentController() = default; explicit CameraComponentController(const CameraComponentConfig& config); - void ActivateAtomView(); - void DeactivateAtomView(); - // Controller interface static void Reflect(AZ::ReflectContext* context); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); @@ -107,12 +104,14 @@ namespace Camera void SetOrthographicHalfWidth(float halfWidth) override; void MakeActiveView() override; + bool IsActiveView() override; // AZ::TransformNotificationBus::Handler interface void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; // AZ::RPI::ViewportContextNotificationBus::Handler interface void OnViewportSizeChanged(AzFramework::WindowSize size) override; + void OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) override; // AZ::RPI::ViewProviderBus::Handler interface AZ::RPI::ViewPtr GetView() const override; @@ -120,6 +119,8 @@ namespace Camera private: AZ_DISABLE_COPY(CameraComponentController); + void ActivateAtomView(); + void DeactivateAtomView(); void UpdateCamera(); void SetupAtomAuxGeom(AZ::RPI::ViewportContextPtr viewportContext); @@ -131,6 +132,7 @@ namespace Camera AZ::RPI::AuxGeomDrawPtr m_atomAuxGeom; AZ::Event::Handler m_onViewMatrixChanged; bool m_updatingTransformFromEntity = false; + bool m_isActiveView = false; // Cry view integration IView* m_view = nullptr; diff --git a/Gems/Camera/Code/Source/CameraGem.cpp b/Gems/Camera/Code/Source/CameraGem.cpp index 11da0310bd..7efb09a59c 100644 --- a/Gems/Camera/Code/Source/CameraGem.cpp +++ b/Gems/Camera/Code/Source/CameraGem.cpp @@ -10,6 +10,7 @@ #include #include "CameraComponent.h" +#include "CameraSystemComponent.h" #if defined(CAMERA_EDITOR) #include "CameraEditorSystemComponent.h" @@ -31,6 +32,7 @@ namespace Camera { m_descriptors.insert(m_descriptors.end(), { Camera::CameraComponent::CreateDescriptor(), + Camera::CameraSystemComponent::CreateDescriptor(), #if defined(CAMERA_EDITOR) CameraEditorSystemComponent::CreateDescriptor(), @@ -55,6 +57,7 @@ namespace Camera AZ::ComponentTypeList GetRequiredSystemComponents() const override { return AZ::ComponentTypeList { + azrtti_typeid(), #if defined(CAMERA_EDITOR) azrtti_typeid(), #endif // CAMERA_EDITOR diff --git a/Gems/Camera/Code/Source/CameraSystemComponent.cpp b/Gems/Camera/Code/Source/CameraSystemComponent.cpp new file mode 100644 index 0000000000..e9b0132cf8 --- /dev/null +++ b/Gems/Camera/Code/Source/CameraSystemComponent.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include "CameraSystemComponent.h" + +#include +#include + +#include + +#include +#include + +namespace Camera +{ + void CameraSystemComponent::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ; + } + } + + void CameraSystemComponent::Activate() + { + CameraSystemRequestBus::Handler::BusConnect(); + ActiveCameraRequestBus::Handler::BusConnect(); + CameraNotificationBus::Handler::BusConnect(); + } + + void CameraSystemComponent::Deactivate() + { + CameraNotificationBus::Handler::BusDisconnect(); + ActiveCameraRequestBus::Handler::BusDisconnect(); + CameraSystemRequestBus::Handler::BusDisconnect(); + } + + AZ::EntityId CameraSystemComponent::GetActiveCamera() + { + return m_activeView; + } + + const AZ::Transform& CameraSystemComponent::GetActiveCameraTransform() + { + if (m_activeView.IsValid()) + { + AZ::TransformBus::EventResult(m_activeViewProperties.transform, m_activeView, &AZ::TransformBus::Events::GetWorldTM); + } + else + { + // In editor, invalid entity ID for the active view denotes the "default editor camera" + // In game, this is an impossible state and if we reached here, we'll likely fail somehow... + m_activeViewProperties.transform = AZ::Transform::CreateIdentity(); + + using namespace AZ::RPI; + if (auto viewSystem = ViewportContextRequests::Get()) + { + if (auto view = viewSystem->GetCurrentView(viewSystem->GetDefaultViewportContextName())) + { + m_activeViewProperties.transform = view->GetCameraTransform(); + } + } + } + + return m_activeViewProperties.transform; + } + + const Configuration& CameraSystemComponent::GetActiveCameraConfiguration() + { + if (m_activeView.IsValid()) + { + CameraRequestBus::EventResult(m_activeViewProperties.configuration, m_activeView, &CameraRequestBus::Events::GetCameraConfiguration); + } + else + { + auto& cfg = m_activeViewProperties.configuration; + cfg = Configuration(); + + // In editor, invalid entity ID for the active view denotes the "default editor camera" + // In game, this is an impossible state and if we reached here, we'll likely fail somehow... + using namespace AZ::RPI; + if (auto viewSystem = ViewportContextRequests::Get()) + { + if (auto view = viewSystem->GetCurrentView(viewSystem->GetDefaultViewportContextName())) + { + AzFramework::CameraState cam; + AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cam, view->GetViewToClipMatrix()); + + cfg.m_fovRadians = cam.m_fovOrZoom; + cfg.m_nearClipDistance = cam.m_nearClip; + cfg.m_farClipDistance = cam.m_farClip; + + // No idea what to do here. Seems to be unused? + cfg.m_frustumWidth = cfg.m_frustumHeight = 1.0f; + } + } + } + + return m_activeViewProperties.configuration; + } + + void CameraSystemComponent::OnActiveViewChanged(const AZ::EntityId& activeView) + { + m_activeView = activeView; + } +} // namespace Camera diff --git a/Gems/Camera/Code/Source/CameraSystemComponent.h b/Gems/Camera/Code/Source/CameraSystemComponent.h new file mode 100644 index 0000000000..7fc8d15d6b --- /dev/null +++ b/Gems/Camera/Code/Source/CameraSystemComponent.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include + +#include + +namespace Camera +{ + class CameraSystemComponent + : public AZ::Component + , private CameraSystemRequestBus::Handler + , private ActiveCameraRequestBus::Handler + , private CameraNotificationBus::Handler + { + public: + AZ_COMPONENT(CameraSystemComponent, "{5DF8DB49-6430-4718-9417-85321596EDA5}"); + static void Reflect(AZ::ReflectContext* context); + + CameraSystemComponent() = default; + ~CameraSystemComponent() override = default; + + ////////////////////////////////////////////////////////////////////////// + // AZ::Component + void Activate() override; + void Deactivate() override; + ////////////////////////////////////////////////////////////////////////// + + private: + ////////////////////////////////////////////////////////////////////////// + // CameraSystemRequestBus + AZ::EntityId GetActiveCamera() override; + ////////////////////////////////////////////////////////////////////////// + + ////////////////////////////////////////////////////////////////////////// + // ActiveCameraRequestBus + const AZ::Transform& GetActiveCameraTransform() override; + const Configuration& GetActiveCameraConfiguration() override; + ////////////////////////////////////////////////////////////////////////// + + ////////////////////////////////////////////////////////////////////////// + // CameraNotificationBus + void OnActiveViewChanged(const AZ::EntityId&) override; + ////////////////////////////////////////////////////////////////////////// + + struct CameraProperties + { + AZ::Transform transform; + Configuration configuration; + }; + + AZ::EntityId m_activeView; + CameraProperties m_activeViewProperties; + }; +} // namespace Camera diff --git a/Gems/Camera/Code/Source/EditorCameraComponent.cpp b/Gems/Camera/Code/Source/EditorCameraComponent.cpp index 14e8e46e72..4ebec334ec 100644 --- a/Gems/Camera/Code/Source/EditorCameraComponent.cpp +++ b/Gems/Camera/Code/Source/EditorCameraComponent.cpp @@ -38,40 +38,24 @@ namespace Camera EditorCameraComponentBase::Activate(); AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); - EditorCameraNotificationBus::Handler::BusConnect(); EditorCameraViewRequestBus::Handler::BusConnect(GetEntityId()); - - AZ::EntityId currentViewEntity; - EditorCameraRequests::Bus::BroadcastResult(currentViewEntity, &EditorCameraRequests::GetCurrentViewEntityId); - if (currentViewEntity == GetEntityId()) - { - m_controller.ActivateAtomView(); - m_isActiveEditorCamera = true; - } } void EditorCameraComponent::Deactivate() { - if (m_isActiveEditorCamera) - { - m_controller.DeactivateAtomView(); - m_isActiveEditorCamera = false; - } - EditorCameraViewRequestBus::Handler::BusDisconnect(GetEntityId()); - EditorCameraNotificationBus::Handler::BusDisconnect(); AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); EditorCameraComponentBase::Deactivate(); } AZ::u32 EditorCameraComponent::OnConfigurationChanged() { - bool isActiveEditorCamera = m_isActiveEditorCamera; + bool isActiveEditorCamera = m_controller.IsActiveView(); AZ::u32 configurationHash = EditorCameraComponentBase::OnConfigurationChanged(); // If we were the active editor camera before, ensure we get reactivated after our controller gets disabled then re-enabled if (isActiveEditorCamera) { - EditorCameraRequests::Bus::Broadcast(&EditorCameraRequests::SetViewFromEntityPerspective, GetEntityId()); + m_controller.MakeActiveView(); } return configurationHash; } @@ -139,25 +123,6 @@ namespace Camera } } - void EditorCameraComponent::OnViewportViewEntityChanged([[maybe_unused]] const AZ::EntityId& newViewId) - { - if (newViewId == GetEntityId()) - { - if (!m_isActiveEditorCamera) - { - m_controller.ActivateAtomView(); - m_isActiveEditorCamera = true; - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); - } - } - else if (m_isActiveEditorCamera) - { - m_controller.DeactivateAtomView(); - m_isActiveEditorCamera = false; - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); - } - } - bool EditorCameraComponent::GetCameraState(AzFramework::CameraState& cameraState) { const CameraComponentConfig& config = m_controller.GetConfiguration(); diff --git a/Gems/Camera/Code/Source/EditorCameraComponent.h b/Gems/Camera/Code/Source/EditorCameraComponent.h index 095427a4a7..02b9d591d0 100644 --- a/Gems/Camera/Code/Source/EditorCameraComponent.h +++ b/Gems/Camera/Code/Source/EditorCameraComponent.h @@ -37,7 +37,6 @@ namespace Camera : public EditorCameraComponentBase , public EditorCameraViewRequestBus::Handler , private AzFramework::EntityDebugDisplayEventBus::Handler - , private EditorCameraNotificationBus::Handler { public: AZ_EDITOR_COMPONENT(EditorCameraComponent, EditorCameraComponentTypeId, AzToolsFramework::Components::EditorComponentBase); @@ -55,9 +54,6 @@ namespace Camera const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; - /// EditorCameraNotificationBus::Handler interface - void OnViewportViewEntityChanged(const AZ::EntityId& newViewId) override; - /// EditorCameraViewRequestBus::Handler interface void ToggleCameraAsActiveView() override { OnPossessCameraButtonClicked(); } bool GetCameraState(AzFramework::CameraState& cameraState) override; @@ -67,7 +63,6 @@ namespace Camera AZ::Crc32 OnPossessCameraButtonClicked(); AZStd::string GetCameraViewButtonText() const; - bool m_isActiveEditorCamera = false; float m_frustumViewPercentLength = 1.f; AZ::Color m_frustumDrawColor = AzFramework::ViewportColors::HoverColor; }; diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp index f664d78c0e..87624b1c8d 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow.cpp @@ -17,6 +17,7 @@ #include #include #include +#include namespace Qt { @@ -38,7 +39,6 @@ namespace Camera { CameraListItem::CameraListItem(const AZ::EntityId& cameraId) : m_cameraId(cameraId) - , m_sequenceId(AZ::EntityId()) { if (cameraId.IsValid()) { @@ -51,44 +51,24 @@ namespace Camera } } - // Used for a virtual camera that is really whatever camera is being - // used for a Track View Sequence. - CameraListItem::CameraListItem(const char* cameraName, const AZ::EntityId& sequenceId) - : m_cameraName(cameraName) - , m_sequenceId(sequenceId) - { - Maestro::SequenceComponentNotificationBus::Handler::BusConnect(sequenceId); - } - CameraListItem::~CameraListItem() { - Maestro::SequenceComponentNotificationBus::Handler::BusDisconnect(); - if (m_cameraId.IsValid()) { AZ::EntityBus::Handler::BusDisconnect(m_cameraId); } } - ////////////////////////////////////////////////////////////////////////// - /// Maestro::SequenceComponentNotificationBus::Handler - void CameraListItem::OnCameraChanged(const AZ::EntityId& oldCameraEntityId, const AZ::EntityId& newCameraEntityId) - { - AZ_UNUSED(oldCameraEntityId); - m_cameraId = newCameraEntityId; - } - bool CameraListItem::operator<(const CameraListItem& rhs) { return m_cameraId < rhs.m_cameraId; } - CameraListModel::CameraListModel(QObject* myParent) + CameraListModel::CameraListModel(QWidget* myParent) : QAbstractListModel(myParent) { m_cameraItems.push_back(AZ::EntityId()); CameraNotificationBus::Handler::BusConnect(); - Maestro::EditorSequenceNotificationBus::Handler::BusConnect(); } CameraListModel::~CameraListModel() @@ -96,7 +76,6 @@ namespace Camera // set the view entity id back to Invalid, thus enabling the editor camera EditorCameraRequests::Bus::Broadcast(&EditorCameraRequests::SetViewFromEntityPerspective, AZ::EntityId()); - Maestro::EditorSequenceNotificationBus::Handler::BusDisconnect(); CameraNotificationBus::Handler::BusDisconnect(); } @@ -120,6 +99,18 @@ namespace Camera void CameraListModel::OnCameraAdded(const AZ::EntityId& cameraId) { + // If the camera entity is not an editor camera entity, don't add it to the list. + // This occurs when we're in simulation mode. + bool isEditorEntity = false; + AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult( + isEditorEntity, + &AzToolsFramework::EditorEntityContextRequests::IsEditorEntity, + cameraId); + if (!isEditorEntity) + { + return; + } + beginInsertRows(QModelIndex(), rowCount(), rowCount()); m_cameraItems.push_back(cameraId); endInsertRows(); @@ -141,42 +132,6 @@ namespace Camera } } - ////////////////////////////////////////////////////////////////////////// - /// Maestro::EditorSequenceNotificationBus::Handler - void CameraListModel::OnSequenceSelected(const AZ::EntityId& sequenceEntityId) - { - // Add or Remove the Sequence Camera option if a valid - // sequence is selected in Track View. - - // Check to see if the Sequence Camera option is already present - bool found = false; - int index = 0; - for (const CameraListItem& cameraItem : m_cameraItems) - { - if (cameraItem.m_cameraName == m_sequenceCameraName) - { - found = true; - break; - } - ++index; - } - - // If it is present, but no sequence is selected, removed it. - if (found && !sequenceEntityId.IsValid()) - { - beginRemoveRows(QModelIndex(), index, index); - m_cameraItems.erase(m_cameraItems.begin() + index); - endRemoveRows(); - } - // If it is not present, and there is a sequence selected show it. - else if (!found && sequenceEntityId.IsValid()) - { - beginInsertRows(QModelIndex(), rowCount(), rowCount()); - m_cameraItems.push_back(CameraListItem(m_sequenceCameraName, sequenceEntityId)); - endInsertRows(); - } - } - QModelIndex CameraListModel::GetIndexForEntityId(const AZ::EntityId entityId) { int row = 0; @@ -191,8 +146,6 @@ namespace Camera return index(row, 0); } - const char* CameraListModel::m_sequenceCameraName = "Sequence camera"; - ViewportCameraSelectorWindow::ViewportCameraSelectorWindow(QWidget* parent) : m_ignoreViewportViewEntityChanged(false) { @@ -222,17 +175,10 @@ namespace Camera // bus connections EditorCameraNotificationBus::Handler::BusConnect(); AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); - Maestro::EditorSequenceNotificationBus::Handler::BusConnect(); } ViewportCameraSelectorWindow::~ViewportCameraSelectorWindow() { - if (Maestro::SequenceComponentNotificationBus::Handler::BusIsConnected()) - { - Maestro::SequenceComponentNotificationBus::Handler::BusDisconnect(); - } - - Maestro::EditorSequenceNotificationBus::Handler::BusDisconnect(); AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusDisconnect(); EditorCameraNotificationBus::Handler::BusDisconnect(); } @@ -241,9 +187,7 @@ namespace Camera { if (current.row() != previous.row()) { - // Lock camera editing when in sequence camera mode. - const AZStd::string& selectedCameraName = selectionModel()->currentIndex().data(Qt::DisplayRole).toString().toUtf8().data(); - bool lockCameraMovement = (selectedCameraName == CameraListModel::m_sequenceCameraName); + bool lockCameraMovement = false; QScopedValueRollback rb(m_ignoreViewportViewEntityChanged, true); AZ::EntityId entityId = selectionModel()->currentIndex().data(Qt::CameraIdRole).value(); @@ -278,36 +222,6 @@ namespace Camera setDisabled(false); } - ////////////////////////////////////////////////////////////////////////// - /// Maestro::EditorSequenceNotificationBus::Handler - void ViewportCameraSelectorWindow::OnSequenceSelected(const AZ::EntityId& sequenceEntityId) - { - // Connect to the Sequence Component Bus when a sequence is selected for OnCameraChanged. - if (Maestro::SequenceComponentNotificationBus::Handler::BusIsConnected()) - { - Maestro::SequenceComponentNotificationBus::Handler::BusDisconnect(); - } - if (sequenceEntityId.IsValid()) - { - Maestro::SequenceComponentNotificationBus::Handler::BusConnect(sequenceEntityId); - } - } - - ////////////////////////////////////////////////////////////////////////// - /// Maestro::SequenceComponentNotificationBus::Handler - void ViewportCameraSelectorWindow::OnCameraChanged(const AZ::EntityId& oldCameraEntityId, const AZ::EntityId& newCameraEntityId) - { - AZ_UNUSED(oldCameraEntityId); - - // If the Sequence camera option is selected, respond to camera changes by selecting the camera used by the sequence. - const AZStd::string& selectedCameraName = selectionModel()->currentIndex().data(Qt::DisplayRole).toString().toUtf8().data(); - if (selectedCameraName == CameraListModel::m_sequenceCameraName) - { - QScopedValueRollback rb(m_ignoreViewportViewEntityChanged, true); - EditorCameraRequests::Bus::Broadcast(&EditorCameraRequests::SetViewAndMovementLockFromEntityPerspective, newCameraEntityId, true); - } - } - // swallow mouse move events so we can disable sloppy selection void ViewportCameraSelectorWindow::mouseMoveEvent(QMouseEvent*) {} diff --git a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h index a681d049c3..2c3d114908 100644 --- a/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h +++ b/Gems/Camera/Code/Source/ViewportCameraSelectorWindow_Internals.h @@ -9,8 +9,6 @@ #include #include -#include -#include #include #include #include @@ -25,38 +23,26 @@ namespace Camera // Each item in the list holds the camera's entityId and name struct CameraListItem : public AZ::EntityBus::Handler - , public Maestro::SequenceComponentNotificationBus::Handler { public: CameraListItem(const AZ::EntityId& cameraId); - // Used for a virtual camera that is really whatever camera is being - // used for a Track View Sequence. - CameraListItem(const char* cameraName, const AZ::EntityId& sequenceId); ~CameraListItem(); void OnEntityNameChanged(const AZStd::string& name) override { m_cameraName = name; } - ////////////////////////////////////////////////////////////////////////// - /// Maestro::SequenceComponentNotificationBus::Handler - void OnCameraChanged(const AZ::EntityId& oldCameraEntityId, const AZ::EntityId& newCameraEntityId) override; bool operator<(const CameraListItem& rhs); AZ::EntityId m_cameraId; AZStd::string m_cameraName; - AZ::EntityId m_sequenceId; }; // holds a list of camera items struct CameraListModel : public QAbstractListModel , public CameraNotificationBus::Handler - , public Maestro::EditorSequenceNotificationBus::Handler { public: - - static const char* m_sequenceCameraName; - - CameraListModel(QObject* myParent); + explicit CameraListModel(QWidget* myParent); ~CameraListModel(); // QAbstractItemModel interface @@ -67,9 +53,6 @@ namespace Camera void OnCameraAdded(const AZ::EntityId& cameraId) override; void OnCameraRemoved(const AZ::EntityId& cameraId) override; - ////////////////////////////////////////////////////////////////////////// - /// Maestro::EditorSequenceNotificationBus::Handler - void OnSequenceSelected(const AZ::EntityId& sequenceEntityId) override; QModelIndex GetIndexForEntityId(const AZ::EntityId entityId); private: @@ -82,8 +65,6 @@ namespace Camera : public QListView , public EditorCameraNotificationBus::Handler , public AzToolsFramework::EditorEntityContextNotificationBus::Handler - , public Maestro::EditorSequenceNotificationBus::Handler - , public Maestro::SequenceComponentNotificationBus::Handler { public: ViewportCameraSelectorWindow(QWidget* parent = nullptr); @@ -101,14 +82,6 @@ namespace Camera void OnStartPlayInEditor() override; void OnStopPlayInEditor() override; - ////////////////////////////////////////////////////////////////////////// - /// Maestro::EditorSequenceNotificationBus::Handler - void OnSequenceSelected(const AZ::EntityId& sequenceEntityId) override; - - ////////////////////////////////////////////////////////////////////////// - /// Maestro::SequenceComponentNotificationBus::Handler - void OnCameraChanged(const AZ::EntityId& oldCameraEntityId, const AZ::EntityId& newCameraEntityId) override; - void mouseMoveEvent(QMouseEvent*) override; void mouseDoubleClickEvent(QMouseEvent* event) override; QModelIndex moveCursor(CursorAction cursorAction, Qt::KeyboardModifiers modifiers) override; diff --git a/Gems/Camera/Code/camera_files.cmake b/Gems/Camera/Code/camera_files.cmake index 295589e453..26769b071c 100644 --- a/Gems/Camera/Code/camera_files.cmake +++ b/Gems/Camera/Code/camera_files.cmake @@ -9,6 +9,8 @@ set(FILES camera_files.cmake Source/CameraComponent.cpp Source/CameraComponent.h + Source/CameraSystemComponent.cpp + Source/CameraSystemComponent.h Source/CameraComponentConverter.cpp Source/CameraComponentController.cpp Source/CameraComponentController.h diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp index a21b618b91..da5366f6cf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.cpp @@ -57,7 +57,7 @@ namespace CommandSystem // Set motion extraction node. if (parameters.CheckIfHasParameter("motionExtractionNodeName")) { - mOldMotionExtractionNodeIndex = actor->GetMotionExtractionNodeIndex(); + m_oldMotionExtractionNodeIndex = actor->GetMotionExtractionNodeIndex(); AZStd::string motionExtractionNodeName; parameters.GetValue("motionExtractionNodeName", this, motionExtractionNodeName); @@ -67,21 +67,21 @@ namespace CommandSystem } else { - EMotionFX::Node* node = skeleton->FindNodeByName(motionExtractionNodeName.c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(motionExtractionNodeName); actor->SetMotionExtractionNode(node); } // Inform all animgraph nodes about this. - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (animGraph->GetIsOwnedByRuntime()) { continue; } - const uint32 numObjects = animGraph->GetNumObjects(); - for (uint32 n = 0; n < numObjects; ++n) + const size_t numObjects = animGraph->GetNumObjects(); + for (size_t n = 0; n < numObjects; ++n) { animGraph->GetObject(n)->OnActorMotionExtractionNodeChanged(); } @@ -91,7 +91,7 @@ namespace CommandSystem // Set retarget root node. if (parameters.CheckIfHasParameter("retargetRootNodeName")) { - mOldRetargetRootNodeIndex = actor->GetRetargetRootNodeIndex(); + m_oldRetargetRootNodeIndex = actor->GetRetargetRootNodeIndex(); AZStd::string retargetRootNodeName = parameters.GetValue("retargetRootNodeName", this); if (retargetRootNodeName.empty() || retargetRootNodeName == "$NULL$") @@ -100,7 +100,7 @@ namespace CommandSystem } else { - EMotionFX::Node* node = skeleton->FindNodeByName(retargetRootNodeName.c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(retargetRootNodeName); actor->SetRetargetRootNode(node); } } @@ -108,7 +108,7 @@ namespace CommandSystem // Set actor name. if (parameters.CheckIfHasParameter("name")) { - mOldName = actor->GetName(); + m_oldName = actor->GetName(); AZStd::string actorName; parameters.GetValue("name", this, actorName); @@ -119,9 +119,9 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("attachmentNodes")) { // Store old attachment nodes for undo. - mOldAttachmentNodes = ""; - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + m_oldAttachmentNodes = ""; + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = skeleton->GetNode(i); if (!node) @@ -132,8 +132,8 @@ namespace CommandSystem // Check if the node has the attachment flag enabled and add it. if (node->GetIsAttachmentNode()) { - mOldAttachmentNodes += node->GetName(); - mOldAttachmentNodes += ";"; + m_oldAttachmentNodes += node->GetName(); + m_oldAttachmentNodes += ";"; } } @@ -150,9 +150,9 @@ namespace CommandSystem // Remove the given nodes from the attachment node list by unsetting the flag. if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "remove")) { - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::Node* node = skeleton->FindNodeByName(nodeNames[i].c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(nodeName); if (!node) { continue; @@ -164,9 +164,9 @@ namespace CommandSystem // Add the given nodes to the attachment node list by setting attachment flag. else if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "add")) { - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::Node* node = skeleton->FindNodeByName(nodeNames[i].c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(nodeName); if (!node) { continue; @@ -181,9 +181,9 @@ namespace CommandSystem SetIsAttachmentNode(actor, false); // Set attachment node flag based on selection list. - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::Node* node = skeleton->FindNodeByName(nodeNames[i].c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(nodeName); if (!node) { continue; @@ -198,9 +198,9 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("nodesExcludedFromBounds")) { // Store old nodes for undo. - mOldExcludedFromBoundsNodes = ""; - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + m_oldExcludedFromBoundsNodes = ""; + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = skeleton->GetNode(i); if (!node) @@ -211,8 +211,8 @@ namespace CommandSystem // Check if the node has the attachment flag enabled and add it. if (!node->GetIncludeInBoundsCalc()) { - mOldExcludedFromBoundsNodes += node->GetName(); - mOldExcludedFromBoundsNodes += ";"; + m_oldExcludedFromBoundsNodes += node->GetName(); + m_oldExcludedFromBoundsNodes += ";"; } } @@ -229,9 +229,9 @@ namespace CommandSystem // Remove the selected nodes from the bounding volume calculations. if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "remove")) { - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::Node* node = skeleton->FindNodeByName(nodeNames[i].c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(nodeName); if (!node) { continue; @@ -243,9 +243,9 @@ namespace CommandSystem // Add the given nodes to the bounding volume calculations. if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "add")) { - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::Node* node = skeleton->FindNodeByName(nodeNames[i].c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(nodeName); if (!node) { continue; @@ -260,9 +260,9 @@ namespace CommandSystem SetIsExcludedFromBoundsNode(actor, false); // Remove the nodes from bounding volume calculation based on the selection. - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::Node* node = skeleton->FindNodeByName(nodeNames[i].c_str()); + EMotionFX::Node* node = skeleton->FindNodeByName(nodeName); if (!node) { continue; @@ -276,7 +276,7 @@ namespace CommandSystem // Adjust the mirror setup. if (parameters.CheckIfHasParameter("mirrorSetup")) { - mOldMirrorSetup = actor->GetNodeMirrorInfos(); + m_oldMirrorSetup = actor->GetNodeMirrorInfos(); AZStd::string mirrorSetupString; parameters.GetValue("mirrorSetup", this, mirrorSetupString); @@ -294,23 +294,22 @@ namespace CommandSystem AzFramework::StringFunc::Tokenize(mirrorSetupString.c_str(), pairs, ";", false, true); // Parse the mirror setup string, which is like "nodeA,nodeB;nodeC,nodeD;". - const size_t numPairs = pairs.size(); - for (size_t p = 0; p < numPairs; ++p) + for (const AZStd::string& pair : pairs) { // Split the pairs into the node names. AZStd::vector pairValues; - AzFramework::StringFunc::Tokenize(pairs[p].c_str(), pairValues, ",", false, true); + AzFramework::StringFunc::Tokenize(pair.c_str(), pairValues, ",", false, true); if (pairValues.size() != 2) { continue; } - EMotionFX::Node* nodeA = actor->GetSkeleton()->FindNodeByName(pairValues[0].c_str()); - EMotionFX::Node* nodeB = actor->GetSkeleton()->FindNodeByName(pairValues[1].c_str()); + EMotionFX::Node* nodeA = actor->GetSkeleton()->FindNodeByName(pairValues[0]); + EMotionFX::Node* nodeB = actor->GetSkeleton()->FindNodeByName(pairValues[1]); if (nodeA && nodeB) { - actor->GetNodeMirrorInfo(nodeA->GetNodeIndex()).mSourceNode = static_cast(nodeB->GetNodeIndex()); - actor->GetNodeMirrorInfo(nodeB->GetNodeIndex()).mSourceNode = static_cast(nodeA->GetNodeIndex()); + actor->GetNodeMirrorInfo(nodeA->GetNodeIndex()).m_sourceNode = static_cast(nodeB->GetNodeIndex()); + actor->GetNodeMirrorInfo(nodeB->GetNodeIndex()).m_sourceNode = static_cast(nodeA->GetNodeIndex()); } } @@ -319,7 +318,7 @@ namespace CommandSystem } } - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); return true; } @@ -339,29 +338,29 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("motionExtractionNodeName")) { - actor->SetMotionExtractionNodeIndex(mOldMotionExtractionNodeIndex); + actor->SetMotionExtractionNodeIndex(m_oldMotionExtractionNodeIndex); } if (parameters.CheckIfHasParameter("retargetRootNodeName")) { - actor->SetRetargetRootNodeIndex(mOldRetargetRootNodeIndex); + actor->SetRetargetRootNodeIndex(m_oldRetargetRootNodeIndex); } if (parameters.CheckIfHasParameter("name")) { - actor->SetName(mOldName.c_str()); + actor->SetName(m_oldName.c_str()); } if (parameters.CheckIfHasParameter("mirrorSetup")) { - actor->SetNodeMirrorInfos(mOldMirrorSetup); + actor->SetNodeMirrorInfos(m_oldMirrorSetup); actor->AutoDetectMirrorAxes(); } // Set the attachment nodes. if (parameters.CheckIfHasParameter("attachmentNodes")) { - const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -attachmentNodes \"%s\"", actorID, mOldAttachmentNodes.c_str()); + const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -attachmentNodes \"%s\"", actorID, m_oldAttachmentNodes.c_str()); if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult)) { @@ -373,7 +372,7 @@ namespace CommandSystem // Set the nodes that are not taken into account in the bounding volume calculations. if (parameters.CheckIfHasParameter("nodesExcludedFromBounds")) { - const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -nodesExcludedFromBounds \"%s\"", actorID, mOldExcludedFromBoundsNodes.c_str()); + const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"select\" -nodesExcludedFromBounds \"%s\"", actorID, m_oldExcludedFromBoundsNodes.c_str()); if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult)) { @@ -383,7 +382,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -411,8 +410,8 @@ namespace CommandSystem // Static function to set all IsAttachmentNode flags of the actor to the given value. void CommandAdjustActor::SetIsAttachmentNode(EMotionFX::Actor* actor, bool isAttachmentNode) { - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); if (!node) @@ -428,8 +427,8 @@ namespace CommandSystem // Static function to set all IsAttachmentNode flags of the actor to the given value. void CommandAdjustActor::SetIsExcludedFromBoundsNode(EMotionFX::Actor* actor, bool excludedFromBounds) { - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); if (!node) @@ -476,22 +475,22 @@ namespace CommandSystem return false; } - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); // Store the old nodes for the undo. - mOldNodeList = ""; - for (uint32 i = 0; i < numNodes; ++i) + m_oldNodeList = ""; + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Mesh* mesh = actor->GetMesh(lod, i); if (mesh && mesh->GetIsCollisionMesh()) { - if (!mOldNodeList.empty()) + if (!m_oldNodeList.empty()) { - mOldNodeList += ";"; + m_oldNodeList += ";"; } - mOldNodeList += skeleton->GetNode(i)->GetName(); + m_oldNodeList += skeleton->GetNode(i)->GetName(); } } @@ -504,7 +503,7 @@ namespace CommandSystem AzFramework::StringFunc::Tokenize(nodeList.c_str(), nodeNames, ";", false, true); // Update the collision mesh flags. - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { const EMotionFX::Node* node = skeleton->GetNode(i); EMotionFX::Mesh* mesh = actor->GetMesh(lod, i); @@ -518,7 +517,7 @@ namespace CommandSystem } // Save the current dirty flag and tell the actor that something changed. - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); // Reinit the renderable actors. @@ -543,11 +542,11 @@ namespace CommandSystem const uint32 lod = parameters.GetValueAsInt("lod", MCORE_INVALIDINDEX32); // Undo command. - const AZStd::string command = AZStd::string::format("ActorSetCollisionMeshes -actorID %i -lod %i -nodeList %s", actorID, lod, mOldNodeList.c_str()); + const AZStd::string command = AZStd::string::format("ActorSetCollisionMeshes -actorID %i -lod %i -nodeList %s", actorID, lod, m_oldNodeList.c_str()); GetCommandManager()->ExecuteCommandInsideCommand(command, outResult); // Set the dirty flag back to the old value - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -574,7 +573,7 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - const uint32 numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); + const size_t numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); if (numSelectedActorInstances == 0) { outResult = "Cannot reset actor instances to bind pose. No actor instance selected."; @@ -582,7 +581,7 @@ namespace CommandSystem } // Iterate through all selected actor instances and reset them to bind pose. - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetActorInstance(i); @@ -687,7 +686,7 @@ namespace CommandSystem CommandRemoveActor::CommandRemoveActor(MCore::Command* orgCommand) : MCore::Command("RemoveActor", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -726,10 +725,10 @@ namespace CommandSystem } // store the previously used id and the actor filename - mPreviouslyUsedID = actor->GetID(); - mOldFileName = actor->GetFileName(); - mOldDirtyFlag = actor->GetDirtyFlag(); - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_previouslyUsedId = actor->GetID(); + m_oldFileName = actor->GetFileName(); + m_oldDirtyFlag = actor->GetDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); // get rid of the actor EMotionFX::GetActorManager().UnregisterActor(EMotionFX::GetActorManager().FindSharedActorByID(actor->GetID())); @@ -748,7 +747,7 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - const AZStd::string command = AZStd::string::format("ImportActor -filename \"%s\" -actorID %i", mOldFileName.c_str(), mPreviouslyUsedID); + const AZStd::string command = AZStd::string::format("ImportActor -filename \"%s\" -actorID %i", m_oldFileName.c_str(), m_previouslyUsedId); if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult)) { return false; @@ -762,7 +761,7 @@ namespace CommandSystem } // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return true; } @@ -792,8 +791,8 @@ namespace CommandSystem } // get number of actors and instances - const uint32 numActors = EMotionFX::GetActorManager().GetNumActors(); - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + const size_t numActors = EMotionFX::GetActorManager().GetNumActors(); + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); // create the command group MCore::CommandGroup internalCommandGroup("Clear scene"); @@ -811,7 +810,7 @@ namespace CommandSystem if (deleteActors || deleteActorInstances) { // get rid of all actor instances - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get pointer to the current actor instance EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -847,7 +846,7 @@ namespace CommandSystem if (deleteActors) { // iterate through all available actors - for (uint32 i = 0; i < numActors; ++i) + for (size_t i = 0; i < numActors; ++i) { // get the current actor EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); @@ -903,7 +902,7 @@ namespace CommandSystem // walk over the meshes and check which of them we want to set as collision mesh - void PrepareCollisionMeshesNodesString(EMotionFX::Actor* actor, uint32 lod, AZStd::string* outNodeNames) + void PrepareCollisionMeshesNodesString(EMotionFX::Actor* actor, size_t lod, AZStd::string* outNodeNames) { // reset the resulting string outNodeNames->clear(); @@ -922,8 +921,8 @@ namespace CommandSystem } // get the number of nodes and iterate through them - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Mesh* mesh = actor->GetMesh(lod, i); if (mesh && mesh->GetIsCollisionMesh()) @@ -951,8 +950,8 @@ namespace CommandSystem } // get the number of nodes and iterate through them - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); @@ -974,10 +973,10 @@ namespace CommandSystem CommandScaleActorData::CommandScaleActorData(MCore::Command* orgCommand) : MCore::Command("ScaleActorData", orgCommand) { - mActorID = MCORE_INVALIDINDEX32; - mScaleFactor = 1.0f; - mOldActorDirtyFlag = false; - mUseUnitType = false; + m_actorId = MCORE_INVALIDINDEX32; + m_scaleFactor = 1.0f; + m_oldActorDirtyFlag = false; + m_useUnitType = false; } @@ -1021,32 +1020,32 @@ namespace CommandSystem return false; } - mActorID = actor->GetID(); - mScaleFactor = parameters.GetValueAsFloat("scaleFactor", this); + m_actorId = actor->GetID(); + m_scaleFactor = parameters.GetValueAsFloat("scaleFactor", this); AZStd::string targetUnitTypeString; parameters.GetValue("unitType", this, &targetUnitTypeString); - mUseUnitType = parameters.CheckIfHasParameter("unitType"); + m_useUnitType = parameters.CheckIfHasParameter("unitType"); MCore::Distance::EUnitType targetUnitType; bool stringConvertSuccess = MCore::Distance::StringToUnitType(targetUnitTypeString, &targetUnitType); - if (mUseUnitType && stringConvertSuccess == false) + if (m_useUnitType && stringConvertSuccess == false) { outResult = AZStd::string::format("The passed unitType '%s' is not a valid unit type.", targetUnitTypeString.c_str()); return false; } MCore::Distance::EUnitType beforeUnitType = actor->GetUnitType(); - mOldUnitType = MCore::Distance::UnitTypeToString(beforeUnitType); + m_oldUnitType = MCore::Distance::UnitTypeToString(beforeUnitType); - mOldActorDirtyFlag = actor->GetDirtyFlag(); + m_oldActorDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); // perform the scaling - if (mUseUnitType == false) + if (m_useUnitType == false) { - actor->Scale(mScaleFactor); + actor->Scale(m_scaleFactor); } else { @@ -1054,8 +1053,8 @@ namespace CommandSystem } // update the static aabb's of all actor instances - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); if (actorInstance->GetActor() != actor) @@ -1063,11 +1062,10 @@ namespace CommandSystem continue; } - MCore::AABB newAABB; - actorInstance->SetStaticBasedAABB(actor->GetStaticAABB()); // this is needed as the CalcStaticBasedAABB uses the current AABB as starting point - actorInstance->CalcStaticBasedAABB(&newAABB); - actorInstance->SetStaticBasedAABB(newAABB); - //actorInstance->UpdateVisualizeScale(); + actorInstance->SetStaticBasedAabb(actor->GetStaticAabb()); // this is needed as the CalcStaticBasedAabb uses the current AABB as starting point + AZ::Aabb newAabb; + actorInstance->CalcStaticBasedAabb(&newAabb); + actorInstance->SetStaticBasedAabb(newAabb); const float factor = (float)MCore::Distance::GetConversionFactor(beforeUnitType, targetUnitType); actorInstance->SetVisualizeScale(actorInstance->GetVisualizeScale() * factor); @@ -1085,21 +1083,21 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - if (!mUseUnitType) + if (!m_useUnitType) { - const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -scaleFactor %.8f", mActorID, 1.0f / mScaleFactor); + const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -scaleFactor %.8f", m_actorId, 1.0f / m_scaleFactor); GetCommandManager()->ExecuteCommandInsideCommand(command, outResult); } else { - const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -unitType \"%s\"", mActorID, mOldUnitType.c_str()); + const AZStd::string command = AZStd::string::format("ScaleActorData -id %d -unitType \"%s\"", m_actorId, m_oldUnitType.c_str()); GetCommandManager()->ExecuteCommandInsideCommand(command, outResult); } - EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(mActorID); + EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(m_actorId); if (actor) { - actor->SetDirtyFlag(mOldActorDirtyFlag); + actor->SetDirtyFlag(m_oldActorDirtyFlag); } return true; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h index 75d92d5f27..6495577de7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorCommands.h @@ -19,14 +19,14 @@ namespace CommandSystem { // Adjust the given actor. MCORE_DEFINECOMMAND_START(CommandAdjustActor, "Adjust actor", true) - uint32 mOldMotionExtractionNodeIndex; - uint32 mOldRetargetRootNodeIndex; - uint32 mOldTrajectoryNodeIndex; - AZStd::string mOldAttachmentNodes; - AZStd::string mOldExcludedFromBoundsNodes; - AZStd::string mOldName; - MCore::Array mOldMirrorSetup; - bool mOldDirtyFlag; + size_t m_oldMotionExtractionNodeIndex; + size_t m_oldRetargetRootNodeIndex; + size_t m_oldTrajectoryNodeIndex; + AZStd::string m_oldAttachmentNodes; + AZStd::string m_oldExcludedFromBoundsNodes; + AZStd::string m_oldName; + AZStd::vector m_oldMirrorSetup; + bool m_oldDirtyFlag; void SetIsAttachmentNode(EMotionFX::Actor* actor, bool isAttachmentNode); void SetIsExcludedFromBoundsNode(EMotionFX::Actor* actor, bool excludedFromBounds); @@ -34,8 +34,8 @@ namespace CommandSystem // Set the collision meshes of the given actor. MCORE_DEFINECOMMAND_START(CommandActorSetCollisionMeshes, "Actor set collison meshes", true) - AZStd::string mOldNodeList; - bool mOldDirtyFlag; + AZStd::string m_oldNodeList; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // Reset actor instance to bind pose. @@ -50,27 +50,27 @@ namespace CommandSystem // Remove actor. MCORE_DEFINECOMMAND_START(CommandRemoveActor, "Remove actor", true) public: - uint32 mPreviouslyUsedID; - AZStd::string mOldFileName; - bool mOldDirtyFlag; - bool mOldWorkspaceDirtyFlag; + uint32 m_previouslyUsedId; + AZStd::string m_oldFileName; + bool m_oldDirtyFlag; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // Scale actor data. MCORE_DEFINECOMMAND_START(CommandScaleActorData, "Scale actor data", true) public: - AZStd::string mOldUnitType; - uint32 mActorID; - float mScaleFactor; - bool mOldActorDirtyFlag; - bool mUseUnitType; + AZStd::string m_oldUnitType; + uint32 m_actorId; + float m_scaleFactor; + bool m_oldActorDirtyFlag; + bool m_useUnitType; MCORE_DEFINECOMMAND_END ////////////////////////////////////////////////////////////////////////////////////////////////////////// // Helper functions ////////////////////////////////////////////////////////////////////////////////////////////////////////// void COMMANDSYSTEM_API ClearScene(bool deleteActors = true, bool deleteActorInstances = true, MCore::CommandGroup* commandGroup = nullptr); - void COMMANDSYSTEM_API PrepareCollisionMeshesNodesString(EMotionFX::Actor* actor, uint32 lod, AZStd::string* outNodeNames); + void COMMANDSYSTEM_API PrepareCollisionMeshesNodesString(EMotionFX::Actor* actor, size_t lod, AZStd::string* outNodeNames); void COMMANDSYSTEM_API PrepareExcludedNodesString(EMotionFX::Actor* actor, AZStd::string* outNodeNames); } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp index 24cca2e416..ba25318944 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.cpp @@ -25,7 +25,7 @@ namespace CommandSystem CommandCreateActorInstance::CommandCreateActorInstance(MCore::Command* orgCommand) : MCore::Command("CreateActorInstance", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -109,15 +109,15 @@ namespace CommandSystem } // in case of redoing the command set the previously used id - if (mPreviouslyUsedID != MCORE_INVALIDINDEX32) + if (m_previouslyUsedId != MCORE_INVALIDINDEX32) { - newInstance->SetID(mPreviouslyUsedID); + newInstance->SetID(m_previouslyUsedId); } - mPreviouslyUsedID = newInstance->GetID(); + m_previouslyUsedId = newInstance->GetID(); // setup the position, rotation and scale - AZ::Vector3 newPos = newInstance->GetLocalSpaceTransform().mPosition; + AZ::Vector3 newPos = newInstance->GetLocalSpaceTransform().m_position; if (parameters.CheckIfHasParameter("xPos")) { newPos.SetX(parameters.GetValueAsFloat("xPos", this)); @@ -141,7 +141,7 @@ namespace CommandSystem // add the actor instance to the selection if (select) { - GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("Select -actorInstanceID %i", newInstance->GetID()).c_str(), outResult); + GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("Select -actorInstanceID %u", newInstance->GetID()).c_str(), outResult); if (EMotionFX::GetActorManager().GetNumActorInstances() == 1 && GetCommandManager()->GetLockSelection() == false) { @@ -155,7 +155,7 @@ namespace CommandSystem } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); // return the id of the newly created actor instance @@ -174,7 +174,7 @@ namespace CommandSystem uint32 actorInstanceID = parameters.GetValueAsInt("actorInstanceID", MCORE_INVALIDINDEX32); if (actorInstanceID == MCORE_INVALIDINDEX32) { - actorInstanceID = mPreviouslyUsedID; + actorInstanceID = m_previouslyUsedId; } // find the actor intance based on the given id @@ -202,7 +202,7 @@ namespace CommandSystem } // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); // get rid of the actor instance if (actorInstance) @@ -274,7 +274,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("pos")) { AZ::Vector3 value = parameters.GetValueAsVector3("pos", this); - mOldPosition = actorInstance->GetLocalSpaceTransform().mPosition; + m_oldPosition = actorInstance->GetLocalSpaceTransform().m_position; actorInstance->SetLocalSpacePosition(value); } @@ -282,7 +282,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("rot")) { AZ::Vector4 value = parameters.GetValueAsVector4("rot", this); - mOldRotation = actorInstance->GetLocalSpaceTransform().mRotation; + m_oldRotation = actorInstance->GetLocalSpaceTransform().m_rotation; actorInstance->SetLocalSpaceRotation(AZ::Quaternion(value.GetX(), value.GetY(), value.GetZ(), value.GetW())); } @@ -292,7 +292,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("scale")) { AZ::Vector3 value = parameters.GetValueAsVector3("scale", this); - mOldScale = actorInstance->GetLocalSpaceTransform().mScale; + m_oldScale = actorInstance->GetLocalSpaceTransform().m_scale; actorInstance->SetLocalSpaceScale(value); } ) @@ -301,7 +301,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("lodLevel")) { uint32 value = parameters.GetValueAsInt("lodLevel", this); - mOldLODLevel = actorInstance->GetLODLevel(); + m_oldLodLevel = actorInstance->GetLODLevel(); actorInstance->SetLODLevel(value); } @@ -309,7 +309,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("isVisible")) { bool value = parameters.GetValueAsBool("isVisible", this); - mOldIsVisible = actorInstance->GetIsVisible(); + m_oldIsVisible = actorInstance->GetIsVisible(); actorInstance->SetIsVisible(value); } @@ -317,12 +317,12 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("doRender")) { bool value = parameters.GetValueAsBool("doRender", this); - mOldDoRender = actorInstance->GetRender(); + m_oldDoRender = actorInstance->GetRender(); actorInstance->SetRender(value); } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; @@ -345,13 +345,13 @@ namespace CommandSystem // set the position if (parameters.CheckIfHasParameter("pos")) { - actorInstance->SetLocalSpacePosition(mOldPosition); + actorInstance->SetLocalSpacePosition(m_oldPosition); } // set the rotation if (parameters.CheckIfHasParameter("rot")) { - actorInstance->SetLocalSpaceRotation(mOldRotation); + actorInstance->SetLocalSpaceRotation(m_oldRotation); } // set the scale @@ -359,30 +359,30 @@ namespace CommandSystem ( if (parameters.CheckIfHasParameter("scale")) { - actorInstance->SetLocalSpaceScale(mOldScale); + actorInstance->SetLocalSpaceScale(m_oldScale); } ) // set the LOD level if (parameters.CheckIfHasParameter("lodLevel")) { - actorInstance->SetLODLevel(mOldLODLevel); + actorInstance->SetLODLevel(m_oldLodLevel); } // set the visibility flag if (parameters.CheckIfHasParameter("isVisible")) { - actorInstance->SetIsVisible(mOldIsVisible); + actorInstance->SetIsVisible(m_oldIsVisible); } // set the rendering flag if (parameters.CheckIfHasParameter("doRender")) { - actorInstance->SetRender(mOldDoRender); + actorInstance->SetRender(m_oldDoRender); } // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return true; } @@ -440,15 +440,15 @@ namespace CommandSystem } // store the old values before removing the instance - mOldPosition = actorInstance->GetLocalSpaceTransform().mPosition; - mOldRotation = actorInstance->GetLocalSpaceTransform().mRotation; + m_oldPosition = actorInstance->GetLocalSpaceTransform().m_position; + m_oldRotation = actorInstance->GetLocalSpaceTransform().m_rotation; EMFX_SCALECODE ( - mOldScale = actorInstance->GetLocalSpaceTransform().mScale; + m_oldScale = actorInstance->GetLocalSpaceTransform().m_scale; ) - mOldLODLevel = actorInstance->GetLODLevel(); - mOldIsVisible = actorInstance->GetIsVisible(); - mOldDoRender = actorInstance->GetRender(); + m_oldLodLevel = actorInstance->GetLODLevel(); + m_oldIsVisible = actorInstance->GetIsVisible(); + m_oldDoRender = actorInstance->GetRender(); // remove the actor instance from the selection if (GetCommandManager()->GetLockSelection()) @@ -458,7 +458,7 @@ namespace CommandSystem // get the id from the corresponding actor and save it for undo EMotionFX::Actor* actor = actorInstance->GetActor(); - mOldActorID = actor->GetID(); + m_oldActorId = actor->GetID(); // get rid of the actor instance if (actorInstance) @@ -467,7 +467,7 @@ namespace CommandSystem } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; @@ -489,17 +489,17 @@ namespace CommandSystem AZStd::string commandString; MCore::CommandGroup commandGroup("Undo remove actor instance", 2); - commandString = AZStd::string::format("CreateActorInstance -actorID %i -actorInstanceID %i", mOldActorID, actorInstanceID); + commandString = AZStd::string::format("CreateActorInstance -actorID %i -actorInstanceID %i", m_oldActorId, actorInstanceID); commandGroup.AddCommandString(commandString.c_str()); - commandString = AZStd::string::format("AdjustActorInstance -actorInstanceID %i -pos \"%s\" -rot \"%s\" -scale \"%s\" -lodLevel %d -isVisible \"%s\" -doRender \"%s\"", + commandString = AZStd::string::format("AdjustActorInstance -actorInstanceID %i -pos \"%s\" -rot \"%s\" -scale \"%s\" -lodLevel %zu -isVisible \"%s\" -doRender \"%s\"", actorInstanceID, - AZStd::to_string(mOldPosition).c_str(), - AZStd::to_string(mOldRotation).c_str(), - AZStd::to_string(mOldScale).c_str(), - mOldLODLevel, - AZStd::to_string(mOldIsVisible).c_str(), - AZStd::to_string(mOldDoRender).c_str() + AZStd::to_string(m_oldPosition).c_str(), + AZStd::to_string(m_oldRotation).c_str(), + AZStd::to_string(m_oldScale).c_str(), + m_oldLodLevel, + AZStd::to_string(m_oldIsVisible).c_str(), + AZStd::to_string(m_oldDoRender).c_str() ); commandGroup.AddCommandString(commandString); @@ -507,7 +507,7 @@ namespace CommandSystem bool result = GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, outResult); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -538,10 +538,10 @@ namespace CommandSystem return; } - const AZ::Vector3& pos = actorInstance->GetLocalSpaceTransform().mPosition; - const AZ::Quaternion& rot = actorInstance->GetLocalSpaceTransform().mRotation; + const AZ::Vector3& pos = actorInstance->GetLocalSpaceTransform().m_position; + const AZ::Quaternion& rot = actorInstance->GetLocalSpaceTransform().m_rotation; #ifndef EMFX_SCALE_DISABLED - const AZ::Vector3& scale = actorInstance->GetLocalSpaceTransform().mScale; + const AZ::Vector3& scale = actorInstance->GetLocalSpaceTransform().m_scale; #else const AZ::Vector3 scale = AZ::Vector3::CreateOne(); #endif @@ -561,7 +561,7 @@ namespace CommandSystem { // get the selection and number of selected actor instances const SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selection.GetNumSelectedActorInstances(); + const size_t numActorInstances = selection.GetNumSelectedActorInstances(); // create the command group MCore::CommandGroup commandGroup("Clone actor instances", numActorInstances); @@ -570,7 +570,7 @@ namespace CommandSystem commandGroup.AddCommandString("Unselect -actorInstanceID SELECT_ALL -actorID SELECT_ALL"); // iterate over the selected instances and clone them - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get the current actor instance EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(i); @@ -612,14 +612,14 @@ namespace CommandSystem { // get the selection and number of selected actor instances const SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selection.GetNumSelectedActorInstances(); + const size_t numActorInstances = selection.GetNumSelectedActorInstances(); // create the command group MCore::CommandGroup commandGroup("Remove actor instances", numActorInstances); AZStd::string tempString; // iterate over the selected instances and clone them - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get the current actor instance EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(i); @@ -645,7 +645,7 @@ namespace CommandSystem { // get the selection and number of selected actor instances const SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selection.GetNumSelectedActorInstances(); + const size_t numActorInstances = selection.GetNumSelectedActorInstances(); // create the command group AZStd::string outResult; @@ -653,7 +653,7 @@ namespace CommandSystem MCore::CommandGroup commandGroup("Hide actor instances", numActorInstances * 2); // iterate over the selected instances - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get the current actor instance EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(i); @@ -685,7 +685,7 @@ namespace CommandSystem { // get the selection and number of selected actor instances const SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selection.GetNumSelectedActorInstances(); + const size_t numActorInstances = selection.GetNumSelectedActorInstances(); // create the command group AZStd::string outResult; @@ -693,7 +693,7 @@ namespace CommandSystem MCore::CommandGroup commandGroup("Unhide actor instances", numActorInstances * 2); // iterate over the selected instances - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get the current actor instance EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(i); @@ -722,7 +722,7 @@ namespace CommandSystem { // get the selection and number of selected actor instances SelectionList selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selection.GetNumSelectedActorInstances(); + const size_t numActorInstances = selection.GetNumSelectedActorInstances(); // create the command group AZStd::string outResult; @@ -730,7 +730,7 @@ namespace CommandSystem MCore::CommandGroup commandGroup("Unselect all actor instances", numActorInstances + 1); // iterate over the selected instances and clone them - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get the current actor instance EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h index 553fdbf0e6..604d88d037 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ActorInstanceCommands.h @@ -20,34 +20,34 @@ namespace CommandSystem // create a new actor instance MCORE_DEFINECOMMAND_START(CommandCreateActorInstance, "Create actor instance", true) public: - uint32 mPreviouslyUsedID; - bool mOldWorkspaceDirtyFlag; + uint32 m_previouslyUsedId; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // adjust a given actor instance MCORE_DEFINECOMMAND_START(CommandAdjustActorInstance, "Adjust actor instance", true) public: - AZ::Vector3 mOldPosition; - AZ::Quaternion mOldRotation; - AZ::Vector3 mOldScale; - uint32 mOldLODLevel; - bool mOldIsVisible; - bool mOldDoRender; - bool mOldWorkspaceDirtyFlag; + AZ::Vector3 m_oldPosition; + AZ::Quaternion m_oldRotation; + AZ::Vector3 m_oldScale; + size_t m_oldLodLevel; + bool m_oldIsVisible; + bool m_oldDoRender; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // remove an actor instance MCORE_DEFINECOMMAND_START(CommandRemoveActorInstance, "Remove actor instance", true) - uint32 mOldActorID; - AZ::Vector3 mOldPosition; - AZ::Quaternion mOldRotation; - AZ::Vector3 mOldScale; - uint32 mOldLODLevel; - bool mOldIsVisible; - bool mOldDoRender; - bool mOldWorkspaceDirtyFlag; + uint32 m_oldActorId; + AZ::Vector3 m_oldPosition; + AZ::Quaternion m_oldRotation; + AZ::Vector3 m_oldScale; + size_t m_oldLodLevel; + bool m_oldIsVisible; + bool m_oldDoRender; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END ////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp index fdc4e4d0e5..dbc25d7a60 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.cpp @@ -39,7 +39,7 @@ namespace CommandSystem CommandLoadAnimGraph::CommandLoadAnimGraph(MCore::Command* orgCommand) : MCore::Command("LoadAnimGraph", orgCommand) { - mOldAnimGraphID = MCORE_INVALIDINDEX32; + m_oldAnimGraphId = MCORE_INVALIDINDEX32; } @@ -77,8 +77,8 @@ namespace CommandSystem } // Check if the anim graph got already loaded via the command system. - const AZ::u32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (AZ::u32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (animGraph->GetFileNameString() == filename && @@ -107,11 +107,11 @@ namespace CommandSystem } // in case we are in a redo call assign the previously used id - if (mOldAnimGraphID != MCORE_INVALIDINDEX32) + if (m_oldAnimGraphId != MCORE_INVALIDINDEX32) { - animGraph->SetID(mOldAnimGraphID); + animGraph->SetID(m_oldAnimGraphId); } - mOldAnimGraphID = animGraph->GetID(); + m_oldAnimGraphId = animGraph->GetID(); animGraph->RecursiveInvalidateUniqueDatas(); @@ -126,7 +126,7 @@ namespace CommandSystem } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); // automatically select the anim graph after loading it @@ -144,18 +144,18 @@ namespace CommandSystem MCORE_UNUSED(parameters); // get the anim graph the command created - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mOldAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_oldAnimGraphId); if (animGraph == nullptr) { - outResult = AZStd::string::format("Cannot undo load anim graph command. Previously used anim graph id '%i' is not valid.", mOldAnimGraphID); + outResult = AZStd::string::format("Cannot undo load anim graph command. Previously used anim graph id '%i' is not valid.", m_oldAnimGraphId); return false; } // Remove the newly created anim graph. - const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", mOldAnimGraphID), outResult); + const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", m_oldAnimGraphId), outResult); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -184,7 +184,7 @@ namespace CommandSystem CommandCreateAnimGraph::CommandCreateAnimGraph(MCore::Command* orgCommand) : MCore::Command("CreateAnimGraph", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -221,11 +221,11 @@ namespace CommandSystem { animGraph->SetID(parameters.GetValueAsInt("animGraphID", this)); } - if (mPreviouslyUsedID != MCORE_INVALIDINDEX32) + if (m_previouslyUsedId != MCORE_INVALIDINDEX32) { - animGraph->SetID(mPreviouslyUsedID); + animGraph->SetID(m_previouslyUsedId); } - mPreviouslyUsedID = animGraph->GetID(); + m_previouslyUsedId = animGraph->GetID(); animGraph->RecursiveReinit(); animGraph->RecursiveInvalidateUniqueDatas(); @@ -238,7 +238,7 @@ namespace CommandSystem AZStd::to_string(outResult, animGraph->GetID()); // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; @@ -251,18 +251,18 @@ namespace CommandSystem MCORE_UNUSED(parameters); // get the anim graph the command created - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mPreviouslyUsedID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_previouslyUsedId); if (animGraph == nullptr) { - outResult = AZStd::string::format("Cannot undo create anim graph command. Previously used anim graph id '%i' is not valid.", mPreviouslyUsedID); + outResult = AZStd::string::format("Cannot undo create anim graph command. Previously used anim graph id '%i' is not valid.", m_previouslyUsedId); return false; } // remove the newly created anim graph again - const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", mPreviouslyUsedID), outResult); + const bool result = GetCommandManager()->ExecuteCommandInsideCommand(AZStd::string::format("RemoveAnimGraph -animGraphID %i", m_previouslyUsedId), outResult); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -312,7 +312,7 @@ namespace CommandSystem // remove all anim graphs, to do so we will iterate over them and issue an internal command for // that specific ID. This way we don't need to add complexity to this command to deal with all // the anim graph's undo data - for (uint32 i = 0; i < EMotionFX::GetAnimGraphManager().GetNumAnimGraphs();) + for (size_t i = 0; i < EMotionFX::GetAnimGraphManager().GetNumAnimGraphs();) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (!animGraph->GetIsOwnedByRuntime() && !animGraph->GetIsOwnedByAsset()) @@ -334,7 +334,7 @@ namespace CommandSystem if (someAnimGraphRemoved) { - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); } @@ -354,7 +354,7 @@ namespace CommandSystem // remove the given anim graph m_oldFileNamesAndIds.emplace_back(animGraph->GetFileName(), animGraph->GetID()); - uint32 oldIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); + size_t oldIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); // iterate through all anim graph instances and remove the ones that depend on the anim graph to be removed for (size_t i = 0; i < EMotionFX::GetAnimGraphManager().GetNumAnimGraphInstances(); ) @@ -375,15 +375,9 @@ namespace CommandSystem EMotionFX::GetAnimGraphManager().RemoveAnimGraph(animGraph); // Reselect the anim graph at the index of the removed one if possible. - const int numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (int indexToSelect = oldIndex; indexToSelect >= 0; indexToSelect--) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t indexToSelect = oldIndex; indexToSelect < numAnimGraphs; indexToSelect--) { - // Is the index to select in a valid range? - if (indexToSelect >= numAnimGraphs) - { - break; - } - EMotionFX::AnimGraph* selectionCandidate = EMotionFX::GetAnimGraphManager().GetAnimGraph(indexToSelect); if (!selectionCandidate->GetIsOwnedByRuntime()) { @@ -394,7 +388,7 @@ namespace CommandSystem } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; @@ -420,7 +414,7 @@ namespace CommandSystem } // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -446,9 +440,9 @@ namespace CommandSystem CommandActivateAnimGraph::CommandActivateAnimGraph(MCore::Command* orgCommand) : MCore::Command(s_activateAnimGraphCmdName, orgCommand) { - mActorInstanceID = MCORE_INVALIDINDEX32; - mOldAnimGraphUsed = MCORE_INVALIDINDEX32; - mOldMotionSetUsed = MCORE_INVALIDINDEX32; + m_actorInstanceId = MCORE_INVALIDINDEX32; + m_oldAnimGraphUsed = MCORE_INVALIDINDEX32; + m_oldMotionSetUsed = MCORE_INVALIDINDEX32; } CommandActivateAnimGraph::~CommandActivateAnimGraph() @@ -515,14 +509,14 @@ namespace CommandSystem } // store the actor instance ID - mActorInstanceID = actorInstance->GetID(); + m_actorInstanceId = actorInstance->GetID(); // get the motion system from the actor instance EMotionFX::MotionSystem* motionSystem = actorInstance->GetMotionSystem(); // remove all motion instances from this motion system - const uint32 numMotionInstances = motionSystem->GetNumMotionInstances(); - for (uint32 j = 0; j < numMotionInstances; ++j) + const size_t numMotionInstances = motionSystem->GetNumMotionInstances(); + for (size_t j = 0; j < numMotionInstances; ++j) { EMotionFX::MotionInstance* motionInstance = motionSystem->GetMotionInstance(j); motionSystem->RemoveMotionInstance(motionInstance); @@ -539,9 +533,9 @@ namespace CommandSystem EMotionFX::MotionSet* animGraphInstanceMotionSet = animGraphInstance->GetMotionSet(); // store the currently used anim graph ID, motion set ID and the visualize scale - mOldAnimGraphUsed = animGraphInstanceAnimGraph->GetID(); - mOldMotionSetUsed = (animGraphInstanceMotionSet) ? animGraphInstanceMotionSet->GetID() : MCORE_INVALIDINDEX32; - mOldVisualizeScaleUsed = animGraphInstance->GetVisualizeScale(); + m_oldAnimGraphUsed = animGraphInstanceAnimGraph->GetID(); + m_oldMotionSetUsed = (animGraphInstanceMotionSet) ? animGraphInstanceMotionSet->GetID() : MCORE_INVALIDINDEX32; + m_oldVisualizeScaleUsed = animGraphInstance->GetVisualizeScale(); // check if the anim graph is valid if (animGraph) @@ -572,8 +566,8 @@ namespace CommandSystem else // no one anim graph instance set on the actor instance, create a new one { // store the currently used ID as invalid - mOldAnimGraphUsed = MCORE_INVALIDINDEX32; - mOldMotionSetUsed = MCORE_INVALIDINDEX32; + m_oldAnimGraphUsed = MCORE_INVALIDINDEX32; + m_oldMotionSetUsed = MCORE_INVALIDINDEX32; // check if the anim graph is valid if (animGraph) @@ -591,7 +585,7 @@ namespace CommandSystem AZStd::to_string(outResult, animGraph ? animGraph->GetID() : MCORE_INVALIDINDEX32); // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); AZStd::string resultString; @@ -604,12 +598,12 @@ namespace CommandSystem if (parameters.GetValueAsBool("startRecording", this)) { EMotionFX::Recorder::RecordSettings settings; - settings.mFPS = 1000000; - settings.mRecordTransforms = true; - settings.mRecordAnimGraphStates = true; - settings.mRecordNodeHistory = true; - settings.mRecordScale = true; - settings.mInitialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb + settings.m_fps = 1000000; + settings.m_recordTransforms = true; + settings.m_recordAnimGraphStates = true; + settings.m_recordNodeHistory = true; + settings.m_recordScale = true; + settings.m_initialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb EMotionFX::GetRecorder().StartRecording(settings); } @@ -622,41 +616,41 @@ namespace CommandSystem MCORE_UNUSED(parameters); // get the actor instance id and check if it is valid - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceID); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(m_actorInstanceId); if (actorInstance == nullptr) { - outResult = AZStd::string::format("Cannot undo activate anim graph. Actor instance id '%i' is not valid.", mActorInstanceID); + outResult = AZStd::string::format("Cannot undo activate anim graph. Actor instance id '%i' is not valid.", m_actorInstanceId); return false; } // get the anim graph, invalid index is a special case to allow the anim graph to be nullptr EMotionFX::AnimGraph* animGraph; - if (mOldAnimGraphUsed == MCORE_INVALIDINDEX32) + if (m_oldAnimGraphUsed == MCORE_INVALIDINDEX32) { animGraph = nullptr; } else { - animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mOldAnimGraphUsed); + animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_oldAnimGraphUsed); if (animGraph == nullptr) { - outResult = AZStd::string::format("Cannot undo activate anim graph. Anim graph id '%i' is not valid.", mOldAnimGraphUsed); + outResult = AZStd::string::format("Cannot undo activate anim graph. Anim graph id '%i' is not valid.", m_oldAnimGraphUsed); return false; } } // get the motion set, invalid index is a special case to allow the motion set to be nullptr EMotionFX::MotionSet* motionSet; - if (mOldMotionSetUsed == MCORE_INVALIDINDEX32) + if (m_oldMotionSetUsed == MCORE_INVALIDINDEX32) { motionSet = nullptr; } else { - motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(mOldMotionSetUsed); + motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(m_oldMotionSetUsed); if (motionSet == nullptr) { - outResult = AZStd::string::format("Cannot undo activate anim graph. Motion set id '%i' is not valid.", mOldMotionSetUsed); + outResult = AZStd::string::format("Cannot undo activate anim graph. Motion set id '%i' is not valid.", m_oldMotionSetUsed); return false; } } @@ -665,8 +659,8 @@ namespace CommandSystem EMotionFX::MotionSystem* motionSystem = actorInstance->GetMotionSystem(); // remove all motion instances from this motion system - const uint32 numMotionInstances = motionSystem->GetNumMotionInstances(); - for (uint32 j = 0; j < numMotionInstances; ++j) + const size_t numMotionInstances = motionSystem->GetNumMotionInstances(); + for (size_t j = 0; j < numMotionInstances; ++j) { EMotionFX::MotionInstance* motionInstance = motionSystem->GetMotionInstance(j); motionSystem->RemoveMotionInstance(motionInstance); @@ -689,7 +683,7 @@ namespace CommandSystem // create a new anim graph instance animGraphInstance = EMotionFX::AnimGraphInstance::Create(animGraph, actorInstance, motionSet); - animGraphInstance->SetVisualizeScale(mOldVisualizeScaleUsed); + animGraphInstance->SetVisualizeScale(m_oldVisualizeScaleUsed); actorInstance->SetAnimGraphInstance(animGraphInstance); animGraphInstance->RecursiveInvalidateUniqueDatas(); @@ -708,7 +702,7 @@ namespace CommandSystem { // create a new anim graph instance animGraphInstance = EMotionFX::AnimGraphInstance::Create(animGraph, actorInstance, motionSet); - animGraphInstance->SetVisualizeScale(mOldVisualizeScaleUsed); + animGraphInstance->SetVisualizeScale(m_oldVisualizeScaleUsed); actorInstance->SetAnimGraphInstance(animGraphInstance); animGraphInstance->RecursiveInvalidateUniqueDatas(); @@ -719,7 +713,7 @@ namespace CommandSystem AZStd::to_string(outResult, animGraph ? animGraph->GetID() : MCORE_INVALIDINDEX32); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); AZStd::string resultString; GetCommandManager()->ExecuteCommandInsideCommand("Unselect -animGraphIndex SELECT_ALL", resultString); @@ -791,8 +785,8 @@ namespace CommandSystem if (reload) { // Remove all anim graphs with the given filename. - const AZ::u32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (AZ::u32 j = 0; j < numAnimGraphs; ++j) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t j = 0; j < numAnimGraphs; ++j) { const EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(j); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.h index 963e80fd8d..ae09420a29 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphCommands.h @@ -23,16 +23,16 @@ namespace CommandSystem public: using RelocateFilenameFunction = AZStd::function; RelocateFilenameFunction m_relocateFilenameFunction; - uint32 mOldAnimGraphID; - bool mOldWorkspaceDirtyFlag; + uint32 m_oldAnimGraphId; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // create a new anim graph MCORE_DEFINECOMMAND_START(CommandCreateAnimGraph, "Create a anim graph", true) public: - uint32 mPreviouslyUsedID; - bool mOldWorkspaceDirtyFlag; + uint32 m_previouslyUsedId; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END @@ -40,18 +40,18 @@ public: MCORE_DEFINECOMMAND_START(CommandRemoveAnimGraph, "Remove a anim graph", true) public: AZStd::vector> m_oldFileNamesAndIds; - bool mOldWorkspaceDirtyFlag; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // Activate the given anim graph. MCORE_DEFINECOMMAND_START(CommandActivateAnimGraph, "Activate a anim graph", true) public: - uint32 mActorInstanceID; - uint32 mOldAnimGraphUsed; - uint32 mOldMotionSetUsed; - float mOldVisualizeScaleUsed; - bool mOldWorkspaceDirtyFlag; + uint32 m_actorInstanceId; + uint32 m_oldAnimGraphUsed; + uint32 m_oldMotionSetUsed; + float m_oldVisualizeScaleUsed; + bool m_oldWorkspaceDirtyFlag; static const char* s_activateAnimGraphCmdName; MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp index 25e3924e0d..b6a3870073 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.cpp @@ -63,7 +63,7 @@ namespace CommandSystem CommandAnimGraphCreateConnection::CommandAnimGraphCreateConnection(MCore::Command* orgCommand) : MCore::Command("AnimGraphCreateConnection", orgCommand) { - mTransitionType = AZ::TypeId::CreateNull(); + m_transitionType = AZ::TypeId::CreateNull(); } // destructor @@ -83,13 +83,13 @@ namespace CommandSystem } // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); // get the transition type AZ::Outcome transitionTypeString = parameters.GetValueIfExists("transitionType", this); if (transitionTypeString.IsSuccess()) { - mTransitionType = AZ::TypeId::CreateString(transitionTypeString.GetValue().c_str()); + m_transitionType = AZ::TypeId::CreateString(transitionTypeString.GetValue().c_str()); } // get the node names @@ -116,18 +116,18 @@ namespace CommandSystem } // get the ports - mSourcePort = parameters.GetValueAsInt("sourcePort", 0); - mTargetPort = parameters.GetValueAsInt("targetPort", 0); - parameters.GetValue("sourcePortName", this, mSourcePortName); - parameters.GetValue("targetPortName", this, mTargetPortName); + m_sourcePort = parameters.GetValueAsInt("sourcePort", 0); + m_targetPort = parameters.GetValueAsInt("targetPort", 0); + parameters.GetValue("sourcePortName", this, m_sourcePortName); + parameters.GetValue("targetPortName", this, m_targetPortName); // in case the source port got specified by name, overwrite the source port number - if (!mSourcePortName.empty()) + if (!m_sourcePortName.empty()) { - mSourcePort = sourceNode->FindOutputPortIndex(mSourcePortName.c_str()); + m_sourcePort = sourceNode->FindOutputPortIndex(m_sourcePortName); // in case we want to add this connection to a parameter node while the parameter name doesn't exist, still return true so that copy paste doesn't fail - if (azrtti_typeid(sourceNode) == azrtti_typeid() && mSourcePort == -1) + if (azrtti_typeid(sourceNode) == azrtti_typeid() && m_sourcePort == InvalidIndex) { m_connectionId.SetInvalid(); return true; @@ -135,9 +135,9 @@ namespace CommandSystem } // in case the target port got specified by name, overwrite the target port number - if (!mTargetPortName.empty()) + if (!m_targetPortName.empty()) { - mTargetPort = targetNode->FindInputPortIndex(mTargetPortName.c_str()); + m_targetPort = targetNode->FindInputPortIndex(m_targetPortName.c_str()); } // get the parent of the source node @@ -157,27 +157,27 @@ namespace CommandSystem } // verify port ranges - if (mSourcePort >= static_cast(sourceNode->GetOutputPorts().size()) || mSourcePort < 0) + if (m_sourcePort >= sourceNode->GetOutputPorts().size()) { outResult = AZStd::string::format("The output port number is not valid for the given node. Node '%s' only has %zu output ports.", sourceNode->GetName(), sourceNode->GetOutputPorts().size()); return false; } - if (mTargetPort >= static_cast(targetNode->GetInputPorts().size()) || mTargetPort < 0) + if (m_targetPort >= targetNode->GetInputPorts().size()) { outResult = AZStd::string::format("The input port number is not valid for the given node. Node '%s' only has %zu input ports.", targetNode->GetName(), targetNode->GetInputPorts().size()); return false; } // check if connection already exists - if (targetNode->GetHasConnection(sourceNode, static_cast(mSourcePort), static_cast(mTargetPort))) + if (targetNode->GetHasConnection(sourceNode, static_cast(m_sourcePort), static_cast(m_targetPort))) { outResult = AZStd::string::format("The connection you are trying to create already exists!"); return false; } // create the connection and auto assign an id first of all - EMotionFX::BlendTreeConnection* connection = targetNode->AddConnection(sourceNode, static_cast(mSourcePort), static_cast(mTargetPort)); + EMotionFX::BlendTreeConnection* connection = targetNode->AddConnection(sourceNode, static_cast(m_sourcePort), static_cast(m_targetPort)); // Overwrite the connection id if specified by a command parameter. if (parameters.CheckIfHasParameter("id")) @@ -201,8 +201,8 @@ namespace CommandSystem if (azrtti_istypeof(targetNode)) { EMotionFX::BlendTreeBlendNNode* blendTreeBlendNNode = static_cast(targetNode); - mUpdateParamFlag = parameters.GetValueAsBool("updateParam", true); - if (mUpdateParamFlag) + m_updateParamFlag = parameters.GetValueAsBool("updateParam", true); + if (m_updateParamFlag) { blendTreeBlendNNode->UpdateParamWeights(); } @@ -214,17 +214,17 @@ namespace CommandSystem EMotionFX::AnimGraphStateMachine* machine = (EMotionFX::AnimGraphStateMachine*)targetNode->GetParentNode(); // try to create the anim graph node - EMotionFX::AnimGraphObject* object = EMotionFX::AnimGraphObjectFactory::Create(mTransitionType, animGraph); + EMotionFX::AnimGraphObject* object = EMotionFX::AnimGraphObjectFactory::Create(m_transitionType, animGraph); if (!object) { - outResult = AZStd::string::format("Cannot create transition of type %s", mTransitionType.ToString().c_str()); + outResult = AZStd::string::format("Cannot create transition of type %s", m_transitionType.ToString().c_str()); return false; } // check if this is really a transition if (!azrtti_istypeof(object)) { - outResult = AZStd::string::format("Cannot create state transition of type %s, because this object type is not inherited from AnimGraphStateTransition.", mTransitionType.ToString().c_str()); + outResult = AZStd::string::format("Cannot create state transition of type %s, because this object type is not inherited from AnimGraphStateTransition.", m_transitionType.ToString().c_str()); return false; } @@ -255,13 +255,13 @@ namespace CommandSystem transition->SetTargetNode(targetNode); // get the offsets - mStartOffsetX = parameters.GetValueAsInt("startOffsetX", 0); - mStartOffsetY = parameters.GetValueAsInt("startOffsetY", 0); - mEndOffsetX = parameters.GetValueAsInt("endOffsetX", 0); - mEndOffsetY = parameters.GetValueAsInt("endOffsetY", 0); + m_startOffsetX = parameters.GetValueAsInt("startOffsetX", 0); + m_startOffsetY = parameters.GetValueAsInt("startOffsetY", 0); + m_endOffsetX = parameters.GetValueAsInt("endOffsetX", 0); + m_endOffsetY = parameters.GetValueAsInt("endOffsetY", 0); if (parameters.CheckIfHasValue("startOffsetX") || parameters.CheckIfHasValue("startOffsetY") || parameters.CheckIfHasValue("endOffsetX") || parameters.CheckIfHasValue("endOffsetY")) { - transition->SetVisualOffsets(mStartOffsetX, mStartOffsetY, mEndOffsetX, mEndOffsetY); + transition->SetVisualOffsets(m_startOffsetX, m_startOffsetY, m_endOffsetX, m_endOffsetY); } transition->SetIsWildcardTransition(isWildcardTransition); @@ -290,19 +290,19 @@ namespace CommandSystem transition->Reinit(); } - mTargetNodeId.SetInvalid(); - mSourceNodeId.SetInvalid(); + m_targetNodeId.SetInvalid(); + m_sourceNodeId.SetInvalid(); if (targetNode) { - mTargetNodeId = targetNode->GetId(); + m_targetNodeId = targetNode->GetId(); } if (sourceNode) { - mSourceNodeId = sourceNode->GetId(); + m_sourceNodeId = sourceNode->GetId(); } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); // set the command result to the connection id @@ -319,16 +319,16 @@ namespace CommandSystem MCORE_UNUSED(parameters); // get the anim graph - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (animGraph == nullptr) { - outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID); + outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId); return false; } // in case of a wildcard transition the source node is the invalid index, so that's all fine - EMotionFX::AnimGraphNode* sourceNode = animGraph->RecursiveFindNodeById(mSourceNodeId); - EMotionFX::AnimGraphNode* targetNode = animGraph->RecursiveFindNodeById(mTargetNodeId); + EMotionFX::AnimGraphNode* sourceNode = animGraph->RecursiveFindNodeById(m_sourceNodeId); + EMotionFX::AnimGraphNode* targetNode = animGraph->RecursiveFindNodeById(m_targetNodeId); // NOTE: When source node is a nullptr, we are dealing with a wildcard transition, so there a nullptr is allowed. if (!targetNode) @@ -345,18 +345,18 @@ namespace CommandSystem } // delete the connection - const AZStd::string commandString = AZStd::string::format("AnimGraphRemoveConnection -animGraphID %i -targetNode \"%s\" -targetPort %d -sourceNode \"%s\" -sourcePort %d -id %s", + const AZStd::string commandString = AZStd::string::format("AnimGraphRemoveConnection -animGraphID %i -targetNode \"%s\" -targetPort %zu -sourceNode \"%s\" -sourcePort %zu -id %s", animGraph->GetID(), targetNode->GetName(), - mTargetPort, + m_targetPort, sourceNodeName.c_str(), - mSourcePort, + m_sourcePort, m_connectionId.ToString().c_str()); // execute the command without putting it in the history if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult)) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -365,11 +365,11 @@ namespace CommandSystem } // reset the data used for undo and redo - mSourceNodeId.SetInvalid(); - mTargetNodeId.SetInvalid(); + m_sourceNodeId.SetInvalid(); + m_targetNodeId.SetInvalid(); // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -414,13 +414,13 @@ namespace CommandSystem CommandAnimGraphRemoveConnection::CommandAnimGraphRemoveConnection(MCore::Command* orgCommand) : MCore::Command("AnimGraphRemoveConnection", orgCommand) { - mSourcePort = MCORE_INVALIDINDEX32; - mTargetPort = MCORE_INVALIDINDEX32; - mTransitionType = AZ::TypeId::CreateNull(); - mStartOffsetX = 0; - mStartOffsetY = 0; - mEndOffsetX = 0; - mEndOffsetY = 0; + m_sourcePort = InvalidIndex; + m_targetPort = InvalidIndex; + m_transitionType = AZ::TypeId::CreateNull(); + m_startOffsetX = 0; + m_startOffsetY = 0; + m_endOffsetX = 0; + m_endOffsetY = 0; } @@ -441,7 +441,7 @@ namespace CommandSystem } // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); // get the node names AZStd::string sourceNodeName; @@ -466,19 +466,19 @@ namespace CommandSystem } // get the ids from the source and destination nodes - mSourceNodeId.SetInvalid(); - mSourceNodeName.clear(); + m_sourceNodeId.SetInvalid(); + m_sourceNodeName.clear(); if (sourceNode) { - mSourceNodeId = sourceNode->GetId(); - mSourceNodeName = sourceNode->GetName(); + m_sourceNodeId = sourceNode->GetId(); + m_sourceNodeName = sourceNode->GetName(); } - mTargetNodeId = targetNode->GetId(); - mTargetNodeName = targetNode->GetName(); + m_targetNodeId = targetNode->GetId(); + m_targetNodeName = targetNode->GetName(); // get the ports - mSourcePort = parameters.GetValueAsInt("sourcePort", 0); - mTargetPort = parameters.GetValueAsInt("targetPort", 0); + m_sourcePort = parameters.GetValueAsInt("sourcePort", 0); + m_targetPort = parameters.GetValueAsInt("targetPort", 0); // get the parent of the source node if (targetNode->GetParentNode() == nullptr) @@ -497,34 +497,34 @@ namespace CommandSystem } // verify port ranges - if (mSourcePort >= static_cast(sourceNode->GetOutputPorts().size()) || mSourcePort < 0) + if (m_sourcePort >= static_cast(sourceNode->GetOutputPorts().size()) || m_sourcePort < 0) { outResult = AZStd::string::format("The output port number is not valid for the given node. Node '%s' only has %zu output ports.", sourceNode->GetName(), sourceNode->GetOutputPorts().size()); return false; } - if (mTargetPort >= static_cast(targetNode->GetInputPorts().size()) || mTargetPort < 0) + if (m_targetPort >= static_cast(targetNode->GetInputPorts().size()) || m_targetPort < 0) { outResult = AZStd::string::format("The input port number is not valid for the given node. Node '%s' only has %zu input ports.", targetNode->GetName(), targetNode->GetInputPorts().size()); return false; } // check if connection already exists - if (!targetNode->GetHasConnection(sourceNode, static_cast(mSourcePort), static_cast(mTargetPort))) + if (!targetNode->GetHasConnection(sourceNode, static_cast(m_sourcePort), static_cast(m_targetPort))) { outResult = AZStd::string::format("The connection you are trying to remove doesn't exist!"); return false; } // get the connection ID and store it - EMotionFX::BlendTreeConnection* connection = targetNode->FindConnection(sourceNode, static_cast(mSourcePort), static_cast(mTargetPort)); + EMotionFX::BlendTreeConnection* connection = targetNode->FindConnection(sourceNode, static_cast(m_sourcePort), static_cast(m_targetPort)); if (connection) { m_connectionId = connection->GetId(); } // create the connection - targetNode->RemoveConnection(sourceNode, static_cast(mSourcePort), static_cast(mTargetPort)); + targetNode->RemoveConnection(sourceNode, static_cast(m_sourcePort), static_cast(m_targetPort)); if (azrtti_istypeof(targetNode)) { @@ -558,13 +558,13 @@ namespace CommandSystem // save the transition information for undo EMotionFX::AnimGraphStateTransition* transition = stateMachine->GetTransition(transitionIndex.GetValue()); - mStartOffsetX = transition->GetVisualStartOffsetX(); - mStartOffsetY = transition->GetVisualStartOffsetY(); - mEndOffsetX = transition->GetVisualEndOffsetX(); - mEndOffsetY = transition->GetVisualEndOffsetY(); - mTransitionType = azrtti_typeid(transition); + m_startOffsetX = transition->GetVisualStartOffsetX(); + m_startOffsetY = transition->GetVisualStartOffsetY(); + m_endOffsetX = transition->GetVisualEndOffsetX(); + m_endOffsetY = transition->GetVisualEndOffsetY(); + m_transitionType = azrtti_typeid(transition); m_connectionId = transition->GetId(); - mOldContents = MCore::ReflectionSerializer::Serialize(transition).GetValue(); + m_oldContents = MCore::ReflectionSerializer::Serialize(transition).GetValue(); // remove all unique datas for the transition itself animGraph->RemoveAllObjectData(transition, true); @@ -574,7 +574,7 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); if(parameters.GetValueAsBool("updateUniqueData", true)) @@ -591,39 +591,39 @@ namespace CommandSystem const AZStd::string updateUniqueData = parameters.GetValue("updateUniqueData", this); // get the anim graph - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (animGraph == nullptr) { - outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID); + outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId); return false; } - if (!mTargetNodeId.IsValid()) + if (!m_targetNodeId.IsValid()) { return false; } - AZStd::string commandString = AZStd::string::format("AnimGraphCreateConnection -animGraphID %i -sourceNode \"%s\" -targetNode \"%s\" -sourcePort %d -targetPort %d -startOffsetX %d -startOffsetY %d -endOffsetX %d -endOffsetY %d -id %s -transitionType \"%s\" -updateUniqueData %s", + AZStd::string commandString = AZStd::string::format("AnimGraphCreateConnection -animGraphID %i -sourceNode \"%s\" -targetNode \"%s\" -sourcePort %zu -targetPort %zu -startOffsetX %d -startOffsetY %d -endOffsetX %d -endOffsetY %d -id %s -transitionType \"%s\" -updateUniqueData %s", animGraph->GetID(), - mSourceNodeName.c_str(), - mTargetNodeName.c_str(), - mSourcePort, - mTargetPort, - mStartOffsetX, mStartOffsetY, - mEndOffsetX, mEndOffsetY, + m_sourceNodeName.c_str(), + m_targetNodeName.c_str(), + m_sourcePort, + m_targetPort, + m_startOffsetX, m_startOffsetY, + m_endOffsetX, m_endOffsetY, m_connectionId.ToString().c_str(), - mTransitionType.ToString().c_str(), + m_transitionType.ToString().c_str(), updateUniqueData.c_str()); // add the old attributes - if (mOldContents.empty() == false) + if (m_oldContents.empty() == false) { - commandString += AZStd::string::format(" -contents {%s}", mOldContents.c_str()); + commandString += AZStd::string::format(" -contents {%s}", m_oldContents.c_str()); } if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult)) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -631,18 +631,18 @@ namespace CommandSystem return false; } - mTargetNodeId.SetInvalid(); - mSourceNodeId.SetInvalid(); + m_targetNodeId.SetInvalid(); + m_sourceNodeId.SetInvalid(); m_connectionId.SetInvalid(); - mSourcePort = MCORE_INVALIDINDEX32; - mTargetPort = MCORE_INVALIDINDEX32; - mStartOffsetX = 0; - mStartOffsetY = 0; - mEndOffsetX = 0; - mEndOffsetY = 0; + m_sourcePort = InvalidIndex; + m_targetPort = InvalidIndex; + m_startOffsetX = 0; + m_startOffsetY = 0; + m_endOffsetX = 0; + m_endOffsetY = 0; // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -839,7 +839,7 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); transition->Reinit(); @@ -865,14 +865,14 @@ namespace CommandSystem } AdjustTransition(transition, - /*mOldDisabledFlag=*/AZStd::nullopt, - /*sourceNodeName=*/AZStd::nullopt, /*targetNodeName=*/AZStd::nullopt, + /*isDisabled=*/AZStd::nullopt, + /*sourceNode=*/AZStd::nullopt, /*targetNode=*/AZStd::nullopt, /*startOffsetX=*/AZStd::nullopt, /*startOffsetY=*/AZStd::nullopt, /*endOffsetX=*/AZStd::nullopt, /*endOffsetY=*/AZStd::nullopt, /*attributesString=*/AZStd::nullopt, /*serializedMembers=*/m_oldSerializedMembers.GetValue(), /*commandGroup*/nullptr, /*executeInsideCommand*/true); - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -970,8 +970,8 @@ namespace CommandSystem // Delete the connections that start from the given node. if (parentNode) { - const uint32 numChildNodes = parentNode->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = parentNode->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { EMotionFX::AnimGraphNode* childNode = parentNode->GetChildNode(i); if (childNode == node) @@ -979,8 +979,8 @@ namespace CommandSystem continue; } - const uint32 numChildConnections = childNode->GetNumConnections(); - for (uint32 j = 0; j < numChildConnections; ++j) + const size_t numChildConnections = childNode->GetNumConnections(); + for (size_t j = 0; j < numChildConnections; ++j) { EMotionFX::BlendTreeConnection* childConnection = childNode->GetConnection(j); @@ -994,8 +994,8 @@ namespace CommandSystem } // Delete the connections that end in the given node. - const uint32 numConnections = node->GetNumConnections(); - for (uint32 i = 0; i < numConnections; ++i) + const size_t numConnections = node->GetNumConnections(); + for (size_t i = 0; i < numConnections; ++i) { EMotionFX::BlendTreeConnection* connection = node->GetConnection(i); DeleteConnection(commandGroup, node, connection, connectionList); @@ -1004,8 +1004,8 @@ namespace CommandSystem // Recursively delete all connections. if (recursive) { - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { EMotionFX::AnimGraphNode* childNode = node->GetChildNode(i); DeleteNodeConnections(commandGroup, childNode, node, connectionList, recursive); @@ -1194,8 +1194,8 @@ namespace CommandSystem // Recursively delete all transitions. if (recursive) { - const uint32 numChildNodes = state->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = state->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { EMotionFX::AnimGraphNode* childNode = state->GetChildNode(i); DeleteStateTransitions(commandGroup, childNode, state, transitionList, recursive); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h index 2bcebb630a..2f0a03a191 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphConnectionCommands.h @@ -26,64 +26,64 @@ namespace CommandSystem { // create a connection MCORE_DEFINECOMMAND_START(CommandAnimGraphCreateConnection, "Connect two anim graph nodes", true) - uint32 mAnimGraphID; - EMotionFX::AnimGraphNodeId mTargetNodeId; - EMotionFX::AnimGraphNodeId mSourceNodeId; + uint32 m_animGraphId; + EMotionFX::AnimGraphNodeId m_targetNodeId; + EMotionFX::AnimGraphNodeId m_sourceNodeId; EMotionFX::AnimGraphConnectionId m_connectionId; - AZ::TypeId mTransitionType; - int32 mStartOffsetX; - int32 mStartOffsetY; - int32 mEndOffsetX; - int32 mEndOffsetY; - int32 mSourcePort; - int32 mTargetPort; - AZStd::string mSourcePortName; - AZStd::string mTargetPortName; - bool mOldDirtyFlag; - bool mUpdateParamFlag; + AZ::TypeId m_transitionType; + int32 m_startOffsetX; + int32 m_startOffsetY; + int32 m_endOffsetX; + int32 m_endOffsetY; + size_t m_sourcePort; + size_t m_targetPort; + AZStd::string m_sourcePortName; + AZStd::string m_targetPortName; + bool m_oldDirtyFlag; + bool m_updateParamFlag; public: EMotionFX::AnimGraphConnectionId GetConnectionId() const{ return m_connectionId; } - EMotionFX::AnimGraphNodeId GetTargetNodeId() const { return mTargetNodeId; } - EMotionFX::AnimGraphNodeId GetSourceNodeId() const { return mSourceNodeId; } - AZ::TypeId GetTransitionType() const { return mTransitionType; } - int32 GetSourcePort() const { return mSourcePort; } - int32 GetTargetPort() const { return mTargetPort; } - int32 GetStartOffsetX() const { return mStartOffsetX; } - int32 GetStartOffsetY() const { return mStartOffsetY; } - int32 GetEndOffsetX() const { return mEndOffsetX; } - int32 GetEndOffsetY() const { return mEndOffsetY; } + EMotionFX::AnimGraphNodeId GetTargetNodeId() const { return m_targetNodeId; } + EMotionFX::AnimGraphNodeId GetSourceNodeId() const { return m_sourceNodeId; } + AZ::TypeId GetTransitionType() const { return m_transitionType; } + size_t GetSourcePort() const { return m_sourcePort; } + size_t GetTargetPort() const { return m_targetPort; } + int32 GetStartOffsetX() const { return m_startOffsetX; } + int32 GetStartOffsetY() const { return m_startOffsetY; } + int32 GetEndOffsetX() const { return m_endOffsetX; } + int32 GetEndOffsetY() const { return m_endOffsetY; } MCORE_DEFINECOMMAND_END // remove a connection MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveConnection, "Remove a anim graph connection", true) - uint32 mAnimGraphID; - EMotionFX::AnimGraphNodeId mTargetNodeId; - AZStd::string mTargetNodeName; - EMotionFX::AnimGraphNodeId mSourceNodeId; - AZStd::string mSourceNodeName; + uint32 m_animGraphId; + EMotionFX::AnimGraphNodeId m_targetNodeId; + AZStd::string m_targetNodeName; + EMotionFX::AnimGraphNodeId m_sourceNodeId; + AZStd::string m_sourceNodeName; EMotionFX::AnimGraphConnectionId m_connectionId; - AZ::TypeId mTransitionType; - int32 mStartOffsetX; - int32 mStartOffsetY; - int32 mEndOffsetX; - int32 mEndOffsetY; - int32 mSourcePort; - int32 mTargetPort; - bool mOldDirtyFlag; - AZStd::string mOldContents; + AZ::TypeId m_transitionType; + int32 m_startOffsetX; + int32 m_startOffsetY; + int32 m_endOffsetX; + int32 m_endOffsetY; + size_t m_sourcePort; + size_t m_targetPort; + bool m_oldDirtyFlag; + AZStd::string m_oldContents; public: - EMotionFX::AnimGraphNodeId GetTargetNodeID() const { return mTargetNodeId; } - EMotionFX::AnimGraphNodeId GetSourceNodeID() const { return mSourceNodeId; } - AZ::TypeId GetTransitionType() const { return mTransitionType; } - int32 GetSourcePort() const { return mSourcePort; } - int32 GetTargetPort() const { return mTargetPort; } - int32 GetStartOffsetX() const { return mStartOffsetX; } - int32 GetStartOffsetY() const { return mStartOffsetY; } - int32 GetEndOffsetX() const { return mEndOffsetX; } - int32 GetEndOffsetY() const { return mEndOffsetY; } + EMotionFX::AnimGraphNodeId GetTargetNodeID() const { return m_targetNodeId; } + EMotionFX::AnimGraphNodeId GetSourceNodeID() const { return m_sourceNodeId; } + AZ::TypeId GetTransitionType() const { return m_transitionType; } + size_t GetSourcePort() const { return m_sourcePort; } + size_t GetTargetPort() const { return m_targetPort; } + int32 GetStartOffsetX() const { return m_startOffsetX; } + int32 GetStartOffsetY() const { return m_startOffsetY; } + int32 GetEndOffsetX() const { return m_endOffsetX; } + int32 GetEndOffsetY() const { return m_endOffsetY; } EMotionFX::AnimGraphConnectionId GetConnectionId() const{ return m_connectionId; } MCORE_DEFINECOMMAND_END @@ -127,7 +127,7 @@ namespace CommandSystem private: AZ::Outcome m_oldSerializedMembers; // Without actions and conditions. - bool mOldDirtyFlag = false; + bool m_oldDirtyFlag = false; }; ////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.cpp index a349059799..9131706b69 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.cpp @@ -54,7 +54,7 @@ namespace CommandSystem { // Get the parameter name. const AZStd::string& name = parameters.GetValue("name", this); - mOldName = name; + m_oldName = name; // Find the anim graph by using the id from command parameter. const uint32 animGraphID = parameters.GetValueAsInt("animGraphID", this); @@ -108,7 +108,7 @@ namespace CommandSystem } const size_t numParameters = parameterNames.size(); - mOldGroupParameterNames.resize(numParameters); + m_oldGroupParameterNames.resize(numParameters); EMotionFX::ValueParameterVector valueParametersBeforeChange = animGraph->RecursivelyGetValueParameters(); @@ -118,13 +118,13 @@ namespace CommandSystem const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(parameterNames[i]); if (!parameter) { - mOldGroupParameterNames[i].clear(); + m_oldGroupParameterNames[i].clear(); continue; } // Save the group parameter (for undo) to which the parameter belonged before command execution. const EMotionFX::GroupParameter* parentParameter = animGraph->FindParentGroupParameter(parameter); - mOldGroupParameterNames[i] = parentParameter ? parentParameter->GetName() : ""; + m_oldGroupParameterNames[i] = parentParameter ? parentParameter->GetName() : ""; // Make sure the parameter is not in any other group. animGraph->TakeParameterFromParent(parameter); @@ -175,7 +175,7 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); animGraph->RecursiveInvalidateUniqueDatas(); @@ -196,13 +196,13 @@ namespace CommandSystem MCore::CommandGroup commandGroup; - // Undo the group name as first step. All commands afterwards have to use mOldName as group name. + // Undo the group name as first step. All commands afterwards have to use m_oldName as group name. if (parameters.CheckIfHasParameter("newName")) { const AZStd::string& newName = parameters.GetValue("newName", this); const AZStd::string command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -newName \"%s\"", - animGraph->GetID(), newName.c_str(), mOldName.c_str()); + animGraph->GetID(), newName.c_str(), m_oldName.c_str()); commandGroup.AddCommandString(command); } @@ -210,7 +210,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("description")) { const AZStd::string command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -description \"%s\"", - animGraph->GetID(), mOldName.c_str(), m_oldDescription.c_str()); + animGraph->GetID(), m_oldName.c_str(), m_oldDescription.c_str()); commandGroup.AddCommandString(command); } @@ -225,12 +225,12 @@ namespace CommandSystem AzFramework::StringFunc::Tokenize(parametersString.c_str(), parameterNames, ";", false, true); const size_t parameterCount = parameterNames.size(); - AZ_Assert(parameterCount == mOldGroupParameterNames.size(), "The number of parameter names has to match the saved group parameter info for undo."); + AZ_Assert(parameterCount == m_oldGroupParameterNames.size(), "The number of parameter names has to match the saved group parameter info for undo."); for (size_t i = 0; i < parameterCount; ++i) { const AZStd::string& parameterName = parameterNames[i]; - const AZStd::string& oldGroupName = mOldGroupParameterNames[i]; + const AZStd::string& oldGroupName = m_oldGroupParameterNames[i]; switch (action) { @@ -240,7 +240,7 @@ namespace CommandSystem { // An empty old group name means that the parameter was in the Default group before, so in this case just remove the parameter from the group. const AZStd::string command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -action \"remove\" -parameterNames \"%s\"", - animGraph->GetID(), mOldName.c_str(), parameterName.c_str()); + animGraph->GetID(), m_oldName.c_str(), parameterName.c_str()); commandGroup.AddCommandString(command); } @@ -277,7 +277,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -364,8 +364,8 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); - mOldName = groupParameter->GetName(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldName = groupParameter->GetName(); animGraph->SetDirtyFlag(true); animGraph->RecursiveInvalidateUniqueDatas(); @@ -385,7 +385,7 @@ namespace CommandSystem } // Construct and execute the command. - const AZStd::string command = AZStd::string::format("AnimGraphRemoveGroupParameter -animGraphID %i -name \"%s\"", animGraphID, mOldName.c_str()); + const AZStd::string command = AZStd::string::format("AnimGraphRemoveGroupParameter -animGraphID %i -name \"%s\"", animGraphID, m_oldName.c_str()); AZStd::string result; if (!GetCommandManager()->ExecuteCommandInsideCommand(command, result)) @@ -394,7 +394,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -457,23 +457,23 @@ namespace CommandSystem } // read out information for the command undo - mOldName = parameter->GetName(); + m_oldName = parameter->GetName(); const EMotionFX::GroupParameter* parentGroup = animGraph->FindParentGroupParameter(parameter); if (parentGroup) { - mOldParent = parentGroup->GetName(); - mOldIndex = parentGroup->FindParameterIndex(parameter).GetValue(); + m_oldParent = parentGroup->GetName(); + m_oldIndex = parentGroup->FindParameterIndex(parameter).GetValue(); } else { - mOldParent = ""; - mOldIndex = animGraph->FindParameterIndex(parameter).GetValue(); + m_oldParent = ""; + m_oldIndex = animGraph->FindParameterIndex(parameter).GetValue(); } - mOldParameterNames.clear(); + m_oldParameterNames.clear(); // Collect all child parameters and move them to the default group. Keep the child hierarchy as it is. - // Add the immediate child ones to mOldParameterNames so they get moved back on undo + // Add the immediate child ones to m_oldParameterNames so they get moved back on undo const EMotionFX::GroupParameter* groupParameter = static_cast(parameter); const EMotionFX::ParameterVector childParameters = groupParameter->RecursivelyGetChildParameters(); AZStd::vector childParents; @@ -497,7 +497,7 @@ namespace CommandSystem const EMotionFX::GroupParameter* parent = childParents[i]; if (parent == groupParameter) { - mOldParameterNames += childParameters[i]->GetName() + ";"; + m_oldParameterNames += childParameters[i]->GetName() + ";"; animGraph->AddParameter(childParameters[i]); // add to default group } else @@ -505,9 +505,9 @@ namespace CommandSystem animGraph->AddParameter(childParameters[i], parent); // add to default group } } - if (!mOldParameterNames.empty()) + if (!m_oldParameterNames.empty()) { - mOldParameterNames.pop_back(); // remove trailing ";" + m_oldParameterNames.pop_back(); // remove trailing ";" } // remove the group parameter @@ -529,7 +529,7 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); animGraph->RecursiveInvalidateUniqueDatas(); @@ -555,18 +555,18 @@ namespace CommandSystem command = AZStd::string::format("AnimGraphAddGroupParameter -animGraphID %i -name \"%s\" -index %zu -parent \"%s\" -updateUI %s", animGraph->GetID(), - mOldName.c_str(), - mOldIndex, - mOldParent.c_str(), + m_oldName.c_str(), + m_oldIndex, + m_oldParent.c_str(), updateWindow.c_str()); commandGroup.AddCommandString(command); - if (!mOldParameterNames.empty()) + if (!m_oldParameterNames.empty()) { command = AZStd::string::format("AnimGraphAdjustGroupParameter -animGraphID %i -name \"%s\" -parameterNames \"%s\" -action \"add\" -updateUI %s", animGraph->GetID(), - mOldName.c_str(), - mOldParameterNames.c_str(), + m_oldName.c_str(), + m_oldParameterNames.c_str(), updateWindow.c_str()); commandGroup.AddCommandString(command); } @@ -579,7 +579,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.h index 80e43818c7..3bdc7f3e0e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphGroupParameterCommands.h @@ -27,25 +27,25 @@ namespace CommandSystem }; Action GetAction(const MCore::CommandLine& parameters); - AZStd::string mOldName; //! group parameter name before command execution. - AZStd::vector mOldGroupParameterNames; - bool mOldDirtyFlag; + AZStd::string m_oldName; //! group parameter name before command execution. + AZStd::vector m_oldGroupParameterNames; + bool m_oldDirtyFlag; AZStd::string m_oldDescription; MCORE_DEFINECOMMAND_END // Add a group parameter. MCORE_DEFINECOMMAND_START(CommandAnimGraphAddGroupParameter, "Add anim graph group parameter", true) - bool mOldDirtyFlag; - AZStd::string mOldName; + bool m_oldDirtyFlag; + AZStd::string m_oldName; MCORE_DEFINECOMMAND_END // Remove a group parameter. MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveGroupParameter, "Remove anim graph group parameter", true) - AZStd::string mOldName; - AZStd::string mOldParameterNames; - AZStd::string mOldParent; - size_t mOldIndex; - bool mOldDirtyFlag; + AZStd::string m_oldName; + AZStd::string m_oldParameterNames; + AZStd::string m_oldParent; + size_t m_oldIndex; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // helper functions diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp index fe41312701..d81d495a4d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp @@ -113,7 +113,7 @@ namespace CommandSystem return EMotionFX::AnimGraphNodeId::CreateFromString(nodeIdString); } - return mNodeId; + return m_nodeId; } void CommandAnimGraphCreateNode::DeleteGraphNode(EMotionFX::AnimGraphNode* node) @@ -142,7 +142,7 @@ namespace CommandSystem } // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); // find the graph EMotionFX::AnimGraphNode* parentNode = nullptr; @@ -204,7 +204,7 @@ namespace CommandSystem EMotionFX::AnimGraphNode* node = static_cast(object); // store the node id for the callbacks - mNodeId = node->GetId(); + m_nodeId = node->GetId(); if (parameters.CheckIfHasParameter("contents")) { @@ -213,7 +213,7 @@ namespace CommandSystem MCore::ReflectionSerializer::DeserializeMembers(node, contents); // The deserialize method will deserialize back the old id - node->SetId(mNodeId); + node->SetId(m_nodeId); // Verify we have not serialized connections, child nodes and transitions AZ_Assert(node->GetNumConnections() == 0, "Unexpected serialized connections"); @@ -232,7 +232,7 @@ namespace CommandSystem const EMotionFX::AnimGraphNodeId nodeId = EMotionFX::AnimGraphNodeId::CreateFromString(nodeIdString); node->SetId(nodeId); - mNodeId = nodeId; + m_nodeId = nodeId; } // if the name is not empty, set it @@ -317,7 +317,7 @@ namespace CommandSystem node->SetIsCollapsed(collapsed); // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); // check if the parent is valid if (parentNode) @@ -357,7 +357,7 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); // return the node name @@ -370,8 +370,8 @@ namespace CommandSystem animGraph->RecursiveInvalidateUniqueDatas(); // init new node for all anim graph instances belonging to it - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::AnimGraphInstance* animGraphInstance = EMotionFX::GetActorManager().GetActorInstance(i)->GetAnimGraphInstance(); if (animGraphInstance && animGraphInstance->GetAnimGraph() == animGraph) @@ -397,26 +397,26 @@ namespace CommandSystem MCORE_UNUSED(parameters); // get the anim graph - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (animGraph == nullptr) { - outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID); + outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId); return false; } // locate the node - EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(mNodeId); + EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(m_nodeId); if (node == nullptr) { return false; } - mNodeId.SetInvalid(); + m_nodeId.SetInvalid(); const AZStd::string commandString = AZStd::string::format("AnimGraphRemoveNode -animGraphID %i -name \"%s\"", animGraph->GetID(), node->GetName()); if (GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult) == false) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -424,7 +424,7 @@ namespace CommandSystem } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -463,8 +463,8 @@ namespace CommandSystem CommandAnimGraphAdjustNode::CommandAnimGraphAdjustNode(MCore::Command* orgCommand) : MCore::Command("AnimGraphAdjustNode", orgCommand) { - mOldPosX = 0; - mOldPosY = 0; + m_oldPosX = 0; + m_oldPosY = 0; } // destructor @@ -483,7 +483,7 @@ namespace CommandSystem } // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); // get the name of the node AZStd::string name; @@ -506,8 +506,8 @@ namespace CommandSystem // get the x and y pos int32 xPos = node->GetVisualPosX(); int32 yPos = node->GetVisualPosY(); - mOldPosX = xPos; - mOldPosY = yPos; + m_oldPosX = xPos; + m_oldPosY = yPos; // get the new position values if (parameters.CheckIfHasParameter("xPos")) @@ -529,17 +529,17 @@ namespace CommandSystem { // find the node group the node was in before the name change EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->FindNodeGroupForNode(node); - mNodeGroupName.clear(); + m_nodeGroupName.clear(); if (nodeGroup) { // remember the node group name for undo - mNodeGroupName = nodeGroup->GetName(); + m_nodeGroupName = nodeGroup->GetName(); // remove the node from the node group as its id is going to change nodeGroup->RemoveNodeById(node->GetId()); } - mOldName = node->GetName(); + m_oldName = node->GetName(); node->SetName(newName.c_str()); // as the id of the node changed after renaming it, we have to readd the node with the new id @@ -549,27 +549,27 @@ namespace CommandSystem } // call the post rename node event - EMotionFX::GetEventManager().OnRenamedNode(animGraph, node, mOldName.c_str()); + EMotionFX::GetEventManager().OnRenamedNode(animGraph, node, m_oldName.c_str()); } // remember and set the new value to the enabled flag - mOldEnabled = node->GetIsEnabled(); + m_oldEnabled = node->GetIsEnabled(); if (parameters.CheckIfHasParameter("enabled")) { node->SetIsEnabled(parameters.GetValueAsBool("enabled", this)); } // remember and set the new value to the visualization flag - mOldVisualized = node->GetIsVisualizationEnabled(); + m_oldVisualized = node->GetIsVisualizationEnabled(); if (parameters.CheckIfHasParameter("visualize")) { node->SetVisualization(parameters.GetValueAsBool("visualize", this)); } - mNodeId = node->GetId(); + m_nodeId = node->GetId(); // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); // only update attributes in case it is wanted @@ -586,22 +586,22 @@ namespace CommandSystem bool CommandAnimGraphAdjustNode::Undo(const MCore::CommandLine& parameters, AZStd::string& outResult) { // get the anim graph - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (animGraph == nullptr) { - outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID); + outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId); return false; } - EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(mNodeId); + EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(m_nodeId); if (node == nullptr) { - outResult = AZStd::string::format("Cannot find node with ID %s.", mNodeId.ToString().c_str()); + outResult = AZStd::string::format("Cannot find node with ID %s.", m_nodeId.ToString().c_str()); return false; } // restore the name - if (!mOldName.empty()) + if (!m_oldName.empty()) { AZStd::string currentName = node->GetName(); @@ -614,7 +614,7 @@ namespace CommandSystem nodeGroup->RemoveNodeById(node->GetId()); } - node->SetName(mOldName.c_str()); + node->SetName(m_oldName.c_str()); // as the id of the node changed after renaming it, we have to readd the node with the new id if (nodeGroup) @@ -626,12 +626,12 @@ namespace CommandSystem EMotionFX::GetEventManager().OnRenamedNode(animGraph, node, node->GetName()); } - mNodeId = node->GetId(); - node->SetVisualPos(mOldPosX, mOldPosY); + m_nodeId = node->GetId(); + node->SetVisualPos(m_oldPosX, m_oldPosY); // set the old values to the enabled flag and the visualization flag - node->SetIsEnabled(mOldEnabled); - node->SetVisualization(mOldVisualized); + node->SetIsEnabled(m_oldEnabled); + node->SetVisualization(m_oldVisualized); // do only for parameter nodes if (azrtti_typeid(node) == azrtti_typeid() && parameters.CheckIfHasParameter("parameterMask")) @@ -640,11 +640,11 @@ namespace CommandSystem EMotionFX::BlendTreeParameterNode* parameterNode = static_cast(node); // get the parameter mask attribute and update the mask - parameterNode->SetParameters(mOldParameterMask); + parameterNode->SetParameters(m_oldParameterMask); } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); node->Reinit(); animGraph->RecursiveInvalidateUniqueDatas(); @@ -681,7 +681,7 @@ namespace CommandSystem CommandAnimGraphRemoveNode::CommandAnimGraphRemoveNode(MCore::Command* orgCommand) : MCore::Command("AnimGraphRemoveNode", orgCommand) { - mIsEntryNode = false; + m_isEntryNode = false; } // destructor @@ -700,7 +700,7 @@ namespace CommandSystem } // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); // find the emfx node AZStd::string name; @@ -712,20 +712,20 @@ namespace CommandSystem return false; } - mType = azrtti_typeid(emfxNode); - mName = emfxNode->GetName(); - mPosX = emfxNode->GetVisualPosX(); - mPosY = emfxNode->GetVisualPosY(); - mCollapsed = emfxNode->GetIsCollapsed(); - mOldContents = MCore::ReflectionSerializer::SerializeMembersExcept(emfxNode, { "childNodes", "connections", "transitions" }).GetValue(); - mNodeId = emfxNode->GetId(); + m_type = azrtti_typeid(emfxNode); + m_name = emfxNode->GetName(); + m_posX = emfxNode->GetVisualPosX(); + m_posY = emfxNode->GetVisualPosY(); + m_collapsed = emfxNode->GetIsCollapsed(); + m_oldContents = MCore::ReflectionSerializer::SerializeMembersExcept(emfxNode, { "childNodes", "connections", "transitions" }).GetValue(); + m_nodeId = emfxNode->GetId(); // remember the node group for the node for undo - mNodeGroupName.clear(); + m_nodeGroupName.clear(); EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->FindNodeGroupForNode(emfxNode); if (nodeGroup) { - mNodeGroupName = nodeGroup->GetName(); + m_nodeGroupName = nodeGroup->GetName(); } // get the parent node @@ -737,14 +737,14 @@ namespace CommandSystem EMotionFX::AnimGraphStateMachine* stateMachine = static_cast(parentNode); if (stateMachine->GetEntryState() == emfxNode) { - mIsEntryNode = true; + m_isEntryNode = true; // Find a new entry node if we can //-------------------------- // Find alternative entry state. EMotionFX::AnimGraphNode* newEntryState = nullptr; - uint32 numStates = stateMachine->GetNumChildNodes(); - for (uint32 s = 0; s < numStates; ++s) + size_t numStates = stateMachine->GetNumChildNodes(); + for (size_t s = 0; s < numStates; ++s) { EMotionFX::AnimGraphNode* childNode = stateMachine->GetChildNode(s); if (childNode != emfxNode) @@ -766,8 +766,8 @@ namespace CommandSystem } } - mParentName = parentNode->GetName(); - mParentNodeId = parentNode->GetId(); + m_parentName = parentNode->GetName(); + m_parentNodeId = parentNode->GetId(); // call the pre remove node event EMotionFX::GetEventManager().OnRemoveNode(animGraph, emfxNode); @@ -780,15 +780,15 @@ namespace CommandSystem } else { - mParentNodeId.SetInvalid(); - mParentName.clear(); + m_parentNodeId.SetInvalid(); + m_parentName.clear(); MCore::LogError("Cannot remove root state machine."); MCORE_ASSERT(false); return false; } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); animGraph->RecursiveInvalidateUniqueDatas(); @@ -801,34 +801,34 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (!animGraph) { - outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID); + outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId); return false; } // create the node again MCore::CommandGroup group("Recreating node"); AZStd::string commandString; - if (!mParentName.empty()) + if (!m_parentName.empty()) { commandString = AZStd::string::format("AnimGraphCreateNode -animGraphID %i -type \"%s\" -parentName \"%s\" -name \"%s\" -nodeId \"%s\" -xPos %d -yPos %d -collapsed %s -center false -contents {%s}", animGraph->GetID(), - mType.ToString().c_str(), - mParentName.c_str(), - mName.c_str(), - mNodeId.ToString().c_str(), - mPosX, - mPosY, - AZStd::to_string(mCollapsed).c_str(), - mOldContents.c_str()); + m_type.ToString().c_str(), + m_parentName.c_str(), + m_name.c_str(), + m_nodeId.ToString().c_str(), + m_posX, + m_posY, + AZStd::to_string(m_collapsed).c_str(), + m_oldContents.c_str()); group.AddCommandString(commandString); - if (mIsEntryNode) + if (m_isEntryNode) { - commandString = AZStd::string::format("AnimGraphSetEntryState -animGraphID %i -entryNodeName \"%s\"", animGraph->GetID(), mName.c_str()); + commandString = AZStd::string::format("AnimGraphSetEntryState -animGraphID %i -entryNodeName \"%s\"", animGraph->GetID(), m_name.c_str()); group.AddCommandString(commandString); } } @@ -836,19 +836,19 @@ namespace CommandSystem { commandString = AZStd::string::format("AnimGraphCreateNode -animGraphID %i -type \"%s\" -name \"%s\" -nodeId \"%s\" -xPos %d -yPos %d -collapsed %s -center false -contents {%s}", animGraph->GetID(), - mType.ToString().c_str(), - mName.c_str(), - mNodeId.ToString().c_str(), - mPosX, - mPosY, - AZStd::to_string(mCollapsed).c_str(), - mOldContents.c_str()); + m_type.ToString().c_str(), + m_name.c_str(), + m_nodeId.ToString().c_str(), + m_posX, + m_posY, + AZStd::to_string(m_collapsed).c_str(), + m_oldContents.c_str()); group.AddCommandString(commandString); } if (!GetCommandManager()->ExecuteCommandGroupInsideCommand(group, outResult)) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -857,20 +857,20 @@ namespace CommandSystem } // add it to the old node group if it was assigned to one before - if (!mNodeGroupName.empty()) + if (!m_nodeGroupName.empty()) { auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), /*animGraphId = */ animGraph->GetID(), - /*name = */ mNodeGroupName, + /*name = */ m_nodeGroupName, /*visible = */ AZStd::nullopt, /*newName = */ AZStd::nullopt, - /*nodeNames = */ {{mName}}, + /*nodeNames = */ {{m_name}}, /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Add ); if (GetCommandManager()->ExecuteCommandInsideCommand(command, outResult) == false) { - if (outResult.size() > 0) + if (!outResult.empty()) { MCore::LogError(outResult.c_str()); } @@ -880,7 +880,7 @@ namespace CommandSystem } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -925,7 +925,7 @@ namespace CommandSystem } // store the anim graph id for undo - mAnimGraphID = animGraph->GetID(); + m_animGraphId = animGraph->GetID(); AZStd::string entryNodeName; parameters.GetValue("entryNodeName", this, entryNodeName); @@ -960,21 +960,21 @@ namespace CommandSystem EMotionFX::AnimGraphNode* oldEntryNode = stateMachine->GetEntryState(); if (oldEntryNode) { - mOldEntryStateNodeId = oldEntryNode->GetId(); + m_oldEntryStateNodeId = oldEntryNode->GetId(); } else { - mOldEntryStateNodeId.SetInvalid(); + m_oldEntryStateNodeId.SetInvalid(); } // store the id of the state machine - mOldStateMachineNodeId = stateMachineNode->GetId(); + m_oldStateMachineNodeId = stateMachineNode->GetId(); // set the new entry state for the state machine stateMachine->SetEntryState(entryNode); // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); stateMachine->Reinit(); @@ -989,15 +989,15 @@ namespace CommandSystem MCORE_UNUSED(parameters); // get the anim graph - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (animGraph == nullptr) { - outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", mAnimGraphID); + outResult = AZStd::string::format("The anim graph with id '%i' does not exist anymore.", m_animGraphId); return false; } // get the state machine - EMotionFX::AnimGraphNode* stateMachineNode = animGraph->RecursiveFindNodeById(mOldStateMachineNodeId); + EMotionFX::AnimGraphNode* stateMachineNode = animGraph->RecursiveFindNodeById(m_oldStateMachineNodeId); if (stateMachineNode == nullptr || azrtti_typeid(stateMachineNode) != azrtti_typeid()) { outResult = "Cannot undo set entry node. Parent node is not a state machine or not valid at all."; @@ -1008,9 +1008,9 @@ namespace CommandSystem EMotionFX::AnimGraphStateMachine* stateMachine = (EMotionFX::AnimGraphStateMachine*)stateMachineNode; // find the entry anim graph node - if (mOldEntryStateNodeId.IsValid()) + if (m_oldEntryStateNodeId.IsValid()) { - EMotionFX::AnimGraphNode* entryNode = animGraph->RecursiveFindNodeById(mOldEntryStateNodeId); + EMotionFX::AnimGraphNode* entryNode = animGraph->RecursiveFindNodeById(m_oldEntryStateNodeId); if (!entryNode) { outResult = "Cannot undo set entry node. Old entry node cannot be found."; @@ -1027,7 +1027,7 @@ namespace CommandSystem } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); stateMachine->Reinit(); animGraph->RecursiveInvalidateUniqueDatas(); @@ -1204,19 +1204,18 @@ namespace CommandSystem if (parentNode) { // Gather the number of nodes with the same type as the one we're trying to remove. - MCore::Array outNodes; + AZStd::vector outNodes; const AZ::TypeId nodeType = azrtti_typeid(node); parentNode->CollectChildNodesOfType(nodeType, &outNodes); - const uint32 numTypeNodes = outNodes.GetLength(); + const size_t numTypeNodes = outNodes.size(); // Gather the number of already removed nodes with the same type as the one we're trying to remove. - const size_t numTotalDeletedNodes = nodeList.size(); - uint32 numTypeDeletedNodes = 0; - for (size_t i = 0; i < numTotalDeletedNodes; ++i) + size_t numTypeDeletedNodes = 0; + for (const EMotionFX::AnimGraphNode* i : nodeList) { // Check if the nodes have the same parent, meaning they are in the same graph plus check if they have the same type // if that both is the same we can increase the number of deleted nodes for the graph where the current node is in. - if (nodeList[i]->GetParentNode() == parentNode && azrtti_typeid(nodeList[i]) == nodeType) + if (i->GetParentNode() == parentNode && azrtti_typeid(i) == nodeType) { numTypeDeletedNodes++; } @@ -1242,8 +1241,8 @@ namespace CommandSystem // 2. Delete all child nodes recursively before deleting the node. // Get the number of child nodes, iterate through them and recursively call the function. - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { EMotionFX::AnimGraphNode* childNode = node->GetChildNode(i); DeleteNode(commandGroup, animGraph, childNode, nodeList, connectionList, transitionList, true, false, false); @@ -1268,10 +1267,9 @@ namespace CommandSystem void DeleteNodes(MCore::CommandGroup* commandGroup, EMotionFX::AnimGraph* animGraph, const AZStd::vector& nodeNames, AZStd::vector& nodeList, AZStd::vector& connectionList, AZStd::vector& transitionList, bool autoChangeEntryStates) { - const size_t numNodeNames = nodeNames.size(); - for (size_t i = 0; i < numNodeNames; ++i) + for (const AZStd::string& nodeName : nodeNames) { - EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeByName(nodeNames[i].c_str()); + EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeByName(nodeName.c_str()); // Add the delete node commands to the command group. DeleteNode(commandGroup, animGraph, node, nodeList, connectionList, transitionList, true, true, autoChangeEntryStates); @@ -1385,8 +1383,8 @@ namespace CommandSystem } // Recurse through the child nodes. - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { EMotionFX::AnimGraphNode* childNode = node->GetChildNode(i); CopyAnimGraphNodeCommand(commandGroup, targetAnimGraph, node, childNode, @@ -1404,8 +1402,8 @@ namespace CommandSystem } // Recurse through the child nodes. - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { EMotionFX::AnimGraphNode* childNode = node->GetChildNode(i); CopyAnimGraphConnectionsCommand(commandGroup, targetAnimGraph, childNode, @@ -1436,8 +1434,8 @@ namespace CommandSystem } else { - const uint32 numConnections = node->GetNumConnections(); - for (uint32 i = 0; i < numConnections; ++i) + const size_t numConnections = node->GetNumConnections(); + for (size_t i = 0; i < numConnections; ++i) { EMotionFX::BlendTreeConnection* connection = node->GetConnection(i); CopyBlendTreeConnection(commandGroup, targetAnimGraph, node, connection, @@ -1455,29 +1453,14 @@ namespace CommandSystem } // Remove all nodes that are child nodes of other selected nodes. - for (size_t i = 0; i < nodesToCopy.size();) + AZStd::erase_if(nodesToCopy, [&nodesToCopy](const EMotionFX::AnimGraphNode* node) { - EMotionFX::AnimGraphNode* node = nodesToCopy[i]; - - bool removeNode = false; - for (size_t j = 0; j < nodesToCopy.size(); ++j) - { - if (node != nodesToCopy[j] && node->RecursiveIsParentNode(nodesToCopy[j])) - { - removeNode = true; - break; - } - } - - if (removeNode) + const auto found = AZStd::find_if(begin(nodesToCopy), end(nodesToCopy), [node](const EMotionFX::AnimGraphNode* parent) { - nodesToCopy.erase(nodesToCopy.begin() + i); - } - else - { - i++; - } - } + return node != parent && node->RecursiveIsParentNode(parent); + }); + return found != end(nodesToCopy); + }); // In case we are in cut and paste mode and delete the cut nodes. if (cutMode) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.h index 6a5a991809..4d02d55921 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.h @@ -25,60 +25,60 @@ public: EMotionFX::AnimGraphNodeId GetNodeId(const MCore::CommandLine& parameters); void DeleteGraphNode(EMotionFX::AnimGraphNode* node); - uint32 mAnimGraphID; - bool mOldDirtyFlag; - EMotionFX::AnimGraphNodeId mNodeId; + uint32 m_animGraphId; + bool m_oldDirtyFlag; + EMotionFX::AnimGraphNodeId m_nodeId; MCORE_DEFINECOMMAND_END // adjust a node MCORE_DEFINECOMMAND_START(CommandAnimGraphAdjustNode, "Adjust a anim graph node", true) - EMotionFX::AnimGraphNodeId mNodeId; - int32 mOldPosX; - int32 mOldPosY; - AZStd::string mOldName; - AZStd::string mOldParameterMask; - bool mOldDirtyFlag; - bool mOldEnabled; - bool mOldVisualized; - AZStd::string mNodeGroupName; + EMotionFX::AnimGraphNodeId m_nodeId; + int32 m_oldPosX; + int32 m_oldPosY; + AZStd::string m_oldName; + AZStd::string m_oldParameterMask; + bool m_oldDirtyFlag; + bool m_oldEnabled; + bool m_oldVisualized; + AZStd::string m_nodeGroupName; public: - EMotionFX::AnimGraphNodeId GetNodeId() const { return mNodeId; } - const AZStd::string& GetOldName() const { return mOldName; } - uint32 mAnimGraphID; + EMotionFX::AnimGraphNodeId GetNodeId() const { return m_nodeId; } + const AZStd::string& GetOldName() const { return m_oldName; } + uint32 m_animGraphId; MCORE_DEFINECOMMAND_END // remove a node MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveNode, "Remove a anim graph node", true) - EMotionFX::AnimGraphNodeId mNodeId; - uint32 mAnimGraphID; - EMotionFX::AnimGraphNodeId mParentNodeId; - AZ::TypeId mType; - AZStd::string mParentName; - AZStd::string mName; - AZStd::string mNodeGroupName; - int32 mPosX; - int32 mPosY; - AZStd::string mOldContents; - bool mCollapsed; - bool mOldDirtyFlag; - bool mIsEntryNode; + EMotionFX::AnimGraphNodeId m_nodeId; + uint32 m_animGraphId; + EMotionFX::AnimGraphNodeId m_parentNodeId; + AZ::TypeId m_type; + AZStd::string m_parentName; + AZStd::string m_name; + AZStd::string m_nodeGroupName; + int32 m_posX; + int32 m_posY; + AZStd::string m_oldContents; + bool m_collapsed; + bool m_oldDirtyFlag; + bool m_isEntryNode; public: - EMotionFX::AnimGraphNodeId GetNodeId() const { return mNodeId; } - EMotionFX::AnimGraphNodeId GetParentNodeId() const { return mParentNodeId; } + EMotionFX::AnimGraphNodeId GetNodeId() const { return m_nodeId; } + EMotionFX::AnimGraphNodeId GetParentNodeId() const { return m_parentNodeId; } MCORE_DEFINECOMMAND_END // set the entry state of a state machine MCORE_DEFINECOMMAND_START(CommandAnimGraphSetEntryState, "Set entry state", true) public: - uint32 mAnimGraphID; - EMotionFX::AnimGraphNodeId mOldEntryStateNodeId; - EMotionFX::AnimGraphNodeId mOldStateMachineNodeId; - bool mOldDirtyFlag; + uint32 m_animGraphId; + EMotionFX::AnimGraphNodeId m_oldEntryStateNodeId; + EMotionFX::AnimGraphNodeId m_oldStateMachineNodeId; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp index f5f913f0ca..0f04bb0e79 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp @@ -71,9 +71,9 @@ namespace CommandSystem { AZStd::vector result; - const uint32 numNodes = nodeGroup->GetNumNodes(); + const size_t numNodes = nodeGroup->GetNumNodes(); result.reserve(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { result.push_back(nodeGroup->GetNode(i)); } @@ -91,8 +91,8 @@ namespace CommandSystem } // find the node group index - const uint32 groupIndex = animGraph->FindNodeGroupIndexByName(m_name.c_str()); - if (groupIndex == MCORE_INVALIDINDEX32) + const size_t groupIndex = animGraph->FindNodeGroupIndexByName(m_name.c_str()); + if (groupIndex == InvalidIndex) { outResult = AZStd::string::format("Node group \"%s\" can not be found.", m_name.c_str()); return false; @@ -149,8 +149,8 @@ namespace CommandSystem } // remove the node from all node groups - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); - for (uint32 n = 0; n < numNodeGroups; ++n) + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); + for (size_t n = 0; n < numNodeGroups; ++n) { animGraph->GetNodeGroup(n)->RemoveNodeById(animGraphNode->GetId()); } @@ -173,8 +173,8 @@ namespace CommandSystem } // remove the node from all node groups - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); - for (uint32 n = 0; n < numNodeGroups; ++n) + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); + for (size_t n = 0; n < numNodeGroups; ++n) { animGraph->GetNodeGroup(n)->RemoveNodeById(animGraphNode->GetId()); } @@ -334,8 +334,8 @@ namespace CommandSystem nodeGroup->SetColor(color.ToU32()); // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); - mOldName = nodeGroup->GetName(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldName = nodeGroup->GetName(); animGraph->SetDirtyFlag(true); return true; } @@ -349,7 +349,7 @@ namespace CommandSystem return false; } - AZStd::string commandString = AZStd::string::format("AnimGraphRemoveNodeGroup -animGraphID %i -name \"%s\"", animGraph->GetID(), mOldName.c_str()); + AZStd::string commandString = AZStd::string::format("AnimGraphRemoveNodeGroup -animGraphID %i -name \"%s\"", animGraph->GetID(), m_oldName.c_str()); // execute the command AZStd::string result; @@ -359,7 +359,7 @@ namespace CommandSystem } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -404,25 +404,25 @@ namespace CommandSystem parameters.GetValue("name", this, groupName); // find the node group index and remove it - const uint32 groupIndex = animGraph->FindNodeGroupIndexByName(groupName.c_str()); - if (groupIndex == MCORE_INVALIDINDEX32) + const size_t groupIndex = animGraph->FindNodeGroupIndexByName(groupName.c_str()); + if (groupIndex == InvalidIndex) { - outResult = AZStd::string::format("Cannot add node group to anim graph. Node group index %u is invalid.", groupIndex); + outResult = AZStd::string::format("Cannot add node group to anim graph. Node group index %zu is invalid.", groupIndex); return false; } // read out information for the command undo EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(groupIndex); - mOldName = nodeGroup->GetName(); - mOldColor = nodeGroup->GetColor(); - mOldIsVisible = nodeGroup->GetIsVisible(); - mOldNodeIds = CommandAnimGraphAdjustNodeGroup::CollectNodeIdsFromGroup(nodeGroup); + m_oldName = nodeGroup->GetName(); + m_oldColor = nodeGroup->GetColor(); + m_oldIsVisible = nodeGroup->GetIsVisible(); + m_oldNodeIds = CommandAnimGraphAdjustNodeGroup::CollectNodeIdsFromGroup(nodeGroup); // remove the node group animGraph->RemoveNodeGroup(groupIndex); // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); return true; } @@ -439,17 +439,17 @@ namespace CommandSystem MCore::CommandGroup commandGroup; - commandGroup.AddCommandString(AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"%s\" -updateUI %s",animGraph->GetID(), mOldName.c_str(), updateWindow.c_str())); + commandGroup.AddCommandString(AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"%s\" -updateUI %s",animGraph->GetID(), m_oldName.c_str(), updateWindow.c_str())); auto* command = aznew CommandAnimGraphAdjustNodeGroup( GetCommandManager()->FindCommand(CommandAnimGraphAdjustNodeGroup::s_commandName), /*animGraphId = */ animGraph->GetID(), - /*name = */ mOldName, - /*visible = */ mOldIsVisible, + /*name = */ m_oldName, + /*visible = */ m_oldIsVisible, /*newName = */ AZStd::nullopt, - /*nodeNames = */ CommandAnimGraphAdjustNodeGroup::GenerateNodeNameVector(animGraph, mOldNodeIds), + /*nodeNames = */ CommandAnimGraphAdjustNodeGroup::GenerateNodeNameVector(animGraph, m_oldNodeIds), /*nodeAction = */ CommandAnimGraphAdjustNodeGroup::NodeAction::Add, - /*color = */ mOldColor + /*color = */ m_oldColor ); commandGroup.AddCommand(command); @@ -461,7 +461,7 @@ namespace CommandSystem } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -487,7 +487,7 @@ namespace CommandSystem void ClearNodeGroups(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup) { // get number of node groups - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); if (numNodeGroups == 0) { return; @@ -498,7 +498,7 @@ namespace CommandSystem // get rid of all node groups AZStd::string commandString; - for (uint32 i = 0; i < numNodeGroups; ++i) + for (size_t i = 0; i < numNodeGroups; ++i) { // get pointer to the current actor instance EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h index 0fc497d2f1..014d3b0398 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h @@ -83,18 +83,18 @@ namespace CommandSystem // add node group MCORE_DEFINECOMMAND_START(CommandAnimGraphAddNodeGroup, "Add anim graph node group", true) - bool mOldDirtyFlag; - AZStd::string mOldName; + bool m_oldDirtyFlag; + AZStd::string m_oldName; MCORE_DEFINECOMMAND_END // remove a node group MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveNodeGroup, "Remove anim graph node group", true) - AZStd::string mOldName; - bool mOldIsVisible; - AZ::u32 mOldColor; - AZStd::vector mOldNodeIds; - bool mOldDirtyFlag; + AZStd::string m_oldName; + bool m_oldIsVisible; + AZ::u32 m_oldColor; + AZStd::vector m_oldNodeIds; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // helper function diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp index 41a6a26b89..571b6c5e97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.cpp @@ -170,7 +170,7 @@ namespace CommandSystem for (size_t i = 0; i < numInstances; ++i) { EMotionFX::AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(i); - animGraphInstance->InsertParameterValue(static_cast(valueParameterIndex.GetValue())); + animGraphInstance->InsertParameterValue(valueParameterIndex.GetValue()); } AZStd::vector affectedObjects; @@ -188,7 +188,7 @@ namespace CommandSystem outResult = name.c_str(); // Save the current dirty flag and tell the anim graph that something got changed. - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); return true; @@ -219,7 +219,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -258,22 +258,22 @@ namespace CommandSystem bool CommandAnimGraphRemoveParameter::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) { // Get the parameter name. - parameters.GetValue("name", this, mName); + parameters.GetValue("name", this, m_name); // Find the anim graph by using the id from command parameter. const uint32 animGraphID = parameters.GetValueAsInt("animGraphID", this); EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID); if (!animGraph) { - outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", mName.c_str(), animGraphID); + outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", m_name.c_str(), animGraphID); return false; } // Check if there is a parameter with the given name. - const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(mName); + const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(m_name); if (!parameter) { - outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. There is no parameter with the given name.", mName.c_str()); + outResult = AZStd::string::format("Cannot remove parameter '%s' from anim graph. There is no parameter with the given name.", m_name.c_str()); return false; } AZ_Assert(azrtti_typeid(parameter) != azrtti_typeid(), "CommmandAnimGraphRemoveParameter called for a group parameter"); @@ -284,13 +284,13 @@ namespace CommandSystem AZ_Assert(parameterIndex.IsSuccess(), "Expected valid parameter index"); // Store undo info before we remove it, so that we can recreate it later. - mType = azrtti_typeid(parameter); - mIndex = parameterIndex.GetValue(); - mParent = parentGroup ? parentGroup->GetName() : ""; - mContents = MCore::ReflectionSerializer::Serialize(parameter).GetValue(); + m_type = azrtti_typeid(parameter); + m_index = parameterIndex.GetValue(); + m_parent = parentGroup ? parentGroup->GetName() : ""; + m_contents = MCore::ReflectionSerializer::Serialize(parameter).GetValue(); AZ::Outcome valueParameterIndex = AZ::Failure(); - if (mType != azrtti_typeid()) + if (m_type != azrtti_typeid()) { valueParameterIndex = animGraph->FindValueParameterIndex(static_cast(parameter)); } @@ -299,7 +299,7 @@ namespace CommandSystem if (animGraph->RemoveParameter(const_cast(parameter))) { // Remove the parameter from all corresponding anim graph instances if it is a value parameter - if (mType != azrtti_typeid()) + if (m_type != azrtti_typeid()) { AZStd::vector affectedObjects; animGraph->RecursiveCollectObjectsOfType(azrtti_typeid(), affectedObjects); @@ -308,7 +308,7 @@ namespace CommandSystem for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects) { EMotionFX::ObjectAffectedByParameterChanges* parameterDriven = azdynamic_cast(affectedObject); - parameterDriven->ParameterRemoved(mName); + parameterDriven->ParameterRemoved(m_name); } const size_t numInstances = animGraph->GetNumAnimGraphInstances(); @@ -316,11 +316,11 @@ namespace CommandSystem { EMotionFX::AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(i); // Remove the parameter. - animGraphInstance->RemoveParameterValue(static_cast(valueParameterIndex.GetValue())); + animGraphInstance->RemoveParameterValue(valueParameterIndex.GetValue()); } // Save the current dirty flag and tell the anim graph that something got changed. - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); } return true; @@ -336,7 +336,7 @@ namespace CommandSystem EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID); if (!animGraph) { - outResult = AZStd::string::format("Cannot undo remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", mName.c_str(), animGraphID); + outResult = AZStd::string::format("Cannot undo remove parameter '%s' from anim graph. Anim graph id '%i' is not valid.", m_name.c_str(), animGraphID); return false; } @@ -347,11 +347,11 @@ namespace CommandSystem commandString = AZStd::string::format("AnimGraphCreateParameter -animGraphID %i -name \"%s\" -index %zu -type \"%s\" -contents {%s} -parent \"%s\" -updateUI %s", animGraph->GetID(), - mName.c_str(), - mIndex, - mType.ToString().c_str(), - mContents.c_str(), - mParent.c_str(), + m_name.c_str(), + m_index, + m_type.ToString().c_str(), + m_contents.c_str(), + m_parent.c_str(), updateUI.c_str()); // The parameter will be restored to the right parent group because the index is absolute @@ -364,7 +364,7 @@ namespace CommandSystem } // Set the dirty flag back to the old value. - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -399,21 +399,21 @@ namespace CommandSystem bool CommandAnimGraphAdjustParameter::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) { // Get the parameter name. - parameters.GetValue("name", this, mOldName); + parameters.GetValue("name", this, m_oldName); // Find the anim graph by using the id from command parameter. const uint32 animGraphID = parameters.GetValueAsInt("animGraphID", this); EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(animGraphID); if (!animGraph) { - outResult = AZStd::string::format("Cannot adjust parameter '%s'. Anim graph with id '%d' not found.", mOldName.c_str(), animGraphID); + outResult = AZStd::string::format("Cannot adjust parameter '%s'. Anim graph with id '%d' not found.", m_oldName.c_str(), animGraphID); return false; } - const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(mOldName); + const EMotionFX::Parameter* parameter = animGraph->FindParameterByName(m_oldName); if (!parameter) { - outResult = AZStd::string::format("There is no parameter with the name '%s'.", mOldName.c_str()); + outResult = AZStd::string::format("There is no parameter with the name '%s'.", m_oldName.c_str()); return false; } AZ::Outcome oldValueParameterIndex = AZ::Failure(); @@ -426,15 +426,15 @@ namespace CommandSystem const EMotionFX::GroupParameter* currentParent = animGraph->FindParentGroupParameter(parameter); // Store the undo info. - mOldType = azrtti_typeid(parameter); - mOldContents = MCore::ReflectionSerializer::Serialize(parameter).GetValue(); + m_oldType = azrtti_typeid(parameter); + m_oldContents = MCore::ReflectionSerializer::Serialize(parameter).GetValue(); // Get the new name and check if it is valid. AZStd::string newName; parameters.GetValue("newName", this, newName); if (!newName.empty()) { - if (newName == mOldName) + if (newName == m_oldName) { newName.clear(); } @@ -461,10 +461,10 @@ namespace CommandSystem outResult = AZStd::string::format("The type is not a valid UUID type. Please use -help or use the command browser to see a list of valid options."); return false; } - if (type != mOldType) + if (type != m_oldType) { AZStd::unique_ptr newParameter(EMotionFX::ParameterFactory::Create(type)); - newParameter->SetName(newName.empty() ? mOldName : newName); + newParameter->SetName(newName.empty() ? m_oldName : newName); newParameter->SetDescription(parameter->GetDescription()); const AZ::Outcome paramIndexRelativeToParent = currentParent ? currentParent->FindRelativeParameterIndex(parameter) : animGraph->FindRelativeParameterIndex(parameter); @@ -472,7 +472,7 @@ namespace CommandSystem if (!animGraph->RemoveParameter(const_cast(parameter))) { - outResult = AZStd::string::format("Could not remove current parameter '%s' to change its type.", mOldName.c_str()); + outResult = AZStd::string::format("Could not remove current parameter '%s' to change its type.", m_oldName.c_str()); return false; } if (!animGraph->InsertParameter(paramIndexRelativeToParent.GetValue(), newParameter.get(), currentParent)) @@ -521,13 +521,13 @@ namespace CommandSystem // Update all corresponding anim graph instances. const size_t numInstances = animGraph->GetNumAnimGraphInstances(); - for (uint32 i = 0; i < numInstances; ++i) + for (size_t i = 0; i < numInstances; ++i) { EMotionFX::AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(i); // reinit the modified parameters - if (mOldType != azrtti_typeid()) + if (m_oldType != azrtti_typeid()) { - animGraphInstance->ReInitParameterValue(static_cast(valueParameterIndex.GetValue())); + animGraphInstance->ReInitParameterValue(valueParameterIndex.GetValue()); } else { @@ -547,7 +547,7 @@ namespace CommandSystem for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects) { EMotionFX::ObjectAffectedByParameterChanges* affectedObjectByParameterChanges = azdynamic_cast(affectedObject); - affectedObjectByParameterChanges->ParameterRenamed(mOldName, newName); + affectedObjectByParameterChanges->ParameterRenamed(m_oldName, newName); } } } @@ -561,16 +561,16 @@ namespace CommandSystem for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects) { EMotionFX::ObjectAffectedByParameterChanges* affectedObjectByParameterChanges = azdynamic_cast(affectedObject); - affectedObjectByParameterChanges->ParameterRemoved(mOldName); + affectedObjectByParameterChanges->ParameterRemoved(m_oldName); affectedObjectByParameterChanges->ParameterAdded(newName); } } // Save the current dirty flag and tell the anim graph that something got changed. - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); } - else if (mOldType != azrtti_typeid()) + else if (m_oldType != azrtti_typeid()) { AZ_Assert(oldValueParameterIndex.IsSuccess(), "Unable to find parameter index when changing parameter to a group"); @@ -582,11 +582,11 @@ namespace CommandSystem for (EMotionFX::AnimGraphObject* affectedObject : affectedObjects) { EMotionFX::ObjectAffectedByParameterChanges* affectedObjectByParameterChanges = azdynamic_cast(affectedObject); - affectedObjectByParameterChanges->ParameterRemoved(mOldName); + affectedObjectByParameterChanges->ParameterRemoved(m_oldName); } // Save the current dirty flag and tell the anim graph that something got changed. - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); } @@ -638,15 +638,15 @@ namespace CommandSystem animGraph->GetID(), newName.c_str(), name.c_str(), - mOldType.ToString().c_str(), - mOldContents.c_str()); + m_oldType.ToString().c_str(), + m_oldContents.c_str()); if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult)) { AZ_Error("EMotionFX", false, outResult.c_str()); } - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -728,13 +728,13 @@ namespace CommandSystem const EMotionFX::GroupParameter* currentParent = animGraph->FindParentGroupParameter(parameter); if (currentParent) { - mOldParent = currentParent->GetName(); - mOldIndex = currentParent->FindRelativeParameterIndex(parameter).GetValue(); + m_oldParent = currentParent->GetName(); + m_oldIndex = currentParent->FindRelativeParameterIndex(parameter).GetValue(); } else { - mOldParent.clear(); // means the root - mOldIndex = animGraph->FindRelativeParameterIndex(parameter).GetValue(); + m_oldParent.clear(); // means the root + m_oldIndex = animGraph->FindRelativeParameterIndex(parameter).GetValue(); } EMotionFX::ValueParameterVector valueParametersBeforeChange = animGraph->RecursivelyGetValueParameters(); @@ -773,7 +773,7 @@ namespace CommandSystem { EMotionFX::AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(i); // Move the parameter from original position to the new position - animGraphInstance->MoveParameterValue(static_cast(valueIndexBeforeMove.GetValue()), static_cast(valueIndexAfterMove.GetValue())); + animGraphInstance->MoveParameterValue(valueIndexBeforeMove.GetValue(), valueIndexAfterMove.GetValue()); } EMotionFX::ValueParameterVector valueParametersAfterChange = animGraph->RecursivelyGetValueParameters(); @@ -789,7 +789,7 @@ namespace CommandSystem } // Save the current dirty flag and tell the anim graph that something got changed. - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); return true; @@ -813,10 +813,10 @@ namespace CommandSystem AZStd::string commandString = AZStd::string::format("AnimGraphMoveParameter -animGraphID %i -name \"%s\" -index %zu", animGraphID, name.c_str(), - mOldIndex); - if (!mOldParent.empty()) + m_oldIndex); + if (!m_oldParent.empty()) { - commandString += AZStd::string::format(" -parent \"%s\"", mOldParent.c_str()); + commandString += AZStd::string::format(" -parent \"%s\"", m_oldParent.c_str()); } if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult)) @@ -825,7 +825,7 @@ namespace CommandSystem return false; } - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -853,7 +853,7 @@ namespace CommandSystem //-------------------------------------------------------------------------------- // Construct create parameter command strings //-------------------------------------------------------------------------------- - void ConstructCreateParameterCommand(AZStd::string& outResult, EMotionFX::AnimGraph* animGraph, const EMotionFX::Parameter* parameter, uint32 insertAtIndex) + void ConstructCreateParameterCommand(AZStd::string& outResult, EMotionFX::AnimGraph* animGraph, const EMotionFX::Parameter* parameter, size_t insertAtIndex) { // Build the command string. AZStd::string parameterContents; @@ -865,9 +865,9 @@ namespace CommandSystem parameter->GetName().c_str(), parameterContents.c_str()); - if (insertAtIndex != MCORE_INVALIDINDEX32) + if (insertAtIndex != InvalidIndex) { - outResult += AZStd::string::format(" -index \"%i\"", insertAtIndex); + outResult += AZStd::string::format(" -index \"%zu\"", insertAtIndex); } } @@ -920,11 +920,11 @@ namespace CommandSystem AZStd::vector> outgoingConnectionsFromThisPort; for (const EMotionFX::AnimGraphNode* parameterNode : parameterNodes) { - const AZ::u32 sourcePortIndex = parameterNode->FindOutputPortIndex(parameterName); + const size_t sourcePortIndex = parameterNode->FindOutputPortIndex(parameterName); parameterNode->CollectOutgoingConnections(outgoingConnectionsFromThisPort, sourcePortIndex); // outgoingConnectionsFromThisPort will be cleared inside the function. const size_t numConnections = outgoingConnectionsFromThisPort.size(); - for (uint32 i = 0; i < numConnections; ++i) + for (size_t i = 0; i < numConnections; ++i) { const EMotionFX::AnimGraphNode* targetNode = outgoingConnectionsFromThisPort[i].second; const EMotionFX::BlendTreeConnection* connection = outgoingConnectionsFromThisPort[i].first; @@ -999,7 +999,7 @@ namespace CommandSystem // 3. Remove the actual parameters. size_t numIterations = parameterNamesToRemove.size(); - for (uint32 i = 0; i < numIterations; ++i) + for (size_t i = 0; i < numIterations; ++i) { commandString = AZStd::string::format("AnimGraphRemoveParameter -animGraphID %i -name \"%s\"", animGraph->GetID(), parameterNamesToRemove[i].c_str()); if (i != 0 && i != numIterations - 1) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h index b70e8d24d2..b1adbcbbab 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphParameterCommands.h @@ -22,35 +22,35 @@ namespace CommandSystem { // Create a new anim graph parameter. MCORE_DEFINECOMMAND_START(CommandAnimGraphCreateParameter, "Create an anim graph parameter", true) - bool mOldDirtyFlag; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // Remove a given anim graph parameter. MCORE_DEFINECOMMAND_START(CommandAnimGraphRemoveParameter, "Remove an anim graph parameter", true) - size_t mIndex; - AZ::TypeId mType; - AZStd::string mName; - AZStd::string mContents; - AZStd::string mParent; - bool mOldDirtyFlag; + size_t m_index; + AZ::TypeId m_type; + AZStd::string m_name; + AZStd::string m_contents; + AZStd::string m_parent; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // Adjust a given anim graph parameter. MCORE_DEFINECOMMAND_START(CommandAnimGraphAdjustParameter, "Adjust an anim graph parameter", true) - AZ::TypeId mOldType; - AZStd::string mOldName; - AZStd::string mOldContents; - bool mOldDirtyFlag; + AZ::TypeId m_oldType; + AZStd::string m_oldName; + AZStd::string m_oldContents; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // Move the parameter to another position. MCORE_DEFINECOMMAND_START(CommandAnimGraphMoveParameter, "Move an anim graph parameter", true) - AZStd::string mOldParent; - size_t mOldIndex; - bool mOldDirtyFlag; + AZStd::string m_oldParent; + size_t m_oldIndex; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END ////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -59,20 +59,18 @@ namespace CommandSystem struct COMMANDSYSTEM_API ParameterConnectionItem { - uint32 mTargetNodePort; + void SetParameterNodeName(const char* name) { m_parameterNodeNameId = MCore::GetStringIdPool().GenerateIdForString(name); } + void SetTargetNodeName(const char* name) { m_targetNodeNameId = MCore::GetStringIdPool().GenerateIdForString(name); } + void SetParameterName(const char* name) { m_parameterNameId = MCore::GetStringIdPool().GenerateIdForString(name); } - void SetParameterNodeName(const char* name) { mParameterNodeNameID = MCore::GetStringIdPool().GenerateIdForString(name); } - void SetTargetNodeName(const char* name) { mTargetNodeNameID = MCore::GetStringIdPool().GenerateIdForString(name); } - void SetParameterName(const char* name) { mParameterNameID = MCore::GetStringIdPool().GenerateIdForString(name); } - - const char* GetParameterNodeName() const { return MCore::GetStringIdPool().GetName(mParameterNodeNameID).c_str(); } - const char* GetTargetNodeName() const { return MCore::GetStringIdPool().GetName(mTargetNodeNameID).c_str(); } - const char* GetParameterName() const { return MCore::GetStringIdPool().GetName(mParameterNameID).c_str(); } + const char* GetParameterNodeName() const { return MCore::GetStringIdPool().GetName(m_parameterNodeNameId).c_str(); } + const char* GetTargetNodeName() const { return MCore::GetStringIdPool().GetName(m_targetNodeNameId).c_str(); } + const char* GetParameterName() const { return MCore::GetStringIdPool().GetName(m_parameterNameId).c_str(); } private: - uint32 mParameterNodeNameID; - uint32 mTargetNodeNameID; - uint32 mParameterNameID; + uint32 m_parameterNodeNameId; + uint32 m_targetNodeNameId; + uint32 m_parameterNameId; }; COMMANDSYSTEM_API void RemoveConnectionsForParameter(EMotionFX::AnimGraph* animGraph, const char* parameterName, MCore::CommandGroup& commandGroup); @@ -81,6 +79,6 @@ namespace CommandSystem COMMANDSYSTEM_API void ClearParametersCommand(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup = nullptr); // Construct the create parameter command string using the the given information. - COMMANDSYSTEM_API void ConstructCreateParameterCommand(AZStd::string& outResult, EMotionFX::AnimGraph* animGraph, const EMotionFX::Parameter* parameter, uint32 insertAtIndex = MCORE_INVALIDINDEX32); + COMMANDSYSTEM_API void ConstructCreateParameterCommand(AZStd::string& outResult, EMotionFX::AnimGraph* animGraph, const EMotionFX::Parameter* parameter, size_t insertAtIndex = InvalidIndex); } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphTriggerActionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphTriggerActionCommands.cpp index 8b04a80085..d5f43348f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphTriggerActionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphTriggerActionCommands.cpp @@ -58,7 +58,7 @@ namespace CommandSystem CommandAnimGraphAddTransitionAction::CommandAnimGraphAddTransitionAction(MCore::Command* orgCommand) : MCore::Command(s_commandName, orgCommand) - , m_oldActionIndex(MCORE_INVALIDINDEX32) + , m_oldActionIndex(InvalidIndex) { } @@ -105,14 +105,14 @@ namespace CommandSystem } // get the location where to add the new action - size_t insertAt = MCORE_INVALIDINDEX32; + size_t insertAt = InvalidIndex; if (parameters.CheckIfHasParameter("insertAt")) { insertAt = parameters.GetValueAsInt("insertAt", this); } // add it to the transition - if (insertAt == MCORE_INVALIDINDEX32) + if (insertAt == InvalidIndex) { actionSetup.AddAction(newAction); } @@ -214,7 +214,7 @@ namespace CommandSystem : MCore::Command(s_commandName, orgCommand) { m_oldActionType = AZ::TypeId::CreateNull(); - m_oldActionIndex = MCORE_INVALIDINDEX32; + m_oldActionIndex = InvalidIndex; } bool CommandAnimGraphRemoveTransitionAction::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) @@ -331,7 +331,7 @@ namespace CommandSystem CommandAnimGraphAddStateAction::CommandAnimGraphAddStateAction(MCore::Command* orgCommand) : MCore::Command(s_commandName, orgCommand) - , m_oldActionIndex(MCORE_INVALIDINDEX32) + , m_oldActionIndex(InvalidIndex) { } @@ -385,14 +385,14 @@ namespace CommandSystem } // get the location where to add the new action - size_t insertAt = MCORE_INVALIDINDEX32; + size_t insertAt = InvalidIndex; if (parameters.CheckIfHasParameter("insertAt")) { insertAt = parameters.GetValueAsInt("insertAt", this); } // add it to the transition - if (insertAt == MCORE_INVALIDINDEX32) + if (insertAt == InvalidIndex) { actionSetup.AddAction(newAction); } @@ -501,7 +501,7 @@ namespace CommandSystem : MCore::Command(s_commandName, orgCommand) { m_oldActionType = AZ::TypeId::CreateNull(); - m_oldActionIndex = MCORE_INVALIDINDEX32; + m_oldActionIndex = InvalidIndex; } bool CommandAnimGraphRemoveStateAction::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AttachmentCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AttachmentCommands.cpp index 23c429b04a..a22cf18149 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AttachmentCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AttachmentCommands.cpp @@ -139,13 +139,11 @@ namespace CommandSystem { EMotionFX::AttachmentNode* newAttachment = EMotionFX::AttachmentNode::Create(attachToActorInstance, node->GetNodeIndex(), attachment); attachToActorInstance->AddAttachment(newAttachment); - //attachToActorInstance->AddAttachment( node->GetNodeIndex(), attachment ); } else { attachToActorInstance->RemoveAttachment(attachment, true); } - // attachToActorInstance->RemoveAttachment( attachment, false ); return true; } @@ -300,10 +298,10 @@ namespace CommandSystem bool CommandAddDeformableAttachment::AddAttachment(MCore::Command* command, const MCore::CommandLine& parameters, AZStd::string& outResult, bool remove) { uint32 attachToActorID = parameters.GetValueAsInt("attachToID", command); - uint32 attachToActorIndex = parameters.GetValueAsInt("attachToIndex", command); + size_t attachToActorIndex = parameters.GetValueAsInt("attachToIndex", command); // in case we only specified an attach to index, get the id from that - if (attachToActorIndex != MCORE_INVALIDINDEX32 && attachToActorID == MCORE_INVALIDINDEX32) + if (attachToActorIndex != InvalidIndex && attachToActorID == MCORE_INVALIDINDEX32) { if (EMotionFX::GetActorManager().GetNumActorInstances() <= attachToActorIndex) { @@ -315,11 +313,11 @@ namespace CommandSystem } uint32 attachmentID = parameters.GetValueAsInt("attachmentID", command); - uint32 attachmentIndex = parameters.GetValueAsInt("attachmentIndex", command); + size_t attachmentIndex = parameters.GetValueAsInt("attachmentIndex", command); if (attachmentID == MCORE_INVALIDINDEX32) { // in case we only specified an attachment index, get the id from that - if (attachmentIndex != MCORE_INVALIDINDEX32) + if (attachmentIndex != InvalidIndex) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(attachmentIndex); attachmentID = actorInstance->GetID(); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.cpp index 893fea2224..be4626f592 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.cpp @@ -147,8 +147,8 @@ namespace CommandSystem RegisterCommand(new CommandRecorderClear()); gCommandManager = this; - mLockSelection = false; - mWorkspaceDirtyFlag = false; + m_lockSelection = false; + m_workspaceDirtyFlag = false; } CommandManager::~CommandManager() diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.h index b2c6986297..8fe7e05895 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/CommandManager.h @@ -33,28 +33,28 @@ namespace CommandSystem * Get current selection. * @return The selection list containing all selected actors, motions and nodes. */ - MCORE_INLINE SelectionList& GetCurrentSelection() { mCurrentSelection.MakeValid(); return mCurrentSelection; } + MCORE_INLINE SelectionList& GetCurrentSelection() { m_currentSelection.MakeValid(); return m_currentSelection; } /** * Set current selection. * @param selection The selection list containing all selected actors, motions and nodes. */ - MCORE_INLINE void SetCurrentSelection(SelectionList& selection) { mCurrentSelection.Clear(); mCurrentSelection.Add(selection); } + MCORE_INLINE void SetCurrentSelection(SelectionList& selection) { m_currentSelection.Clear(); m_currentSelection.Add(selection); } - MCORE_INLINE bool GetLockSelection() const { return mLockSelection; } - void SetLockSelection(bool lockSelection) { mLockSelection = lockSelection; } + MCORE_INLINE bool GetLockSelection() const { return m_lockSelection; } + void SetLockSelection(bool lockSelection) { m_lockSelection = lockSelection; } - void SetWorkspaceDirtyFlag(bool dirty) { mWorkspaceDirtyFlag = dirty; } - MCORE_INLINE bool GetWorkspaceDirtyFlag() const { return mWorkspaceDirtyFlag; } + void SetWorkspaceDirtyFlag(bool dirty) { m_workspaceDirtyFlag = dirty; } + MCORE_INLINE bool GetWorkspaceDirtyFlag() const { return m_workspaceDirtyFlag; } // Only true when user create or open a workspace. void SetUserOpenedWorkspaceFlag(bool flag); bool GetUserOpenedWorkspaceFlag() const { return m_userOpenedWorkspaceFlag; } private: - SelectionList mCurrentSelection; /**< The current selected actors, motions and nodes. */ - bool mLockSelection; - bool mWorkspaceDirtyFlag; + SelectionList m_currentSelection; /**< The current selected actors, motions and nodes. */ + bool m_lockSelection; + bool m_workspaceDirtyFlag; bool m_userOpenedWorkspaceFlag = false; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp index b86c23677c..168de93e38 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.cpp @@ -29,7 +29,7 @@ namespace CommandSystem CommandImportActor::CommandImportActor(MCore::Command* orgCommand) : MCore::Command("ImportActor", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -77,10 +77,10 @@ namespace CommandSystem EMotionFX::Importer::ActorSettings settings; // extract default values from the command syntax automatically, if they aren't specified explicitly - settings.mLoadLimits = parameters.GetValueAsBool("loadLimits", this); - settings.mLoadMorphTargets = parameters.GetValueAsBool("loadMorphTargets", this); - settings.mLoadSkeletalLODs = parameters.GetValueAsBool("loadSkeletalLODs", this); - settings.mDualQuatSkinning = parameters.GetValueAsBool("dualQuatSkinning", this); + settings.m_loadLimits = parameters.GetValueAsBool("loadLimits", this); + settings.m_loadMorphTargets = parameters.GetValueAsBool("loadMorphTargets", this); + settings.m_loadSkeletalLoDs = parameters.GetValueAsBool("loadSkeletalLODs", this); + settings.m_dualQuatSkinning = parameters.GetValueAsBool("dualQuatSkinning", this); // try to load the actor AZStd::shared_ptr actor {EMotionFX::GetImporter().LoadActor(filename.c_str(), &settings)}; @@ -101,11 +101,11 @@ namespace CommandSystem } // in case we are in a redo call assign the previously used id - if (mPreviouslyUsedID != MCORE_INVALIDINDEX32) + if (m_previouslyUsedId != MCORE_INVALIDINDEX32) { - actor->SetID(mPreviouslyUsedID); + actor->SetID(m_previouslyUsedId); } - mPreviouslyUsedID = actor->GetID(); + m_previouslyUsedId = actor->GetID(); // select the actor automatically if (parameters.GetValueAsBool("autoSelect", this)) @@ -115,7 +115,7 @@ namespace CommandSystem // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); // return the id of the newly created actor @@ -134,7 +134,7 @@ namespace CommandSystem uint32 actorID = parameters.GetValueAsInt("actorID", MCORE_INVALIDINDEX32); if (actorID == MCORE_INVALIDINDEX32) { - actorID = mPreviouslyUsedID; + actorID = m_previouslyUsedId; } // check if we have to unselect the actors created by this command @@ -159,7 +159,7 @@ namespace CommandSystem GetCommandManager()->ExecuteCommandInsideCommand("UpdateRenderActors", updateRenderActorsResult); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return true; } @@ -203,7 +203,7 @@ namespace CommandSystem CommandImportMotion::CommandImportMotion(MCore::Command* orgCommand) : MCore::Command("ImportMotion", orgCommand) { - mOldMotionID = MCORE_INVALIDINDEX32; + m_oldMotionId = MCORE_INVALIDINDEX32; } @@ -255,7 +255,7 @@ namespace CommandSystem if (AzFramework::StringFunc::Equal(extension.c_str(), "motion", false /* no case */)) { EMotionFX::Importer::MotionSettings settings; - settings.mLoadMotionEvents = parameters.GetValueAsBool("loadMotionEvents", this); + settings.m_loadMotionEvents = parameters.GetValueAsBool("loadMotionEvents", this); motion = EMotionFX::GetImporter().LoadMotion(filename.c_str(), &settings); } @@ -273,12 +273,12 @@ namespace CommandSystem } // in case we are in a redo call assign the previously used id - if (mOldMotionID != MCORE_INVALIDINDEX32) + if (m_oldMotionId != MCORE_INVALIDINDEX32) { - motion->SetID(mOldMotionID); + motion->SetID(m_oldMotionId); } - mOldMotionID = motion->GetID(); - mOldFileName = motion->GetFileName(); + m_oldMotionId = motion->GetID(); + m_oldFileName = motion->GetFileName(); // set the motion name AZStd::string motionName; @@ -292,7 +292,7 @@ namespace CommandSystem } // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); // reset the dirty flag @@ -308,11 +308,11 @@ namespace CommandSystem // execute the group command AZStd::string commandString; - commandString = AZStd::string::format("RemoveMotion -filename \"%s\"", mOldFileName.c_str()); + commandString = AZStd::string::format("RemoveMotion -filename \"%s\"", m_oldFileName.c_str()); bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.h index 9eb27a06f6..6e8f4728c7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ImporterCommands.h @@ -21,17 +21,17 @@ namespace CommandSystem // add actor MCORE_DEFINECOMMAND_START(CommandImportActor, "Import actor", true) public: - uint32 mPreviouslyUsedID; - uint32 mOldIndex; - bool mOldWorkspaceDirtyFlag; + uint32 m_previouslyUsedId; + uint32 m_oldIndex; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // add motion MCORE_DEFINECOMMAND_START(CommandImportMotion, "Import motion", true) public: - uint32 mOldMotionID; - AZStd::string mOldFileName; - bool mOldWorkspaceDirtyFlag; + uint32 m_oldMotionId; + AZStd::string m_oldFileName; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp index 506f47fcac..9a0913a5db 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MetaData.cpp @@ -71,8 +71,8 @@ namespace CommandSystem void MetaData::GeneratePhonemeMetaData(EMotionFX::Actor* actor, AZStd::string& outMetaDataString) { - const AZ::u32 numLODLevels = actor->GetNumLODLevels(); - for (AZ::u32 lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) + const size_t numLODLevels = actor->GetNumLODLevels(); + for (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) { EMotionFX::MorphSetup* morphSetup = actor->GetMorphSetup(lodLevel); if (!morphSetup) @@ -80,8 +80,8 @@ namespace CommandSystem continue; } - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (uint32 i = 0; i < numMorphTargets; ++i) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t i = 0; i < numMorphTargets; ++i) { EMotionFX::MorphTarget* morphTarget = morphSetup->GetMorphTarget(i); if (!morphTarget) @@ -89,7 +89,7 @@ namespace CommandSystem continue; } - outMetaDataString += AZStd::string::format("AdjustMorphTarget -actorID $(ACTORID) -lodLevel %i -name \"%s\" -phonemeAction \"replace\" ", lodLevel, morphTarget->GetName()); + outMetaDataString += AZStd::string::format("AdjustMorphTarget -actorID $(ACTORID) -lodLevel %zu -name \"%s\" -phonemeAction \"replace\" ", lodLevel, morphTarget->GetName()); outMetaDataString += AZStd::string::format("-phonemeSets \"%s\" ", morphTarget->GetPhonemeSetString(morphTarget->GetPhonemeSets()).c_str()); outMetaDataString += AZStd::string::format("-rangeMin %f -rangeMax %f\n", morphTarget->GetRangeMin(), morphTarget->GetRangeMax()); } @@ -101,8 +101,8 @@ namespace CommandSystem { AZStd::string attachmentNodeNameList; - const AZ::u32 numNodes = actor->GetNumNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); if (!node) @@ -153,7 +153,7 @@ namespace CommandSystem for (uint32 i = 0; i < actor->GetNumNodes(); ++i) { const EMotionFX::Actor::NodeMirrorInfo& mirrorInfo = actor->GetNodeMirrorInfo(i); - uint16 sourceNode = mirrorInfo.mSourceNode; + uint16 sourceNode = mirrorInfo.m_sourceNode; if (sourceNode != MCORE_INVALIDINDEX16 && sourceNode != static_cast(i)) { outMetaDataString += actor->GetSkeleton()->GetNode(i)->GetNameString(); @@ -233,10 +233,9 @@ namespace CommandSystem // Construct a new command group and fill it with all meta data commands. MCore::CommandGroup commandGroup; - const size_t numTokens = tokens.size(); - for (size_t i = 0; i < numTokens; ++i) + for (const AZStd::string& token : tokens) { - commandGroup.AddCommandString(tokens[i].c_str()); + commandGroup.AddCommandString(token); } // Execute the command group and apply the meta data. diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.cpp index 0abec28850..0a48952bfc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.cpp @@ -122,7 +122,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("weight") && morphTargetInstance) { const float value = parameters.GetValueAsFloat("weight", this); - mOldWeight = morphTargetInstance->GetWeight(); + m_oldWeight = morphTargetInstance->GetWeight(); morphTargetInstance->SetWeight(value); } @@ -130,7 +130,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("manualMode") && morphTargetInstance) { const bool value = parameters.GetValueAsBool("manualMode", this); - mOldManualModeEnabled = morphTargetInstance->GetIsInManualMode(); + m_oldManualModeEnabled = morphTargetInstance->GetIsInManualMode(); morphTargetInstance->SetManualMode(value); } @@ -138,7 +138,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("rangeMin") && morphTarget) { const float value = parameters.GetValueAsFloat("rangeMin", this); - mOldRangeMin = morphTarget->GetRangeMin(); + m_oldRangeMin = morphTarget->GetRangeMin(); morphTarget->SetRangeMin(value); } @@ -146,7 +146,7 @@ namespace CommandSystem if (parameters.CheckIfHasParameter("rangeMax") && morphTarget) { const float value = parameters.GetValueAsFloat("rangeMax", this); - mOldRangeMax = morphTarget->GetRangeMax(); + m_oldRangeMax = morphTarget->GetRangeMax(); morphTarget->SetRangeMax(value); } @@ -159,7 +159,7 @@ namespace CommandSystem parameters.GetValue("phonemeSets", this, &phonemeSetsString); // store old phoneme sets - mOldPhonemeSets = morphTarget->GetPhonemeSets(); + m_oldPhonemeSets = morphTarget->GetPhonemeSets(); // remove the phoneme set if (AzFramework::StringFunc::Equal(valueString.c_str(), "remove", false /* no case */)) @@ -203,7 +203,7 @@ namespace CommandSystem } // save the current dirty flag and tell the actor that something got changed - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); return true; } @@ -240,35 +240,35 @@ namespace CommandSystem // set the old weight of the morph target if (parameters.CheckIfHasParameter("weight") && morphTargetInstance) { - morphTargetInstance->SetWeight(mOldWeight); + morphTargetInstance->SetWeight(m_oldWeight); } // set the old manual mode if (parameters.CheckIfHasParameter("manualMode") && morphTargetInstance) { - morphTargetInstance->SetManualMode(mOldManualModeEnabled); + morphTargetInstance->SetManualMode(m_oldManualModeEnabled); } // set the old range min if (parameters.CheckIfHasParameter("rangeMin") && morphTarget) { - morphTarget->SetRangeMin(mOldRangeMin); + morphTarget->SetRangeMin(m_oldRangeMin); } // set the old range max if (parameters.CheckIfHasParameter("rangeMax") && morphTarget) { - morphTarget->SetRangeMax(mOldRangeMax); + morphTarget->SetRangeMax(m_oldRangeMax); } // set the old phoneme sets if (parameters.CheckIfHasParameter("phonemeAction") && morphTarget) { - morphTarget->SetPhonemeSets(mOldPhonemeSets); + morphTarget->SetPhonemeSets(m_oldPhonemeSets); } // set the dirty flag back to the old value - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.h index 4ab06fe827..2ae284e907 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MorphTargetCommands.h @@ -20,12 +20,12 @@ namespace CommandSystem { // adjust a given morph target of an actor MCORE_DEFINECOMMAND_START(CommandAdjustMorphTarget, "Adjust morph target", true) - float mOldWeight; - float mOldRangeMin; - float mOldRangeMax; - bool mOldManualModeEnabled; - EMotionFX::MorphTarget::EPhonemeSet mOldPhonemeSets; - bool mOldDirtyFlag; + float m_oldWeight; + float m_oldRangeMin; + float m_oldRangeMax; + bool m_oldManualModeEnabled; + EMotionFX::MorphTarget::EPhonemeSet m_oldPhonemeSets; + bool m_oldDirtyFlag; bool GetMorphTarget(EMotionFX::Actor* actor, EMotionFX::ActorInstance* actorInstance, uint32 lodLevel, const char* morphTargetName, EMotionFX::MorphTarget** outMorphTarget, EMotionFX::MorphSetupInstance::MorphTarget** outMorphTargetInstance, AZStd::string& outResult); MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp index 5655f2f293..2bec066549 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.cpp @@ -79,27 +79,27 @@ namespace CommandSystem AZStd::string CommandPlayMotion::PlayBackInfoToCommandParameters(const EMotionFX::PlayBackInfo* playbackInfo) { return AZStd::string::format("-blendInTime %f -blendOutTime %f -playSpeed %f -targetWeight %f -eventWeightThreshold %f -maxPlayTime %f -numLoops %i -priorityLevel %i -blendMode %i -playMode %i -mirrorMotion %s -mix %s -playNow %s -motionExtraction %s -retarget %s -freezeAtLastFrame %s -enableMotionEvents %s -blendOutBeforeEnded %s -canOverwrite %s -deleteOnZeroWeight %s -inPlace %s", - playbackInfo->mBlendInTime, - playbackInfo->mBlendOutTime, - playbackInfo->mPlaySpeed, - playbackInfo->mTargetWeight, - playbackInfo->mEventWeightThreshold, - playbackInfo->mMaxPlayTime, - playbackInfo->mNumLoops, - playbackInfo->mPriorityLevel, - static_cast(playbackInfo->mBlendMode), - static_cast(playbackInfo->mPlayMode), - AZStd::to_string(playbackInfo->mMirrorMotion).c_str(), - AZStd::to_string(playbackInfo->mMix).c_str(), - AZStd::to_string(playbackInfo->mPlayNow).c_str(), - AZStd::to_string(playbackInfo->mMotionExtractionEnabled).c_str(), - AZStd::to_string(playbackInfo->mRetarget).c_str(), - AZStd::to_string(playbackInfo->mFreezeAtLastFrame).c_str(), - AZStd::to_string(playbackInfo->mEnableMotionEvents).c_str(), - AZStd::to_string(playbackInfo->mBlendOutBeforeEnded).c_str(), - AZStd::to_string(playbackInfo->mCanOverwrite).c_str(), - AZStd::to_string(playbackInfo->mDeleteOnZeroWeight).c_str(), - AZStd::to_string(playbackInfo->mInPlace).c_str()); + playbackInfo->m_blendInTime, + playbackInfo->m_blendOutTime, + playbackInfo->m_playSpeed, + playbackInfo->m_targetWeight, + playbackInfo->m_eventWeightThreshold, + playbackInfo->m_maxPlayTime, + playbackInfo->m_numLoops, + playbackInfo->m_priorityLevel, + static_cast(playbackInfo->m_blendMode), + static_cast(playbackInfo->m_playMode), + AZStd::to_string(playbackInfo->m_mirrorMotion).c_str(), + AZStd::to_string(playbackInfo->m_mix).c_str(), + AZStd::to_string(playbackInfo->m_playNow).c_str(), + AZStd::to_string(playbackInfo->m_motionExtractionEnabled).c_str(), + AZStd::to_string(playbackInfo->m_retarget).c_str(), + AZStd::to_string(playbackInfo->m_freezeAtLastFrame).c_str(), + AZStd::to_string(playbackInfo->m_enableMotionEvents).c_str(), + AZStd::to_string(playbackInfo->m_blendOutBeforeEnded).c_str(), + AZStd::to_string(playbackInfo->m_canOverwrite).c_str(), + AZStd::to_string(playbackInfo->m_deleteOnZeroWeight).c_str(), + AZStd::to_string(playbackInfo->m_inPlace).c_str()); } @@ -108,87 +108,87 @@ namespace CommandSystem { if (parameters.CheckIfHasParameter("blendInTime") == true) { - outPlaybackInfo->mBlendInTime = parameters.GetValueAsFloat("blendInTime", command); + outPlaybackInfo->m_blendInTime = parameters.GetValueAsFloat("blendInTime", command); } if (parameters.CheckIfHasParameter("blendOutTime")) { - outPlaybackInfo->mBlendOutTime = parameters.GetValueAsFloat("blendOutTime", command); + outPlaybackInfo->m_blendOutTime = parameters.GetValueAsFloat("blendOutTime", command); } if (parameters.CheckIfHasParameter("playSpeed")) { - outPlaybackInfo->mPlaySpeed = parameters.GetValueAsFloat("playSpeed", command); + outPlaybackInfo->m_playSpeed = parameters.GetValueAsFloat("playSpeed", command); } if (parameters.CheckIfHasParameter("targetWeight")) { - outPlaybackInfo->mTargetWeight = parameters.GetValueAsFloat("targetWeight", command); + outPlaybackInfo->m_targetWeight = parameters.GetValueAsFloat("targetWeight", command); } if (parameters.CheckIfHasParameter("eventWeightThreshold")) { - outPlaybackInfo->mEventWeightThreshold = parameters.GetValueAsFloat("eventWeightThreshold", command); + outPlaybackInfo->m_eventWeightThreshold = parameters.GetValueAsFloat("eventWeightThreshold", command); } if (parameters.CheckIfHasParameter("maxPlayTime")) { - outPlaybackInfo->mMaxPlayTime = parameters.GetValueAsFloat("maxPlayTime", command); + outPlaybackInfo->m_maxPlayTime = parameters.GetValueAsFloat("maxPlayTime", command); } if (parameters.CheckIfHasParameter("numLoops")) { - outPlaybackInfo->mNumLoops = parameters.GetValueAsInt("numLoops", command); + outPlaybackInfo->m_numLoops = parameters.GetValueAsInt("numLoops", command); } if (parameters.CheckIfHasParameter("priorityLevel")) { - outPlaybackInfo->mPriorityLevel = parameters.GetValueAsInt("priorityLevel", command); + outPlaybackInfo->m_priorityLevel = parameters.GetValueAsInt("priorityLevel", command); } if (parameters.CheckIfHasParameter("blendMode")) { - outPlaybackInfo->mBlendMode = (EMotionFX::EMotionBlendMode)parameters.GetValueAsInt("blendMode", command); + outPlaybackInfo->m_blendMode = (EMotionFX::EMotionBlendMode)parameters.GetValueAsInt("blendMode", command); } if (parameters.CheckIfHasParameter("playMode")) { - outPlaybackInfo->mPlayMode = (EMotionFX::EPlayMode)parameters.GetValueAsInt("playMode", command); + outPlaybackInfo->m_playMode = (EMotionFX::EPlayMode)parameters.GetValueAsInt("playMode", command); } if (parameters.CheckIfHasParameter("mirrorMotion")) { - outPlaybackInfo->mMirrorMotion = parameters.GetValueAsBool("mirrorMotion", command); + outPlaybackInfo->m_mirrorMotion = parameters.GetValueAsBool("mirrorMotion", command); } if (parameters.CheckIfHasParameter("mix")) { - outPlaybackInfo->mMix = parameters.GetValueAsBool("mix", command); + outPlaybackInfo->m_mix = parameters.GetValueAsBool("mix", command); } if (parameters.CheckIfHasParameter("playNow")) { - outPlaybackInfo->mPlayNow = parameters.GetValueAsBool("playNow", command); + outPlaybackInfo->m_playNow = parameters.GetValueAsBool("playNow", command); } if (parameters.CheckIfHasParameter("motionExtraction")) { - outPlaybackInfo->mMotionExtractionEnabled = parameters.GetValueAsBool("motionExtraction", command); + outPlaybackInfo->m_motionExtractionEnabled = parameters.GetValueAsBool("motionExtraction", command); } if (parameters.CheckIfHasParameter("retarget")) { - outPlaybackInfo->mRetarget = parameters.GetValueAsBool("retarget", command); + outPlaybackInfo->m_retarget = parameters.GetValueAsBool("retarget", command); } if (parameters.CheckIfHasParameter("freezeAtLastFrame")) { - outPlaybackInfo->mFreezeAtLastFrame = parameters.GetValueAsBool("freezeAtLastFrame", command); + outPlaybackInfo->m_freezeAtLastFrame = parameters.GetValueAsBool("freezeAtLastFrame", command); } if (parameters.CheckIfHasParameter("enableMotionEvents")) { - outPlaybackInfo->mEnableMotionEvents = parameters.GetValueAsBool("enableMotionEvents", command); + outPlaybackInfo->m_enableMotionEvents = parameters.GetValueAsBool("enableMotionEvents", command); } if (parameters.CheckIfHasParameter("blendOutBeforeEnded")) { - outPlaybackInfo->mBlendOutBeforeEnded = parameters.GetValueAsBool("blendOutBeforeEnded", command); + outPlaybackInfo->m_blendOutBeforeEnded = parameters.GetValueAsBool("blendOutBeforeEnded", command); } if (parameters.CheckIfHasParameter("canOverwrite")) { - outPlaybackInfo->mCanOverwrite = parameters.GetValueAsBool("canOverwrite", command); + outPlaybackInfo->m_canOverwrite = parameters.GetValueAsBool("canOverwrite", command); } if (parameters.CheckIfHasParameter("deleteOnZeroWeight")) { - outPlaybackInfo->mDeleteOnZeroWeight = parameters.GetValueAsBool("deleteOnZeroWeight", command); + outPlaybackInfo->m_deleteOnZeroWeight = parameters.GetValueAsBool("deleteOnZeroWeight", command); } if (parameters.CheckIfHasParameter("inPlace")) { - outPlaybackInfo->mInPlace = parameters.GetValueAsBool("inPlace", command); + outPlaybackInfo->m_inPlace = parameters.GetValueAsBool("inPlace", command); } } @@ -200,7 +200,7 @@ namespace CommandSystem m_oldData.clear(); // check if there is any actor instance selected and if not return false so that the command doesn't get called and doesn't get inside the action history - const uint32 numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); + const size_t numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); // verify if we actually have selected an actor instance if (numSelectedActorInstances == 0) @@ -236,7 +236,7 @@ namespace CommandSystem CommandParametersToPlaybackInfo(this, parameters, &playbackInfo); // iterate through all actor instances and start playing all selected motions - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetActorInstance(i); @@ -327,7 +327,7 @@ namespace CommandSystem #define SYNTAX_MOTIONCOMMANDS \ GetSyntax().ReserveParameters(30); \ GetSyntax().AddRequiredParameter("filename", "The filename of the motion file to play.", MCore::CommandSyntax::PARAMTYPE_STRING); \ - /*GetSyntax().AddParameter( "mirrorPlaneNormal", "The motion mirror plane normal, which is (1,0,0) on default. This setting is only used when mMirrorMotion is set to true.", MCore::CommandSyntax::PARAMTYPE_VECTOR3, "(1, 0, 0)" );*/ \ + /*GetSyntax().AddParameter( "mirrorPlaneNormal", "The motion mirror plane normal, which is (1,0,0) on default. This setting is only used when mirrorMotion is set to true.", MCore::CommandSyntax::PARAMTYPE_VECTOR3, "(1, 0, 0)" );*/ \ GetSyntax().AddParameter("blendInTime", "The time, in seconds, which it will take to fully have blended to the target weight.", MCore::CommandSyntax::PARAMTYPE_FLOAT, "0.3"); \ GetSyntax().AddParameter("blendOutTime", "The time, in seconds, which it takes to smoothly fadeout the motion, after it has been stopped playing.", MCore::CommandSyntax::PARAMTYPE_FLOAT, "0.3"); \ GetSyntax().AddParameter("playSpeed", "The playback speed factor. A value of 1 stands for the original speed, while for example 2 means twice the original speed.", MCore::CommandSyntax::PARAMTYPE_FLOAT, "1.0"); \ @@ -340,7 +340,7 @@ namespace CommandSystem GetSyntax().AddParameter("retargetRootIndex", "The retargeting root node index.", MCore::CommandSyntax::PARAMTYPE_INT, "0"); \ GetSyntax().AddParameter("blendMode", "The motion blend mode. Please read the MotionInstance::SetBlendMode(...) method for more information.", MCore::CommandSyntax::PARAMTYPE_INT, "0"); /* 4294967296 == MCORE_INVALIDINDEX32 */ \ GetSyntax().AddParameter("playMode", "The motion playback mode. This means forward or backward playback.", MCore::CommandSyntax::PARAMTYPE_INT, "0"); \ - GetSyntax().AddParameter("mirrorMotion", "Is motion mirroring enabled or not? When set to true, the mMirrorPlaneNormal is used as mirroring axis.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); \ + GetSyntax().AddParameter("mirrorMotion", "Is motion mirroring enabled or not? When set to true, the mirrorPlaneNormal is used as mirroring axis.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); \ GetSyntax().AddParameter("mix", "Set to true if you want this motion to mix or not.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); \ GetSyntax().AddParameter("playNow", "Set to true if you want to start playing the motion right away. If set to false it will be scheduled for later by inserting it into the motion queue.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "true"); \ GetSyntax().AddParameter("motionExtraction", "Set to true when you want to use motion extraction.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "true"); \ @@ -467,8 +467,8 @@ namespace CommandSystem MCORE_UNUSED(outResult); // iterate through the motion instances and modify them - const uint32 numSelectedMotionInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedMotionInstances(); - for (uint32 i = 0; i < numSelectedMotionInstances; ++i) + const size_t numSelectedMotionInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedMotionInstances(); + for (size_t i = 0; i < numSelectedMotionInstances; ++i) { // get the current selected motion instance and adjust it based on the parameters EMotionFX::MotionInstance* selectedMotionInstance = GetCommandManager()->GetCurrentSelection().GetMotionInstance(i); @@ -546,13 +546,13 @@ namespace CommandSystem EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo(); // copy the current playback info to the undo data - mOldPlaybackInfo = *defaultPlayBackInfo; + m_oldPlaybackInfo = *defaultPlayBackInfo; // adjust the playback info based on the parameters CommandPlayMotion::CommandParametersToPlaybackInfo(this, parameters, defaultPlayBackInfo); // save the current dirty flag and tell the motion that something got changed - mOldDirtyFlag = motion->GetDirtyFlag(); + m_oldDirtyFlag = motion->GetDirtyFlag(); return true; } @@ -585,10 +585,10 @@ namespace CommandSystem } // copy the saved playback info to the actual one - *defaultPlayBackInfo = mOldPlaybackInfo; + *defaultPlayBackInfo = m_oldPlaybackInfo; // set the dirty flag back to the old value - motion->SetDirtyFlag(mOldDirtyFlag); + motion->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -614,11 +614,8 @@ namespace CommandSystem // execute bool CommandStopMotionInstances::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) { - // clear our old data so that we start fresh in case of a redo - //mOldData.Clear(); - // get the number of selected actor instances - const uint32 numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); + const size_t numSelectedActorInstances = GetCommandManager()->GetCurrentSelection().GetNumSelectedActorInstances(); // check if there is any actor instance selected and if not return false so that the command doesn't get called and doesn't get inside the action history if (numSelectedActorInstances == 0) @@ -645,7 +642,7 @@ namespace CommandSystem } // iterate through all actor instances and stop all selected motion instances - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { // get the actor instance and the corresponding motion system EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetActorInstance(i); @@ -665,8 +662,8 @@ namespace CommandSystem } // get the number of motion instances and iterate through them - const uint32 numMotionInstances = motionSystem->GetNumMotionInstances(); - for (uint32 j = 0; j < numMotionInstances; ++j) + const size_t numMotionInstances = motionSystem->GetNumMotionInstances(); + for (size_t j = 0; j < numMotionInstances; ++j) { EMotionFX::MotionInstance* motionInstance = motionSystem->GetMotionInstance(j); @@ -716,12 +713,9 @@ namespace CommandSystem MCORE_UNUSED(parameters); MCORE_UNUSED(outResult); - // clear our old data so that we start fresh in case of a redo - //mOldData.Clear(); - // iterate through all actor instances and stop all selected motion instances - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { // get the actor instance and the corresponding motion system EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -741,8 +735,8 @@ namespace CommandSystem } // get the number of motion instances and iterate through them - const uint32 numMotionInstances = motionSystem->GetNumMotionInstances(); - for (uint32 j = 0; j < numMotionInstances; ++j) + const size_t numMotionInstances = motionSystem->GetNumMotionInstances(); + for (size_t j = 0; j < numMotionInstances; ++j) { // get the motion instance and stop it EMotionFX::MotionInstance* motionInstance = motionSystem->GetMotionInstance(j); @@ -823,26 +817,26 @@ namespace CommandSystem // adjust the dirty flag if (m_dirtyFlag) { - mOldDirtyFlag = motion->GetDirtyFlag(); + m_oldDirtyFlag = motion->GetDirtyFlag(); motion->SetDirtyFlag(m_dirtyFlag.value()); } // adjust the name if (m_name) { - mOldName = motion->GetName(); + m_oldName = motion->GetName(); motion->SetName(m_name.value().c_str()); - mOldDirtyFlag = motion->GetDirtyFlag(); + m_oldDirtyFlag = motion->GetDirtyFlag(); motion->SetDirtyFlag(true); } // Adjust the motion extraction flags. if (m_extractionFlags) { - mOldExtractionFlags = motion->GetMotionExtractionFlags(); + m_oldExtractionFlags = motion->GetMotionExtractionFlags(); motion->SetMotionExtractionFlags(m_extractionFlags.value()); - mOldDirtyFlag = motion->GetDirtyFlag(); + m_oldDirtyFlag = motion->GetDirtyFlag(); motion->SetDirtyFlag(true); } @@ -866,20 +860,20 @@ namespace CommandSystem // adjust the dirty flag if (m_dirtyFlag) { - motion->SetDirtyFlag(mOldDirtyFlag); + motion->SetDirtyFlag(m_oldDirtyFlag); } // adjust the name if (m_name) { - motion->SetName(mOldName.c_str()); - motion->SetDirtyFlag(mOldDirtyFlag); + motion->SetName(m_oldName.c_str()); + motion->SetDirtyFlag(m_oldDirtyFlag); } if (m_extractionFlags) { - motion->SetMotionExtractionFlags(mOldExtractionFlags); - motion->SetDirtyFlag(mOldDirtyFlag); + motion->SetMotionExtractionFlags(m_oldExtractionFlags); + motion->SetDirtyFlag(m_oldDirtyFlag); } return true; @@ -933,7 +927,7 @@ namespace CommandSystem CommandRemoveMotion::CommandRemoveMotion(MCore::Command* orgCommand) : MCore::Command("RemoveMotion", orgCommand) { - mOldMotionID = MCORE_INVALIDINDEX32; + m_oldMotionId = MCORE_INVALIDINDEX32; } @@ -974,8 +968,8 @@ namespace CommandSystem } // make sure the motion is not part of any motion set - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { // get the current motion set and check if the motion we want to remove is used by it EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -992,12 +986,12 @@ namespace CommandSystem GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult); // store the previously used id and remove the motion - mOldIndex = EMotionFX::GetMotionManager().FindMotionIndex(motion); - mOldMotionID = motion->GetID(); - mOldFileName = motion->GetFileName(); + m_oldIndex = EMotionFX::GetMotionManager().FindMotionIndex(motion); + m_oldMotionId = motion->GetID(); + m_oldFileName = motion->GetFileName(); // mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); EMotionFX::GetMotionManager().RemoveMotionByID(motion->GetID()); @@ -1012,11 +1006,11 @@ namespace CommandSystem // execute the group command AZStd::string commandString; - commandString = AZStd::string::format("ImportMotion -filename \"%s\" -motionID %i", mOldFileName.c_str(), mOldMotionID); + commandString = AZStd::string::format("ImportMotion -filename \"%s\" -motionID %i", m_oldFileName.c_str(), m_oldMotionId); bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult); // restore the workspace dirty flag - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -1045,9 +1039,9 @@ namespace CommandSystem CommandScaleMotionData::CommandScaleMotionData(MCore::Command* orgCommand) : MCore::Command("ScaleMotionData", orgCommand) { - mMotionID = MCORE_INVALIDINDEX32; - mScaleFactor = 1.0f; - mOldDirtyFlag = false; + m_motionId = MCORE_INVALIDINDEX32; + m_scaleFactor = 1.0f; + m_oldDirtyFlag = false; } @@ -1092,29 +1086,29 @@ namespace CommandSystem return false; } - mMotionID = motion->GetID(); - mScaleFactor = parameters.GetValueAsFloat("scaleFactor", 1.0f); + m_motionId = motion->GetID(); + m_scaleFactor = parameters.GetValueAsFloat("scaleFactor", 1.0f); AZStd::string targetUnitTypeString; parameters.GetValue("unitType", this, &targetUnitTypeString); - mUseUnitType = parameters.CheckIfHasParameter("unitType"); + m_useUnitType = parameters.CheckIfHasParameter("unitType"); MCore::Distance::EUnitType targetUnitType; bool stringConvertSuccess = MCore::Distance::StringToUnitType(targetUnitTypeString, &targetUnitType); - if (mUseUnitType && stringConvertSuccess == false) + if (m_useUnitType && stringConvertSuccess == false) { outResult = AZStd::string::format("The passed unitType '%s' is not a valid unit type.", targetUnitTypeString.c_str()); return false; } - mOldUnitType = MCore::Distance::UnitTypeToString(motion->GetUnitType()); + m_oldUnitType = MCore::Distance::UnitTypeToString(motion->GetUnitType()); - mOldDirtyFlag = motion->GetDirtyFlag(); + m_oldDirtyFlag = motion->GetDirtyFlag(); motion->SetDirtyFlag(true); // perform the scaling - if (mUseUnitType == false) + if (m_useUnitType == false) { - motion->Scale(mScaleFactor); + motion->Scale(m_scaleFactor); } else { @@ -1130,23 +1124,23 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - if (mUseUnitType == false) + if (m_useUnitType == false) { AZStd::string commandString; - commandString = AZStd::string::format("ScaleMotionData -id %d -scaleFactor %.8f", mMotionID, 1.0f / mScaleFactor); + commandString = AZStd::string::format("ScaleMotionData -id %d -scaleFactor %.8f", m_motionId, 1.0f / m_scaleFactor); GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult); } else { AZStd::string commandString; - commandString = AZStd::string::format("ScaleMotionData -id %d -unitType \"%s\"", mMotionID, mOldUnitType.c_str()); + commandString = AZStd::string::format("ScaleMotionData -id %d -unitType \"%s\"", m_motionId, m_oldUnitType.c_str()); GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult); } - EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(mMotionID); + EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(m_motionId); if (motion) { - motion->SetDirtyFlag(mOldDirtyFlag); + motion->SetDirtyFlag(m_oldDirtyFlag); } return true; @@ -1185,13 +1179,12 @@ namespace CommandSystem const size_t numFileNames = filenames.size(); const AZStd::string commandGroupName = AZStd::string::format("%s %zu motion%s", reload ? "Reload" : "Load", numFileNames, (numFileNames > 1) ? "s" : ""); - MCore::CommandGroup commandGroup(commandGroupName, static_cast(numFileNames * 2)); + MCore::CommandGroup commandGroup(commandGroupName, numFileNames * 2); AZStd::string command; const EMotionFX::MotionManager& motionManager = EMotionFX::GetMotionManager(); - for (size_t i = 0; i < numFileNames; ++i) + for (const AZStd::string& filename : filenames) { - const AZStd::string& filename = filenames[i]; const EMotionFX::Motion* motion = motionManager.FindMotionByFileName(filename.c_str()); if (reload && motion) @@ -1234,11 +1227,11 @@ namespace CommandSystem void ClearMotions(MCore::CommandGroup* commandGroup, bool forceRemove) { // iterate through the motions and put them into some array - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); + const size_t numMotions = EMotionFX::GetMotionManager().GetNumMotions(); AZStd::vector motionsToRemove; motionsToRemove.reserve(numMotions); - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); @@ -1283,10 +1276,8 @@ namespace CommandSystem // Iterate through all motions and remove them. AZStd::string commandString; - for (uint32 i = 0; i < numMotions; ++i) + for (const EMotionFX::Motion* motion : motions) { - EMotionFX::Motion* motion = motions[i]; - if (motion->GetIsOwnedByRuntime()) { continue; @@ -1294,10 +1285,10 @@ namespace CommandSystem // Is the motion part of a motion set? bool isUsed = false; - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 j = 0; j < numMotionSets; ++j) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { - EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(j); + EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); EMotionFX::MotionSet::MotionEntry* motionEntry = motionSet->FindMotionEntry(motion); if (motionEntry) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h index 2dbee2ad4a..2a87b11627 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionCommands.h @@ -38,9 +38,9 @@ namespace CommandSystem bool SetCommandParameters(const MCore::CommandLine& parameters); - void SetMotionID(int32 motionID) { m_motionID = motionID; } + void SetMotionID(uint32 motionID) { m_motionID = motionID; } protected: - int32 m_motionID = 0; + uint32 m_motionID = 0; }; // Adjust motion command. @@ -69,33 +69,33 @@ namespace CommandSystem private: AZStd::optional m_dirtyFlag; - bool mOldDirtyFlag; + bool m_oldDirtyFlag; AZStd::optional m_extractionFlags; - EMotionFX::EMotionExtractionFlags mOldExtractionFlags; + EMotionFX::EMotionExtractionFlags m_oldExtractionFlags; AZStd::optional m_name; - AZStd::string mOldName; - AZStd::string mOldMotionExtractionNodeName; + AZStd::string m_oldName; + AZStd::string m_oldMotionExtractionNodeName; }; // Remove motion command. MCORE_DEFINECOMMAND_START(CommandRemoveMotion, "Remove motion", true) public: - uint32 mOldMotionID; - AZStd::string mOldFileName; - uint32 mOldIndex; - bool mOldWorkspaceDirtyFlag; + uint32 m_oldMotionId; + AZStd::string m_oldFileName; + size_t m_oldIndex; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END // Scale motion data. MCORE_DEFINECOMMAND_START(CommandScaleMotionData, "Scale motion data", true) public: - AZStd::string mOldUnitType; - uint32 mMotionID; - float mScaleFactor; - bool mOldDirtyFlag; - bool mUseUnitType; + AZStd::string m_oldUnitType; + uint32 m_motionId; + float m_scaleFactor; + bool m_oldDirtyFlag; + bool m_useUnitType; MCORE_DEFINECOMMAND_END @@ -129,8 +129,8 @@ namespace CommandSystem // Adjust default playback info command. MCORE_DEFINECOMMAND_START(CommandAdjustDefaultPlayBackInfo, "Adjust default playback info", true) - EMotionFX::PlayBackInfo mOldPlaybackInfo; - bool mOldDirtyFlag; + EMotionFX::PlayBackInfo m_oldPlaybackInfo; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp index 8ee207713c..7c02972b78 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.cpp @@ -293,7 +293,7 @@ namespace CommandSystem CommandRemoveMotionEventTrack::CommandRemoveMotionEventTrack(MCore::Command* orgCommand) : MCore::Command("RemoveMotionEventTrack", orgCommand) { - mOldTrackIndex = MCORE_INVALIDINDEX32; + m_oldTrackIndex = InvalidIndex; } @@ -332,8 +332,8 @@ namespace CommandSystem } // store information for undo - mOldTrackIndex = eventTrackIndex.GetValue(); - mOldEnabled = eventTable->GetTrack(eventTrackIndex.GetValue())->GetIsEnabled(); + m_oldTrackIndex = eventTrackIndex.GetValue(); + m_oldEnabled = eventTable->GetTrack(eventTrackIndex.GetValue())->GetIsEnabled(); // remove the motion event track eventTable->RemoveTrack(eventTrackIndex.GetValue()); @@ -353,7 +353,7 @@ namespace CommandSystem const int32 motionID = parameters.GetValueAsInt("motionID", this); AZStd::string command; - command = AZStd::string::format("CreateMotionEventTrack -motionID %i -eventTrackName \"%s\" -index %zu -enabled %s", motionID, eventTrackName.c_str(), mOldTrackIndex, mOldEnabled ? "true" : "false"); + command = AZStd::string::format("CreateMotionEventTrack -motionID %i -eventTrackName \"%s\" -index %zu -enabled %s", motionID, eventTrackName.c_str(), m_oldTrackIndex, m_oldEnabled ? "true" : "false"); return GetCommandManager()->ExecuteCommandInsideCommand(command.c_str(), outResult); } @@ -586,9 +586,9 @@ namespace CommandSystem } // add the motion event and check if everything worked fine - mMotionEventNr = eventTrack->AddEvent(m_startTime, m_endTime, AZStd::move(m_eventDatas.value_or(EMotionFX::EventDataSet()))); + m_motionEventNr = eventTrack->AddEvent(m_startTime, m_endTime, m_eventDatas.value_or(EMotionFX::EventDataSet())); - if (mMotionEventNr == MCORE_INVALIDINDEX32) + if (m_motionEventNr == InvalidIndex) { outResult = AZStd::string::format("Cannot create motion event. The returned motion event index is not valid."); return false; @@ -604,7 +604,7 @@ namespace CommandSystem { AZ_UNUSED(parameters); - const AZStd::string command = AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu", m_motionID, m_eventTrackName.c_str(), mMotionEventNr); + const AZStd::string command = AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu", m_motionID, m_eventTrackName.c_str(), m_motionEventNr); return GetCommandManager()->ExecuteCommandInsideCommand(command.c_str(), outResult); } @@ -700,8 +700,8 @@ namespace CommandSystem // get the motion event and store the old values of the motion event for undo const EMotionFX::MotionEvent& motionEvent = eventTrack->GetEvent(eventNr); - mOldStartTime = motionEvent.GetStartTime(); - mOldEndTime = motionEvent.GetEndTime(); + m_oldStartTime = motionEvent.GetStartTime(); + m_oldEndTime = motionEvent.GetEndTime(); m_oldEventDatas = motionEvent.GetEventDatas(); // remove the motion event @@ -728,7 +728,7 @@ namespace CommandSystem } MCore::CommandGroup commandGroup; - CommandHelperAddMotionEvent(motion, eventTrackName.c_str(), mOldStartTime, mOldEndTime, m_oldEventDatas, &commandGroup); + CommandHelperAddMotionEvent(motion, eventTrackName.c_str(), m_oldStartTime, m_oldEndTime, m_oldEventDatas, &commandGroup); return GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, outResult); } @@ -956,7 +956,7 @@ namespace CommandSystem } // get the event index and check if it is in range - if (m_eventNr < 0 || m_eventNr >= eventTrack->GetNumEvents()) + if (m_eventNr >= eventTrack->GetNumEvents()) { return AZ::Failure(); } @@ -1006,7 +1006,7 @@ namespace CommandSystem // remove event track - void CommandRemoveEventTrack(EMotionFX::Motion* motion, uint32 trackIndex) + void CommandRemoveEventTrack(EMotionFX::Motion* motion, size_t trackIndex) { if (!motion) { @@ -1035,7 +1035,7 @@ namespace CommandSystem // remove event track - void CommandRemoveEventTrack(uint32 trackIndex) + void CommandRemoveEventTrack(size_t trackIndex) { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); CommandRemoveEventTrack(motion, trackIndex); @@ -1043,7 +1043,7 @@ namespace CommandSystem // rename event track - void CommandRenameEventTrack(EMotionFX::Motion* motion, uint32 trackIndex, const char* newName) + void CommandRenameEventTrack(EMotionFX::Motion* motion, size_t trackIndex, const char* newName) { // make sure the motion is valid if (motion == nullptr) @@ -1065,7 +1065,7 @@ namespace CommandSystem // rename event track - void CommandRenameEventTrack(uint32 trackIndex, const char* newName) + void CommandRenameEventTrack(size_t trackIndex, const char* newName) { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); CommandRenameEventTrack(motion, trackIndex, newName); @@ -1073,7 +1073,7 @@ namespace CommandSystem // enable or disable event track - void CommandEnableEventTrack(EMotionFX::Motion* motion, uint32 trackIndex, bool isEnabled) + void CommandEnableEventTrack(EMotionFX::Motion* motion, size_t trackIndex, bool isEnabled) { // make sure the motion is valid if (motion == nullptr) @@ -1098,7 +1098,7 @@ namespace CommandSystem // enable or disable event track - void CommandEnableEventTrack(uint32 trackIndex, bool isEnabled) + void CommandEnableEventTrack(size_t trackIndex, bool isEnabled) { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); CommandEnableEventTrack(motion, trackIndex, isEnabled); @@ -1114,7 +1114,7 @@ namespace CommandSystem // remove motion event - void CommandHelperRemoveMotionEvent(EMotionFX::Motion* motion, const char* trackName, uint32 eventNr, MCore::CommandGroup* commandGroup) + void CommandHelperRemoveMotionEvent(EMotionFX::Motion* motion, const char* trackName, size_t eventNr, MCore::CommandGroup* commandGroup) { // make sure the motion is valid if (motion == nullptr) @@ -1127,7 +1127,7 @@ namespace CommandSystem // execute the create motion event command AZStd::string command; - command = AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %i", motion->GetID(), trackName, eventNr); + command = AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu", motion->GetID(), trackName, eventNr); // add the command to the command group if (commandGroup == nullptr) @@ -1152,7 +1152,7 @@ namespace CommandSystem // remove motion event - void CommandHelperRemoveMotionEvent(uint32 motionID, const char* trackName, uint32 eventNr, MCore::CommandGroup* commandGroup) + void CommandHelperRemoveMotionEvent(uint32 motionID, const char* trackName, size_t eventNr, MCore::CommandGroup* commandGroup) { // find the motion by id EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(motionID); @@ -1165,7 +1165,7 @@ namespace CommandSystem } // remove motion event - void CommandHelperRemoveMotionEvent(const char* trackName, uint32 eventNr, MCore::CommandGroup* commandGroup) + void CommandHelperRemoveMotionEvent(const char* trackName, size_t eventNr, MCore::CommandGroup* commandGroup) { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); if (motion == nullptr) @@ -1178,7 +1178,7 @@ namespace CommandSystem // remove motion event - void CommandHelperRemoveMotionEvents(uint32 motionID, const char* trackName, const MCore::Array& eventNumbers, MCore::CommandGroup* commandGroup) + void CommandHelperRemoveMotionEvents(uint32 motionID, const char* trackName, const AZStd::vector& eventNumbers, MCore::CommandGroup* commandGroup) { // find the motion by id EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(motionID); @@ -1191,11 +1191,11 @@ namespace CommandSystem MCore::CommandGroup internalCommandGroup("Remove motion events"); // get the number of events to remove and iterate through them - const int32 numEvents = eventNumbers.GetLength(); - for (int32 i = 0; i < numEvents; ++i) + const size_t numEvents = eventNumbers.size(); + for (size_t i = 0; i < numEvents; ++i) { // remove the events from back to front - uint32 eventNr = eventNumbers[numEvents - 1 - i]; + size_t eventNr = eventNumbers[numEvents - 1 - i]; // add the command to the command group if (commandGroup == nullptr) @@ -1221,7 +1221,7 @@ namespace CommandSystem // remove motion event - void CommandHelperRemoveMotionEvents(const char* trackName, const MCore::Array& eventNumbers, MCore::CommandGroup* commandGroup) + void CommandHelperRemoveMotionEvents(const char* trackName, const AZStd::vector& eventNumbers, MCore::CommandGroup* commandGroup) { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); if (motion == nullptr) @@ -1233,7 +1233,7 @@ namespace CommandSystem } - void CommandHelperMotionEventTrackChanged(EMotionFX::Motion* motion, uint32 eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName) + void CommandHelperMotionEventTrackChanged(EMotionFX::Motion* motion, size_t eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName) { // get the motion event track EMotionFX::MotionEventTable* eventTable = motion->GetEventTable(); @@ -1256,7 +1256,7 @@ namespace CommandSystem // get the motion event EMotionFX::MotionEvent& motionEvent = eventTrack->GetEvent(eventNr); - commandGroup.AddCommandString(AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %i", motion->GetID(), oldTrackName, eventNr)); + commandGroup.AddCommandString(AZStd::string::format("RemoveMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu", motion->GetID(), oldTrackName, eventNr)); CommandHelperAddMotionEvent(motion, newTrackName, startTime, endTime, motionEvent.GetEventDatas(), &commandGroup); // execute the command group @@ -1267,7 +1267,7 @@ namespace CommandSystem } - void CommandHelperMotionEventTrackChanged(uint32 eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName) + void CommandHelperMotionEventTrackChanged(size_t eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName) { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); CommandHelperMotionEventTrackChanged(motion, eventNr, startTime, endTime, oldTrackName, newTrackName); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h index 30caae2713..54dce0fca6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionEventCommands.h @@ -55,13 +55,13 @@ namespace CommandSystem private: AZStd::string m_eventTrackName; - AZStd::optional m_eventTrackIndex; + AZStd::optional m_eventTrackIndex; AZStd::optional m_isEnabled; }; MCORE_DEFINECOMMAND_START(CommandRemoveMotionEventTrack, "Remove motion event track", true) - size_t mOldTrackIndex; - bool mOldEnabled; + size_t m_oldTrackIndex; + bool m_oldEnabled; MCORE_DEFINECOMMAND_END class DEFINECOMMAND_API CommandAdjustMotionEventTrack @@ -151,12 +151,12 @@ namespace CommandSystem AZStd::optional m_eventDatas; float m_startTime = 0.0f; float m_endTime = 0.0f; - size_t mMotionEventNr; + size_t m_motionEventNr; }; MCORE_DEFINECOMMAND_START(CommandRemoveMotionEvent, "Remove motion event", true) - float mOldStartTime; - float mOldEndTime; + float m_oldStartTime; + float m_oldEndTime; EMotionFX::EventDataSet m_oldEventDatas; MCORE_DEFINECOMMAND_END @@ -215,13 +215,13 @@ namespace CommandSystem // Command helpers ////////////////////////////////////////////////////////////////////////////////////////////////////////// void COMMANDSYSTEM_API CommandAddEventTrack(); - void COMMANDSYSTEM_API CommandRemoveEventTrack(uint32 trackIndex); - void COMMANDSYSTEM_API CommandRemoveEventTrack(EMotionFX::Motion* motion, uint32 trackIndex); - void COMMANDSYSTEM_API CommandRenameEventTrack(uint32 trackIndex, const char* newName); - void COMMANDSYSTEM_API CommandEnableEventTrack(uint32 trackIndex, bool isEnabled); + void COMMANDSYSTEM_API CommandRemoveEventTrack(size_t trackIndex); + void COMMANDSYSTEM_API CommandRemoveEventTrack(EMotionFX::Motion* motion, size_t trackIndex); + void COMMANDSYSTEM_API CommandRenameEventTrack(size_t trackIndex, const char* newName); + void COMMANDSYSTEM_API CommandEnableEventTrack(size_t trackIndex, bool isEnabled); void COMMANDSYSTEM_API CommandHelperAddMotionEvent(const char* trackName, float startTime, float endTime, const EMotionFX::EventDataSet& eventDatas = EMotionFX::EventDataSet {}, MCore::CommandGroup* commandGroup = nullptr); - void COMMANDSYSTEM_API CommandHelperRemoveMotionEvent(const char* trackName, uint32 eventNr, MCore::CommandGroup* commandGroup = nullptr); - void COMMANDSYSTEM_API CommandHelperRemoveMotionEvent(uint32 motionID, const char* trackName, uint32 eventNr, MCore::CommandGroup* commandGroup = nullptr); - void COMMANDSYSTEM_API CommandHelperRemoveMotionEvents(const char* trackName, const MCore::Array& eventNumbers, MCore::CommandGroup* commandGroup = nullptr); - void COMMANDSYSTEM_API CommandHelperMotionEventTrackChanged(uint32 eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName); + void COMMANDSYSTEM_API CommandHelperRemoveMotionEvent(const char* trackName, size_t eventNr, MCore::CommandGroup* commandGroup = nullptr); + void COMMANDSYSTEM_API CommandHelperRemoveMotionEvent(uint32 motionID, const char* trackName, size_t eventNr, MCore::CommandGroup* commandGroup = nullptr); + void COMMANDSYSTEM_API CommandHelperRemoveMotionEvents(const char* trackName, const AZStd::vector& eventNumbers, MCore::CommandGroup* commandGroup = nullptr); + void COMMANDSYSTEM_API CommandHelperMotionEventTrackChanged(size_t eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName); } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp index 6c38a7b0db..c3d9a88471 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.cpp @@ -68,7 +68,7 @@ namespace CommandSystem CommandCreateMotionSet::CommandCreateMotionSet(MCore::Command* orgCommand) : MCore::Command("CreateMotionSet", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -130,9 +130,9 @@ namespace CommandSystem } // In case of redoing the command set the previously used id. - if (mPreviouslyUsedID != MCORE_INVALIDINDEX32) + if (m_previouslyUsedId != MCORE_INVALIDINDEX32) { - motionSet->SetID(mPreviouslyUsedID); + motionSet->SetID(m_previouslyUsedId); } // Set the filename. @@ -145,22 +145,22 @@ namespace CommandSystem } // Store info for undo. - mPreviouslyUsedID = motionSet->GetID(); - AZStd::to_string(outResult, mPreviouslyUsedID); + m_previouslyUsedId = motionSet->GetID(); + AZStd::to_string(outResult, m_previouslyUsedId); // Set the motion set callback for custom motion loading. motionSet->SetCallback(aznew CommandSystemMotionSetCallback(motionSet), true); // Set the dirty flag. - const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", mPreviouslyUsedID); + const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", m_previouslyUsedId); GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult); // Seturn the id of the newly created motion set. AZStd::to_string(outResult, motionSet->GetID()); // Recursively update attributes of all nodes. - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -176,7 +176,7 @@ namespace CommandSystem EMotionFX::GetAnimGraphManager().InvalidateInstanceUniqueDataUsingMotionSet(motionSet); // Mark the workspace as dirty - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; } @@ -186,11 +186,11 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - const AZStd::string commandString = AZStd::string::format("RemoveMotionSet -motionSetID %i", mPreviouslyUsedID); + const AZStd::string commandString = AZStd::string::format("RemoveMotionSet -motionSetID %i", m_previouslyUsedId); bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult); // Restore the workspace dirty flag. - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -218,7 +218,7 @@ namespace CommandSystem CommandRemoveMotionSet::CommandRemoveMotionSet(MCore::Command* orgCommand) : MCore::Command("RemoveMotionSet", orgCommand) { - mPreviouslyUsedID = MCORE_INVALIDINDEX32; + m_previouslyUsedId = MCORE_INVALIDINDEX32; } @@ -240,20 +240,20 @@ namespace CommandSystem } // Store information used by undo. - mPreviouslyUsedID = motionSet->GetID(); - mOldName = motionSet->GetName(); - mOldFileName = motionSet->GetFilename(); + m_previouslyUsedId = motionSet->GetID(); + m_oldName = motionSet->GetName(); + m_oldFileName = motionSet->GetFilename(); if (!motionSet->GetParentSet()) { - mOldParentSetID = MCORE_INVALIDINDEX32; + m_oldParentSetId = MCORE_INVALIDINDEX32; } else { - mOldParentSetID = motionSet->GetParentSet()->GetID(); + m_oldParentSetId = motionSet->GetParentSet()->GetID(); // Set the dirty flag on the parent. - const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", mOldParentSetID); + const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -dirtyFlag true", m_oldParentSetId); GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult); } @@ -266,8 +266,8 @@ namespace CommandSystem EMotionFX::GetMotionManager().RemoveMotionSet(motionSet, true); // Recursively update attributes of all nodes. - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -280,7 +280,7 @@ namespace CommandSystem } // Mark the workspace as dirty. - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); return true; @@ -291,22 +291,22 @@ namespace CommandSystem { MCORE_UNUSED(parameters); - AZStd::string commandString = AZStd::string::format("CreateMotionSet -name \"%s\" -motionSetID %i", mOldName.c_str(), mPreviouslyUsedID); + AZStd::string commandString = AZStd::string::format("CreateMotionSet -name \"%s\" -motionSetID %i", m_oldName.c_str(), m_previouslyUsedId); - if (!mOldFileName.empty()) + if (!m_oldFileName.empty()) { - commandString += AZStd::string::format(" -fileName \"%s\"", mOldFileName.c_str()); + commandString += AZStd::string::format(" -fileName \"%s\"", m_oldFileName.c_str()); } - if (mOldParentSetID != MCORE_INVALIDINDEX32) + if (m_oldParentSetId != MCORE_INVALIDINDEX32) { - commandString += AZStd::string::format(" -parentSetID %i", mOldParentSetID); + commandString += AZStd::string::format(" -parentSetID %i", m_oldParentSetId); } const bool result = GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult); // Restore the workspace dirty flag. - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -353,7 +353,7 @@ namespace CommandSystem // Adjust the dirty flag. if (parameters.CheckIfHasParameter("dirtyFlag")) { - mOldDirtyFlag = motionSet->GetDirtyFlag(); + m_oldDirtyFlag = motionSet->GetDirtyFlag(); const bool dirtyFlag = parameters.GetValueAsBool("dirtyFlag", this); motionSet->SetDirtyFlag(dirtyFlag); } @@ -361,12 +361,12 @@ namespace CommandSystem // Set the new name in case the name parameter is specified. if (parameters.CheckIfHasParameter("newName")) { - mOldSetName = motionSet->GetName(); + m_oldSetName = motionSet->GetName(); AZStd::string name; parameters.GetValue("newName", this, name); motionSet->SetName(name.c_str()); - mOldDirtyFlag = motionSet->GetDirtyFlag(); + m_oldDirtyFlag = motionSet->GetDirtyFlag(); motionSet->SetDirtyFlag(true); } @@ -389,13 +389,13 @@ namespace CommandSystem // Adjust the dirty flag if (parameters.CheckIfHasParameter("dirtyFlag")) { - motionSet->SetDirtyFlag(mOldDirtyFlag); + motionSet->SetDirtyFlag(m_oldDirtyFlag); } // Adjust the name. if (parameters.CheckIfHasParameter("newName")) { - motionSet->SetName(mOldSetName.c_str()); + motionSet->SetName(m_oldSetName.c_str()); } return true; @@ -471,8 +471,8 @@ namespace CommandSystem motionSet->SetDirtyFlag(true); // Recursively update attributes of all nodes. - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -554,18 +554,15 @@ namespace CommandSystem m_oldMotionFilenamesAndIds.clear(); // Get the motion ids from the parameter. - const AZStd::string motionIdsString = parameters.GetValue("motionIds", this); + const AZStd::string& motionIdsString = parameters.GetValue("motionIds", this); AZStd::vector tokens; AzFramework::StringFunc::Tokenize(motionIdsString.c_str(), tokens, ";", false, true); // Iterate over all motion ids and remove the corresponding motion entries. AZStd::string failedToRemoveMotionIdsString; - const size_t tokenCount = tokens.size(); - for (size_t i = 0; i < tokenCount; ++i) + for (const AZStd::string& motionId : tokens) { - const AZStd::string& motionId = tokens[i]; - - // Get the motion entry by id string. + // Get the motion entry by id string. EMotionFX::MotionSet::MotionEntry* motionEntry = motionSet->FindMotionEntryById(motionId); if (!motionEntry) { @@ -594,8 +591,8 @@ namespace CommandSystem motionSet->SetDirtyFlag(true); // Recursively update attributes of all nodes. - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -673,8 +670,8 @@ namespace CommandSystem void CommandMotionSetAdjustMotion::UpdateMotionNodes(const char* oldID, const char* newID) { // iterate through the anim graphs and update all motion nodes - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { // get the current anim graph EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -722,8 +719,8 @@ namespace CommandSystem } // Save the old infos for undo. - mOldIdString = motionEntry->GetId(); - mOldMotionFilename = motionEntry->GetFilename(); + m_oldIdString = motionEntry->GetId(); + m_oldMotionFilename = motionEntry->GetFilename(); if (parameters.CheckIfHasParameter("motionFileName")) { @@ -785,13 +782,13 @@ namespace CommandSystem // Update all motion nodes and link them to the new motion id. if (parameters.GetValueAsBool("updateMotionNodeStringIDs", this)) { - UpdateMotionNodes(mOldIdString.c_str(), newId.c_str()); + UpdateMotionNodes(m_oldIdString.c_str(), newId.c_str()); } } // Recursively update attributes of all nodes. - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -836,12 +833,12 @@ namespace CommandSystem if (idStringChanged) { - command += AZStd::string::format(" -newIDString \"%s\"", mOldIdString.c_str()); + command += AZStd::string::format(" -newIDString \"%s\"", m_oldIdString.c_str()); } if (parameters.CheckIfHasParameter("motionFileName")) { - command += AZStd::string::format(" -motionFileName \"%s\"", mOldMotionFilename.c_str()); + command += AZStd::string::format(" -motionFileName \"%s\"", m_oldMotionFilename.c_str()); } return GetCommandManager()->ExecuteCommandInsideCommand(command, outResult); @@ -872,7 +869,7 @@ namespace CommandSystem CommandLoadMotionSet::CommandLoadMotionSet(MCore::Command* orgCommand) : MCore::Command("LoadMotionSet", orgCommand) { - mOldMotionSetID = MCORE_INVALIDINDEX32; + m_oldMotionSetId = MCORE_INVALIDINDEX32; } @@ -913,11 +910,11 @@ namespace CommandSystem } // In case we are in a redo call assign the previously used id. - if (mOldMotionSetID != MCORE_INVALIDINDEX32) + if (m_oldMotionSetId != MCORE_INVALIDINDEX32) { - motionSet->SetID(mOldMotionSetID); + motionSet->SetID(m_oldMotionSetId); } - mOldMotionSetID = motionSet->GetID(); + m_oldMotionSetId = motionSet->GetID(); // Set the custom loading callback and preload all motions. motionSet->SetCallback(aznew CommandSystemMotionSetCallback(motionSet), true); @@ -927,7 +924,7 @@ namespace CommandSystem AZStd::to_string(outResult, motionSet->GetID()); // Mark the workspace as dirty. - mOldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); + m_oldWorkspaceDirtyFlag = GetCommandManager()->GetWorkspaceDirtyFlag(); GetCommandManager()->SetWorkspaceDirtyFlag(true); // Restore original log levels. @@ -941,10 +938,10 @@ namespace CommandSystem MCORE_UNUSED(parameters); // Get the motion set the command created earlier by id. - EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(mOldMotionSetID); + EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(m_oldMotionSetId); if (motionSet == nullptr) { - outResult = AZStd::string::format("Cannot undo load motion set command. Previously used motion set id '%i' is not valid.", mOldMotionSetID); + outResult = AZStd::string::format("Cannot undo load motion set command. Previously used motion set id '%i' is not valid.", m_oldMotionSetId); return false; } @@ -955,7 +952,7 @@ namespace CommandSystem const bool result = GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, outResult); // Restore the workspace dirty flag. - GetCommandManager()->SetWorkspaceDirtyFlag(mOldWorkspaceDirtyFlag); + GetCommandManager()->SetWorkspaceDirtyFlag(m_oldWorkspaceDirtyFlag); return result; } @@ -1058,8 +1055,8 @@ namespace CommandSystem } // Iterate through the child motion sets and recursively remove them. - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { EMotionFX::MotionSet* childSet = motionSet->GetChildSet(i); RecursivelyRemoveMotionSets(childSet, commandGroup, toBeRemoved); @@ -1077,9 +1074,9 @@ namespace CommandSystem MCore::CommandGroup internalCommandGroup("Clear motion sets"); // Iterate through all root motion sets and remove them. - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); AZStd::set toBeRemoved; - for (uint32 i = 0; i < numMotionSets; ++i) + for (size_t i = 0; i < numMotionSets; ++i) { // Is the given motion set a root one? Only process root motion sets in the loop and remove all others recursively. EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -1139,10 +1136,10 @@ namespace CommandSystem // Iterate over all filenames and load the motion sets. AZStd::string commandString; AZStd::set toBeRemoved; - for (size_t i = 0; i < numFilenames; ++i) + for (const AZStd::string& filename : filenames) { // In case we want to reload the same motion set remove the old version first. - EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByFileName(filenames[i].c_str()); + EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByFileName(filename.c_str()); if (reload && !clearUpfront && motionSet) { @@ -1150,15 +1147,15 @@ namespace CommandSystem } // Construct the load motion set command and add it to the group. - commandString = AZStd::string::format("LoadMotionSet -filename \"%s\"", filenames[i].c_str()); + commandString = AZStd::string::format("LoadMotionSet -filename \"%s\"", filename.c_str()); commandGroup.AddCommandString(commandString); // iterate over each actor instance and re-active the motion set if (motionSet) { - int32 commandIndex = 1; - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 j = 0; j < numActorInstances; ++j) + size_t commandIndex = 1; + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t j = 0; j < numActorInstances; ++j) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(j); if (!actorInstance) @@ -1174,7 +1171,7 @@ namespace CommandSystem EMotionFX::MotionSet* currentActiveMotionSet = animGraphInstance->GetMotionSet(); if (currentActiveMotionSet == motionSet) { - commandString = AZStd::string::format("ActivateAnimGraph -actorInstanceID %d -animGraphID %d -motionSetID %%LASTRESULT%d%%", + commandString = AZStd::string::format("ActivateAnimGraph -actorInstanceID %d -animGraphID %d -motionSetID %%LASTRESULT%zu%%", actorInstance->GetID(), animGraphInstance->GetAnimGraph()->GetID(), commandIndex); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.h index 70f08b1c67..d630f98a45 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/MotionSetCommands.h @@ -40,22 +40,22 @@ namespace CommandSystem ////////////////////////////////////////////////////////////////////////////////////////////////////////// MCORE_DEFINECOMMAND_START(CommandCreateMotionSet, "Create motion set", true) public: - uint32 mPreviouslyUsedID; - bool mOldWorkspaceDirtyFlag; + uint32 m_previouslyUsedId; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END MCORE_DEFINECOMMAND_START(CommandRemoveMotionSet, "Remove motion set", true) public: - AZStd::string mOldName; - AZStd::string mOldFileName; - uint32 mOldParentSetID; - uint32 mPreviouslyUsedID; - bool mOldWorkspaceDirtyFlag; + AZStd::string m_oldName; + AZStd::string m_oldFileName; + uint32 m_oldParentSetId; + uint32 m_previouslyUsedId; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END MCORE_DEFINECOMMAND_START(CommandAdjustMotionSet, "Adjust motion set", true) - AZStd::string mOldSetName; - bool mOldDirtyFlag; + AZStd::string m_oldSetName; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END ////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -73,8 +73,8 @@ namespace CommandSystem MCORE_DEFINECOMMAND_START(CommandMotionSetAdjustMotion, "Adjust motion set", true) public: - AZStd::string mOldIdString; - AZStd::string mOldMotionFilename; + AZStd::string m_oldIdString; + AZStd::string m_oldMotionFilename; void UpdateMotionNodes(const char* oldID, const char* newID); MCORE_DEFINECOMMAND_END @@ -85,8 +85,8 @@ namespace CommandSystem public: using RelocateFilenameFunction = AZStd::function; RelocateFilenameFunction m_relocateFilenameFunction; - uint32 mOldMotionSetID; - bool mOldWorkspaceDirtyFlag; + uint32 m_oldMotionSetId; + bool m_oldWorkspaceDirtyFlag; MCORE_DEFINECOMMAND_END ////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp index ea83d90d4b..c65429ab83 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp @@ -264,7 +264,7 @@ namespace CommandSystem actor->AddNodeGroup(nodeGroup); // save the current dirty flag and tell the actor that something got changed - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); return true; } @@ -295,7 +295,7 @@ namespace CommandSystem } // set the dirty flag back to the old value - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -322,7 +322,7 @@ namespace CommandSystem // constructor CommandRemoveNodeGroup::CommandRemoveNodeGroup(MCore::Command* orgCommand) : MCore::Command("RemoveNodeGroup", orgCommand) - , mOldNodeGroup(nullptr) + , m_oldNodeGroup(nullptr) { } @@ -330,7 +330,7 @@ namespace CommandSystem // destructor CommandRemoveNodeGroup::~CommandRemoveNodeGroup() { - delete mOldNodeGroup; + delete m_oldNodeGroup; } @@ -360,14 +360,14 @@ namespace CommandSystem } // copy the old node group for undo - delete mOldNodeGroup; - mOldNodeGroup = aznew EMotionFX::NodeGroup(*nodeGroup); + delete m_oldNodeGroup; + m_oldNodeGroup = aznew EMotionFX::NodeGroup(*nodeGroup); // remove the node group actor->RemoveNodeGroup(nodeGroup); // save the current dirty flag and tell the actor that something got changed - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); return true; } @@ -377,7 +377,7 @@ namespace CommandSystem bool CommandRemoveNodeGroup::Undo(const MCore::CommandLine& parameters, AZStd::string& outResult) { // check if old node group exists - if (!mOldNodeGroup) + if (!m_oldNodeGroup) { return false; } @@ -397,13 +397,13 @@ namespace CommandSystem } // add the node to the group again - if (name == mOldNodeGroup->GetName()) + if (name == m_oldNodeGroup->GetName()) { - actor->AddNodeGroup(aznew EMotionFX::NodeGroup(*mOldNodeGroup)); + actor->AddNodeGroup(aznew EMotionFX::NodeGroup(*m_oldNodeGroup)); } // set the dirty flag back to the old value - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h index d29918822d..6c57877bd5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h @@ -79,14 +79,14 @@ namespace CommandSystem // add node group MCORE_DEFINECOMMAND_START(CommandAddNodeGroup, "Add node group", true) - bool mOldDirtyFlag; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END // remove a node group MCORE_DEFINECOMMAND_START(CommandRemoveNodeGroup, "Remove node group", true) - EMotionFX::NodeGroup * mOldNodeGroup; - bool mOldDirtyFlag; + EMotionFX::NodeGroup * m_oldNodeGroup; + bool m_oldDirtyFlag; MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/RagdollCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/RagdollCommands.cpp index 37657699d4..e51c9ece0b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/RagdollCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/RagdollCommands.cpp @@ -90,8 +90,8 @@ namespace EMotionFX const Transform& parentBindTransform = node->GetParentNode() ? bindPose->GetModelSpaceTransform(node->GetParentIndex()) : Transform::CreateIdentity(); - const AZ::Quaternion& nodeBindRotationWorld = nodeBindTransform.mRotation; - const AZ::Quaternion& parentBindRotationWorld = parentBindTransform.mRotation; + const AZ::Quaternion& nodeBindRotationWorld = nodeBindTransform.m_rotation; + const AZ::Quaternion& parentBindRotationWorld = parentBindTransform.m_rotation; AZ::Vector3 boneDirection = GetBoneDirection(skeleton, node); AZStd::vector exampleRotationsLocal; diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp index 7f0fcfa9d0..bcc9769c44 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.cpp @@ -33,14 +33,14 @@ namespace CommandSystem : MCore::Command(s_toggleLockSelectionCmdName, orgCommand) { } - void SelectActorInstancesUsingCommands(const MCore::Array& selectedActorInstances) + void SelectActorInstancesUsingCommands(const AZStd::vector& selectedActorInstances) { SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedActorInstances = selectedActorInstances.GetLength(); + const size_t numSelectedActorInstances = selectedActorInstances.size(); // check if the current selection is equal to the desired actor instances selection list bool nothingChanged = true; - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectedActorInstances[i]; if (selection.CheckIfHasActorInstance(actorInstance) == false) @@ -49,10 +49,10 @@ namespace CommandSystem break; } } - for (uint32 i = 0; i < selection.GetNumSelectedActorInstances(); ++i) + for (size_t i = 0; i < selection.GetNumSelectedActorInstances(); ++i) { EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(i); - if (selectedActorInstances.Find(actorInstance) == MCORE_INVALIDINDEX32) + if (AZStd::find(begin(selectedActorInstances), end(selectedActorInstances), actorInstance) == end(selectedActorInstances)) { nothingChanged = false; break; @@ -70,7 +70,7 @@ namespace CommandSystem // add the newly selected actor instances AZStd::string commandString; - for (uint32 a = 0; a < numSelectedActorInstances; ++a) + for (size_t a = 0; a < numSelectedActorInstances; ++a) { EMotionFX::ActorInstance* actorInstance = selectedActorInstances[a]; commandString = AZStd::string::format("Select -actorInstanceID %i -actorID %i", actorInstance->GetID(), actorInstance->GetActor()->GetID()); @@ -166,10 +166,10 @@ namespace CommandSystem // return false; SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numActors = EMotionFX::GetActorManager().GetNumActors(); - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + const size_t numActors = EMotionFX::GetActorManager().GetNumActors(); + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + const size_t numMotions = EMotionFX::GetMotionManager().GetNumMotions(); + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); AZStd::string valueString; @@ -180,7 +180,7 @@ namespace CommandSystem if (AzFramework::StringFunc::Equal(valueString.c_str(), "SELECT_ALL", false /* no case */)) { // iterate through all available actors and add them to the selection - for (uint32 i = 0; i < numActors; ++i) + for (size_t i = 0; i < numActors; ++i) { EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); @@ -240,7 +240,7 @@ namespace CommandSystem } // iterate through all available actors and add them to the selection - for (uint32 i = 0; i < numActors; ++i) + for (size_t i = 0; i < numActors; ++i) { EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); @@ -271,7 +271,7 @@ namespace CommandSystem if (AzFramework::StringFunc::Equal(valueString.c_str(), "SELECT_ALL", false /* no case */)) { // iterate through all available actor instances and add them to the selection - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -330,7 +330,7 @@ namespace CommandSystem } // iterate through all available motions and add them to the selection - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { // get the current motion EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); @@ -362,7 +362,7 @@ namespace CommandSystem if (AzFramework::StringFunc::Equal(valueString.c_str(), "SELECT_ALL", false /* no case */)) { // iterate through all available motions and add them to the selection - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { // get the current motion EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); @@ -385,7 +385,7 @@ namespace CommandSystem else { // get the motion index from the string and check if it is valid - const uint32 motionIndex = parameters.GetValueAsInt("motionIndex", command); + const size_t motionIndex = parameters.GetValueAsInt("motionIndex", command); if (motionIndex >= numMotions) { if (numMotions == 0) @@ -394,7 +394,7 @@ namespace CommandSystem } else { - outResult = AZStd::string::format("Motion index '%i' is not valid. Valid range is [0, %i].", motionIndex, numMotions - 1); + outResult = AZStd::string::format("Motion index '%zu' is not valid. Valid range is [0, %zu].", motionIndex, numMotions - 1); } return false; @@ -427,7 +427,7 @@ namespace CommandSystem if (AzFramework::StringFunc::Equal(valueString.c_str(), "SELECT_ALL", false /* no case */)) { // iterate through all available motions and add them to the selection - for (uint32 i = 0; i < numAnimGraphs; ++i) + for (size_t i = 0; i < numAnimGraphs; ++i) { // get the current anim graph EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -450,7 +450,7 @@ namespace CommandSystem else { // get the anim graph index from the string and check if it is valid - const uint32 animGraphIndex = parameters.GetValueAsInt("animGraphIndex", command); + const size_t animGraphIndex = parameters.GetValueAsInt("animGraphIndex", command); if (animGraphIndex >= numAnimGraphs) { if (numAnimGraphs == 0) @@ -459,7 +459,7 @@ namespace CommandSystem } else { - outResult = AZStd::string::format("Anim graph index '%i' is not valid. Valid range is [0, %i].", animGraphIndex, numAnimGraphs - 1); + outResult = AZStd::string::format("Anim graph index '%zu' is not valid. Valid range is [0, %zu].", animGraphIndex, numAnimGraphs - 1); } return false; @@ -492,7 +492,7 @@ namespace CommandSystem if (AzFramework::StringFunc::Equal(valueString.c_str(), "SELECT_ALL", false /* no case */)) { // iterate through all available motions and add them to the selection - for (uint32 i = 0; i < numAnimGraphs; ++i) + for (size_t i = 0; i < numAnimGraphs; ++i) { // get the current anim graph EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -547,7 +547,7 @@ namespace CommandSystem bool CommandSelect::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) { // store the old selection list for undo - mData = GetCommandManager()->GetCurrentSelection(); + m_data = GetCommandManager()->GetCurrentSelection(); // selection add mode return Select(this, parameters, outResult, false); @@ -561,7 +561,7 @@ namespace CommandSystem MCORE_UNUSED(outResult); // restore the old selection and return success - GetCommandManager()->SetCurrentSelection(mData); + GetCommandManager()->SetCurrentSelection(m_data); return true; } @@ -604,7 +604,7 @@ namespace CommandSystem bool CommandUnselect::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) { // store the old selection list for undo - mData = GetCommandManager()->GetCurrentSelection(); + m_data = GetCommandManager()->GetCurrentSelection(); // unselect mode return CommandSelect::Select(this, parameters, outResult, true); @@ -618,7 +618,7 @@ namespace CommandSystem MCORE_UNUSED(outResult); // restore the old selection and return success - GetCommandManager()->SetCurrentSelection(mData); + GetCommandManager()->SetCurrentSelection(m_data); return true; } @@ -665,7 +665,7 @@ namespace CommandSystem // get the current selection, store it for the undo function and unselect everything SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - mData = selection; + m_data = selection; // if we are in selection lock mode return directly //if (GetCommandManager()->GetLockSelection()) @@ -686,7 +686,7 @@ namespace CommandSystem MCORE_UNUSED(outResult); // restore the old selection and return success - GetCommandManager()->SetCurrentSelection(mData); + GetCommandManager()->SetCurrentSelection(m_data); return true; } @@ -721,10 +721,10 @@ namespace CommandSystem MCORE_UNUSED(outResult); // store the selection locked flag for the undo function - mData = GetCommandManager()->GetLockSelection(); + m_data = GetCommandManager()->GetLockSelection(); // toggle the flag - GetCommandManager()->SetLockSelection(!mData); + GetCommandManager()->SetLockSelection(!m_data); return true; } @@ -737,7 +737,7 @@ namespace CommandSystem MCORE_UNUSED(outResult); // restore the old selection locked flag and return success - GetCommandManager()->SetLockSelection(mData); + GetCommandManager()->SetLockSelection(m_data); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h index d48bc3d3b6..13a39e5e8a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionCommands.h @@ -19,7 +19,7 @@ namespace CommandSystem { MCORE_DEFINECOMMAND_START(CommandSelect, "Select object", true) - SelectionList mData; + SelectionList m_data; public: static const char* s_SelectCmdName; static bool Select(MCore::Command* command, const MCore::CommandLine& parameters, AZStd::string& outResult, bool unselect); @@ -44,7 +44,7 @@ public: MCORE_DEFINECOMMAND_1_END // helper functions - void COMMANDSYSTEM_API SelectActorInstancesUsingCommands(const MCore::Array& selectedActorInstances); + void COMMANDSYSTEM_API SelectActorInstancesUsingCommands(const AZStd::vector& selectedActorInstances); bool COMMANDSYSTEM_API CheckIfHasMotionSelectionParameter(const MCore::CommandLine& parameters); bool COMMANDSYSTEM_API CheckIfHasAnimGraphSelectionParameter(const MCore::CommandLine& parameters); bool COMMANDSYSTEM_API CheckIfHasActorSelectionParameter(const MCore::CommandLine& parameters, bool ignoreInstanceParameters = false); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp index a6ff4de440..e115c24221 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.cpp @@ -25,41 +25,41 @@ namespace CommandSystem EMotionFX::ActorNotificationBus::Handler::BusDisconnect(); } - uint32 SelectionList::GetNumTotalItems() const + size_t SelectionList::GetNumTotalItems() const { - return static_cast(mSelectedNodes.size() + - mSelectedActors.size() + - mSelectedActorInstances.size() + - mSelectedMotions.size() + - mSelectedMotionInstances.size() + - mSelectedAnimGraphs.size()); + return m_selectedNodes.size() + + m_selectedActors.size() + + m_selectedActorInstances.size() + + m_selectedMotions.size() + + m_selectedMotionInstances.size() + + m_selectedAnimGraphs.size(); } bool SelectionList::GetIsEmpty() const { - return (mSelectedNodes.empty() && - mSelectedActors.empty() && - mSelectedActorInstances.empty() && - mSelectedMotions.empty() && - mSelectedMotionInstances.empty() && - mSelectedAnimGraphs.empty()); + return (m_selectedNodes.empty() && + m_selectedActors.empty() && + m_selectedActorInstances.empty() && + m_selectedMotions.empty() && + m_selectedMotionInstances.empty() && + m_selectedAnimGraphs.empty()); } void SelectionList::Clear() { - mSelectedNodes.clear(); - mSelectedActors.clear(); - mSelectedActorInstances.clear(); - mSelectedMotions.clear(); - mSelectedMotionInstances.clear(); - mSelectedAnimGraphs.clear(); + m_selectedNodes.clear(); + m_selectedActors.clear(); + m_selectedActorInstances.clear(); + m_selectedMotions.clear(); + m_selectedMotionInstances.clear(); + m_selectedAnimGraphs.clear(); } void SelectionList::AddNode(EMotionFX::Node* node) { if (!CheckIfHasNode(node)) { - mSelectedNodes.emplace_back(node); + m_selectedNodes.emplace_back(node); } } @@ -67,7 +67,7 @@ namespace CommandSystem { if (!CheckIfHasActor(actor)) { - mSelectedActors.emplace_back(actor); + m_selectedActors.emplace_back(actor); } } @@ -76,7 +76,7 @@ namespace CommandSystem { if (!CheckIfHasActorInstance(actorInstance)) { - mSelectedActorInstances.emplace_back(actorInstance); + m_selectedActorInstances.emplace_back(actorInstance); } } @@ -86,7 +86,7 @@ namespace CommandSystem { if (!CheckIfHasMotion(motion)) { - mSelectedMotions.emplace_back(motion); + m_selectedMotions.emplace_back(motion); } } @@ -96,7 +96,7 @@ namespace CommandSystem { if (!CheckIfHasMotionInstance(motionInstance)) { - mSelectedMotionInstances.emplace_back(motionInstance); + m_selectedMotionInstances.emplace_back(motionInstance); } } @@ -106,55 +106,53 @@ namespace CommandSystem { if (!CheckIfHasAnimGraph(animGraph)) { - mSelectedAnimGraphs.emplace_back(animGraph); + m_selectedAnimGraphs.emplace_back(animGraph); } } // add a complete selection list to this one void SelectionList::Add(SelectionList& selection) { - uint32 i; - // get the number of selected objects - const uint32 numSelectedNodes = selection.GetNumSelectedNodes(); - const uint32 numSelectedActors = selection.GetNumSelectedActors(); - const uint32 numSelectedActorInstances = selection.GetNumSelectedActorInstances(); - const uint32 numSelectedMotions = selection.GetNumSelectedMotions(); - const uint32 numSelectedMotionInstances = selection.GetNumSelectedMotionInstances(); - const uint32 numSelectedAnimGraphs = selection.GetNumSelectedAnimGraphs(); + const size_t numSelectedNodes = selection.GetNumSelectedNodes(); + const size_t numSelectedActors = selection.GetNumSelectedActors(); + const size_t numSelectedActorInstances = selection.GetNumSelectedActorInstances(); + const size_t numSelectedMotions = selection.GetNumSelectedMotions(); + const size_t numSelectedMotionInstances = selection.GetNumSelectedMotionInstances(); + const size_t numSelectedAnimGraphs = selection.GetNumSelectedAnimGraphs(); // iterate through all nodes and select them - for (i = 0; i < numSelectedNodes; ++i) + for (size_t i = 0; i < numSelectedNodes; ++i) { AddNode(selection.GetNode(i)); } // iterate through all actors and select them - for (i = 0; i < numSelectedActors; ++i) + for (size_t i = 0; i < numSelectedActors; ++i) { AddActor(selection.GetActor(i)); } // iterate through all actor instances and select them - for (i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { AddActorInstance(selection.GetActorInstance(i)); } // iterate through all motions and select them - for (i = 0; i < numSelectedMotions; ++i) + for (size_t i = 0; i < numSelectedMotions; ++i) { AddMotion(selection.GetMotion(i)); } // iterate through all motion instances and select them - for (i = 0; i < numSelectedMotionInstances; ++i) + for (size_t i = 0; i < numSelectedMotionInstances; ++i) { AddMotionInstance(selection.GetMotionInstance(i)); } // iterate through all anim graphs and select them - for (i = 0; i < numSelectedAnimGraphs; ++i) + for (size_t i = 0; i < numSelectedAnimGraphs; ++i) { AddAnimGraph(selection.GetAnimGraph(i)); } @@ -164,53 +162,46 @@ namespace CommandSystem // log the current selection void SelectionList::Log() { - uint32 i; - // get the number of selected objects - const uint32 numSelectedNodes = GetNumSelectedNodes(); - const uint32 numSelectedActorInstances = GetNumSelectedActorInstances(); - const uint32 numSelectedActors = GetNumSelectedActors(); - const uint32 numSelectedMotions = GetNumSelectedMotions(); - const uint32 numSelectedMotionInstances = GetNumSelectedMotionInstances(); - const uint32 numSelectedAnimGraphs = GetNumSelectedAnimGraphs(); + const size_t numSelectedNodes = GetNumSelectedNodes(); + const size_t numSelectedActorInstances = GetNumSelectedActorInstances(); + const size_t numSelectedActors = GetNumSelectedActors(); + const size_t numSelectedMotions = GetNumSelectedMotions(); + const size_t numSelectedAnimGraphs = GetNumSelectedAnimGraphs(); MCore::LogInfo("SelectionList:"); // iterate through all nodes and select them MCore::LogInfo(" - Nodes (%i)", numSelectedNodes); - for (i = 0; i < numSelectedNodes; ++i) + for (size_t i = 0; i < numSelectedNodes; ++i) { MCore::LogInfo(" + Node #%.3d: name='%s'", i, GetNode(i)->GetName()); } // iterate through all actors and select them MCore::LogInfo(" - Actors (%i)", numSelectedActors); - for (i = 0; i < numSelectedActors; ++i) + for (size_t i = 0; i < numSelectedActors; ++i) { MCore::LogInfo(" + Actor #%.3d: name='%s'", i, GetActor(i)->GetName()); } // iterate through all actor instances and select them MCore::LogInfo(" - Actor instances (%i)", numSelectedActorInstances); - for (i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { MCore::LogInfo(" + Actor instance #%.3d: name='%s'", i, GetActorInstance(i)->GetActor()->GetName()); } // iterate through all motions and select them MCore::LogInfo(" - Motions (%i)", numSelectedMotions); - for (i = 0; i < numSelectedMotions; ++i) + for (size_t i = 0; i < numSelectedMotions; ++i) { MCore::LogInfo(" + Motion #%.3d: name='%s'", i, GetMotion(i)->GetName()); } - // iterate through all motion instances and select them - MCore::LogInfo(" - Motion instances (%i)", numSelectedMotionInstances); - //for (i=0; iGetFileName()); } @@ -218,52 +209,52 @@ namespace CommandSystem void SelectionList::RemoveNode(EMotionFX::Node* node) { - mSelectedNodes.erase(AZStd::remove(mSelectedNodes.begin(), mSelectedNodes.end(), node), mSelectedNodes.end()); + m_selectedNodes.erase(AZStd::remove(m_selectedNodes.begin(), m_selectedNodes.end(), node), m_selectedNodes.end()); } void SelectionList::RemoveActor(EMotionFX::Actor* actor) { - mSelectedActors.erase(AZStd::remove(mSelectedActors.begin(), mSelectedActors.end(), actor), mSelectedActors.end()); + m_selectedActors.erase(AZStd::remove(m_selectedActors.begin(), m_selectedActors.end(), actor), m_selectedActors.end()); } // remove the actor from the selection list void SelectionList::RemoveActorInstance(EMotionFX::ActorInstance* actorInstance) { - mSelectedActorInstances.erase(AZStd::remove(mSelectedActorInstances.begin(), mSelectedActorInstances.end(), actorInstance), mSelectedActorInstances.end()); + m_selectedActorInstances.erase(AZStd::remove(m_selectedActorInstances.begin(), m_selectedActorInstances.end(), actorInstance), m_selectedActorInstances.end()); } // remove the motion from the selection list void SelectionList::RemoveMotion(EMotionFX::Motion* motion) { - mSelectedMotions.erase(AZStd::remove(mSelectedMotions.begin(), mSelectedMotions.end(), motion), mSelectedMotions.end()); + m_selectedMotions.erase(AZStd::remove(m_selectedMotions.begin(), m_selectedMotions.end(), motion), m_selectedMotions.end()); } // remove the motion instance from the selection list void SelectionList::RemoveMotionInstance(EMotionFX::MotionInstance* motionInstance) { - mSelectedMotionInstances.erase(AZStd::remove(mSelectedMotionInstances.begin(), mSelectedMotionInstances.end(), motionInstance), mSelectedMotionInstances.end()); + m_selectedMotionInstances.erase(AZStd::remove(m_selectedMotionInstances.begin(), m_selectedMotionInstances.end(), motionInstance), m_selectedMotionInstances.end()); } // remove the anim graph void SelectionList::RemoveAnimGraph(EMotionFX::AnimGraph* animGraph) { - mSelectedAnimGraphs.erase(AZStd::remove(mSelectedAnimGraphs.begin(), mSelectedAnimGraphs.end(), animGraph), mSelectedAnimGraphs.end()); + m_selectedAnimGraphs.erase(AZStd::remove(m_selectedAnimGraphs.begin(), m_selectedAnimGraphs.end(), animGraph), m_selectedAnimGraphs.end()); } // make the selection valid void SelectionList::MakeValid() { // iterate through all actor instances and remove the invalid ones - for (size_t i = 0; i < mSelectedActorInstances.size();) + for (size_t i = 0; i < m_selectedActorInstances.size();) { - EMotionFX::ActorInstance* actorInstance = mSelectedActorInstances[i]; + EMotionFX::ActorInstance* actorInstance = m_selectedActorInstances[i]; if (EMotionFX::GetActorManager().CheckIfIsActorInstanceRegistered(actorInstance) == false) { - mSelectedActorInstances.erase(mSelectedActorInstances.begin() + i); + m_selectedActorInstances.erase(m_selectedActorInstances.begin() + i); } else { @@ -272,13 +263,13 @@ namespace CommandSystem } // iterate through all anim graphs and remove all valid ones - for (size_t i = 0; i < mSelectedAnimGraphs.size();) + for (size_t i = 0; i < m_selectedAnimGraphs.size();) { - EMotionFX::AnimGraph* animGraph = mSelectedAnimGraphs[i]; + EMotionFX::AnimGraph* animGraph = m_selectedAnimGraphs[i]; if (EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph) == MCORE_INVALIDINDEX32) { - mSelectedAnimGraphs.erase(mSelectedAnimGraphs.begin() + i); + m_selectedAnimGraphs.erase(m_selectedAnimGraphs.begin() + i); } else { @@ -303,7 +294,7 @@ namespace CommandSystem return nullptr; } - return mSelectedActors[0]; + return m_selectedActors[0]; } @@ -322,7 +313,7 @@ namespace CommandSystem return nullptr; } - EMotionFX::ActorInstance* actorInstance = mSelectedActorInstances[0]; + EMotionFX::ActorInstance* actorInstance = m_selectedActorInstances[0]; if (!actorInstance) { return nullptr; @@ -333,7 +324,7 @@ namespace CommandSystem return nullptr; } - return mSelectedActorInstances[0]; + return m_selectedActorInstances[0]; } @@ -350,7 +341,7 @@ namespace CommandSystem return nullptr; } - EMotionFX::Motion* motion = mSelectedMotions[0]; + EMotionFX::Motion* motion = m_selectedMotions[0]; if (!motion) { return nullptr; @@ -367,8 +358,8 @@ namespace CommandSystem void SelectionList::OnActorDestroyed(EMotionFX::Actor* actor) { const EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); - const AZ::u32 numJoints = skeleton->GetNumNodes(); - for (AZ::u32 i = 0; i < numJoints; ++i) + const size_t numJoints = skeleton->GetNumNodes(); + for (size_t i = 0; i < numJoints; ++i) { EMotionFX::Node* joint = skeleton->GetNode(i); RemoveNode(joint); diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h index 2b317fdee7..ce53a1378f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SelectionList.h @@ -45,42 +45,42 @@ namespace CommandSystem * Get the number of selected nodes. * @return The number of selected nodes. */ - MCORE_INLINE uint32 GetNumSelectedNodes() const { return static_cast(mSelectedNodes.size()); } + MCORE_INLINE size_t GetNumSelectedNodes() const { return m_selectedNodes.size(); } /** * Get the number of selected actors */ - MCORE_INLINE uint32 GetNumSelectedActors() const { return static_cast(mSelectedActors.size()); } + MCORE_INLINE size_t GetNumSelectedActors() const { return m_selectedActors.size(); } /** * Get the number of selected actor instances. * @return The number of selected actor instances. */ - MCORE_INLINE uint32 GetNumSelectedActorInstances() const { return static_cast(mSelectedActorInstances.size()); } + MCORE_INLINE size_t GetNumSelectedActorInstances() const { return m_selectedActorInstances.size(); } /** * Get the number of selected motion instances. * @return The number of selected motion instances. */ - MCORE_INLINE uint32 GetNumSelectedMotionInstances() const { return static_cast(mSelectedMotionInstances.size()); } + MCORE_INLINE size_t GetNumSelectedMotionInstances() const { return m_selectedMotionInstances.size(); } /** * Get the number of selected motions. * @return The number of selected motions. */ - MCORE_INLINE uint32 GetNumSelectedMotions() const { return static_cast(mSelectedMotions.size()); } + MCORE_INLINE size_t GetNumSelectedMotions() const { return m_selectedMotions.size(); } /** * Get the number of selected anim graphs. * @return The number of selected anim graphs. */ - MCORE_INLINE uint32 GetNumSelectedAnimGraphs() const { return static_cast(mSelectedAnimGraphs.size()); } + MCORE_INLINE size_t GetNumSelectedAnimGraphs() const { return m_selectedAnimGraphs.size(); } /** * Get the total number of selected objects. * @return The number of selected nodes, actors and motions. */ - MCORE_INLINE uint32 GetNumTotalItems() const; + MCORE_INLINE size_t GetNumTotalItems() const; /** * Check whether or not the selection list contains any objects. @@ -139,7 +139,7 @@ namespace CommandSystem * @param index The index of the node to get from the selection list. * @return A pointer to the given node from the selection list. */ - MCORE_INLINE EMotionFX::Node* GetNode(uint32 index) const { return mSelectedNodes[index]; } + MCORE_INLINE EMotionFX::Node* GetNode(size_t index) const { return m_selectedNodes[index]; } /** * Get the first node from the selection list. @@ -147,11 +147,11 @@ namespace CommandSystem */ MCORE_INLINE EMotionFX::Node* GetFirstNode() const { - if (mSelectedNodes.empty()) + if (m_selectedNodes.empty()) { return nullptr; } - return mSelectedNodes[0]; + return m_selectedNodes[0]; } /** @@ -159,7 +159,7 @@ namespace CommandSystem * @param index The index of the actor to get from the selection list. * @return A pointer to the given actor from the selection list. */ - MCORE_INLINE EMotionFX::Actor* GetActor(uint32 index) const { return mSelectedActors[index]; } + MCORE_INLINE EMotionFX::Actor* GetActor(size_t index) const { return m_selectedActors[index]; } /** * Get the first actor from the selection list. @@ -167,11 +167,11 @@ namespace CommandSystem */ MCORE_INLINE EMotionFX::Actor* GetFirstActor() const { - if (mSelectedActors.empty()) + if (m_selectedActors.empty()) { return nullptr; } - return mSelectedActors[0]; + return m_selectedActors[0]; } /** @@ -179,7 +179,7 @@ namespace CommandSystem * @param index The index of the actor instance to get from the selection list. * @return A pointer to the given actor instance from the selection list. */ - MCORE_INLINE EMotionFX::ActorInstance* GetActorInstance(uint32 index) const { return mSelectedActorInstances[index]; } + MCORE_INLINE EMotionFX::ActorInstance* GetActorInstance(size_t index) const { return m_selectedActorInstances[index]; } /** * Get the first actor instance from the selection list. @@ -187,11 +187,11 @@ namespace CommandSystem */ MCORE_INLINE EMotionFX::ActorInstance* GetFirstActorInstance() const { - if (mSelectedActorInstances.empty()) + if (m_selectedActorInstances.empty()) { return nullptr; } - return mSelectedActorInstances[0]; + return m_selectedActorInstances[0]; } /** @@ -199,7 +199,7 @@ namespace CommandSystem * @param index The index of the anim graph to get from the selection list. * @return A pointer to the given anim graph from the selection list. */ - MCORE_INLINE EMotionFX::AnimGraph* GetAnimGraph(uint32 index) const { return mSelectedAnimGraphs[index]; } + MCORE_INLINE EMotionFX::AnimGraph* GetAnimGraph(size_t index) const { return m_selectedAnimGraphs[index]; } /** * Get the first anim graph from the selection list. @@ -207,11 +207,11 @@ namespace CommandSystem */ MCORE_INLINE EMotionFX::AnimGraph* GetFirstAnimGraph() const { - if (mSelectedAnimGraphs.empty()) + if (m_selectedAnimGraphs.empty()) { return nullptr; } - return mSelectedAnimGraphs[0]; + return m_selectedAnimGraphs[0]; } /** @@ -231,7 +231,7 @@ namespace CommandSystem * @param index The index of the motion to get from the selection list. * @return A pointer to the given motion from the selection list. */ - MCORE_INLINE EMotionFX::Motion* GetMotion(uint32 index) const { return mSelectedMotions[index]; } + MCORE_INLINE EMotionFX::Motion* GetMotion(size_t index) const { return m_selectedMotions[index]; } /** * Get the first motion from the selection list. @@ -239,11 +239,11 @@ namespace CommandSystem */ MCORE_INLINE EMotionFX::Motion* GetFirstMotion() const { - if (mSelectedMotions.empty()) + if (m_selectedMotions.empty()) { return nullptr; } - return mSelectedMotions[0]; + return m_selectedMotions[0]; } /** @@ -257,7 +257,7 @@ namespace CommandSystem * @param index The index of the motion instance to get from the selection list. * @return A pointer to the given motion instance from the selection list. */ - MCORE_INLINE EMotionFX::MotionInstance* GetMotionInstance(uint32 index) const { return mSelectedMotionInstances[index]; } + MCORE_INLINE EMotionFX::MotionInstance* GetMotionInstance(size_t index) const { return m_selectedMotionInstances[index]; } /** * Get the first motion instance from the selection list. @@ -265,48 +265,48 @@ namespace CommandSystem */ MCORE_INLINE EMotionFX::MotionInstance* GetFirstMotionInstance() const { - if (mSelectedMotionInstances.empty()) + if (m_selectedMotionInstances.empty()) { return nullptr; } - return mSelectedMotionInstances[0]; + return m_selectedMotionInstances[0]; } /** * Remove the given node from the selection list. * @param index The index of the node to be removed from the selection list. */ - MCORE_INLINE void RemoveNode(uint32 index) { mSelectedNodes.erase(mSelectedNodes.begin() + index); } + MCORE_INLINE void RemoveNode(size_t index) { m_selectedNodes.erase(m_selectedNodes.begin() + index); } /** * Remove the given actor instance from the selection list. * @param index The index of the actor instance to be removed from the selection list. */ - MCORE_INLINE void RemoveActor(uint32 index) { mSelectedActors.erase(mSelectedActors.begin() + index); } + MCORE_INLINE void RemoveActor(size_t index) { m_selectedActors.erase(m_selectedActors.begin() + index); } /** * Remove the given actor instance from the selection list. * @param index The index of the actor instance to be removed from the selection list. */ - MCORE_INLINE void RemoveActorInstance(uint32 index) { mSelectedActorInstances.erase(mSelectedActorInstances.begin() + index); } + MCORE_INLINE void RemoveActorInstance(size_t index) { m_selectedActorInstances.erase(m_selectedActorInstances.begin() + index); } /** * Remove the given motion from the selection list. * @param index The index of the motion to be removed from the selection list. */ - MCORE_INLINE void RemoveMotion(uint32 index) { mSelectedMotions.erase(mSelectedMotions.begin() + index); } + MCORE_INLINE void RemoveMotion(size_t index) { m_selectedMotions.erase(m_selectedMotions.begin() + index); } /** * Remove the given motion instance from the selection list. * @param index The index of the motion instance to be removed from the selection list. */ - MCORE_INLINE void RemoveMotionInstance(uint32 index) { mSelectedMotionInstances.erase(mSelectedMotionInstances.begin() + index); } + MCORE_INLINE void RemoveMotionInstance(size_t index) { m_selectedMotionInstances.erase(m_selectedMotionInstances.begin() + index); } /** * Remove the given anim graph from the selection list. * @param index The index of the anim graph to remove from the selection list. */ - MCORE_INLINE void RemoveAnimGraph(uint32 index) { mSelectedAnimGraphs.erase(mSelectedAnimGraphs.begin() + index); } + MCORE_INLINE void RemoveAnimGraph(size_t index) { m_selectedAnimGraphs.erase(m_selectedAnimGraphs.begin() + index); } /** * Remove the given node from the selection list. @@ -349,47 +349,47 @@ namespace CommandSystem * @param node A pointer to the node to be checked. * @return True if the node is inside this selection list, false if not. */ - MCORE_INLINE bool CheckIfHasNode(EMotionFX::Node* node) const { return(AZStd::find(mSelectedNodes.begin(), mSelectedNodes.end(), node) != mSelectedNodes.end()); } + MCORE_INLINE bool CheckIfHasNode(EMotionFX::Node* node) const { return(AZStd::find(m_selectedNodes.begin(), m_selectedNodes.end(), node) != m_selectedNodes.end()); } /** * Has actor */ - MCORE_INLINE bool CheckIfHasActor(EMotionFX::Actor* actor) const { return (AZStd::find(mSelectedActors.begin(), mSelectedActors.end(), actor) != mSelectedActors.end()); } + MCORE_INLINE bool CheckIfHasActor(EMotionFX::Actor* actor) const { return (AZStd::find(m_selectedActors.begin(), m_selectedActors.end(), actor) != m_selectedActors.end()); } /** * Check if a given actor instance is selected / is in this selection list. * @param node A pointer to the actor instance to be checked. * @return True if the actor instance is inside this selection list, false if not. */ - MCORE_INLINE bool CheckIfHasActorInstance(EMotionFX::ActorInstance* actorInstance) const { return (AZStd::find(mSelectedActorInstances.begin(), mSelectedActorInstances.end(), actorInstance) != mSelectedActorInstances.end()); } + MCORE_INLINE bool CheckIfHasActorInstance(EMotionFX::ActorInstance* actorInstance) const { return (AZStd::find(m_selectedActorInstances.begin(), m_selectedActorInstances.end(), actorInstance) != m_selectedActorInstances.end()); } /** * Check if a given motion is selected / is in this selection list. * @param node A pointer to the motion to be checked. * @return True if the motion is inside this selection list, false if not. */ - MCORE_INLINE bool CheckIfHasMotion(EMotionFX::Motion* motion) const { return (AZStd::find(mSelectedMotions.begin(), mSelectedMotions.end(), motion) != mSelectedMotions.end()); } + MCORE_INLINE bool CheckIfHasMotion(EMotionFX::Motion* motion) const { return (AZStd::find(m_selectedMotions.begin(), m_selectedMotions.end(), motion) != m_selectedMotions.end()); } /** * Check if a given anim graph is in this selection list. * @param animGraph The anim graph to check for. * @return True if the anim graph is selected inside the selection list, otherwise false is returned. */ - MCORE_INLINE bool CheckIfHasAnimGraph(EMotionFX::AnimGraph* animGraph) const { return (AZStd::find(mSelectedAnimGraphs.begin(), mSelectedAnimGraphs.end(), animGraph) != mSelectedAnimGraphs.end()); } + MCORE_INLINE bool CheckIfHasAnimGraph(EMotionFX::AnimGraph* animGraph) const { return (AZStd::find(m_selectedAnimGraphs.begin(), m_selectedAnimGraphs.end(), animGraph) != m_selectedAnimGraphs.end()); } /** * Check if a given motion instance is selected / is in this selection list. * @param node A pointer to the motion instance to be checked. * @return True if the motion instance is inside this selection list, false if not. */ - MCORE_INLINE bool CheckIfHasMotionInstance(EMotionFX::MotionInstance* motionInstance) const { return (AZStd::find(mSelectedMotionInstances.begin(), mSelectedMotionInstances.end(), motionInstance) != mSelectedMotionInstances.end()); } + MCORE_INLINE bool CheckIfHasMotionInstance(EMotionFX::MotionInstance* motionInstance) const { return (AZStd::find(m_selectedMotionInstances.begin(), m_selectedMotionInstances.end(), motionInstance) != m_selectedMotionInstances.end()); } - MCORE_INLINE void ClearActorSelection() { mSelectedActors.clear(); } - MCORE_INLINE void ClearActorInstanceSelection() { mSelectedActorInstances.clear(); } - MCORE_INLINE void ClearNodeSelection() { mSelectedNodes.clear(); } - MCORE_INLINE void ClearMotionSelection() { mSelectedMotions.clear(); } - MCORE_INLINE void ClearMotionInstanceSelection() { mSelectedMotionInstances.clear(); } - MCORE_INLINE void ClearAnimGraphSelection() { mSelectedAnimGraphs.clear(); } + MCORE_INLINE void ClearActorSelection() { m_selectedActors.clear(); } + MCORE_INLINE void ClearActorInstanceSelection() { m_selectedActorInstances.clear(); } + MCORE_INLINE void ClearNodeSelection() { m_selectedNodes.clear(); } + MCORE_INLINE void ClearMotionSelection() { m_selectedMotions.clear(); } + MCORE_INLINE void ClearMotionInstanceSelection() { m_selectedMotionInstances.clear(); } + MCORE_INLINE void ClearAnimGraphSelection() { m_selectedAnimGraphs.clear(); } void Log(); void MakeValid(); @@ -401,11 +401,11 @@ namespace CommandSystem // ActorInstanceNotificationBus overrides void OnActorInstanceDestroyed(EMotionFX::ActorInstance* actorInstance) override; - AZStd::vector mSelectedNodes; /**< Array of selected nodes. */ - AZStd::vector mSelectedActors; /**< The selected actors. */ - AZStd::vector mSelectedActorInstances; /**< Array of selected actor instances. */ - AZStd::vector mSelectedMotionInstances; /**< Array of selected motion instances. */ - AZStd::vector mSelectedMotions; /**< Array of selected motions. */ - AZStd::vector mSelectedAnimGraphs; /**< Array of selected anim graphs. */ + AZStd::vector m_selectedNodes; /**< Array of selected nodes. */ + AZStd::vector m_selectedActors; /**< The selected actors. */ + AZStd::vector m_selectedActorInstances; /**< Array of selected actor instances. */ + AZStd::vector m_selectedMotionInstances; /**< Array of selected motion instances. */ + AZStd::vector m_selectedMotions; /**< Array of selected motions. */ + AZStd::vector m_selectedAnimGraphs; /**< Array of selected anim graphs. */ }; } // namespace CommandSystem diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.cpp index a3e98b16f8..c35b724f63 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.cpp @@ -34,20 +34,20 @@ namespace EMotionFX /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CommandSimulatedObjectHelpers /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - void CommandSimulatedObjectHelpers::JointIndicesToString(const AZStd::vector& jointIndices, AZStd::string& outJointIndicesString) + void CommandSimulatedObjectHelpers::JointIndicesToString(const AZStd::vector& jointIndices, AZStd::string& outJointIndicesString) { outJointIndicesString.clear(); - for (AZ::u32 jointIndex : jointIndices) + for (size_t jointIndex : jointIndices) { if (!outJointIndicesString.empty()) { outJointIndicesString += ';'; } - outJointIndicesString += AZStd::string::format("%d", jointIndex); + outJointIndicesString += AZStd::string::format("%zu", jointIndex); } } - void CommandSimulatedObjectHelpers::StringToJointIndices(const AZStd::string& jointIndicesString, AZStd::vector& outJointIndices) + void CommandSimulatedObjectHelpers::StringToJointIndices(const AZStd::string& jointIndicesString, AZStd::vector& outJointIndices) { outJointIndices.clear(); AZStd::vector jointIndicesStrings; @@ -86,7 +86,7 @@ namespace EMotionFX return CommandSystem::GetCommandManager()->ExecuteCommandOrAddToGroup(command, commandGroup, executeInsideCommand); } - bool CommandSimulatedObjectHelpers::AddSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool addChildren, + bool CommandSimulatedObjectHelpers::AddSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool addChildren, MCore::CommandGroup* commandGroup, bool executeInsideCommand) { AZStd::string jointIndicesStr; @@ -102,7 +102,7 @@ namespace EMotionFX return CommandSystem::GetCommandManager()->ExecuteCommandOrAddToGroup(command, commandGroup, executeInsideCommand); } - bool CommandSimulatedObjectHelpers::RemoveSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool removeChildren, + bool CommandSimulatedObjectHelpers::RemoveSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool removeChildren, MCore::CommandGroup* commandGroup, bool executeInsideCommand) { AZStd::string jointIndicesStr; @@ -737,7 +737,7 @@ namespace EMotionFX } else { - for (AZ::u32 jointIndex: m_jointIndices) + for (size_t jointIndex: m_jointIndices) { object->AddSimulatedJointAndChildren(jointIndex); } @@ -878,7 +878,7 @@ namespace EMotionFX // and having to deal with merging two object. Since we are rebuilding the simulated object model when removing joints anyway, it's more convenient to serialize the whole object. m_oldContents = MCore::ReflectionSerializer::Serialize(object).GetValue(); - for (AZ::u32 jointIndex : m_jointIndices) + for (size_t jointIndex : m_jointIndices) { if (!object->FindSimulatedJointBySkeletonJointIndex(jointIndex)) { @@ -1235,8 +1235,8 @@ namespace EMotionFX bool CommandAdjustSimulatedJoint::SetCommandParameters(const MCore::CommandLine& parameters) { ParameterMixinActorId::SetCommandParameters(parameters); - m_objectIndex = static_cast(parameters.GetValueAsInt(s_objectIndexParameterName, this)); - m_jointIndex = static_cast(parameters.GetValueAsInt(s_jointIndexParameterName, this)); + m_objectIndex = parameters.GetValueAsInt(s_objectIndexParameterName, this); + m_jointIndex = parameters.GetValueAsInt(s_jointIndexParameterName, this); if (parameters.CheckIfHasParameter(s_coneAngleLimitParameterName)) { diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.h index cfb7e10f9a..b9a017d2e4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/SimulatedObjectCommands.h @@ -16,6 +16,7 @@ #include #include #include +#include namespace AZ @@ -34,11 +35,11 @@ namespace EMotionFX public: static bool AddSimulatedObject(AZ::u32 actorId, AZStd::optional name = AZStd::nullopt, MCore::CommandGroup* commandGroup = nullptr, bool executeInsideCommand = false); static bool RemoveSimulatedObject(AZ::u32 actorId, size_t objectIndex, MCore::CommandGroup* commandGroup = nullptr, bool executeInsideCommand = false); - static bool AddSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool addChildren, MCore::CommandGroup* commandGroup = nullptr, bool executeInsideCommand = false); - static bool RemoveSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool removeChildren, MCore::CommandGroup* commandGroup = nullptr, bool executeInsideCommand = false); + static bool AddSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool addChildren, MCore::CommandGroup* commandGroup = nullptr, bool executeInsideCommand = false); + static bool RemoveSimulatedJoints(AZ::u32 actorId, const AZStd::vector& jointIndices, size_t objectIndex, bool removeChildren, MCore::CommandGroup* commandGroup = nullptr, bool executeInsideCommand = false); - static void JointIndicesToString(const AZStd::vector& jointIndices, AZStd::string& outJointIndicesString); - static void StringToJointIndices(const AZStd::string& jointIndicesString, AZStd::vector& outJointIndices); + static void JointIndicesToString(const AZStd::vector& jointIndices, AZStd::string& outJointIndicesString); + static void StringToJointIndices(const AZStd::string& jointIndicesString, AZStd::vector& outJointIndices); static void ReplaceTag(const Actor* actor, const PhysicsSetup::ColliderConfigType colliderType, const AZStd::string& oldTag, const AZStd::string& newTag, MCore::CommandGroup& outCommandGroup); @@ -203,8 +204,8 @@ namespace EMotionFX const char* GetDescription() const override { return "Add simulated joints to a simulated object"; } MCore::Command* Create() override { return aznew CommandAddSimulatedJoints(this); } - const AZStd::vector& GetJointIndices() const { return m_jointIndices; } - void SetJointIndices(AZStd::vector newJointIndices) { m_jointIndices = AZStd::move(newJointIndices); } + const AZStd::vector& GetJointIndices() const { return m_jointIndices; } + void SetJointIndices(AZStd::vector newJointIndices) { m_jointIndices = AZStd::move(newJointIndices); } size_t GetObjectIndex() { return m_objectIndex; } void SetObjectIndex(size_t newObjectIndex ) { m_objectIndex = newObjectIndex; } @@ -215,8 +216,8 @@ namespace EMotionFX static const char* s_addChildrenParameterName; static const char* s_contentsParameterName; private: - size_t m_objectIndex = MCORE_INVALIDINDEX32; - AZStd::vector m_jointIndices; + size_t m_objectIndex = InvalidIndex; + AZStd::vector m_jointIndices; AZStd::optional m_contents; bool m_addChildren = false; bool m_oldDirtyFlag = false; @@ -245,7 +246,7 @@ namespace EMotionFX const char* GetDescription() const override { return "Remove simulated joints from a simulated object"; } MCore::Command* Create() override { return aznew CommandRemoveSimulatedJoints(this); } - const AZStd::vector& GetJointIndices() const { return m_jointIndices; } + const AZStd::vector& GetJointIndices() const { return m_jointIndices; } size_t GetObjectIndex() { return m_objectIndex; } static const char* s_commandName; @@ -254,8 +255,8 @@ namespace EMotionFX static const char* s_removeChildrenParameterName; private: - size_t m_objectIndex = MCORE_INVALIDINDEX32; - AZStd::vector m_jointIndices; + size_t m_objectIndex = InvalidIndex; + AZStd::vector m_jointIndices; AZStd::optional m_oldContents; bool m_removeChildren = false; bool m_oldDirtyFlag = false; diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp index a513710c83..064c786b0a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/EndianConversion.cpp @@ -14,15 +14,15 @@ namespace ExporterLib { void CopyVector2(EMotionFX::FileFormat::FileVector2& to, const AZ::Vector2& from) { - to.mX = from.GetX(); - to.mY = from.GetY(); + to.m_x = from.GetX(); + to.m_y = from.GetY(); } void CopyVector(EMotionFX::FileFormat::FileVector3& to, const AZ::PackedVector3f& from) { - to.mX = from.GetX(); - to.mY = from.GetY(); - to.mZ = from.GetZ(); + to.m_x = from.GetX(); + to.m_y = from.GetY(); + to.m_z = from.GetZ(); } void CopyQuaternion(EMotionFX::FileFormat::FileQuaternion& to, const AZ::Quaternion& from) @@ -33,10 +33,10 @@ namespace ExporterLib q = -q; } - to.mX = q.GetX(); - to.mY = q.GetY(); - to.mZ = q.GetZ(); - to.mW = q.GetW(); + to.m_x = q.GetX(); + to.m_y = q.GetY(); + to.m_z = q.GetZ(); + to.m_w = q.GetW(); } @@ -49,37 +49,37 @@ namespace ExporterLib } const MCore::Compressed16BitQuaternion compressedQuat(q); - to.mX = compressedQuat.mX; - to.mY = compressedQuat.mY; - to.mZ = compressedQuat.mZ; - to.mW = compressedQuat.mW; + to.m_x = compressedQuat.m_x; + to.m_y = compressedQuat.m_y; + to.m_z = compressedQuat.m_z; + to.m_w = compressedQuat.m_w; } void Copy16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion& to, const MCore::Compressed16BitQuaternion& from) { MCore::Compressed16BitQuaternion q = from; - if (q.mW < 0) + if (q.m_w < 0) { - q.mX = -q.mX; - q.mY = -q.mY; - q.mZ = -q.mZ; - q.mW = -q.mW; + q.m_x = -q.m_x; + q.m_y = -q.m_y; + q.m_z = -q.m_z; + q.m_w = -q.m_w; } - to.mX = q.mX; - to.mY = q.mY; - to.mZ = q.mZ; - to.mW = q.mW; + to.m_x = q.m_x; + to.m_y = q.m_y; + to.m_z = q.m_z; + to.m_w = q.m_w; } void CopyColor(const MCore::RGBAColor& from, EMotionFX::FileFormat::FileColor& to) { - to.mR = from.r; - to.mG = from.g; - to.mB = from.b; - to.mA = from.a; + to.m_r = from.m_r; + to.m_g = from.m_g; + to.m_b = from.m_b; + to.m_a = from.m_a; } @@ -88,6 +88,11 @@ namespace ExporterLib MCore::Endian::ConvertUnsignedInt32(value, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } + void ConvertUnsignedInt(uint64* value, MCore::Endian::EEndianType targetEndianType) + { + MCore::Endian::ConvertUnsignedInt64(value, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + } + void ConvertInt(int* value, MCore::Endian::EEndianType targetEndianType) { @@ -109,87 +114,87 @@ namespace ExporterLib void ConvertFileChunk(EMotionFX::FileFormat::FileChunk* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertUnsignedInt32(&value->mChunkID, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mSizeInBytes, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mVersion, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_chunkId, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_sizeInBytes, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_version, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileColor(EMotionFX::FileFormat::FileColor* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertFloat(&value->mR, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mG, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mB, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mA, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_r, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_g, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_b, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_a, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileVector2(EMotionFX::FileFormat::FileVector2* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileVector3(EMotionFX::FileFormat::FileVector3* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFile16BitVector3(EMotionFX::FileFormat::File16BitVector3* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertUnsignedInt16(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt16(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt16(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt16(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt16(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt16(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileQuaternion(EMotionFX::FileFormat::FileQuaternion* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertFloat(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mW, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_w, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFile16BitQuaternion(EMotionFX::FileFormat::File16BitQuaternion* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertSignedInt16(&value->mX, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertSignedInt16(&value->mY, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertSignedInt16(&value->mZ, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertSignedInt16(&value->mW, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertSignedInt16(&value->m_x, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertSignedInt16(&value->m_y, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertSignedInt16(&value->m_z, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertSignedInt16(&value->m_w, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileMotionEvent(EMotionFX::FileFormat::FileMotionEvent* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertFloat(&value->mStartTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->mEndTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mEventTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mMirrorTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt16(&value->mParamIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_startTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_endTime, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_eventTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_mirrorTypeIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt16(&value->m_paramIndex, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertFileMotionEventTable(EMotionFX::FileFormat::FileMotionEventTrack* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertUnsignedInt32(&value->mNumEvents, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mNumTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mNumParamStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertUnsignedInt32(&value->mNumMirrorTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_numEvents, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_numTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_numParamStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertUnsignedInt32(&value->m_numMirrorTypeStrings, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } void ConvertRGBAColor(MCore::RGBAColor* value, MCore::Endian::EEndianType targetEndianType) { - MCore::Endian::ConvertFloat(&value->r, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->g, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->b, EXPLIB_PLATFORM_ENDIAN, targetEndianType); - MCore::Endian::ConvertFloat(&value->a, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_r, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_g, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_b, EXPLIB_PLATFORM_ENDIAN, targetEndianType); + MCore::Endian::ConvertFloat(&value->m_a, EXPLIB_PLATFORM_ENDIAN, targetEndianType); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h index e302f3ffe2..9cd3efc6ba 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/Exporter.h @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -58,6 +57,7 @@ namespace ExporterLib // endian conversion void ConvertUnsignedInt(uint32* value, MCore::Endian::EEndianType targetEndianType); + void ConvertUnsignedInt(uint64* value, MCore::Endian::EEndianType targetEndianType); void ConvertInt(int* value, MCore::Endian::EEndianType targetEndianType); void ConvertUnsignedShort(uint16* value, MCore::Endian::EEndianType targetEndianType); void ConvertFloat(float* value, MCore::Endian::EEndianType targetEndianType); @@ -100,21 +100,21 @@ namespace ExporterLib // nodes void SaveNodes(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType); void SaveNodeGroup(MCore::Stream* file, EMotionFX::NodeGroup* nodeGroup, MCore::Endian::EEndianType targetEndianType); - void SaveNodeGroups(MCore::Stream* file, const MCore::Array& nodeGroups, MCore::Endian::EEndianType targetEndianType); + void SaveNodeGroups(MCore::Stream* file, const AZStd::vector& nodeGroups, MCore::Endian::EEndianType targetEndianType); void SaveNodeGroups(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType); - void SaveNodeMotionSources(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Array* mirrorInfo, MCore::Endian::EEndianType targetEndianType); + void SaveNodeMotionSources(MCore::Stream* file, EMotionFX::Actor* actor, AZStd::vector* mirrorInfo, MCore::Endian::EEndianType targetEndianType); void SaveAttachmentNodes(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType); void SaveAttachmentNodes(MCore::Stream* file, EMotionFX::Actor* actor, const AZStd::vector& attachmentNodes, MCore::Endian::EEndianType targetEndianType); // morph targets - void SaveMorphTarget(MCore::Stream* file, EMotionFX::Actor* actor, EMotionFX::MorphTarget* inputMorphTarget, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType); - void SaveMorphTargets(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType); + void SaveMorphTarget(MCore::Stream* file, EMotionFX::Actor* actor, EMotionFX::MorphTarget* inputMorphTarget, size_t lodLevel, MCore::Endian::EEndianType targetEndianType); + void SaveMorphTargets(MCore::Stream* file, EMotionFX::Actor* actor, size_t lodLevel, MCore::Endian::EEndianType targetEndianType); void SaveMorphTargets(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType); // actors const char* GetActorExtension(bool includingDot = true); void SaveActorHeader(MCore::Stream* file, MCore::Endian::EEndianType targetEndianType); - void SaveActorFileInfo(MCore::Stream* file, uint32 numLODLevels, uint32 motionExtractionNodeIndex, uint32 retargetRootNodeIndex, const char* sourceApp, const char* orgFileName, const char* actorName, MCore::Distance::EUnitType unitType, MCore::Endian::EEndianType targetEndianType, bool optimizeSkeleton); + void SaveActorFileInfo(MCore::Stream* file, uint64 numLODLevels, uint64 motionExtractionNodeIndex, uint64 retargetRootNodeIndex, const char* sourceApp, const char* orgFileName, const char* actorName, MCore::Distance::EUnitType unitType, MCore::Endian::EEndianType targetEndianType, bool optimizeSkeleton); void SaveActor(MCore::MemoryFile* file, const EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType, const AZStd::optional meshAssetId = AZStd::nullopt); bool SaveActor(AZStd::string& filename, const EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType, const AZStd::optional meshAssetId = AZStd::nullopt); diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/ExporterActor.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/ExporterActor.cpp index 491326552e..598e5fcc9e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/ExporterActor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/ExporterActor.cpp @@ -52,9 +52,9 @@ namespace ExporterLib const AZ::u32 bufferSize = static_cast(buffer.size()); EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_PHYSICSSETUP; - chunkHeader.mVersion = 1; - chunkHeader.mSizeInBytes = bufferSize + sizeof(AZ::u32); + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_PHYSICSSETUP; + chunkHeader.m_version = 1; + chunkHeader.m_sizeInBytes = bufferSize + sizeof(AZ::u32); ConvertFileChunk(&chunkHeader, targetEndianType); file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); @@ -90,9 +90,9 @@ namespace ExporterLib const AZ::u32 bufferSize = static_cast(buffer.size()); EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_SIMULATEDOBJECTSETUP; - chunkHeader.mVersion = 1; - chunkHeader.mSizeInBytes = bufferSize + sizeof(AZ::u32); + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_SIMULATEDOBJECTSETUP; + chunkHeader.m_version = 1; + chunkHeader.m_sizeInBytes = bufferSize + sizeof(AZ::u32); ConvertFileChunk(&chunkHeader, targetEndianType); file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); @@ -122,9 +122,9 @@ namespace ExporterLib // Write the chunk header EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MESHASSET; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MeshAsset) + GetStringChunkSize(meshAssetIdString.c_str()); - chunkHeader.mVersion = 1; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_MESHASSET; + chunkHeader.m_sizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MeshAsset) + GetStringChunkSize(meshAssetIdString.c_str()); + chunkHeader.m_version = 1; ConvertFileChunk(&chunkHeader, targetEndianType); file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp index 5a7f8d13e0..ffeab884a5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/FileHeaderExport.cpp @@ -23,14 +23,13 @@ namespace ExporterLib // the header information EMotionFX::FileFormat::Actor_Header header; memset(&header, 0, sizeof(EMotionFX::FileFormat::Actor_Header)); - header.mFourcc[0] = 'A'; - header.mFourcc[1] = 'C'; - header.mFourcc[2] = 'T'; - header.mFourcc[3] = 'R'; - header.mHiVersion = static_cast(GetFileHighVersion()); - header.mLoVersion = static_cast(GetFileLowVersion()); - header.mEndianType = static_cast(targetEndianType); - //header.mMulOrder = EMotionFX::FileFormat::MULORDER_ROT_SCALE_TRANS; + header.m_fourcc[0] = 'A'; + header.m_fourcc[1] = 'C'; + header.m_fourcc[2] = 'T'; + header.m_fourcc[3] = 'R'; + header.m_hiVersion = static_cast(GetFileHighVersion()); + header.m_loVersion = static_cast(GetFileLowVersion()); + header.m_endianType = static_cast(targetEndianType); // write the header to the stream file->Write(&header, sizeof(EMotionFX::FileFormat::Actor_Header)); @@ -38,9 +37,9 @@ namespace ExporterLib void SaveActorFileInfo(MCore::Stream* file, - uint32 numLODLevels, - uint32 motionExtractionNodeIndex, - uint32 retargetRootNodeIndex, + uint64 numLODLevels, + uint64 motionExtractionNodeIndex, + uint64 retargetRootNodeIndex, const char* sourceApp, const char* orgFileName, const char* actorName, @@ -50,42 +49,42 @@ namespace ExporterLib { // chunk header EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_INFO; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_INFO; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Info3); - chunkHeader.mSizeInBytes += GetStringChunkSize(sourceApp); - chunkHeader.mSizeInBytes += GetStringChunkSize(orgFileName); - chunkHeader.mSizeInBytes += GetStringChunkSize(GetCompilationDate()); - chunkHeader.mSizeInBytes += GetStringChunkSize(actorName); + chunkHeader.m_sizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Info3); + chunkHeader.m_sizeInBytes += GetStringChunkSize(sourceApp); + chunkHeader.m_sizeInBytes += GetStringChunkSize(orgFileName); + chunkHeader.m_sizeInBytes += GetStringChunkSize(GetCompilationDate()); + chunkHeader.m_sizeInBytes += GetStringChunkSize(actorName); - chunkHeader.mVersion = 3; + chunkHeader.m_version = 3; EMotionFX::FileFormat::Actor_Info3 infoChunk; memset(&infoChunk, 0, sizeof(EMotionFX::FileFormat::Actor_Info3)); - infoChunk.mNumLODs = numLODLevels; - infoChunk.mMotionExtractionNodeIndex = motionExtractionNodeIndex; - infoChunk.mRetargetRootNodeIndex = retargetRootNodeIndex; - infoChunk.mExporterHighVersion = static_cast(EMotionFX::GetEMotionFX().GetHighVersion()); - infoChunk.mExporterLowVersion = static_cast(EMotionFX::GetEMotionFX().GetLowVersion()); - infoChunk.mUnitType = static_cast(unitType); - infoChunk.mOptimizeSkeleton = optimizeSkeleton ? 1 : 0; + infoChunk.m_numLoDs = aznumeric_caster(numLODLevels); + infoChunk.m_motionExtractionNodeIndex = aznumeric_caster(motionExtractionNodeIndex); + infoChunk.m_retargetRootNodeIndex = aznumeric_caster(retargetRootNodeIndex); + infoChunk.m_exporterHighVersion = static_cast(EMotionFX::GetEMotionFX().GetHighVersion()); + infoChunk.m_exporterLowVersion = static_cast(EMotionFX::GetEMotionFX().GetLowVersion()); + infoChunk.m_unitType = static_cast(unitType); + infoChunk.m_optimizeSkeleton = optimizeSkeleton ? 1 : 0; // print repositioning node information MCore::LogDetailedInfo("- File Info"); MCore::LogDetailedInfo(" + Actor Name: '%s'", actorName); MCore::LogDetailedInfo(" + Source Application: '%s'", sourceApp); MCore::LogDetailedInfo(" + Original File: '%s'", orgFileName); - MCore::LogDetailedInfo(" + Exporter Version: v%d.%d", infoChunk.mExporterHighVersion, infoChunk.mExporterLowVersion); + MCore::LogDetailedInfo(" + Exporter Version: v%d.%d", infoChunk.m_exporterHighVersion, infoChunk.m_exporterLowVersion); MCore::LogDetailedInfo(" + Exporter Compilation Date: '%s'", GetCompilationDate()); - MCore::LogDetailedInfo(" + Num LODs = %d", infoChunk.mNumLODs); - MCore::LogDetailedInfo(" + Motion extraction node index = %d", infoChunk.mMotionExtractionNodeIndex); - MCore::LogDetailedInfo(" + Retarget root node index = %d", infoChunk.mRetargetRootNodeIndex); + MCore::LogDetailedInfo(" + Num LODs = %d", infoChunk.m_numLoDs); + MCore::LogDetailedInfo(" + Motion extraction node index = %d", infoChunk.m_motionExtractionNodeIndex); + MCore::LogDetailedInfo(" + Retarget root node index = %d", infoChunk.m_retargetRootNodeIndex); // endian conversion ConvertFileChunk(&chunkHeader, targetEndianType); - ConvertUnsignedInt(&infoChunk.mMotionExtractionNodeIndex, targetEndianType); - ConvertUnsignedInt(&infoChunk.mRetargetRootNodeIndex, targetEndianType); - ConvertUnsignedInt(&infoChunk.mNumLODs, targetEndianType); + ConvertUnsignedInt(&infoChunk.m_motionExtractionNodeIndex, targetEndianType); + ConvertUnsignedInt(&infoChunk.m_retargetRootNodeIndex, targetEndianType); + ConvertUnsignedInt(&infoChunk.m_numLoDs, targetEndianType); file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); file->Write(&infoChunk, sizeof(EMotionFX::FileFormat::Actor_Info3)); @@ -104,14 +103,14 @@ namespace ExporterLib EMotionFX::FileFormat::Motion_Header header; memset(&header, 0, sizeof(EMotionFX::FileFormat::Motion_Header)); - header.mFourcc[0] = 'M'; - header.mFourcc[1] = 'O'; - header.mFourcc[2] = 'T'; - header.mFourcc[3] = ' '; + header.m_fourcc[0] = 'M'; + header.m_fourcc[1] = 'O'; + header.m_fourcc[2] = 'T'; + header.m_fourcc[3] = ' '; - header.mHiVersion = static_cast(GetFileHighVersion()); - header.mLoVersion = static_cast(GetFileLowVersion()); - header.mEndianType = static_cast(targetEndianType); + header.m_hiVersion = static_cast(GetFileHighVersion()); + header.m_loVersion = static_cast(GetFileLowVersion()); + header.m_endianType = static_cast(targetEndianType); // write the header to the stream file->Write(&header, sizeof(EMotionFX::FileFormat::Motion_Header)); @@ -122,26 +121,26 @@ namespace ExporterLib { // chunk header EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::MOTION_CHUNK_INFO; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Motion_Info3); - chunkHeader.mVersion = 3; + chunkHeader.m_chunkId = EMotionFX::FileFormat::MOTION_CHUNK_INFO; + chunkHeader.m_sizeInBytes = sizeof(EMotionFX::FileFormat::Motion_Info3); + chunkHeader.m_version = 3; EMotionFX::FileFormat::Motion_Info3 infoChunk; memset(&infoChunk, 0, sizeof(EMotionFX::FileFormat::Motion_Info3)); - infoChunk.mMotionExtractionFlags = motion->GetMotionExtractionFlags(); - infoChunk.mMotionExtractionNodeIndex= MCORE_INVALIDINDEX32; // not used anymore - infoChunk.mUnitType = static_cast(motion->GetUnitType()); - infoChunk.mIsAdditive = motion->GetMotionData()->IsAdditive() ? 1 : 0; + infoChunk.m_motionExtractionFlags = motion->GetMotionExtractionFlags(); + infoChunk.m_motionExtractionNodeIndex= MCORE_INVALIDINDEX32; // not used anymore + infoChunk.m_unitType = static_cast(motion->GetUnitType()); + infoChunk.m_isAdditive = motion->GetMotionData()->IsAdditive() ? 1 : 0; MCore::LogDetailedInfo("- File Info"); MCore::LogDetailedInfo(" + Exporter Compilation Date = '%s'", GetCompilationDate()); - MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", infoChunk.mMotionExtractionFlags, (infoChunk.mMotionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0); + MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", infoChunk.m_motionExtractionFlags, (infoChunk.m_motionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0); // endian conversion ConvertFileChunk(&chunkHeader, targetEndianType); - ConvertUnsignedInt(&infoChunk.mMotionExtractionFlags, targetEndianType); - ConvertUnsignedInt(&infoChunk.mMotionExtractionNodeIndex, targetEndianType); + ConvertUnsignedInt(&infoChunk.m_motionExtractionFlags, targetEndianType); + ConvertUnsignedInt(&infoChunk.m_motionExtractionNodeIndex, targetEndianType); file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); file->Write(&infoChunk, sizeof(EMotionFX::FileFormat::Motion_Info2)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp deleted file mode 100644 index 4adee9af84..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MaterialExport.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include "Exporter.h" -#include -#include -#include - -#include -#include - - -namespace ExporterLib -{ - // write the material attribute set - void SaveMaterialAttributeSet(MCore::Stream* file, EMotionFX::Material* material, uint32 lodLevel, uint32 materialNumber, MCore::Endian::EEndianType targetEndianType) - { - AZ_UNUSED(material); - // write the chunk header - EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MATERIALATTRIBUTESET; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MaterialAttributeSet); - chunkHeader.mVersion = 1; - ConvertFileChunk(&chunkHeader, targetEndianType); - file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); - - // write the attribute set info header - EMotionFX::FileFormat::Actor_MaterialAttributeSet setInfo; - setInfo.mMaterialIndex = materialNumber; - setInfo.mLODLevel = lodLevel; - ConvertUnsignedInt(&setInfo.mMaterialIndex, targetEndianType); - ConvertUnsignedInt(&setInfo.mLODLevel, targetEndianType); - file->Write(&setInfo, sizeof(EMotionFX::FileFormat::Actor_MaterialAttributeSet)); - - // Write a former empty attribute set. - uint8 version = 1; - file->Write(&version, sizeof(uint8)); - - uint32 numAttributes = 0; - ConvertUnsignedInt(&numAttributes, targetEndianType); - file->Write(&numAttributes, sizeof(uint32)); - } - - - // save the given material for the given LOD level - void SaveMaterial(MCore::Stream* file, EMotionFX::Material* material, uint32 lodLevel, uint32 materialNumber, MCore::Endian::EEndianType targetEndianType) - { - //---------------------------------------- - // Generic EMotionFX::Material - //---------------------------------------- - if (material->GetType() == EMotionFX::Material::TYPE_ID) - { - // chunk header - EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_GENERICMATERIAL; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_GenericMaterial) + GetStringChunkSize(material->GetName()); - chunkHeader.mVersion = 1; - - EMotionFX::FileFormat::Actor_GenericMaterial materialChunk; - materialChunk.mLOD = lodLevel; - - ConvertFileChunk(&chunkHeader, targetEndianType); - ConvertUnsignedInt(&materialChunk.mLOD, targetEndianType); - - // write header and material - file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); - file->Write(&materialChunk, sizeof(EMotionFX::FileFormat::Actor_GenericMaterial)); - - // followed by: - SaveString(material->GetName(), file, targetEndianType); - - MCore::LogDetailedInfo("- Generic material:"); - MCore::LogDetailedInfo(" + Name: '%s'", material->GetName()); - MCore::LogDetailedInfo(" + LOD: %d", lodLevel); - } - - //---------------------------------------- - // Standard EMotionFX::Material - //---------------------------------------- - if (material->GetType() == EMotionFX::StandardMaterial::TYPE_ID) - { - // typecast to a standard material - EMotionFX::StandardMaterial* standardMaterial = (EMotionFX::StandardMaterial*)material; - - // chunk header - EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_STDMATERIAL; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_StandardMaterial) + GetStringChunkSize(standardMaterial->GetName()); - chunkHeader.mVersion = 1; - - const uint32 numLayers = standardMaterial->GetNumLayers(); - for (uint32 i = 0; i < numLayers; ++i) - { - chunkHeader.mSizeInBytes += sizeof(EMotionFX::FileFormat::Actor_StandardMaterialLayer); - chunkHeader.mSizeInBytes += GetStringChunkSize(standardMaterial->GetLayer(i)->GetFileName()); - } - - EMotionFX::FileFormat::Actor_StandardMaterial materialChunk; - CopyColor(standardMaterial->GetAmbient(), materialChunk.mAmbient); - CopyColor(standardMaterial->GetDiffuse(), materialChunk.mDiffuse); - CopyColor(standardMaterial->GetSpecular(), materialChunk.mSpecular); - CopyColor(standardMaterial->GetEmissive(), materialChunk.mEmissive); - materialChunk.mDoubleSided = standardMaterial->GetDoubleSided(); - materialChunk.mIOR = standardMaterial->GetIOR(); - materialChunk.mOpacity = standardMaterial->GetOpacity(); - materialChunk.mShine = standardMaterial->GetShine(); - materialChunk.mShineStrength = standardMaterial->GetShineStrength(); - materialChunk.mTransparencyType = 'F';//standardMaterial->GetTransparencyType(); - materialChunk.mWireFrame = standardMaterial->GetWireFrame(); - materialChunk.mNumLayers = static_cast(standardMaterial->GetNumLayers()); - materialChunk.mLOD = lodLevel; - - // add it to the log file - MCore::LogDetailedInfo("- Standard material:"); - MCore::LogDetailedInfo(" + Name: '%s'", standardMaterial->GetName()); - MCore::LogDetailedInfo(" + LOD: %d", lodLevel); - MCore::LogDetailedInfo(" + Ambient: r=%f g=%f b=%f", materialChunk.mAmbient.mR, materialChunk.mAmbient.mG, materialChunk.mAmbient.mB); - MCore::LogDetailedInfo(" + Diffuse: r=%f g=%f b=%f", materialChunk.mDiffuse.mR, materialChunk.mDiffuse.mG, materialChunk.mDiffuse.mB); - MCore::LogDetailedInfo(" + Specular: r=%f g=%f b=%f", materialChunk.mSpecular.mR, materialChunk.mSpecular.mG, materialChunk.mSpecular.mB); - MCore::LogDetailedInfo(" + Emissive: r=%f g=%f b=%f", materialChunk.mEmissive.mR, materialChunk.mEmissive.mG, materialChunk.mEmissive.mB); - MCore::LogDetailedInfo(" + Shine: %f", materialChunk.mShine); - MCore::LogDetailedInfo(" + ShineStrength: %f", materialChunk.mShineStrength); - MCore::LogDetailedInfo(" + Opacity: %f", materialChunk.mOpacity); - MCore::LogDetailedInfo(" + IndexOfRefraction: %f", materialChunk.mIOR); - MCore::LogDetailedInfo(" + DoubleSided: %i", (int)materialChunk.mDoubleSided); - MCore::LogDetailedInfo(" + WireFrame: %i", (int)materialChunk.mWireFrame); - MCore::LogDetailedInfo(" + TransparencyType: %c", (char)materialChunk.mTransparencyType); - MCore::LogDetailedInfo(" + NumLayers: %i", materialChunk.mNumLayers); - - // endian conversion - ConvertFileChunk(&chunkHeader, targetEndianType); - ConvertFileColor(&materialChunk.mAmbient, targetEndianType); - ConvertFileColor(&materialChunk.mDiffuse, targetEndianType); - ConvertFileColor(&materialChunk.mSpecular, targetEndianType); - ConvertFileColor(&materialChunk.mEmissive, targetEndianType); - ConvertFloat(&materialChunk.mIOR, targetEndianType); - ConvertFloat(&materialChunk.mOpacity, targetEndianType); - ConvertFloat(&materialChunk.mShine, targetEndianType); - ConvertFloat(&materialChunk.mShineStrength, targetEndianType); - ConvertUnsignedInt(&materialChunk.mLOD, targetEndianType); - - // write header and material - file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); - file->Write(&materialChunk, sizeof(EMotionFX::FileFormat::Actor_StandardMaterial)); - - // followed by: - SaveString(standardMaterial->GetName(), file, targetEndianType); - - // save all material layers - for (uint32 i = 0; i < numLayers; ++i) - { - // get the layer - EMotionFX::StandardMaterialLayer* layer = standardMaterial->GetLayer(i); - - EMotionFX::FileFormat::Actor_StandardMaterialLayer materialChunkLayer; - materialChunkLayer.mAmount = layer->GetAmount(); - materialChunkLayer.mMapType = static_cast(layer->GetType()); - materialChunkLayer.mMaterialNumber = (uint16)materialNumber; - materialChunkLayer.mRotationRadians = layer->GetRotationRadians(); - materialChunkLayer.mUOffset = layer->GetUOffset(); - materialChunkLayer.mVOffset = layer->GetVOffset(); - materialChunkLayer.mUTiling = layer->GetUTiling(); - materialChunkLayer.mVTiling = layer->GetVTiling(); - materialChunkLayer.mBlendMode = layer->GetBlendMode(); - - // add to log file - MCore::LogDetailedInfo(" - Material layer #%d:", i); - MCore::LogDetailedInfo(" + Name: '%s' (MatNr=%i)", layer->GetFileName(), materialNumber); - MCore::LogDetailedInfo(" + Amount: %f", materialChunkLayer.mAmount); - MCore::LogDetailedInfo(" + Type: %i", (int)materialChunkLayer.mMapType); - MCore::LogDetailedInfo(" + BlendMode: %i", (int)materialChunkLayer.mBlendMode); - MCore::LogDetailedInfo(" + MaterialNumber: %i", (uint32)materialChunkLayer.mMaterialNumber); - MCore::LogDetailedInfo(" + UOffset: %f", materialChunkLayer.mUOffset); - MCore::LogDetailedInfo(" + VOffset: %f", materialChunkLayer.mVOffset); - MCore::LogDetailedInfo(" + UTiling: %f", materialChunkLayer.mUTiling); - MCore::LogDetailedInfo(" + VTiling: %f", materialChunkLayer.mVTiling); - MCore::LogDetailedInfo(" + RotationRadians: %f", materialChunkLayer.mRotationRadians); - - // endian conversion - ConvertFloat(&materialChunkLayer.mAmount, targetEndianType); - ConvertUnsignedShort(&materialChunkLayer.mMaterialNumber, targetEndianType); - ConvertFloat(&materialChunkLayer.mRotationRadians, targetEndianType); - ConvertFloat(&materialChunkLayer.mUOffset, targetEndianType); - ConvertFloat(&materialChunkLayer.mVOffset, targetEndianType); - ConvertFloat(&materialChunkLayer.mUTiling, targetEndianType); - ConvertFloat(&materialChunkLayer.mVTiling, targetEndianType); - - // write header and material layer - file->Write(&materialChunkLayer, sizeof(EMotionFX::FileFormat::Actor_StandardMaterialLayer)); - SaveString(layer->GetFileName(), file, targetEndianType); - } - } - } - - - // save the given materials - void SaveMaterials(MCore::Stream* file, MCore::Array& materials, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - // get the number of materials - const uint32 numMaterials = materials.GetLength(); - - // chunk header - EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MATERIALINFO; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_MaterialInfo); - chunkHeader.mVersion = 1; - - // convert endian and write to file - ConvertFileChunk(&chunkHeader, targetEndianType); - file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); - - EMotionFX::FileFormat::Actor_MaterialInfo materialInfoChunk; - materialInfoChunk.mLOD = lodLevel; - materialInfoChunk.mNumTotalMaterials = numMaterials; - materialInfoChunk.mNumStandardMaterials = 0; - materialInfoChunk.mNumFXMaterials = 0; - materialInfoChunk.mNumGenericMaterials = 0; - - for (uint32 i = 0; i < numMaterials; i++) - { - if (materials[i]->GetType() == EMotionFX::Material::TYPE_ID) - { - materialInfoChunk.mNumGenericMaterials++; - } - - if (materials[i]->GetType() == EMotionFX::StandardMaterial::TYPE_ID) - { - materialInfoChunk.mNumStandardMaterials++; - } - } - - MCore::LogDetailedInfo("============================================================"); - MCore::LogInfo("Materials (%d)", numMaterials); - MCore::LogDetailedInfo("============================================================"); - - MCORE_ASSERT(materialInfoChunk.mNumTotalMaterials == materialInfoChunk.mNumStandardMaterials + materialInfoChunk.mNumFXMaterials + materialInfoChunk.mNumGenericMaterials); - - // convert endian and write to disk - ConvertUnsignedInt(&materialInfoChunk.mNumTotalMaterials, targetEndianType); - ConvertUnsignedInt(&materialInfoChunk.mNumStandardMaterials, targetEndianType); - ConvertUnsignedInt(&materialInfoChunk.mNumFXMaterials, targetEndianType); - ConvertUnsignedInt(&materialInfoChunk.mNumGenericMaterials, targetEndianType); - ConvertUnsignedInt(&materialInfoChunk.mLOD, targetEndianType); - file->Write(&materialInfoChunk, sizeof(EMotionFX::FileFormat::Actor_MaterialInfo)); - - // export all materials - for (uint32 i = 0; i < numMaterials; i++) - { - SaveMaterial(file, materials[i], lodLevel, i, targetEndianType); - } - - // save all material attribute sets - for (uint32 i = 0; i < numMaterials; i++) - { - SaveMaterialAttributeSet(file, materials[i], lodLevel, i, targetEndianType); - } - } - - - // save out all materials for a given LOD level - void SaveMaterials(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - // get the number of materials in the given lod level - const uint32 numMaterials = actor->GetNumMaterials(lodLevel); - - // create our materials array and reserve some elements - MCore::Array materials; - materials.Reserve(numMaterials); - - // iterate through the materials - for (uint32 j = 0; j < numMaterials; j++) - { - // get the base material - EMotionFX::Material* baseMaterial = actor->GetMaterial(lodLevel, j); - materials.Add(baseMaterial); - } - - // save the materials - SaveMaterials(file, materials, lodLevel, targetEndianType); - } - - - // save all materials for all LOD levels - void SaveMaterials(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType) - { - // get the number of LOD levels and iterate through them - const uint32 numLODLevels = actor->GetNumLODLevels(); - for (uint32 i = 0; i < numLODLevels; ++i) - { - SaveMaterials(file, actor, i, targetEndianType); - } - } -} // namespace ExporterLib diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MeshExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MeshExport.cpp deleted file mode 100644 index 40b13d896f..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MeshExport.cpp +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include "Exporter.h" -#include -#include -#include -#include -#include -#include -#include - - -namespace ExporterLib -{ - // save the given mesh - void SaveMesh(MCore::Stream* file, EMotionFX::Mesh* mesh, uint32 nodeIndex, bool isCollisionMesh, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - // convert endian for abstract layers - for (uint32 i = 0; i < mesh->GetNumVertexAttributeLayers(); ++i) - { - EMotionFX::VertexAttributeLayer* layer = mesh->GetVertexAttributeLayer(i); - if (!layer->GetIsAbstractDataClass()) - { - continue; - } - - EMotionFX::VertexAttributeLayerAbstractData* abstractLayer = static_cast(layer); - - const uint32 type = abstractLayer->GetType(); - - EMotionFX::Importer::AbstractLayerConverter layerConvertFunction; - layerConvertFunction = EMotionFX::Importer::StandardLayerConvert; - - // convert endian and coordinate systems of all data - if (layerConvertFunction(abstractLayer, targetEndianType) == false) - { - MCore::LogError("Don't know how to endian and/or coordinate system convert layer with type %d (%s)", type, EMotionFX::Importer::ActorVertexAttributeLayerTypeToString(type)); - } - } - - uint32 totalSize = sizeof(EMotionFX::FileFormat::Actor_Mesh); - - // add all layers to the total size - uint32 numMeshVerts = mesh->GetNumVertices(); - for (uint32 i = 0; i < mesh->GetNumVertexAttributeLayers(); ++i) - { - EMotionFX::VertexAttributeLayer* layer = mesh->GetVertexAttributeLayer(i); - if (!layer->GetIsAbstractDataClass()) - { - continue; - } - - EMotionFX::VertexAttributeLayerAbstractData* abstractLayer = static_cast(layer); - - totalSize += sizeof(EMotionFX::FileFormat::Actor_VertexAttributeLayer); - totalSize += numMeshVerts * abstractLayer->GetAttributeSizeInBytes(); - totalSize += GetStringChunkSize(layer->GetNameString()); - } - - // add the submeshes - for (uint32 i = 0; i < mesh->GetNumSubMeshes(); ++i) - { - EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(i); - totalSize += sizeof(EMotionFX::FileFormat::Actor_SubMesh); - totalSize += sizeof(uint32) * subMesh->GetNumIndices(); - totalSize += sizeof(uint8) * subMesh->GetNumPolygons(); - totalSize += sizeof(uint32) * subMesh->GetNumBones(); - } - - // write the chunk header - EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_MESH; - chunkHeader.mSizeInBytes = totalSize; - chunkHeader.mVersion = 1; - ConvertFileChunk(&chunkHeader, targetEndianType); - file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); - - // write the mesh header - EMotionFX::FileFormat::Actor_Mesh meshHeader; - memset(&meshHeader, 0, sizeof(EMotionFX::FileFormat::Actor_Mesh)); - meshHeader.mIsCollisionMesh = isCollisionMesh ? 1 : 0; - meshHeader.mNodeIndex = nodeIndex; - meshHeader.mNumLayers = mesh->GetNumVertexAttributeLayers(); - meshHeader.mNumOrgVerts = mesh->GetNumOrgVertices(); - meshHeader.mNumSubMeshes = mesh->GetNumSubMeshes(); - meshHeader.mNumPolygons = mesh->GetNumPolygons(); - meshHeader.mTotalIndices = mesh->GetNumIndices(); - meshHeader.mLOD = lodLevel; - meshHeader.mTotalVerts = (mesh->GetNumVertexAttributeLayers() > 0) ? mesh->GetNumVertices() : 0; - meshHeader.mIsTriangleMesh = mesh->CheckIfIsTriangleMesh(); - - MCore::LogDetailedInfo("- Mesh for node with node number %d:", meshHeader.mNodeIndex); - MCore::LogDetailedInfo(" + LOD: %d", meshHeader.mLOD); - MCore::LogDetailedInfo(" + Num original vertices: %d", meshHeader.mNumOrgVerts); - MCore::LogDetailedInfo(" + Total vertices: %d", meshHeader.mTotalVerts); - MCore::LogDetailedInfo(" + Total polygons: %d", meshHeader.mNumPolygons); - MCore::LogDetailedInfo(" + Total indices: %d", meshHeader.mTotalIndices); - MCore::LogDetailedInfo(" + Num submeshes: %d", meshHeader.mNumSubMeshes); - MCore::LogDetailedInfo(" + Num attribute layers: %d", meshHeader.mNumLayers); - MCore::LogDetailedInfo(" + Is collision mesh: %s", meshHeader.mIsCollisionMesh ? "Yes" : "No"); - MCore::LogDetailedInfo(" + Is triangle mesh: %s", meshHeader.mIsTriangleMesh ? "Yes" : "No"); - - //for (uint32 i=0; iGetNumPolygons(); ++i) - //MCore::LogInfo("poly %d = %d verts", i, mesh->GetPolygonVertexCounts()[i] ); - - // convert endian - ConvertUnsignedInt(&meshHeader.mNodeIndex, targetEndianType); - ConvertUnsignedInt(&meshHeader.mNumLayers, targetEndianType); - ConvertUnsignedInt(&meshHeader.mNumSubMeshes, targetEndianType); - ConvertUnsignedInt(&meshHeader.mNumPolygons, targetEndianType); - ConvertUnsignedInt(&meshHeader.mTotalIndices, targetEndianType); - ConvertUnsignedInt(&meshHeader.mTotalVerts, targetEndianType); - ConvertUnsignedInt(&meshHeader.mNumOrgVerts, targetEndianType); - ConvertUnsignedInt(&meshHeader.mLOD, targetEndianType); - - // write to file - file->Write(&meshHeader, sizeof(EMotionFX::FileFormat::Actor_Mesh)); - - // now save all layers - const uint32 numLayers = mesh->GetNumVertexAttributeLayers(); - for (uint32 layerNr = 0; layerNr < numLayers; ++layerNr) - { - EMotionFX::VertexAttributeLayer* layer = mesh->GetVertexAttributeLayer(layerNr); - if (!layer->GetIsAbstractDataClass()) - { - continue; - } - - EMotionFX::VertexAttributeLayerAbstractData* abstractLayer = static_cast(layer); - - EMotionFX::FileFormat::Actor_VertexAttributeLayer fileLayer; - memset(&fileLayer, 0, sizeof(EMotionFX::FileFormat::Actor_VertexAttributeLayer)); - fileLayer.mLayerTypeID = layer->GetType(); - fileLayer.mAttribSizeInBytes = abstractLayer->GetAttributeSizeInBytes(); - fileLayer.mEnableDeformations = layer->GetKeepOriginals() ? 1 : 0; - fileLayer.mIsScale = 0;// TODO: not used - - MCore::LogDetailedInfo(" - Layer #%d (%s):", layerNr, EMotionFX::Importer::ActorVertexAttributeLayerTypeToString(fileLayer.mLayerTypeID)); - MCore::LogDetailedInfo(" + Type ID: %d", fileLayer.mLayerTypeID); - MCore::LogDetailedInfo(" + Attrib size: %d bytes", fileLayer.mAttribSizeInBytes); - MCore::LogDetailedInfo(" + Enable deforms: %s", fileLayer.mEnableDeformations ? "Yes" : "No"); - MCore::LogDetailedInfo(" + Name: %s", layer->GetName()); - - // convert endian - ConvertUnsignedInt(&fileLayer.mAttribSizeInBytes, targetEndianType); - ConvertUnsignedInt(&fileLayer.mLayerTypeID, targetEndianType); - - // write the layer header - file->Write(&fileLayer, sizeof(EMotionFX::FileFormat::Actor_VertexAttributeLayer)); - - // write the name - SaveString(layer->GetNameString(), file, targetEndianType); - - // write the layer - file->Write((uint8*)abstractLayer->GetOriginalData(), abstractLayer->CalcTotalDataSizeInBytes(false)); - } - - - // and finally save all submeshes - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) - { - EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(s); - - EMotionFX::FileFormat::Actor_SubMesh fileSubMesh; - fileSubMesh.mMaterialIndex = subMesh->GetMaterial(); - fileSubMesh.mNumBones = subMesh->GetNumBones(); - fileSubMesh.mNumIndices = subMesh->GetNumIndices(); - fileSubMesh.mNumVerts = subMesh->GetNumVertices(); - fileSubMesh.mNumPolygons = subMesh->GetNumPolygons(); - - MCore::LogDetailedInfo(" - SubMesh #%d:", s); - MCore::LogDetailedInfo(" + Material: %d", fileSubMesh.mMaterialIndex); - MCore::LogDetailedInfo(" + Num vertices: %d", fileSubMesh.mNumVerts); - MCore::LogDetailedInfo(" + Num indices: %d (%d polygons)", fileSubMesh.mNumIndices, fileSubMesh.mNumPolygons); - MCore::LogDetailedInfo(" + Num bones: %d", fileSubMesh.mNumBones); - - // convert endian - ConvertUnsignedInt(&fileSubMesh.mMaterialIndex, targetEndianType); - ConvertUnsignedInt(&fileSubMesh.mNumBones, targetEndianType); - ConvertUnsignedInt(&fileSubMesh.mNumIndices, targetEndianType); - ConvertUnsignedInt(&fileSubMesh.mNumPolygons, targetEndianType); - ConvertUnsignedInt(&fileSubMesh.mNumVerts, targetEndianType); - - // write the submesh header - file->Write(&fileSubMesh, sizeof(EMotionFX::FileFormat::Actor_SubMesh)); - - // write the index data - const uint32 numIndices = subMesh->GetNumIndices(); - const uint32 numPolygons = subMesh->GetNumPolygons(); - const uint32 startVertex = subMesh->GetStartVertex(); - uint32* indices = subMesh->GetIndices(); - uint8* polyVertCounts = subMesh->GetPolygonVertexCounts(); - - for (uint32 i = 0; i < numIndices; ++i) - { - uint32 index = indices[i] - startVertex; - ConvertUnsignedInt(&index, targetEndianType); - file->Write(&index, sizeof(uint32)); - } - - for (uint32 i = 0; i < numPolygons; ++i) - { - uint8 numPolyVerts = polyVertCounts[i]; - file->Write(&numPolyVerts, sizeof(uint8)); - } - - // write the bone numbers - const uint32 numBones = subMesh->GetNumBones(); - for (uint32 i = 0; i < numBones; ++i) - { - uint32 value = subMesh->GetBone(i); - ConvertUnsignedInt(&value, targetEndianType); - file->Write(&value, sizeof(uint32)); - } - } - } - - - // save meshes for all nodes for a given LOD level - void SaveMeshes(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - MCORE_ASSERT(file); - MCORE_ASSERT(actor); - - MCore::LogDetailedInfo("============================================================"); - MCore::LogInfo("Meshes (LOD=%i", lodLevel); - MCore::LogDetailedInfo("============================================================"); - - // get the number of nodes - const uint32 numNodes = actor->GetNumNodes(); - - // iterate through all nodes - for (uint32 i = 0; i < numNodes; i++) - { - // get the node from the actor - //EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); - - // get the mesh and save it - EMotionFX::Mesh* mesh = actor->GetMesh(lodLevel, i); - if (mesh) - { - SaveMesh(file, mesh, i, mesh->GetIsCollisionMesh(), lodLevel, targetEndianType); - } - - // get the collision mesh and save it - /* EMotionFX::Mesh* collisionMesh = actor->GetCollisionMesh(lodLevel, i); - if (collisionMesh) - SaveMesh( file, collisionMesh, i, true, lodLevel, targetEndianType );*/ - } - } - - - // save all meshes for all nodes and all LOD levels - void SaveMeshes(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType) - { - // get the number of LOD levels, iterate through them and save all meshes - const uint32 numLODLevels = actor->GetNumLODLevels(); - for (uint32 i = 0; i < numLODLevels; ++i) - { - SaveMeshes(file, actor, i, targetEndianType); - } - } -} // namespace ExporterLib diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp index b2d88295b4..5205dcbc97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MorphTargetExport.cpp @@ -20,7 +20,7 @@ namespace ExporterLib { // save the given morph target - void SaveMorphTarget(MCore::Stream* file, EMotionFX::Actor* actor, EMotionFX::MorphTarget* inputMorphTarget, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) + void SaveMorphTarget(MCore::Stream* file, EMotionFX::Actor* actor, EMotionFX::MorphTarget* inputMorphTarget, size_t lodLevel, MCore::Endian::EEndianType targetEndianType) { MCORE_ASSERT(file); MCORE_ASSERT(actor); @@ -28,15 +28,15 @@ namespace ExporterLib MCORE_ASSERT(inputMorphTarget->GetType() == EMotionFX::MorphTargetStandard::TYPE_ID); EMotionFX::MorphTargetStandard* morphTarget = (EMotionFX::MorphTargetStandard*)inputMorphTarget; - const uint32 numTransformations = morphTarget->GetNumTransformations(); + const size_t numTransformations = morphTarget->GetNumTransformations(); // copy over the information to the chunk EMotionFX::FileFormat::Actor_MorphTarget morphTargetChunk; - morphTargetChunk.mLOD = lodLevel; - morphTargetChunk.mNumTransformations = numTransformations; - morphTargetChunk.mRangeMin = morphTarget->GetRangeMin(); - morphTargetChunk.mRangeMax = morphTarget->GetRangeMax(); - morphTargetChunk.mPhonemeSets = morphTarget->GetPhonemeSets(); + morphTargetChunk.m_lod = aznumeric_caster(lodLevel); + morphTargetChunk.m_numTransformations = aznumeric_caster(numTransformations); + morphTargetChunk.m_rangeMin = morphTarget->GetRangeMin(); + morphTargetChunk.m_rangeMax = morphTarget->GetRangeMax(); + morphTargetChunk.m_phonemeSets = morphTarget->GetPhonemeSets(); // log it MCore::LogDetailedInfo(" - Morph Target: Name='%s'", morphTarget->GetName()); @@ -47,11 +47,11 @@ namespace ExporterLib MCore::LogDetailedInfo(" + PhonemesSets: %s", EMotionFX::MorphTarget::GetPhonemeSetString((EMotionFX::MorphTarget::EPhonemeSet)morphTarget->GetPhonemeSets()).c_str()); // convert endian - ConvertFloat(&morphTargetChunk.mRangeMin, targetEndianType); - ConvertFloat(&morphTargetChunk.mRangeMax, targetEndianType); - ConvertUnsignedInt(&morphTargetChunk.mLOD, targetEndianType); - ConvertUnsignedInt(&morphTargetChunk.mNumTransformations, targetEndianType); - ConvertUnsignedInt(&morphTargetChunk.mPhonemeSets, targetEndianType); + ConvertFloat(&morphTargetChunk.m_rangeMin, targetEndianType); + ConvertFloat(&morphTargetChunk.m_rangeMax, targetEndianType); + ConvertUnsignedInt(&morphTargetChunk.m_lod, targetEndianType); + ConvertUnsignedInt(&morphTargetChunk.m_numTransformations, targetEndianType); + ConvertUnsignedInt(&morphTargetChunk.m_phonemeSets, targetEndianType); // write the bones expression part file->Write(&morphTargetChunk, sizeof(EMotionFX::FileFormat::Actor_MorphTarget)); @@ -60,37 +60,37 @@ namespace ExporterLib SaveString(morphTarget->GetName(), file, targetEndianType); // create and write the transformations - for (uint32 i = 0; i < numTransformations; i++) + for (size_t i = 0; i < numTransformations; i++) { EMotionFX::MorphTargetStandard::Transformation transform = morphTarget->GetTransformation(i); - EMotionFX::Node* node = actor->GetSkeleton()->GetNode(transform.mNodeIndex); + EMotionFX::Node* node = actor->GetSkeleton()->GetNode(transform.m_nodeIndex); if (node == nullptr) { - MCore::LogError("Can't get node '%i'. File is corrupt!", transform.mNodeIndex); + MCore::LogError("Can't get node '%i'. File is corrupt!", transform.m_nodeIndex); continue; } // create and fill the transformation EMotionFX::FileFormat::Actor_MorphTargetTransform transformChunk; - transformChunk.mNodeIndex = transform.mNodeIndex; - CopyVector(transformChunk.mPosition, AZ::PackedVector3f(transform.mPosition)); - CopyVector(transformChunk.mScale, AZ::PackedVector3f(transform.mScale)); - CopyQuaternion(transformChunk.mRotation, transform.mRotation); - CopyQuaternion(transformChunk.mScaleRotation, transform.mScaleRotation); + transformChunk.m_nodeIndex = aznumeric_caster(transform.m_nodeIndex); + CopyVector(transformChunk.m_position, AZ::PackedVector3f(transform.m_position)); + CopyVector(transformChunk.m_scale, AZ::PackedVector3f(transform.m_scale)); + CopyQuaternion(transformChunk.m_rotation, transform.m_rotation); + CopyQuaternion(transformChunk.m_scaleRotation, transform.m_scaleRotation); MCore::LogDetailedInfo(" - EMotionFX::Transform #%i: Node='%s' NodeNr=#%i", i, node->GetName(), node->GetNodeIndex()); - MCore::LogDetailedInfo(" + Pos: %f, %f, %f", transformChunk.mPosition.mX, transformChunk.mPosition.mY, transformChunk.mPosition.mZ); - MCore::LogDetailedInfo(" + Rotation: %f, %f, %f %f", transformChunk.mRotation.mX, transformChunk.mRotation.mY, transformChunk.mRotation.mZ, transformChunk.mRotation.mW); - MCore::LogDetailedInfo(" + Scale: %f, %f, %f", transformChunk.mScale.mX, transformChunk.mScale.mY, transformChunk.mScale.mZ); - MCore::LogDetailedInfo(" + ScaleRot: %f, %f, %f %f", transformChunk.mScaleRotation.mX, transformChunk.mScaleRotation.mY, transformChunk.mScaleRotation.mZ, transformChunk.mScaleRotation.mW); + MCore::LogDetailedInfo(" + Pos: %f, %f, %f", transformChunk.m_position.m_x, transformChunk.m_position.m_y, transformChunk.m_position.m_z); + MCore::LogDetailedInfo(" + Rotation: %f, %f, %f %f", transformChunk.m_rotation.m_x, transformChunk.m_rotation.m_y, transformChunk.m_rotation.m_z, transformChunk.m_rotation.m_w); + MCore::LogDetailedInfo(" + Scale: %f, %f, %f", transformChunk.m_scale.m_x, transformChunk.m_scale.m_y, transformChunk.m_scale.m_z); + MCore::LogDetailedInfo(" + ScaleRot: %f, %f, %f %f", transformChunk.m_scaleRotation.m_x, transformChunk.m_scaleRotation.m_y, transformChunk.m_scaleRotation.m_z, transformChunk.m_scaleRotation.m_w); // convert endian and coordinate system - ConvertUnsignedInt(&transformChunk.mNodeIndex, targetEndianType); - ConvertFileVector3(&transformChunk.mPosition, targetEndianType); - ConvertFileVector3(&transformChunk.mScale, targetEndianType); - ConvertFileQuaternion(&transformChunk.mRotation, targetEndianType); - ConvertFileQuaternion(&transformChunk.mScaleRotation, targetEndianType); + ConvertUnsignedInt(&transformChunk.m_nodeIndex, targetEndianType); + ConvertFileVector3(&transformChunk.m_position, targetEndianType); + ConvertFileVector3(&transformChunk.m_scale, targetEndianType); + ConvertFileQuaternion(&transformChunk.m_rotation, targetEndianType); + ConvertFileQuaternion(&transformChunk.m_scaleRotation, targetEndianType); // write the transformation file->Write(&transformChunk, sizeof(EMotionFX::FileFormat::Actor_MorphTargetTransform)); @@ -99,12 +99,12 @@ namespace ExporterLib // get the size of the chunk for the given morph target - uint32 GetMorphTargetChunkSize(EMotionFX::MorphTarget* inputMorphTarget) + size_t GetMorphTargetChunkSize(EMotionFX::MorphTarget* inputMorphTarget) { MCORE_ASSERT(inputMorphTarget->GetType() == EMotionFX::MorphTargetStandard::TYPE_ID); EMotionFX::MorphTargetStandard* morphTarget = (EMotionFX::MorphTargetStandard*)inputMorphTarget; - uint32 totalSize = 0; + size_t totalSize = 0; totalSize += sizeof(EMotionFX::FileFormat::Actor_MorphTarget); totalSize += GetStringChunkSize(morphTarget->GetName()); totalSize += sizeof(EMotionFX::FileFormat::Actor_MorphTargetTransform) * morphTarget->GetNumTransformations(); @@ -114,14 +114,14 @@ namespace ExporterLib // get the size of the chunk for the complete morph setup - uint32 GetMorphSetupChunkSize(EMotionFX::MorphSetup* morphSetup) + size_t GetMorphSetupChunkSize(EMotionFX::MorphSetup* morphSetup) { // get the number of morph targets - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); // calculate the size of the chunk - uint32 totalSize = sizeof(EMotionFX::FileFormat::Actor_MorphTargets); - for (uint32 i = 0; i < numMorphTargets; ++i) + size_t totalSize = sizeof(EMotionFX::FileFormat::Actor_MorphTargets); + for (size_t i = 0; i < numMorphTargets; ++i) { totalSize += GetMorphTargetChunkSize(morphSetup->GetMorphTarget(i)); } @@ -129,15 +129,14 @@ namespace ExporterLib return totalSize; } - uint32 GetNumSavedMorphTargets(EMotionFX::MorphSetup* morphSetup) + size_t GetNumSavedMorphTargets(EMotionFX::MorphSetup* morphSetup) { return morphSetup->GetNumMorphTargets(); } // save all morph targets for a given LOD level - void SaveMorphTargets(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) + void SaveMorphTargets(MCore::Stream* file, EMotionFX::Actor* actor, size_t lodLevel, MCore::Endian::EEndianType targetEndianType) { - uint32 i; MCORE_ASSERT(file); MCORE_ASSERT(actor); @@ -148,7 +147,7 @@ namespace ExporterLib } // get the number of morph targets we need to save to the file and check if there are any at all - const uint32 numSavedMorphTargets = GetNumSavedMorphTargets(morphSetup); + const size_t numSavedMorphTargets = GetNumSavedMorphTargets(morphSetup); if (numSavedMorphTargets <= 0) { MCore::LogInfo("No morph targets to be saved in morph setup. Skipping writing morph targets."); @@ -156,10 +155,10 @@ namespace ExporterLib } // get the number of morph targets - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); // check if all morph targets have a valid name and rename them in case they are empty - for (i = 0; i < numMorphTargets; ++i) + for (size_t i = 0; i < numMorphTargets; ++i) { EMotionFX::MorphTarget* morphTarget = morphSetup->GetMorphTarget(i); @@ -168,7 +167,7 @@ namespace ExporterLib { // rename the morph target AZStd::string morphTargetName; - morphTargetName = AZStd::string::format("Morph Target %d", MCore::GetIDGenerator().GenerateID()); + morphTargetName = AZStd::string::format("Morph Target %zu", MCore::GetIDGenerator().GenerateID()); MCore::LogWarning("The morph target has an empty name. The morph target will be automatically renamed to '%s'.", morphTargetName.c_str()); morphTarget->SetName(morphTargetName.c_str()); } @@ -176,9 +175,9 @@ namespace ExporterLib // fill in the chunk header EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS; - chunkHeader.mSizeInBytes = GetMorphSetupChunkSize(morphSetup); - chunkHeader.mVersion = 2; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS; + chunkHeader.m_sizeInBytes = aznumeric_caster(GetMorphSetupChunkSize(morphSetup)); + chunkHeader.m_version = 2; // endian convert the chunk and write it to the file ConvertFileChunk(&chunkHeader, targetEndianType); @@ -186,20 +185,20 @@ namespace ExporterLib // fill in the chunk header EMotionFX::FileFormat::Actor_MorphTargets morphTargetsChunk; - morphTargetsChunk.mNumMorphTargets = numSavedMorphTargets; - morphTargetsChunk.mLOD = lodLevel; + morphTargetsChunk.m_numMorphTargets = aznumeric_caster(numSavedMorphTargets); + morphTargetsChunk.m_lod = aznumeric_caster(lodLevel); MCore::LogDetailedInfo("============================================================"); - MCore::LogInfo("Morph Targets (%i, LOD=%d)", morphTargetsChunk.mNumMorphTargets, morphTargetsChunk.mLOD); + MCore::LogInfo("Morph Targets (%i, LOD=%d)", morphTargetsChunk.m_numMorphTargets, morphTargetsChunk.m_lod); MCore::LogDetailedInfo("============================================================"); // endian convert the chunk and write it to the file - ConvertUnsignedInt(&morphTargetsChunk.mNumMorphTargets, targetEndianType); - ConvertUnsignedInt(&morphTargetsChunk.mLOD, targetEndianType); + ConvertUnsignedInt(&morphTargetsChunk.m_numMorphTargets, targetEndianType); + ConvertUnsignedInt(&morphTargetsChunk.m_lod, targetEndianType); file->Write(&morphTargetsChunk, sizeof(EMotionFX::FileFormat::Actor_MorphTargets)); // save morph targets - for (i = 0; i < numMorphTargets; ++i) + for (size_t i = 0; i < numMorphTargets; ++i) { SaveMorphTarget(file, actor, morphSetup->GetMorphTarget(i), lodLevel, targetEndianType); } @@ -209,8 +208,8 @@ namespace ExporterLib void SaveMorphTargets(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType) { // get the number of LOD levels and save the morph targets for each - const uint32 numLODLevels = actor->GetNumLODLevels(); - for (uint32 i = 0; i < numLODLevels; ++i) + const size_t numLODLevels = actor->GetNumLODLevels(); + for (size_t i = 0; i < numLODLevels; ++i) { SaveMorphTargets(file, actor, i, targetEndianType); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp index 1d29ca1056..e1bde1ff79 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/MotionEventExport.cpp @@ -66,10 +66,10 @@ namespace ExporterLib // the motion event table chunk header EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::SHARED_CHUNK_MOTIONEVENTTABLE; - chunkHeader.mVersion = 3; + chunkHeader.m_chunkId = EMotionFX::FileFormat::SHARED_CHUNK_MOTIONEVENTTABLE; + chunkHeader.m_version = 3; - chunkHeader.mSizeInBytes = static_cast(serializedTableSizeInBytes + sizeof(EMotionFX::FileFormat::FileMotionEventTableSerialized)); + chunkHeader.m_sizeInBytes = static_cast(serializedTableSizeInBytes + sizeof(EMotionFX::FileFormat::FileMotionEventTableSerialized)); EMotionFX::FileFormat::FileMotionEventTableSerialized tableHeader; tableHeader.m_size = serializedTableSizeInBytes; diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp index a9010fb524..91727b2113 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/NodeExport.cpp @@ -18,93 +18,71 @@ namespace ExporterLib { - void WriteObbToNodeChunk(EMotionFX::FileFormat::Actor_Node& nodeChunk, const MCore::OBB& obb) - { - AZ::Transform obbMatrix = obb.GetTransformation(); - obbMatrix.GetBasisX().StoreToFloat3(nodeChunk.mOBB); - nodeChunk.mOBB[3] = 0.0f; - obbMatrix.GetBasisY().StoreToFloat3(nodeChunk.mOBB + 4); - nodeChunk.mOBB[7] = 0.0f; - obbMatrix.GetBasisZ().StoreToFloat3(nodeChunk.mOBB + 8); - nodeChunk.mOBB[11] = 0.0f; - nodeChunk.mOBB[12] = 0.0f; - nodeChunk.mOBB[13] = 0.0f; - nodeChunk.mOBB[14] = 0.0f; - nodeChunk.mOBB[15] = 1.0f; - } - void SaveNode(MCore::Stream* file, EMotionFX::Actor* actor, EMotionFX::Node* node, MCore::Endian::EEndianType targetEndianType) { MCORE_ASSERT(file); MCORE_ASSERT(actor); MCORE_ASSERT(node); - uint32 l; - // get some information from the node - const uint32 nodeIndex = node->GetNodeIndex(); - const uint32 parentIndex = node->GetParentIndex(); - const uint32 numChilds = node->GetNumChildNodes(); + const size_t nodeIndex = node->GetNodeIndex(); + const size_t parentIndex = node->GetParentIndex(); + const size_t numChilds = node->GetNumChildNodes(); const EMotionFX::Transform& transform = actor->GetBindPose()->GetLocalSpaceTransform(nodeIndex); - AZ::PackedVector3f position = AZ::PackedVector3f(transform.mPosition); - AZ::Quaternion rotation = transform.mRotation.GetNormalized();; + AZ::PackedVector3f position = AZ::PackedVector3f(transform.m_position); + AZ::Quaternion rotation = transform.m_rotation.GetNormalized(); #ifndef EMFX_SCALE_DISABLED - AZ::PackedVector3f scale = AZ::PackedVector3f(transform.mScale); + AZ::PackedVector3f scale = AZ::PackedVector3f(transform.m_scale); #else AZ::PackedVector3f scale(1.0f, 1.0f, 1.0f); #endif // create the node chunk and copy over the information - EMotionFX::FileFormat::Actor_Node nodeChunk; - memset(&nodeChunk, 0, sizeof(EMotionFX::FileFormat::Actor_Node)); + EMotionFX::FileFormat::Actor_Node2 nodeChunk; + memset(&nodeChunk, 0, sizeof(EMotionFX::FileFormat::Actor_Node2)); - CopyVector(nodeChunk.mLocalPos, position); - CopyQuaternion(nodeChunk.mLocalQuat, rotation); - CopyVector(nodeChunk.mLocalScale, scale); + CopyVector(nodeChunk.m_localPos, position); + CopyQuaternion(nodeChunk.m_localQuat, rotation); + CopyVector(nodeChunk.m_localScale, scale); - //nodeChunk.mImportanceFactor = FLT_MAX;//importance; - nodeChunk.mNumChilds = numChilds; - nodeChunk.mParentIndex = parentIndex; + nodeChunk.m_numChilds = aznumeric_caster(numChilds); + nodeChunk.m_parentIndex = aznumeric_caster(parentIndex); // calculate and copy over the skeletal LODs uint32 skeletalLODs = 0; - for (l = 0; l < 32; ++l) + for (uint32 l = 0; l < 32; ++l) { if (node->GetSkeletalLODStatus(l)) { skeletalLODs |= (1 << l); } } - nodeChunk.mSkeletalLODs = skeletalLODs; + nodeChunk.m_skeletalLoDs = skeletalLODs; // will this node be involved in the bounding volume calculations? if (node->GetIncludeInBoundsCalc()) { - nodeChunk.mNodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC;// first bit + nodeChunk.m_nodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC;// first bit } else { - nodeChunk.mNodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC; + nodeChunk.m_nodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC; } // Add an isCritical option in node flag so it won't be optimized out. if (node->GetIsCritical()) { - nodeChunk.mNodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_CRITICAL; // third bit + nodeChunk.m_nodeFlags |= EMotionFX::Node::ENodeFlags::FLAG_CRITICAL; // third bit } else { - nodeChunk.mNodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_CRITICAL; + nodeChunk.m_nodeFlags &= ~EMotionFX::Node::ENodeFlags::FLAG_CRITICAL; } - // OBB - WriteObbToNodeChunk(nodeChunk, actor->GetNodeOBB(node->GetNodeIndex())); - - // log the node chunk information MCore::LogDetailedInfo("- Node: name='%s' index=%i", actor->GetSkeleton()->GetNode(nodeIndex)->GetName(), nodeIndex); - if (parentIndex == MCORE_INVALIDINDEX32) + if (parentIndex == InvalidIndex) { MCore::LogDetailedInfo(" + Parent: Has no parent(root)."); } @@ -112,20 +90,20 @@ namespace ExporterLib { MCore::LogDetailedInfo(" + Parent: name='%s' index=%i", actor->GetSkeleton()->GetNode(parentIndex)->GetName(), parentIndex); } - MCore::LogDetailedInfo(" + NumChilds: %i", nodeChunk.mNumChilds); - MCore::LogDetailedInfo(" + Position: x=%f y=%f z=%f", nodeChunk.mLocalPos.mX, nodeChunk.mLocalPos.mY, nodeChunk.mLocalPos.mZ); - MCore::LogDetailedInfo(" + Rotation: x=%f y=%f z=%f w=%f", nodeChunk.mLocalQuat.mX, nodeChunk.mLocalQuat.mY, nodeChunk.mLocalQuat.mZ, nodeChunk.mLocalQuat.mW); + MCore::LogDetailedInfo(" + NumChilds: %i", nodeChunk.m_numChilds); + MCore::LogDetailedInfo(" + Position: x=%f y=%f z=%f", nodeChunk.m_localPos.m_x, nodeChunk.m_localPos.m_y, nodeChunk.m_localPos.m_z); + MCore::LogDetailedInfo(" + Rotation: x=%f y=%f z=%f w=%f", nodeChunk.m_localQuat.m_x, nodeChunk.m_localQuat.m_y, nodeChunk.m_localQuat.m_z, nodeChunk.m_localQuat.m_w); const AZ::Vector3 euler = MCore::AzQuaternionToEulerAngles(rotation); MCore::LogDetailedInfo(" + Rotation Euler: x=%f y=%f z=%f", float(euler.GetX()) * 180.0 / MCore::Math::pi, float(euler.GetY()) * 180.0 / MCore::Math::pi, float(euler.GetZ()) * 180.0 / MCore::Math::pi); - MCore::LogDetailedInfo(" + Scale: x=%f y=%f z=%f", nodeChunk.mLocalScale.mX, nodeChunk.mLocalScale.mY, nodeChunk.mLocalScale.mZ); + MCore::LogDetailedInfo(" + Scale: x=%f y=%f z=%f", nodeChunk.m_localScale.m_x, nodeChunk.m_localScale.m_y, nodeChunk.m_localScale.m_z); MCore::LogDetailedInfo(" + IncludeInBoundsCalc: %d", node->GetIncludeInBoundsCalc()); // log skeletal lods AZStd::string lodString = " + Skeletal LODs: "; - for (l = 0; l < 32; ++l) + for (uint32 l = 0; l < 32; ++l) { int32 flag = node->GetSkeletalLODStatus(l); lodString += AZStd::to_string(flag); @@ -133,32 +111,24 @@ namespace ExporterLib MCore::LogDetailedInfo(lodString.c_str()); // endian conversion - ConvertFileVector3(&nodeChunk.mLocalPos, targetEndianType); - ConvertFileQuaternion(&nodeChunk.mLocalQuat, targetEndianType); - ConvertFileVector3(&nodeChunk.mLocalScale, targetEndianType); - ConvertUnsignedInt(&nodeChunk.mParentIndex, targetEndianType); - ConvertUnsignedInt(&nodeChunk.mNumChilds, targetEndianType); - ConvertUnsignedInt(&nodeChunk.mSkeletalLODs, targetEndianType); - - for (uint32 j = 0; j < 16; ++j) - { - ConvertFloat(&nodeChunk.mOBB[j], targetEndianType); - } + ConvertFileVector3(&nodeChunk.m_localPos, targetEndianType); + ConvertFileQuaternion(&nodeChunk.m_localQuat, targetEndianType); + ConvertFileVector3(&nodeChunk.m_localScale, targetEndianType); + ConvertUnsignedInt(&nodeChunk.m_parentIndex, targetEndianType); + ConvertUnsignedInt(&nodeChunk.m_numChilds, targetEndianType); + ConvertUnsignedInt(&nodeChunk.m_skeletalLoDs, targetEndianType); // write it - file->Write(&nodeChunk, sizeof(EMotionFX::FileFormat::Actor_Node)); + file->Write(&nodeChunk, sizeof(EMotionFX::FileFormat::Actor_Node2)); // write the name of the node and parent SaveString(node->GetName(), file, targetEndianType); } - void SaveNodes(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType) { - uint32 i; - // get the number of nodes - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); MCore::LogDetailedInfo("============================================================"); MCore::LogInfo("Nodes (%i)", actor->GetNumNodes()); @@ -166,14 +136,14 @@ namespace ExporterLib // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODES; - chunkHeader.mVersion = 1; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODES; + chunkHeader.m_version = 2; // get the nodes chunk size - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_Nodes) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node); - for (i = 0; i < numNodes; i++) + chunkHeader.m_sizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_Nodes2) + numNodes * sizeof(EMotionFX::FileFormat::Actor_Node2)); + for (size_t i = 0; i < numNodes; i++) { - chunkHeader.mSizeInBytes += GetStringChunkSize(actor->GetSkeleton()->GetNode(i)->GetName()); + chunkHeader.m_sizeInBytes += GetStringChunkSize(actor->GetSkeleton()->GetNode(i)->GetName()); } // endian conversion and write it @@ -181,54 +151,45 @@ namespace ExporterLib file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); // nodes chunk - EMotionFX::FileFormat::Actor_Nodes nodesChunk; - nodesChunk.mNumNodes = numNodes; - nodesChunk.mNumRootNodes = actor->GetSkeleton()->GetNumRootNodes(); - nodesChunk.mStaticBoxMin.mX = actor->GetStaticAABB().GetMin().GetX(); - nodesChunk.mStaticBoxMin.mY = actor->GetStaticAABB().GetMin().GetY(); - nodesChunk.mStaticBoxMin.mZ = actor->GetStaticAABB().GetMin().GetZ(); - nodesChunk.mStaticBoxMax.mX = actor->GetStaticAABB().GetMax().GetX(); - nodesChunk.mStaticBoxMax.mY = actor->GetStaticAABB().GetMax().GetY(); - nodesChunk.mStaticBoxMax.mZ = actor->GetStaticAABB().GetMax().GetZ(); + EMotionFX::FileFormat::Actor_Nodes2 nodesChunk; + nodesChunk.m_numNodes = aznumeric_caster(numNodes); + nodesChunk.m_numRootNodes = aznumeric_caster(actor->GetSkeleton()->GetNumRootNodes()); // endian conversion and write it - ConvertUnsignedInt(&nodesChunk.mNumNodes, targetEndianType); - ConvertUnsignedInt(&nodesChunk.mNumRootNodes, targetEndianType); - ConvertFileVector3(&nodesChunk.mStaticBoxMin, targetEndianType); - ConvertFileVector3(&nodesChunk.mStaticBoxMax, targetEndianType); + ConvertUnsignedInt(&nodesChunk.m_numNodes, targetEndianType); + ConvertUnsignedInt(&nodesChunk.m_numRootNodes, targetEndianType); - file->Write(&nodesChunk, sizeof(EMotionFX::FileFormat::Actor_Nodes)); + file->Write(&nodesChunk, sizeof(EMotionFX::FileFormat::Actor_Nodes2)); // write the nodes - for (uint32 n = 0; n < numNodes; n++) + for (size_t n = 0; n < numNodes; n++) { SaveNode(file, actor, actor->GetSkeleton()->GetNode(n), targetEndianType); } } - void SaveNodeGroup(MCore::Stream* file, EMotionFX::NodeGroup* nodeGroup, MCore::Endian::EEndianType targetEndianType) + void SaveNodeGroup(MCore::Stream* file, const EMotionFX::NodeGroup* nodeGroup, MCore::Endian::EEndianType targetEndianType) { - uint32 i; MCORE_ASSERT(file); MCORE_ASSERT(nodeGroup); // get the number of nodes in the node group - const uint32 numNodes = nodeGroup->GetNumNodes(); + const size_t numNodes = nodeGroup->GetNumNodes(); // the node group chunk EMotionFX::FileFormat::Actor_NodeGroup groupChunk; memset(&groupChunk, 0, sizeof(EMotionFX::FileFormat::Actor_NodeGroup)); // set the data - groupChunk.mNumNodes = static_cast(numNodes); - groupChunk.mDisabledOnDefault = nodeGroup->GetIsEnabledOnDefault() ? false : true; + groupChunk.m_numNodes = static_cast(numNodes); + groupChunk.m_disabledOnDefault = nodeGroup->GetIsEnabledOnDefault() ? false : true; // logging MCore::LogDetailedInfo("- Group: name='%s'", nodeGroup->GetName()); - MCore::LogDetailedInfo(" + DisabledOnDefault: %i", groupChunk.mDisabledOnDefault); + MCore::LogDetailedInfo(" + DisabledOnDefault: %i", groupChunk.m_disabledOnDefault); AZStd::string nodesString; - for (i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { nodesString += AZStd::to_string(nodeGroup->GetNode(static_cast(i))); if (i < numNodes - 1) @@ -236,10 +197,10 @@ namespace ExporterLib nodesString += ", "; } } - MCore::LogDetailedInfo(" + Nodes (%i): %s", groupChunk.mNumNodes, nodesString.c_str()); + MCore::LogDetailedInfo(" + Nodes (%i): %s", groupChunk.m_numNodes, nodesString.c_str()); // endian conversion - ConvertUnsignedShort(&groupChunk.mNumNodes, targetEndianType); + ConvertUnsignedShort(&groupChunk.m_numNodes, targetEndianType); // write it file->Write(&groupChunk, sizeof(EMotionFX::FileFormat::Actor_NodeGroup)); @@ -248,7 +209,7 @@ namespace ExporterLib SaveString(nodeGroup->GetNameString(), file, targetEndianType); // write the node numbers - for (i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { uint16 nodeNumber = nodeGroup->GetNode(static_cast(i)); if (nodeNumber == MCORE_INVALIDINDEX16) @@ -261,13 +222,12 @@ namespace ExporterLib } - void SaveNodeGroups(MCore::Stream* file, const MCore::Array& nodeGroups, MCore::Endian::EEndianType targetEndianType) + void SaveNodeGroups(MCore::Stream* file, const AZStd::vector& nodeGroups, MCore::Endian::EEndianType targetEndianType) { - uint32 i; MCORE_ASSERT(file); // get the number of node groups - const uint32 numGroups = nodeGroups.GetLength(); + const size_t numGroups = nodeGroups.size(); if (numGroups == 0) { @@ -280,16 +240,16 @@ namespace ExporterLib // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODEGROUPS; - chunkHeader.mVersion = 1; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODEGROUPS; + chunkHeader.m_version = 1; // calculate the chunk size - chunkHeader.mSizeInBytes = sizeof(uint16); - for (i = 0; i < numGroups; ++i) + chunkHeader.m_sizeInBytes = sizeof(uint16); + for (const EMotionFX::NodeGroup* nodeGroup : nodeGroups) { - chunkHeader.mSizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup); - chunkHeader.mSizeInBytes += GetStringChunkSize(nodeGroups[i]->GetNameString()); - chunkHeader.mSizeInBytes += sizeof(uint16) * nodeGroups[i]->GetNumNodes(); + chunkHeader.m_sizeInBytes += sizeof(EMotionFX::FileFormat::Actor_NodeGroup); + chunkHeader.m_sizeInBytes += GetStringChunkSize(nodeGroup->GetNameString()); + chunkHeader.m_sizeInBytes += sizeof(uint16) * nodeGroup->GetNumNodes(); } // endian conversion @@ -304,9 +264,9 @@ namespace ExporterLib file->Write(&numGroupsChunk, sizeof(uint16)); // iterate through all groups - for (i = 0; i < numGroups; ++i) + for (const EMotionFX::NodeGroup* nodeGroup : nodeGroups) { - SaveNodeGroup(file, nodeGroups[i], targetEndianType); + SaveNodeGroup(file, nodeGroup, targetEndianType); } } @@ -320,13 +280,13 @@ namespace ExporterLib const uint32 numGroups = actor->GetNumNodeGroups(); // create the node group array and reserve some elements - MCore::Array nodeGroups; - nodeGroups.Reserve(numGroups); + AZStd::vector nodeGroups; + nodeGroups.reserve(numGroups); // iterate through the node groups and add them to the array for (uint32 i = 0; i < numGroups; ++i) { - nodeGroups.Add(actor->GetNodeGroup(i)); + nodeGroups.emplace_back(actor->GetNodeGroup(i)); } // save the node groups @@ -334,7 +294,7 @@ namespace ExporterLib } - void SaveNodeMotionSources(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Array* nodeMirrorInfos, MCore::Endian::EEndianType targetEndianType) + void SaveNodeMotionSources(MCore::Stream* file, EMotionFX::Actor* actor, AZStd::vector* nodeMirrorInfos, MCore::Endian::EEndianType targetEndianType) { MCORE_ASSERT(file); @@ -345,13 +305,13 @@ namespace ExporterLib MCORE_ASSERT(nodeMirrorInfos); - const uint32 numNodes = nodeMirrorInfos->GetLength(); + const size_t numNodes = nodeMirrorInfos->size(); // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_NODEMOTIONSOURCES; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2) + (numNodes * sizeof(uint16)) + (numNodes * sizeof(uint8) * 2); - chunkHeader.mVersion = 1; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_NODEMOTIONSOURCES; + chunkHeader.m_sizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2) + (numNodes * sizeof(uint16)) + (numNodes * sizeof(uint8) * 2)); + chunkHeader.m_version = 1; // endian conversion and write it ConvertFileChunk(&chunkHeader, targetEndianType); @@ -360,10 +320,10 @@ namespace ExporterLib // the node motion sources chunk data EMotionFX::FileFormat::Actor_NodeMotionSources2 nodeMotionSourcesChunk; - nodeMotionSourcesChunk.mNumNodes = numNodes; + nodeMotionSourcesChunk.m_numNodes = aznumeric_caster(numNodes); // convert endian and save to the file - ConvertUnsignedInt(&nodeMotionSourcesChunk.mNumNodes, targetEndianType); + ConvertUnsignedInt(&nodeMotionSourcesChunk.m_numNodes, targetEndianType); file->Write(&nodeMotionSourcesChunk, sizeof(EMotionFX::FileFormat::Actor_NodeMotionSources2)); @@ -373,13 +333,10 @@ namespace ExporterLib MCore::LogInfo("============================================================"); // write all node motion sources and convert endian - for (uint32 i = 0; i < numNodes; ++i) + for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos) { // get the motion node source - uint16 nodeMotionSource = nodeMirrorInfos->GetItem(i).mSourceNode; - - //if (actor && nodeMotionSource != MCORE_INVALIDINDEX16) - //LogInfo(" + '%s' (NodeNr=%i) -> '%s' (NodeNr=%i)", actor->GetNode( i )->GetName(), i, actor->GetNode( nodeMotionSource )->GetName(), nodeMotionSource); + uint16 nodeMotionSource = nodeMirrorInfo.m_sourceNode; // convert endian and save to the file ConvertUnsignedShort(&nodeMotionSource, targetEndianType); @@ -387,16 +344,16 @@ namespace ExporterLib } // write all axes - for (uint32 i = 0; i < numNodes; ++i) + for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos) { - uint8 axis = static_cast(nodeMirrorInfos->GetItem(i).mAxis); + uint8 axis = static_cast(nodeMirrorInfo.m_axis); file->Write(&axis, sizeof(uint8)); } // write all flags - for (uint32 i = 0; i < numNodes; ++i) + for (const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo : *nodeMirrorInfos) { - uint8 flags = static_cast(nodeMirrorInfos->GetItem(i).mFlags); + uint8 flags = static_cast(nodeMirrorInfo.m_flags); file->Write(&flags, sizeof(uint8)); } } @@ -405,14 +362,14 @@ namespace ExporterLib void SaveAttachmentNodes(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType) { // get the number of nodes - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); // create our attachment nodes array and preallocate memory AZStd::vector attachmentNodes; attachmentNodes.reserve(numNodes); // iterate through the nodes and collect all attachments - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { // get the current node, check if it is an attachment and add it to the attachment array in that case EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); @@ -437,13 +394,13 @@ namespace ExporterLib } // get the number of attachment nodes - const uint32 numAttachmentNodes = static_cast(attachmentNodes.size()); + const size_t numAttachmentNodes = attachmentNodes.size(); // chunk information EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_ATTACHMENTNODES; - chunkHeader.mSizeInBytes = sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes) + numAttachmentNodes * sizeof(uint16); - chunkHeader.mVersion = 1; + chunkHeader.m_chunkId = EMotionFX::FileFormat::ACTOR_CHUNK_ATTACHMENTNODES; + chunkHeader.m_sizeInBytes = aznumeric_caster(sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes) + numAttachmentNodes * sizeof(uint16)); + chunkHeader.m_version = 1; // endian conversion and write it ConvertFileChunk(&chunkHeader, targetEndianType); @@ -452,10 +409,10 @@ namespace ExporterLib // the attachment nodes chunk data EMotionFX::FileFormat::Actor_AttachmentNodes attachmentNodesChunk; - attachmentNodesChunk.mNumNodes = numAttachmentNodes; + attachmentNodesChunk.m_numNodes = aznumeric_caster(numAttachmentNodes); // convert endian and save to the file - ConvertUnsignedInt(&attachmentNodesChunk.mNumNodes, targetEndianType); + ConvertUnsignedInt(&attachmentNodesChunk.m_numNodes, targetEndianType); file->Write(&attachmentNodesChunk, sizeof(EMotionFX::FileFormat::Actor_AttachmentNodes)); // log details @@ -464,18 +421,16 @@ namespace ExporterLib MCore::LogInfo("============================================================"); // get all nodes that are affected by the skin - MCore::Array bones; + AZStd::vector bones; if (actor) { actor->ExtractBoneList(0, &bones); } // write all attachment nodes and convert endian - for (uint32 i = 0; i < numAttachmentNodes; ++i) + for (uint16 nodeNr : attachmentNodes) { // get the attachment node index - uint16 nodeNr = attachmentNodes[i]; - if (actor && nodeNr != MCORE_INVALIDINDEX16) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(nodeNr); @@ -489,7 +444,7 @@ namespace ExporterLib } // is the attachment node a skinned one? - if (bones.Find(node->GetNodeIndex()) != MCORE_INVALIDINDEX32) + if (AZStd::find(begin(bones), end(bones), node->GetNodeIndex()) != end(bones)) { MCore::LogWarning("Attachment node '%s' (NodeNr=%i) is used by a skin. Skinning will look incorrectly when using motion mirroring.", node->GetName(), nodeNr); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkeletalMotionExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkeletalMotionExport.cpp index 17c5011275..26c2c2c59e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkeletalMotionExport.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkeletalMotionExport.cpp @@ -26,9 +26,9 @@ namespace ExporterLib EMotionFX::MotionData::SaveSettings saveSettings; saveSettings.m_targetEndianType = targetEndianType; EMotionFX::FileFormat::FileChunk chunkHeader; - chunkHeader.mChunkID = EMotionFX::FileFormat::MOTION_CHUNK_MOTIONDATA; - chunkHeader.mVersion = 1; - chunkHeader.mSizeInBytes = static_cast( + chunkHeader.m_chunkId = EMotionFX::FileFormat::MOTION_CHUNK_MOTIONDATA; + chunkHeader.m_version = 1; + chunkHeader.m_sizeInBytes = static_cast( sizeof(EMotionFX::FileFormat::Motion_MotionData) + ExporterLib::GetAzStringChunkSize(uuidString) + ExporterLib::GetAzStringChunkSize(nameString) + diff --git a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkinExport.cpp b/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkinExport.cpp deleted file mode 100644 index 3c0c30ff53..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Exporters/ExporterLib/Exporter/SkinExport.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include "Exporter.h" -#include -#include -#include -#include -#include -#include - - -namespace ExporterLib -{ - // save the given skin for the given LOD level - void SaveSkin(MCore::Stream* file, EMotionFX::Mesh* mesh, uint32 nodeIndex, bool isCollisionMesh, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - MCORE_ASSERT(mesh); - - const uint32 numLayers = mesh->GetNumSharedVertexAttributeLayers(); - for (uint32 layerNr = 0; layerNr < numLayers; ++layerNr) - { - EMotionFX::VertexAttributeLayer* vertexAttributeLayer = mesh->GetSharedVertexAttributeLayer(layerNr); - - if (vertexAttributeLayer->GetType() != EMotionFX::SkinningInfoVertexAttributeLayer::TYPE_ID) - { - continue; - } - - EMotionFX::SkinningInfoVertexAttributeLayer* skinLayer = static_cast(vertexAttributeLayer); - - // get the number of original vertices - const uint32 numOrgVerts = skinLayer->GetNumAttributes(); - - // get the number of total influences - uint32 numTotalInfluences = 0; - uint32 v; - for (v = 0; v < numOrgVerts; ++v) - { - numTotalInfluences += aznumeric_cast(skinLayer->GetNumInfluences(v)); - } - - // skip meshes which don't contain any influences - if (numOrgVerts <= 0) - { - continue; - } - - if (numOrgVerts != mesh->GetNumOrgVertices()) - { - MCore::LogWarning("More/Less skinning influences (%i) found than the mesh actually has original vertices (%i).", numOrgVerts, mesh->GetNumOrgVertices()); - } - - // chunk header - EMotionFX::FileFormat::FileChunk chunkHeader; - - // calculate the total size and write the chunk header - uint32 totalSize = sizeof(EMotionFX::FileFormat::Actor_SkinningInfo); - totalSize += numTotalInfluences * sizeof(EMotionFX::FileFormat::Actor_SkinInfluence); - totalSize += numOrgVerts * sizeof(EMotionFX::FileFormat::Actor_SkinningInfoTableEntry); - - chunkHeader.mChunkID = EMotionFX::FileFormat::ACTOR_CHUNK_SKINNINGINFO; - chunkHeader.mSizeInBytes = totalSize; - chunkHeader.mVersion = 1; - - // endian conversion - ConvertFileChunk(&chunkHeader, targetEndianType); - - // write header and influence - file->Write(&chunkHeader, sizeof(EMotionFX::FileFormat::FileChunk)); - - if (nodeIndex == MCORE_INVALIDINDEX32) - { - MCore::LogError("Skin (Nr=%i) is not connected to a valid transform node.", nodeIndex); - } - - MCore::LogDetailedInfo(" - Skinning Info (NodeNr=%i):", nodeIndex); - MCore::LogDetailedInfo(" + Total data size: %d kB", totalSize / 1024); - MCore::LogDetailedInfo(" + Num org vertices: %d", numOrgVerts); - MCore::LogDetailedInfo(" + Num total influences: %d", numTotalInfluences); - - EMotionFX::FileFormat::Actor_SkinningInfo skinningInfoChunk; - memset(&skinningInfoChunk, 0, sizeof(EMotionFX::FileFormat::Actor_SkinningInfo)); - skinningInfoChunk.mIsForCollisionMesh = isCollisionMesh ? 1 : 0; - skinningInfoChunk.mNodeIndex = nodeIndex; - skinningInfoChunk.mLOD = lodLevel; - skinningInfoChunk.mNumTotalInfluences = numTotalInfluences; - - AZStd::set localJointIndices = skinLayer->CalcLocalJointIndices(numOrgVerts); - skinningInfoChunk.mNumLocalBones = static_cast(localJointIndices.size()); - - ConvertUnsignedInt(&skinningInfoChunk.mNodeIndex, targetEndianType); - ConvertUnsignedInt(&skinningInfoChunk.mLOD, targetEndianType); - ConvertUnsignedInt(&skinningInfoChunk.mNumTotalInfluences, targetEndianType); - ConvertUnsignedInt(&skinningInfoChunk.mNumLocalBones, targetEndianType); - - file->Write(&skinningInfoChunk, sizeof(EMotionFX::FileFormat::Actor_SkinningInfo)); - - for (v = 0; v < numOrgVerts; ++v) - { - const uint32 weightCount = aznumeric_cast(skinLayer->GetNumInfluences(v)); - - //LogDebug(" - Vertex#%i: NumWeights='%i'", v, weightCount); - - for (uint32 w = 0; w < weightCount; ++w) - { - EMotionFX::FileFormat::Actor_SkinInfluence skinInfluence; - memset(&skinInfluence, 0, sizeof(EMotionFX::FileFormat::Actor_SkinInfluence)); - skinInfluence.mNodeNr = skinLayer->GetInfluence(v, w)->GetNodeNr(); - skinInfluence.mWeight = skinLayer->GetInfluence(v, w)->GetWeight(); - - //LogDebug(" + SkingInfluence#%i: NodeNr='%i', Weight='%f'", w, skinInfluence.mNodeNr, skinInfluence.mWeight); - - ConvertUnsignedShort(&skinInfluence.mNodeNr, targetEndianType); - ConvertFloat(&skinInfluence.mWeight, targetEndianType); - - file->Write(&skinInfluence, sizeof(EMotionFX::FileFormat::Actor_SkinInfluence)); - } - } - - uint32 currentInfluence = 0; - for (v = 0; v < numOrgVerts; ++v) - { - const uint32 weightCount = aznumeric_cast(skinLayer->GetNumInfluences(v)); - - EMotionFX::FileFormat::Actor_SkinningInfoTableEntry skinningTableEntryChunk; - skinningTableEntryChunk.mNumElements = weightCount; - skinningTableEntryChunk.mStartIndex = currentInfluence; - - ConvertUnsignedInt(&skinningTableEntryChunk.mNumElements, targetEndianType); - ConvertUnsignedInt(&skinningTableEntryChunk.mStartIndex, targetEndianType); - - file->Write(&skinningTableEntryChunk, sizeof(EMotionFX::FileFormat::Actor_SkinningInfoTableEntry)); - - currentInfluence += weightCount; - } - } - } - - - // save skins for all nodes for the given LOD level - void SaveSkins(MCore::Stream* file, EMotionFX::Actor* actor, uint32 lodLevel, MCore::Endian::EEndianType targetEndianType) - { - MCORE_ASSERT(file); - - // get the number of nodes - const uint32 numNodes = actor->GetNumNodes(); - - MCore::LogDetailedInfo("============================================================"); - MCore::LogInfo("Skins (LOD=%d", lodLevel); - MCore::LogDetailedInfo("============================================================"); - - // iterate through all nodes - for (uint32 i = 0; i < numNodes; i++) - { - // get the mesh and save it - EMotionFX::Mesh* mesh = actor->GetMesh(lodLevel, i); - if (mesh) - { - SaveSkin(file, mesh, i, false, lodLevel, targetEndianType); - } - - // get the collision mesh and save it - //EMotionFX::Mesh* collisionMesh = actor->GetCollisionMesh(lodLevel, i); - //if (collisionMesh) - //SaveSkin( file, collisionMesh, i, true, lodLevel, targetEndianType ); - } - } - - - // save all skins for all LOD levels - void SaveSkins(MCore::Stream* file, EMotionFX::Actor* actor, MCore::Endian::EEndianType targetEndianType) - { - // get the number of LOD levels, iterate through them and save all skins - const uint32 numLODLevels = actor->GetNumLODLevels(); - for (uint32 i = 0; i < numLODLevels; ++i) - { - SaveSkins(file, actor, i, targetEndianType); - } - } -} // namespace ExporterLib diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp index 35d38dd359..0c5916f684 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp @@ -272,7 +272,7 @@ namespace EMotionFX // Post create actor actor->SetUnitType(MCore::Distance::UNITTYPE_METERS); actor->SetFileUnitType(MCore::Distance::UNITTYPE_METERS); - actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*generateOBBs=*/false, /*convertUnitType=*/false); + actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*convertUnitType=*/false); // Only enable joints that are used for skinning (and their parents). // On top of that, enable all joints marked as critical joints. diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp index bf79fbf05c..a498ed2cb7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorGroupExporter.cpp @@ -48,7 +48,8 @@ namespace EMotionFX AZ::SerializeContext* serializeContext = azrtti_cast(context); if (serializeContext) { - serializeContext->Class()->Version(2); + // Increasing the version number of the actor group exporter will make sure all actor products will be force re-generated. + serializeContext->Class()->Version(3); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/SceneAPIExt/Rules/MetaDataRule.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/SceneAPIExt/Rules/MetaDataRule.cpp index 6d0daf784b..8aefdbe1ff 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/SceneAPIExt/Rules/MetaDataRule.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/SceneAPIExt/Rules/MetaDataRule.cpp @@ -163,10 +163,10 @@ namespace EMotionFX createMotionEventCommand->SetStartTime(commandLine.GetValueAsFloat("startTime", 0.0f)); createMotionEventCommand->SetEndTime(commandLine.GetValueAsFloat("endTime", 0.0f)); - const AZ::u32 eventTypeIndex = commandLine.FindParameterIndex("eventType"); - const AZ::u32 parametersIndex = commandLine.FindParameterIndex("parameters"); - const AZ::u32 mirrorTypeIndex = commandLine.FindParameterIndex("mirrorType"); - if (eventTypeIndex == MCORE_INVALIDINDEX32 || parametersIndex == MCORE_INVALIDINDEX32 || mirrorTypeIndex == MCORE_INVALIDINDEX32) + const size_t eventTypeIndex = commandLine.FindParameterIndex("eventType"); + const size_t parametersIndex = commandLine.FindParameterIndex("parameters"); + const size_t mirrorTypeIndex = commandLine.FindParameterIndex("mirrorType"); + if (eventTypeIndex == InvalidIndex || parametersIndex == InvalidIndex || mirrorTypeIndex == InvalidIndex) { // Note: We have noticed some bad data issue in internal assets. The parameters could contain \r\n inside of the parameter string, which would result in the mirror type missing. // Those are already been fixed in the command line object code, but we don't want to support the bad data in here by creating another loophole. Instead, we want the user to fix diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.cpp index fe33cff6e5..f4447c1b10 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.cpp @@ -17,10 +17,10 @@ namespace MCommon Camera::Camera() { Reset(); - mPosition = AZ::Vector3::CreateZero(); - mScreenWidth = 0; - mScreenHeight = 0; - mProjectionMode = PROJMODE_PERSPECTIVE; + m_position = AZ::Vector3::CreateZero(); + m_screenWidth = 0; + m_screenHeight = 0; + m_projectionMode = PROJMODE_PERSPECTIVE; } @@ -36,27 +36,27 @@ namespace MCommon MCORE_UNUSED(timeDelta); // setup projection matrix - switch (mProjectionMode) + switch (m_projectionMode) { // initialize for perspective projection case PROJMODE_PERSPECTIVE: { - MCore::PerspectiveRH(mProjectionMatrix, MCore::Math::DegreesToRadians(mFOV), mAspect, mNearClipDistance, mFarClipDistance); + MCore::PerspectiveRH(m_projectionMatrix, MCore::Math::DegreesToRadians(m_fov), m_aspect, m_nearClipDistance, m_farClipDistance); break; } // initialize for orthographic projection case PROJMODE_ORTHOGRAPHIC: { - const float halfX = mOrthoClipDimensions.GetX() * 0.5f; - const float halfY = mOrthoClipDimensions.GetY() * 0.5f; - MCore::OrthoOffCenterRH(mProjectionMatrix, -halfX, halfX, halfY, -halfY, -mFarClipDistance, mFarClipDistance); + const float halfX = m_orthoClipDimensions.GetX() * 0.5f; + const float halfY = m_orthoClipDimensions.GetY() * 0.5f; + MCore::OrthoOffCenterRH(m_projectionMatrix, -halfX, halfX, halfY, -halfY, -m_farClipDistance, m_farClipDistance); break; } } // calculate the viewproj matrix - mViewProjMatrix = mProjectionMatrix * mViewMatrix; + m_viewProjMatrix = m_projectionMatrix * m_viewMatrix; } @@ -65,24 +65,24 @@ namespace MCommon { MCORE_UNUSED(flightTime); - mFOV = 55.0f; - mNearClipDistance = 0.1f; - mFarClipDistance = 200.0f; - mAspect = 16.0f / 9.0f; - mRotationSpeed = 0.5f; - mTranslationSpeed = 1.0f; - mViewMatrix = AZ::Matrix4x4::CreateIdentity(); + m_fov = 55.0f; + m_nearClipDistance = 0.1f; + m_farClipDistance = 200.0f; + m_aspect = 16.0f / 9.0f; + m_rotationSpeed = 0.5f; + m_translationSpeed = 1.0f; + m_viewMatrix = AZ::Matrix4x4::CreateIdentity(); } // unproject screen coordinates to a ray MCore::Ray Camera::Unproject(int32 screenX, int32 screenY) { - const AZ::Matrix4x4 invProj = MCore::InvertProjectionMatrix(mProjectionMatrix); - const AZ::Matrix4x4 invView = MCore::InvertProjectionMatrix(mViewMatrix); + const AZ::Matrix4x4 invProj = MCore::InvertProjectionMatrix(m_projectionMatrix); + const AZ::Matrix4x4 invView = MCore::InvertProjectionMatrix(m_viewMatrix); - const AZ::Vector3 start = MCore::Unproject(static_cast(screenX), static_cast(screenY), static_cast(mScreenWidth), static_cast(mScreenHeight), mNearClipDistance, invProj, invView); - const AZ::Vector3 end = MCore::Unproject(static_cast(screenX), static_cast(screenY), static_cast(mScreenWidth), static_cast(mScreenHeight), mFarClipDistance, invProj, invView); + const AZ::Vector3 start = MCore::Unproject(static_cast(screenX), static_cast(screenY), static_cast(m_screenWidth), static_cast(m_screenHeight), m_nearClipDistance, invProj, invView); + const AZ::Vector3 end = MCore::Unproject(static_cast(screenX), static_cast(screenY), static_cast(m_screenWidth), static_cast(m_screenHeight), m_farClipDistance, invProj, invView); return MCore::Ray(start, end); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h index 0c7b19384e..46b81a9d25 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.h @@ -11,6 +11,7 @@ #include #include +#include #include #include #include "MCommonConfig.h" @@ -147,24 +148,24 @@ namespace MCommon * The projection matrix will be calculated every Update(). * @return The projection matrix. */ - MCORE_INLINE AZ::Matrix4x4& GetProjectionMatrix() { return mProjectionMatrix; } - MCORE_INLINE const AZ::Matrix4x4& GetProjectionMatrix() const { return mProjectionMatrix; } + MCORE_INLINE AZ::Matrix4x4& GetProjectionMatrix() { return m_projectionMatrix; } + MCORE_INLINE const AZ::Matrix4x4& GetProjectionMatrix() const { return m_projectionMatrix; } /** * Get the view matrix of the camera. * The view matrix will be calculated every Update(). * @return The view matrix. */ - MCORE_INLINE AZ::Matrix4x4& GetViewMatrix() { return mViewMatrix; } - MCORE_INLINE const AZ::Matrix4x4& GetViewMatrix() const { return mViewMatrix; } + MCORE_INLINE AZ::Matrix4x4& GetViewMatrix() { return m_viewMatrix; } + MCORE_INLINE const AZ::Matrix4x4& GetViewMatrix() const { return m_viewMatrix; } /** * Get the precalculated viewMatrix * projectionMatrix of the camera. * The viewproj matrix will be calculated every Update(). * @return The precalculated matrix containing the result of viewMatrix * projectionMatrix. */ - MCORE_INLINE AZ::Matrix4x4& GetViewProjMatrix() { return mViewProjMatrix; } - MCORE_INLINE const AZ::Matrix4x4& GetViewProjMatrix() const { return mViewProjMatrix; } + MCORE_INLINE AZ::Matrix4x4& GetViewProjMatrix() { return m_viewProjMatrix; } + MCORE_INLINE const AZ::Matrix4x4& GetViewProjMatrix() const { return m_viewProjMatrix; } /** * Get the translation speed. @@ -260,20 +261,20 @@ namespace MCommon virtual void AutoUpdateLimits() {} protected: - AZ::Matrix4x4 mProjectionMatrix; /**< The projection matrix. */ - AZ::Matrix4x4 mViewMatrix; /**< The view matrix. */ - AZ::Matrix4x4 mViewProjMatrix; /**< ViewMatrix * projectionMatrix. Will be recalculated every update call. */ - AZ::Vector3 mPosition; /**< The camera position. */ - AZ::Vector2 mOrthoClipDimensions; /**< A two component vector which defines the distance to the left (x component) and to the top (y component) from the view origin. */ - float mFOV; /**< The vertical field-of-view in degrees. */ - float mNearClipDistance; /**< Distance to the near clipping plane. */ - float mFarClipDistance; /**< Distance to the far clipping plane. */ - float mAspect; /**< x/y viewport ratio. */ - float mRotationSpeed; /**< The angle in degrees that will be applied to the current rotation when the mouse is moving one pixel. */ - float mTranslationSpeed; /**< The value that will be applied to the current camera position when moving the mouse one pixel. */ - ProjectionMode mProjectionMode; /**< The projection mode. The camera supports either perspective or orthographic projection. */ - uint32 mScreenWidth; /**< The screen width in pixels where the camera is used. */ - uint32 mScreenHeight; /**< The screen height in pixels where the camera is used. */ + AZ::Matrix4x4 m_projectionMatrix; /**< The projection matrix. */ + AZ::Matrix4x4 m_viewMatrix; /**< The view matrix. */ + AZ::Matrix4x4 m_viewProjMatrix; /**< ViewMatrix * projectionMatrix. Will be recalculated every update call. */ + AZ::Vector3 m_position; /**< The camera position. */ + AZ::Vector2 m_orthoClipDimensions; /**< A two component vector which defines the distance to the left (x component) and to the top (y component) from the view origin. */ + float m_fov; /**< The vertical field-of-view in degrees. */ + float m_nearClipDistance; /**< Distance to the near clipping plane. */ + float m_farClipDistance; /**< Distance to the far clipping plane. */ + float m_aspect; /**< x/y viewport ratio. */ + float m_rotationSpeed; /**< The angle in degrees that will be applied to the current rotation when the mouse is moving one pixel. */ + float m_translationSpeed; /**< The value that will be applied to the current camera position when moving the mouse one pixel. */ + ProjectionMode m_projectionMode; /**< The projection mode. The camera supports either perspective or orthographic projection. */ + uint32 m_screenWidth; /**< The screen width in pixels where the camera is used. */ + uint32 m_screenHeight; /**< The screen height in pixels where the camera is used. */ }; // include inline code diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.inl b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.inl index c6947576d3..43e2ce6fbd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/Camera.inl @@ -12,139 +12,139 @@ // set the camera position MCORE_INLINE void Camera::SetPosition(const AZ::Vector3& position) { - mPosition = position; + m_position = position; } // get the camera position MCORE_INLINE const AZ::Vector3& Camera::GetPosition() const { - return mPosition; + return m_position; } // set the projection type MCORE_INLINE void Camera::SetProjectionMode(ProjectionMode projectionMode) { - mProjectionMode = projectionMode; + m_projectionMode = projectionMode; } // get the projection type MCORE_INLINE Camera::ProjectionMode Camera::GetProjectionMode() const { - return mProjectionMode; + return m_projectionMode; } // set the clip dimensions for the orthographic projection mode MCORE_INLINE void Camera::SetOrthoClipDimensions(const AZ::Vector2& clipDimensions) { - mOrthoClipDimensions = clipDimensions; + m_orthoClipDimensions = clipDimensions; } // set the screen dimensions where this camera is used in MCORE_INLINE void Camera::SetScreenDimensions(uint32 width, uint32 height) { - mScreenWidth = width; - mScreenHeight = height; + m_screenWidth = width; + m_screenHeight = height; } // set the field of view in degrees MCORE_INLINE void Camera::SetFOV(float fieldOfView) { - mFOV = fieldOfView; + m_fov = fieldOfView; } // set near clip plane distance MCORE_INLINE void Camera::SetNearClipDistance(float nearClipDistance) { - mNearClipDistance = nearClipDistance; + m_nearClipDistance = nearClipDistance; } // set far clip plane distance MCORE_INLINE void Camera::SetFarClipDistance(float farClipDistance) { - mFarClipDistance = farClipDistance; + m_farClipDistance = farClipDistance; } // set the aspect ratio - the aspect ratio is calculated by width/height MCORE_INLINE void Camera::SetAspectRatio(float aspect) { - mAspect = aspect; + m_aspect = aspect; } // return the field of view in degrees MCORE_INLINE float Camera::GetFOV() const { - return mFOV; + return m_fov; } // return the near clip plane distance MCORE_INLINE float Camera::GetNearClipDistance() const { - return mNearClipDistance; + return m_nearClipDistance; } // return the far clip plane distance MCORE_INLINE float Camera::GetFarClipDistance() const { - return mFarClipDistance; + return m_farClipDistance; } // return the aspect ratio MCORE_INLINE float Camera::GetAspectRatio() const { - return mAspect; + return m_aspect; } // get the translation speed MCORE_INLINE float Camera::GetTranslationSpeed() const { - return mTranslationSpeed; + return m_translationSpeed; } // set the translation speed MCORE_INLINE void Camera::SetTranslationSpeed(float translationSpeed) { - mTranslationSpeed = translationSpeed; + m_translationSpeed = translationSpeed; } // get the rotation speed in degrees MCORE_INLINE float Camera::GetRotationSpeed() const { - return mRotationSpeed; + return m_rotationSpeed; } // set the rotation speed in degrees MCORE_INLINE void Camera::SetRotationSpeed(float rotationSpeed) { - mRotationSpeed = rotationSpeed; + m_rotationSpeed = rotationSpeed; } // Get the screen width. MCORE_INLINE uint32 Camera::GetScreenWidth() { - return mScreenWidth; + return m_screenWidth; } // Get the screen height MCORE_INLINE uint32 Camera::GetScreenHeight() { - return mScreenHeight; + return m_screenHeight; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.cpp index cebfc350b1..112d3c1dc1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.cpp @@ -32,20 +32,20 @@ namespace MCommon MCORE_UNUSED(timeDelta); // lock pitching to [-90.0°, 90.0°] - if (mPitch < -90.0f + 0.1f) + if (m_pitch < -90.0f + 0.1f) { - mPitch = -90.0f + 0.1f; + m_pitch = -90.0f + 0.1f; } - if (mPitch > 90.0f - 0.1f) + if (m_pitch > 90.0f - 0.1f) { - mPitch = 90.0f - 0.1f; + m_pitch = 90.0f - 0.1f; } // calculate the camera direction vector based on the yaw and pitch - AZ::Vector3 direction = (AZ::Matrix4x4::CreateRotationX(MCore::Math::DegreesToRadians(mPitch)) * AZ::Matrix4x4::CreateRotationY(MCore::Math::DegreesToRadians(mYaw))) * (AZ::Vector3(0.0f, 0.0f, 1.0f)).GetNormalized(); + AZ::Vector3 direction = (AZ::Matrix4x4::CreateRotationX(MCore::Math::DegreesToRadians(m_pitch)) * AZ::Matrix4x4::CreateRotationY(MCore::Math::DegreesToRadians(m_yaw))) * (AZ::Vector3(0.0f, 0.0f, 1.0f)).GetNormalized(); // look from the camera position into the newly calculated direction - MCore::LookAt(mViewMatrix, mPosition, mPosition + direction * 10.0f, AZ::Vector3(0.0f, 1.0f, 0.0f)); + MCore::LookAt(m_viewMatrix, m_position, m_position + direction * 10.0f, AZ::Vector3(0.0f, 1.0f, 0.0f)); // update our base camera Camera::Update(); @@ -62,7 +62,7 @@ namespace MCommon EKeyboardButtonState buttonState = (EKeyboardButtonState)keyboardKeyFlags; - AZ::Matrix4x4 transposedViewMatrix(mViewMatrix); + AZ::Matrix4x4 transposedViewMatrix(m_viewMatrix); transposedViewMatrix.Transpose(); // get the movement direction vector based on the keyboard input @@ -95,14 +95,14 @@ namespace MCommon // only move the camera when the delta movement is not the zero vector if (MCore::SafeLength(deltaMovement) > MCore::Math::epsilon) { - mPosition += deltaMovement.GetNormalized() * mTranslationSpeed; + m_position += deltaMovement.GetNormalized() * m_translationSpeed; } // rotate the camera if (buttonState & ENABLE_MOUSELOOK) { - mYaw += mouseMovementX * mRotationSpeed; - mPitch += mouseMovementY * mRotationSpeed; + m_yaw += mouseMovementX * m_rotationSpeed; + m_pitch += mouseMovementY * m_rotationSpeed; } } @@ -115,8 +115,8 @@ namespace MCommon // reset the base class attributes Camera::Reset(); - mPitch = 0.0f; - mYaw = 0.0f; - mRoll = 0.0f; + m_pitch = 0.0f; + m_yaw = 0.0f; + m_roll = 0.0f; } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.h index 54addd0bc4..e0abe7922c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/FirstPersonCamera.h @@ -60,37 +60,37 @@ namespace MCommon * Set the pitch angle in degrees. Looking up and down is limited to 90°. (0=Straight Ahead, +Up, -Down) * @param The pitch angle in degrees, range[-90.0°, 90.0°]. */ - MCORE_INLINE void SetPitch(float pitch) { mPitch = pitch; } + MCORE_INLINE void SetPitch(float pitch) { m_pitch = pitch; } /** * Set the yaw angle in degrees. Vertical rotation. (0=East, +North, -South). * @param yaw The yaw angle in degrees. */ - MCORE_INLINE void SetYaw(float yaw) { mYaw = yaw; } + MCORE_INLINE void SetYaw(float yaw) { m_yaw = yaw; } /** * Set the roll angle in degrees. Rotation around the direction axis (0=Straight, +Clockwise, -CCW). * @param roll The roll angle in degrees. */ - MCORE_INLINE void SetRoll(float roll) { mRoll = roll; } + MCORE_INLINE void SetRoll(float roll) { m_roll = roll; } /** * Get the pitch angle in degrees. Looking up and down is limited to 90°. (0=Straight Ahead, +Up, -Down) * @return The pitch angle in degrees, range[-90.0°, 90.0°]. */ - MCORE_INLINE float GetPitch() const { return mPitch; } + MCORE_INLINE float GetPitch() const { return m_pitch; } /** * Get the yaw angle in degrees. Vertical rotation. (0=East, +North, -South). * @return The yaw angle in degrees. */ - MCORE_INLINE float GetYaw() const { return mYaw; } + MCORE_INLINE float GetYaw() const { return m_yaw; } /** * Get the roll angle in degrees. Rotation around the direction axis (0=Straight, +Clockwise, -CCW). * @return The roll angle in degrees. */ - MCORE_INLINE float GetRoll() const { return mRoll; } + MCORE_INLINE float GetRoll() const { return m_roll; } /** * Update the camera transformation. @@ -119,9 +119,9 @@ namespace MCommon void Reset(float flightTime = 0.0f); private: - float mPitch; /**< Up and down. (0=straight ahead, +up, -down) */ - float mYaw; /**< Steering. (0=east, +north, -south) */ - float mRoll; /**< Rotation around axis of screen. (0=straight, +clockwise, -CCW) */ + float m_pitch; /**< Up and down. (0=straight ahead, +up, -down) */ + float m_yaw; /**< Steering. (0=east, +north, -south) */ + float m_roll; /**< Rotation around axis of screen. (0=straight, +clockwise, -CCW) */ }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.cpp index 9cb0355ca0..1599433f9e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.cpp @@ -29,8 +29,8 @@ namespace MCommon // look at target void LookAtCamera::LookAt(const AZ::Vector3& target, const AZ::Vector3& up) { - mTarget = target; - mUp = up; + m_target = target; + m_up = up; } @@ -39,7 +39,7 @@ namespace MCommon { MCORE_UNUSED(timeDelta); - MCore::LookAtRH(mViewMatrix, mPosition, mTarget, mUp); + MCore::LookAtRH(m_viewMatrix, m_position, m_target, m_up); // update our base camera at the very end Camera::Update(); @@ -53,6 +53,6 @@ namespace MCommon // reset the base class attributes Camera::Reset(); - mUp.Set(0.0f, 0.0f, 1.0f); + m_up.Set(0.0f, 0.0f, 1.0f); } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.h index 00b86e3b05..e17fe65985 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/LookAtCamera.h @@ -66,29 +66,29 @@ namespace MCommon * Set the target position. Note that the camera needs an update after setting a new target. * @param[in] target The new camera target. */ - MCORE_INLINE void SetTarget(const AZ::Vector3& target) { mTarget = target; } + MCORE_INLINE void SetTarget(const AZ::Vector3& target) { m_target = target; } /** * Get the target position. * @return The current camera target. */ - MCORE_INLINE AZ::Vector3 GetTarget() const { return mTarget; } + MCORE_INLINE AZ::Vector3 GetTarget() const { return m_target; } /** * Set the up vector for the camera. Note that the camera needs an update after setting a new up vector. * @param[in] up The new camera up vector. */ - MCORE_INLINE void SetUp(const AZ::Vector3& up) { mUp = up; } + MCORE_INLINE void SetUp(const AZ::Vector3& up) { m_up = up; } /** * Get the camera up vector. * @return The current up vector. */ - MCORE_INLINE AZ::Vector3 GetUp() const { return mUp; } + MCORE_INLINE AZ::Vector3 GetUp() const { return m_up; } protected: - AZ::Vector3 mTarget; /**< The camera target. */ - AZ::Vector3 mUp; /**< The up vector of the camera. */ + AZ::Vector3 m_target; /**< The camera target. */ + AZ::Vector3 m_up; /**< The up vector of the camera. */ }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.cpp index 471d4439c6..7a2769ea4d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.cpp @@ -33,32 +33,32 @@ namespace MCommon // reset the parent class attributes LookAtCamera::Reset(); - mMinDistance = mNearClipDistance; - mMaxDistance = mFarClipDistance * 0.5f; - mPosition = AZ::Vector3::CreateZero(); - mPositionDelta = AZ::Vector2(0.0f, 0.0f); + m_minDistance = m_nearClipDistance; + m_maxDistance = m_farClipDistance * 0.5f; + m_position = AZ::Vector3::CreateZero(); + m_positionDelta = AZ::Vector2(0.0f, 0.0f); if (flightTime < MCore::Math::epsilon) { - mFlightActive = false; - mCurrentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); - mAlpha = GetDefaultAlpha(); - mBeta = GetDefaultBeta(); - mTarget = AZ::Vector3::CreateZero(); + m_flightActive = false; + m_currentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); + m_alpha = GetDefaultAlpha(); + m_beta = GetDefaultBeta(); + m_target = AZ::Vector3::CreateZero(); } else { - mFlightActive = true; - mFlightMaxTime = flightTime; - mFlightCurrentTime = 0.0f; - mFlightSourceDistance = mCurrentDistance; - mFlightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); - mFlightSourcePosition = mTarget; - mFlightTargetPosition = AZ::Vector3::CreateZero(); - mFlightSourceAlpha = mAlpha; - mFlightTargetAlpha = GetDefaultAlpha(); - mFlightSourceBeta = mBeta; - mFlightTargetBeta = GetDefaultBeta(); + m_flightActive = true; + m_flightMaxTime = flightTime; + m_flightCurrentTime = 0.0f; + m_flightSourceDistance = m_currentDistance; + m_flightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); + m_flightSourcePosition = m_target; + m_flightTargetPosition = AZ::Vector3::CreateZero(); + m_flightSourceAlpha = m_alpha; + m_flightTargetAlpha = GetDefaultAlpha(); + m_flightSourceBeta = m_beta; + m_flightTargetBeta = GetDefaultBeta(); } } @@ -66,53 +66,53 @@ namespace MCommon // update limits void OrbitCamera::AutoUpdateLimits() { - mMinDistance = mNearClipDistance; - mMaxDistance = mFarClipDistance * 0.5f; + m_minDistance = m_nearClipDistance; + m_maxDistance = m_farClipDistance * 0.5f; } void OrbitCamera::StartFlight(float distance, const AZ::Vector3& position, float alpha, float beta, float flightTime) { - mFlightActive = true; - mFlightMaxTime = flightTime; - mFlightCurrentTime = 0.0f; - mFlightSourceDistance = mCurrentDistance; - mFlightSourcePosition = mTarget; - mFlightTargetDistance = distance; - mFlightTargetPosition = position; - mFlightSourceAlpha = mAlpha; - mFlightTargetAlpha = alpha; - mFlightSourceBeta = mBeta; - mFlightTargetBeta = beta; + m_flightActive = true; + m_flightMaxTime = flightTime; + m_flightCurrentTime = 0.0f; + m_flightSourceDistance = m_currentDistance; + m_flightSourcePosition = m_target; + m_flightTargetDistance = distance; + m_flightTargetPosition = position; + m_flightSourceAlpha = m_alpha; + m_flightTargetAlpha = alpha; + m_flightSourceBeta = m_beta; + m_flightTargetBeta = beta; } // closeup view of the given bounding box void OrbitCamera::ViewCloseup(const MCore::AABB& boundingBox, float flightTime) { - mFlightActive = true; - mFlightMaxTime = flightTime; - mFlightCurrentTime = 0.0f; - mFlightSourceDistance = mCurrentDistance; - mFlightSourcePosition = mTarget; - const float distanceHorizontalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(mFOV)); - const float distanceVerticalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(mFOV * mAspect)); - mFlightTargetDistance = MCore::Max(distanceHorizontalFOV, distanceVerticalFOV) * 0.9f; - mFlightTargetPosition = boundingBox.CalcMiddle(); - mFlightSourceAlpha = mAlpha; - mFlightSourceAlpha = mAlpha; - mFlightTargetAlpha = GetDefaultAlpha(); - mFlightSourceBeta = mBeta; - mFlightTargetBeta = GetDefaultBeta(); + m_flightActive = true; + m_flightMaxTime = flightTime; + m_flightCurrentTime = 0.0f; + m_flightSourceDistance = m_currentDistance; + m_flightSourcePosition = m_target; + const float distanceHorizontalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(m_fov)); + const float distanceVerticalFOV = boundingBox.CalcRadius() / MCore::Math::Tan(0.5f * MCore::Math::DegreesToRadians(m_fov * m_aspect)); + m_flightTargetDistance = MCore::Max(distanceHorizontalFOV, distanceVerticalFOV) * 0.9f; + m_flightTargetPosition = boundingBox.CalcMiddle(); + m_flightSourceAlpha = m_alpha; + m_flightSourceAlpha = m_alpha; + m_flightTargetAlpha = GetDefaultAlpha(); + m_flightSourceBeta = m_beta; + m_flightTargetBeta = GetDefaultBeta(); // make sure the target flight distance is in range - if (mFlightTargetDistance < mMinDistance) + if (m_flightTargetDistance < m_minDistance) { - mFlightTargetDistance = mMinDistance; + m_flightTargetDistance = m_minDistance; } - if (mFlightTargetDistance > mMaxDistance) + if (m_flightTargetDistance > m_maxDistance) { - mFlightTargetDistance = mMaxDistance; + m_flightTargetDistance = m_maxDistance; } } @@ -127,24 +127,24 @@ namespace MCommon if (leftButtonPressed && rightButtonPressed == false && middleButtonPressed == false) { // rotate our camera - mAlpha += mRotationSpeed * (float)-mouseMovementX; - mBeta += mRotationSpeed * (float) mouseMovementY; + m_alpha += m_rotationSpeed * (float)-mouseMovementX; + m_beta += m_rotationSpeed * (float) mouseMovementY; // prevent the camera from looking upside down - if (mBeta >= 90.0f - 0.01f) + if (m_beta >= 90.0f - 0.01f) { - mBeta = 90.0f - 0.01f; + m_beta = 90.0f - 0.01f; } - if (mBeta <= -90.0f + 0.01f) + if (m_beta <= -90.0f + 0.01f) { - mBeta = -90.0f + 0.01f; + m_beta = -90.0f + 0.01f; } // reset the camera to no rotation if we made a whole circle - if (mAlpha >= 360.0f || mAlpha <= -360.0f) + if (m_alpha >= 360.0f || m_alpha <= -360.0f) { - mAlpha = 0.0f; + m_alpha = 0.0f; } } @@ -152,8 +152,8 @@ namespace MCommon // zoom camera in or out if (leftButtonPressed == false && rightButtonPressed && middleButtonPressed == false) { - const float distanceScale = mCurrentDistance * 0.002f; - mCurrentDistance += (float)-mouseMovementY * distanceScale; + const float distanceScale = m_currentDistance * 0.002f; + m_currentDistance += (float)-mouseMovementY * distanceScale; } // is middle (or left+right) mouse button pressed? @@ -161,13 +161,13 @@ namespace MCommon if ((leftButtonPressed == false && rightButtonPressed == false && middleButtonPressed) || (leftButtonPressed && rightButtonPressed && middleButtonPressed == false)) { - const float distanceScale = mCurrentDistance * 0.002f; + const float distanceScale = m_currentDistance * 0.002f; //if (MCore::GetCoordinateSystem().IsRightHanded()) //distanceScale *= -1.0f; - mPositionDelta.SetX((float)mouseMovementX * distanceScale); - mPositionDelta.SetY((float)mouseMovementY * distanceScale); + m_positionDelta.SetX((float)mouseMovementX * distanceScale); + m_positionDelta.SetY((float)mouseMovementY * distanceScale); } } @@ -175,59 +175,59 @@ namespace MCommon // update the camera void OrbitCamera::Update(float timeDelta) { - if (mFlightActive) + if (m_flightActive) { - mFlightCurrentTime += timeDelta; + m_flightCurrentTime += timeDelta; - const float normalizedTime = mFlightCurrentTime / mFlightMaxTime; + const float normalizedTime = m_flightCurrentTime / m_flightMaxTime; const float interpolatedTime = MCore::CosineInterpolate(0.0f, 1.0f, normalizedTime); - mTarget = mFlightSourcePosition + (mFlightTargetPosition - mFlightSourcePosition) * interpolatedTime; - mCurrentDistance = mFlightSourceDistance + (mFlightTargetDistance - mFlightSourceDistance) * interpolatedTime; - mAlpha = mFlightSourceAlpha + (mFlightTargetAlpha - mFlightSourceAlpha) * interpolatedTime; - mBeta = mFlightSourceBeta + (mFlightTargetBeta - mFlightSourceBeta) * interpolatedTime; + m_target = m_flightSourcePosition + (m_flightTargetPosition - m_flightSourcePosition) * interpolatedTime; + m_currentDistance = m_flightSourceDistance + (m_flightTargetDistance - m_flightSourceDistance) * interpolatedTime; + m_alpha = m_flightSourceAlpha + (m_flightTargetAlpha - m_flightSourceAlpha) * interpolatedTime; + m_beta = m_flightSourceBeta + (m_flightTargetBeta - m_flightSourceBeta) * interpolatedTime; - if (mFlightCurrentTime >= mFlightMaxTime) + if (m_flightCurrentTime >= m_flightMaxTime) { - mFlightActive = false; - mTarget = mFlightTargetPosition; - mCurrentDistance = mFlightTargetDistance; - mAlpha = mFlightTargetAlpha; - mBeta = mFlightTargetBeta; + m_flightActive = false; + m_target = m_flightTargetPosition; + m_currentDistance = m_flightTargetDistance; + m_alpha = m_flightTargetAlpha; + m_beta = m_flightTargetBeta; } } // HACK TODO REMOVEME !!! const float scale = 1.0f; - mCurrentDistance *= scale; + m_currentDistance *= scale; - if (mCurrentDistance <= mMinDistance * scale) + if (m_currentDistance <= m_minDistance * scale) { - mCurrentDistance = mMinDistance * scale; + m_currentDistance = m_minDistance * scale; } - if (mCurrentDistance >= mMaxDistance * scale) + if (m_currentDistance >= m_maxDistance * scale) { - mCurrentDistance = mMaxDistance * scale; + m_currentDistance = m_maxDistance * scale; } // calculate unit direction vector based on our two angles AZ::Vector3 unitSphereVector; - unitSphereVector.SetX(MCore::Math::Cos(MCore::Math::DegreesToRadians(mAlpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(mBeta))); - unitSphereVector.SetY(MCore::Math::Sin(MCore::Math::DegreesToRadians(mAlpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(mBeta))); - unitSphereVector.SetZ(MCore::Math::Sin(MCore::Math::DegreesToRadians(mBeta))); + unitSphereVector.SetX(MCore::Math::Cos(MCore::Math::DegreesToRadians(m_alpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(m_beta))); + unitSphereVector.SetY(MCore::Math::Sin(MCore::Math::DegreesToRadians(m_alpha)) * MCore::Math::Cos(MCore::Math::DegreesToRadians(m_beta))); + unitSphereVector.SetZ(MCore::Math::Sin(MCore::Math::DegreesToRadians(m_beta))); // calculate the right and the up vector based on the direction vector AZ::Vector3 rightVec = unitSphereVector.Cross(AZ::Vector3(0.0f, 0.0f, 1.0f)).GetNormalized(); AZ::Vector3 upVec = rightVec.Cross(unitSphereVector).GetNormalized(); // calculate the lookat target and the camera position using our rotation sphere vectors - mTarget += (rightVec * mPositionDelta.GetX()) * mTranslationSpeed + (upVec * mPositionDelta.GetY()) * mTranslationSpeed; - mPosition = mTarget + (unitSphereVector * mCurrentDistance); + m_target += (rightVec * m_positionDelta.GetX()) * m_translationSpeed + (upVec * m_positionDelta.GetY()) * m_translationSpeed; + m_position = m_target + (unitSphereVector * m_currentDistance); // reset the position delta - mPositionDelta = AZ::Vector2(0.0f, 0.0f); + m_positionDelta = AZ::Vector2(0.0f, 0.0f); // update our lookat camera at the very end LookAtCamera::Update(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.h index c3c33a3ef4..8aaa465da9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrbitCamera.h @@ -76,27 +76,27 @@ namespace MCommon void ViewCloseup(const MCore::AABB& boundingBox, float flightTime) override; void StartFlight(float distance, const AZ::Vector3& position, float alpha, float beta, float flightTime); - bool GetIsFlightActive() const { return mFlightActive; } - void SetFlightTargetPosition(const AZ::Vector3& targetPos) { mFlightTargetPosition = targetPos; } + bool GetIsFlightActive() const { return m_flightActive; } + void SetFlightTargetPosition(const AZ::Vector3& targetPos) { m_flightTargetPosition = targetPos; } float FlightTimeLeft() const { - if (mFlightActive == false) + if (m_flightActive == false) { return 0.0f; } - return mFlightMaxTime - mFlightCurrentTime; + return m_flightMaxTime - m_flightCurrentTime; } - MCORE_INLINE float GetCurrentDistance() const { return mCurrentDistance; } - void SetCurrentDistance(float distance) { mCurrentDistance = distance; } + MCORE_INLINE float GetCurrentDistance() const { return m_currentDistance; } + void SetCurrentDistance(float distance) { m_currentDistance = distance; } - MCORE_INLINE float GetAlpha() const { return mAlpha; } + MCORE_INLINE float GetAlpha() const { return m_alpha; } static float GetDefaultAlpha() { return 110.0f; } - void SetAlpha(float alpha) { mAlpha = alpha; } + void SetAlpha(float alpha) { m_alpha = alpha; } - MCORE_INLINE float GetBeta() const { return mBeta; } + MCORE_INLINE float GetBeta() const { return m_beta; } static float GetDefaultBeta() { return 20.0f; } - void SetBeta(float beta) { mBeta = beta; } + void SetBeta(float beta) { m_beta = beta; } // automatically updates the camera afterwards void Set(float alpha, float beta, float currentDistance, const AZ::Vector3& target); @@ -105,24 +105,24 @@ namespace MCommon private: - AZ::Vector2 mPositionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */ - float mMinDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */ - float mMaxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */ - float mCurrentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */ - float mAlpha; /**< The horizontal angle in our orbit sphere. */ - float mBeta; /**< The vertical angle in our orbit sphere. */ - - bool mFlightActive; - float mFlightMaxTime; - float mFlightCurrentTime; - float mFlightSourceDistance; - float mFlightTargetDistance; - AZ::Vector3 mFlightSourcePosition; - AZ::Vector3 mFlightTargetPosition; - float mFlightSourceAlpha; - float mFlightTargetAlpha; - float mFlightSourceBeta; - float mFlightTargetBeta; + AZ::Vector2 m_positionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */ + float m_minDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */ + float m_maxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */ + float m_currentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */ + float m_alpha; /**< The horizontal angle in our orbit sphere. */ + float m_beta; /**< The vertical angle in our orbit sphere. */ + + bool m_flightActive; + float m_flightMaxTime; + float m_flightCurrentTime; + float m_flightSourceDistance; + float m_flightTargetDistance; + AZ::Vector3 m_flightSourcePosition; + AZ::Vector3 m_flightTargetPosition; + float m_flightSourceAlpha; + float m_flightTargetAlpha; + float m_flightSourceBeta; + float m_flightTargetBeta; }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.cpp index 722f43c113..a64cdcc97f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.cpp @@ -21,7 +21,7 @@ namespace MCommon { Reset(); SetMode(viewMode); - mProjectionMode = PROJMODE_ORTHOGRAPHIC; + m_projectionMode = PROJMODE_ORTHOGRAPHIC; } @@ -34,50 +34,50 @@ namespace MCommon // update the camera position, orientation and it's matrices void OrthographicCamera::Update(float timeDelta) { - if (mFlightActive) + if (m_flightActive) { - mFlightCurrentTime += timeDelta; + m_flightCurrentTime += timeDelta; - const float normalizedTime = mFlightCurrentTime / mFlightMaxTime; + const float normalizedTime = m_flightCurrentTime / m_flightMaxTime; const float interpolatedTime = MCore::CosineInterpolate(0.0f, 1.0f, normalizedTime); - mPosition = mFlightSourcePosition + (mFlightTargetPosition - mFlightSourcePosition) * interpolatedTime; - mCurrentDistance = mFlightSourceDistance + (mFlightTargetDistance - mFlightSourceDistance) * interpolatedTime; + m_position = m_flightSourcePosition + (m_flightTargetPosition - m_flightSourcePosition) * interpolatedTime; + m_currentDistance = m_flightSourceDistance + (m_flightTargetDistance - m_flightSourceDistance) * interpolatedTime; - if (mFlightCurrentTime >= mFlightMaxTime) + if (m_flightCurrentTime >= m_flightMaxTime) { - mFlightActive = false; - mPosition = mFlightTargetPosition; - mCurrentDistance = mFlightTargetDistance; + m_flightActive = false; + m_position = m_flightTargetPosition; + m_currentDistance = m_flightTargetDistance; } } // HACK TODO REMOVEME !!! const float scale = 1.0f; - mCurrentDistance *= scale; + m_currentDistance *= scale; - if (mCurrentDistance <= mMinDistance * scale) + if (m_currentDistance <= m_minDistance * scale) { - mCurrentDistance = mMinDistance * scale; + m_currentDistance = m_minDistance * scale; } - if (mCurrentDistance >= mMaxDistance * scale) + if (m_currentDistance >= m_maxDistance * scale) { - mCurrentDistance = mMaxDistance * scale; + m_currentDistance = m_maxDistance * scale; } // fake zoom the orthographic camera const float orthoScale = scale * 0.001f; - const float deltaX = mCurrentDistance * mScreenWidth * orthoScale; - const float deltaY = mCurrentDistance * mScreenHeight * orthoScale; + const float deltaX = m_currentDistance * m_screenWidth * orthoScale; + const float deltaY = m_currentDistance * m_screenHeight * orthoScale; SetOrthoClipDimensions(AZ::Vector2(deltaX, deltaY)); // adjust the mouse delta movement so that one pixel mouse movement is exactly one pixel on screen - mPositionDelta.SetX(mPositionDelta.GetX() * mCurrentDistance * orthoScale); - mPositionDelta.SetY(mPositionDelta.GetY() * mCurrentDistance * orthoScale); + m_positionDelta.SetX(m_positionDelta.GetX() * m_currentDistance * orthoScale); + m_positionDelta.SetY(m_positionDelta.GetY() * m_currentDistance * orthoScale); AZ::Vector3 xAxis, yAxis, zAxis; - switch (mMode) + switch (m_mode) { case VIEWMODE_FRONT: { @@ -86,11 +86,11 @@ namespace MCommon zAxis = AZ::Vector3(0.0f, 1.0f, 0.0f); // depth axis // translate the camera - mPosition += xAxis * -mPositionDelta.GetX(); - mPosition += yAxis * mPositionDelta.GetY(); + m_position += xAxis * -m_positionDelta.GetX(); + m_position += yAxis * m_positionDelta.GetY(); // setup the view matrix - MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis); + MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis); break; } @@ -101,11 +101,11 @@ namespace MCommon zAxis = AZ::Vector3(0.0f, -1.0f, 0.0f); // depth axis // translate the camera - mPosition += xAxis * -mPositionDelta.GetX(); - mPosition += yAxis * mPositionDelta.GetY(); + m_position += xAxis * -m_positionDelta.GetX(); + m_position += yAxis * m_positionDelta.GetY(); // setup the view matrix - MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis); + MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis); break; } @@ -117,11 +117,11 @@ namespace MCommon zAxis = AZ::Vector3(-1.0f, 0.0f, 0.0f); // depth axis // translate the camera - mPosition += xAxis * mPositionDelta.GetX(); - mPosition += yAxis * mPositionDelta.GetY(); + m_position += xAxis * m_positionDelta.GetX(); + m_position += yAxis * m_positionDelta.GetY(); // setup the view matrix - MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis); + MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis); break; } @@ -132,11 +132,11 @@ namespace MCommon zAxis = AZ::Vector3(1.0f, 0.0f, 0.0f); // depth axis // translate the camera - mPosition += xAxis * mPositionDelta.GetX(); - mPosition += yAxis * mPositionDelta.GetY(); + m_position += xAxis * m_positionDelta.GetX(); + m_position += yAxis * m_positionDelta.GetY(); // setup the view matrix - MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis); + MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis); break; } @@ -147,11 +147,11 @@ namespace MCommon zAxis = AZ::Vector3(0.0f, 0.0f, 1.0f); // depth axis // translate the camera - mPosition += -xAxis* mPositionDelta.GetX(); - mPosition += yAxis * mPositionDelta.GetY(); + m_position += -xAxis* m_positionDelta.GetX(); + m_position += yAxis * m_positionDelta.GetY(); // setup the view matrix - MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis); + MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis); break; } @@ -162,18 +162,18 @@ namespace MCommon zAxis = AZ::Vector3(0.0f, 0.0f, -1.0f); // depth axis // translate the camera - mPosition += -xAxis* mPositionDelta.GetX(); - mPosition += yAxis * mPositionDelta.GetY(); + m_position += -xAxis* m_positionDelta.GetX(); + m_position += yAxis * m_positionDelta.GetY(); // setup the view matrix - MCore::LookAtRH(mViewMatrix, mPosition + zAxis * mCurrentDistance, mPosition, yAxis); + MCore::LookAtRH(m_viewMatrix, m_position + zAxis * m_currentDistance, m_position, yAxis); break; } } ; // reset the position delta - mPositionDelta = AZ::Vector2(0.0f, 0.0f); + m_positionDelta = AZ::Vector2(0.0f, 0.0f); // update our base camera Camera::Update(); @@ -189,8 +189,8 @@ namespace MCommon // zoom camera in or out if (leftButtonPressed == false && rightButtonPressed && middleButtonPressed == false) { - const float distanceScale = mCurrentDistance * 0.002f; - mCurrentDistance += (float)-mouseMovementY * distanceScale; + const float distanceScale = m_currentDistance * 0.002f; + m_currentDistance += (float)-mouseMovementY * distanceScale; } // is middle (or left+right) mouse button pressed? @@ -198,8 +198,8 @@ namespace MCommon if ((leftButtonPressed == false && rightButtonPressed == false && middleButtonPressed) || (leftButtonPressed && rightButtonPressed && middleButtonPressed == false)) { - mPositionDelta.SetX((float)mouseMovementX); - mPositionDelta.SetY((float)mouseMovementY); + m_positionDelta.SetX((float)mouseMovementX); + m_positionDelta.SetY((float)mouseMovementY); } } @@ -207,41 +207,41 @@ namespace MCommon // reset the camera attributes void OrthographicCamera::Reset(float flightTime) { - mPositionDelta = AZ::Vector2(0.0f, 0.0f); - mMinDistance = MCore::Math::epsilon; - mMaxDistance = mFarClipDistance * 0.5f; + m_positionDelta = AZ::Vector2(0.0f, 0.0f); + m_minDistance = MCore::Math::epsilon; + m_maxDistance = m_farClipDistance * 0.5f; AZ::Vector3 resetPosition(0.0f, 0.0f, 0.0f); - switch (mMode) + switch (m_mode) { case VIEWMODE_FRONT: { - resetPosition.SetY(mCurrentDistance); + resetPosition.SetY(m_currentDistance); break; } case VIEWMODE_BACK: { - resetPosition.SetY(-mCurrentDistance); + resetPosition.SetY(-m_currentDistance); break; } case VIEWMODE_LEFT: { - resetPosition.SetX(-mCurrentDistance); + resetPosition.SetX(-m_currentDistance); break; } case VIEWMODE_RIGHT: { - resetPosition.SetX(mCurrentDistance); + resetPosition.SetX(m_currentDistance); break; } case VIEWMODE_TOP: { - resetPosition.SetZ(mCurrentDistance); + resetPosition.SetZ(m_currentDistance); break; } case VIEWMODE_BOTTOM: { - resetPosition.SetZ(-mCurrentDistance); + resetPosition.SetZ(-m_currentDistance); break; } } @@ -249,19 +249,19 @@ namespace MCommon if (flightTime < MCore::Math::epsilon) { - mFlightActive = false; - mCurrentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); - mPosition = resetPosition; + m_flightActive = false; + m_currentDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); + m_position = resetPosition; } else { - mFlightActive = true; - mFlightMaxTime = flightTime; - mFlightCurrentTime = 0.0f; - mFlightSourceDistance = mCurrentDistance; - mFlightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); - mFlightSourcePosition = mPosition; - mFlightTargetPosition = resetPosition; + m_flightActive = true; + m_flightMaxTime = flightTime; + m_flightCurrentTime = 0.0f; + m_flightSourceDistance = m_currentDistance; + m_flightTargetDistance = (float)MCore::Distance::ConvertValue(5.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); + m_flightSourcePosition = m_position; + m_flightTargetPosition = resetPosition; } // reset the base class attributes @@ -271,22 +271,22 @@ namespace MCommon void OrthographicCamera::StartFlight(float distance, const AZ::Vector3& position, float flightTime) { - mFlightMaxTime = flightTime; - mFlightCurrentTime = 0.0f; - mFlightSourceDistance = mCurrentDistance; - mFlightSourcePosition = mPosition; + m_flightMaxTime = flightTime; + m_flightCurrentTime = 0.0f; + m_flightSourceDistance = m_currentDistance; + m_flightSourcePosition = m_position; if (flightTime < MCore::Math::epsilon) { - mFlightActive = false; - mCurrentDistance = distance; - mPosition = position; + m_flightActive = false; + m_currentDistance = distance; + m_position = position; } else { - mFlightActive = true; - mFlightTargetDistance = distance; - mFlightTargetPosition = position; + m_flightActive = true; + m_flightTargetDistance = distance; + m_flightTargetPosition = position; } } @@ -294,14 +294,14 @@ namespace MCommon // closeup view of the given bounding box void OrthographicCamera::ViewCloseup(const MCore::AABB& boundingBox, float flightTime) { - mFlightMaxTime = flightTime; - mFlightCurrentTime = 0.0f; - mFlightSourceDistance = mCurrentDistance; - mFlightSourcePosition = mPosition; + m_flightMaxTime = flightTime; + m_flightCurrentTime = 0.0f; + m_flightSourceDistance = m_currentDistance; + m_flightSourcePosition = m_position; float boxWidth = 0.0f; float boxHeight = 0.0f; - switch (mMode) + switch (m_mode) { case VIEWMODE_FRONT: { @@ -343,32 +343,32 @@ namespace MCommon ; const float orthoScale = 0.001f; - assert(mScreenWidth != 0 && mScreenHeight != 0); - const float distanceX = (boxWidth) / (mScreenWidth * orthoScale); - const float distanceY = (boxHeight) / (mScreenHeight * orthoScale); + assert(m_screenWidth != 0 && m_screenHeight != 0); + const float distanceX = (boxWidth) / (m_screenWidth * orthoScale); + const float distanceY = (boxHeight) / (m_screenHeight * orthoScale); //LOG("box: x=%f y=%f, boxAspect=%f, orthoAspect=%f, distX=%f, distY=%f", boxWidth, boxHeight, boxAspect, orthoAspect, distanceX, distanceY); if (flightTime < MCore::Math::epsilon) { - mFlightActive = false; - mCurrentDistance = MCore::Max(distanceX, distanceY) * 1.1f; - mPosition = boundingBox.CalcMiddle(); + m_flightActive = false; + m_currentDistance = MCore::Max(distanceX, distanceY) * 1.1f; + m_position = boundingBox.CalcMiddle(); } else { - mFlightActive = true; - mFlightTargetDistance = MCore::Max(distanceX, distanceY) * 1.1f; - mFlightTargetPosition = boundingBox.CalcMiddle(); + m_flightActive = true; + m_flightTargetDistance = MCore::Max(distanceX, distanceY) * 1.1f; + m_flightTargetPosition = boundingBox.CalcMiddle(); } // make sure the target flight distance is in range - if (mFlightTargetDistance < mMinDistance) + if (m_flightTargetDistance < m_minDistance) { - mFlightTargetDistance = mMinDistance; + m_flightTargetDistance = m_minDistance; } - if (mFlightTargetDistance > mMaxDistance) + if (m_flightTargetDistance > m_maxDistance) { - mFlightTargetDistance = mMaxDistance; + m_flightTargetDistance = m_maxDistance; } } @@ -376,7 +376,7 @@ namespace MCommon // get the type identification string const char* OrthographicCamera::GetTypeString() const { - switch (mMode) + switch (m_mode) { case VIEWMODE_FRONT: { @@ -419,8 +419,8 @@ namespace MCommon // unproject screen coordinates to a ray MCore::Ray OrthographicCamera::Unproject(int32 screenX, int32 screenY) { - AZ::Vector3 start = MCore::UnprojectOrtho(static_cast(screenX), static_cast(screenY), static_cast(mScreenWidth), static_cast(mScreenHeight), -1.0f, mProjectionMatrix, mViewMatrix); - AZ::Vector3 end = MCore::UnprojectOrtho(static_cast(screenX), static_cast(screenY), static_cast(mScreenWidth), static_cast(mScreenHeight), 1.0f, mProjectionMatrix, mViewMatrix); + AZ::Vector3 start = MCore::UnprojectOrtho(static_cast(screenX), static_cast(screenY), static_cast(m_screenWidth), static_cast(m_screenHeight), -1.0f, m_projectionMatrix, m_viewMatrix); + AZ::Vector3 end = MCore::UnprojectOrtho(static_cast(screenX), static_cast(screenY), static_cast(m_screenWidth), static_cast(m_screenHeight), 1.0f, m_projectionMatrix, m_viewMatrix); return MCore::Ray(start, end); } @@ -429,7 +429,7 @@ namespace MCommon // update limits void OrthographicCamera::AutoUpdateLimits() { - mMinDistance = mNearClipDistance; - mMaxDistance = mFarClipDistance * 0.5f; + m_minDistance = m_nearClipDistance; + m_maxDistance = m_farClipDistance * 0.5f; } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.h index 4fc1b47778..e735cc22bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/OrthographicCamera.h @@ -60,8 +60,8 @@ namespace MCommon */ const char* GetTypeString() const override; - MCORE_INLINE void SetMode(ViewMode viewMode) { mMode = viewMode; } - MCORE_INLINE ViewMode GetMode() const { return mMode; } + MCORE_INLINE void SetMode(ViewMode viewMode) { m_mode = viewMode; } + MCORE_INLINE ViewMode GetMode() const { return m_mode; } /** * Update the camera transformation. @@ -99,15 +99,15 @@ namespace MCommon void AutoUpdateLimits() override; void StartFlight(float distance, const AZ::Vector3& position, float flightTime); - bool GetIsFlightActive() const { return mFlightActive; } - void SetFlightTargetPosition(const AZ::Vector3& targetPos) { mFlightTargetPosition = targetPos; } + bool GetIsFlightActive() const { return m_flightActive; } + void SetFlightTargetPosition(const AZ::Vector3& targetPos) { m_flightTargetPosition = targetPos; } float FlightTimeLeft() const { - if (mFlightActive == false) + if (m_flightActive == false) { return 0.0f; } - return mFlightMaxTime - mFlightCurrentTime; + return m_flightMaxTime - m_flightCurrentTime; } /** @@ -118,22 +118,22 @@ namespace MCommon */ MCore::Ray Unproject(int32 screenX, int32 screenY) override; - MCORE_INLINE void SetCurrentDistance(float distance) { mCurrentDistance = distance; } - MCORE_INLINE float GetCurrentDistance() const { return mCurrentDistance; } + MCORE_INLINE void SetCurrentDistance(float distance) { m_currentDistance = distance; } + MCORE_INLINE float GetCurrentDistance() const { return m_currentDistance; } private: - ViewMode mMode; - AZ::Vector2 mPositionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */ - float mMinDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */ - float mMaxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */ - float mCurrentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */ - bool mFlightActive; - float mFlightMaxTime; - float mFlightCurrentTime; - float mFlightSourceDistance; - AZ::Vector3 mFlightSourcePosition; - float mFlightTargetDistance; - AZ::Vector3 mFlightTargetPosition; + ViewMode m_mode; + AZ::Vector2 m_positionDelta; /**< The position delta which will be applied to the camera position when calling update. After adjusting the position it will be reset again. */ + float m_minDistance; /**< The minimum distance from the orbit camera to its target in the orbit sphere. */ + float m_maxDistance; /**< The maximum distance from the orbit camera to its target in the orbit sphere. */ + float m_currentDistance; /**< The current distance from the orbit camera to its target in the orbit sphere. */ + bool m_flightActive; + float m_flightMaxTime; + float m_flightCurrentTime; + float m_flightSourceDistance; + AZ::Vector3 m_flightSourcePosition; + float m_flightTargetDistance; + AZ::Vector3 m_flightTargetPosition; }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp index 6301b0d7e3..183d56a07f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.cpp @@ -22,53 +22,51 @@ namespace MCommon { // gizmo colors - MCore::RGBAColor ManipulatorColors::mSelectionColor = MCore::RGBAColor(1.0f, 1.0f, 0.0f); - MCore::RGBAColor ManipulatorColors::mSelectionColorDarker = MCore::RGBAColor(0.5f, 0.5f, 0.0f, 0.5f); - MCore::RGBAColor ManipulatorColors::mRed = MCore::RGBAColor(0.781f, 0.0f, 0.0f); - MCore::RGBAColor ManipulatorColors::mGreen = MCore::RGBAColor(0.0f, 0.609f, 0.0f); - MCore::RGBAColor ManipulatorColors::mBlue = MCore::RGBAColor(0.0f, 0.0f, 0.762f); + MCore::RGBAColor ManipulatorColors::s_selectionColor = MCore::RGBAColor(1.0f, 1.0f, 0.0f); + MCore::RGBAColor ManipulatorColors::s_selectionColorDarker = MCore::RGBAColor(0.5f, 0.5f, 0.0f, 0.5f); + MCore::RGBAColor ManipulatorColors::s_red = MCore::RGBAColor(0.781f, 0.0f, 0.0f); + MCore::RGBAColor ManipulatorColors::s_green = MCore::RGBAColor(0.0f, 0.609f, 0.0f); + MCore::RGBAColor ManipulatorColors::s_blue = MCore::RGBAColor(0.0f, 0.0f, 0.762f); // static variables - uint32 RenderUtil::mNumMaxLineVertices = 8192 * 16;// 8096 * 16 * sizeof(LineVertex) = 3,5 MB - uint32 RenderUtil::mNumMaxMeshVertices = 1024; - uint32 RenderUtil::mNumMaxMeshIndices = 1024 * 3; - uint32 RenderUtil::mNumMax2DLines = 8192; - uint32 RenderUtil::mNumMaxTriangleVertices = 8192 * 16;// 8096 * 16 * sizeof(LineVertex) = 3,5 MB - float RenderUtil::m_wireframeSphereSegmentCount = 16.0f; + uint32 RenderUtil::s_numMaxLineVertices = 8192 * 16;// 8096 * 16 * sizeof(LineVertex) = 3,5 MB + uint32 RenderUtil::s_numMaxMeshVertices = 1024; + uint32 RenderUtil::s_numMaxMeshIndices = 1024 * 3; + uint32 RenderUtil::s_numMax2DLines = 8192; + uint32 RenderUtil::s_numMaxTriangleVertices = 8192 * 16;// 8096 * 16 * sizeof(LineVertex) = 3,5 MB + float RenderUtil::s_wireframeSphereSegmentCount = 16.0f; // constructor RenderUtil::RenderUtil() : m_devicePixelRatio(1.0f) { - mVertexBuffer = new LineVertex[mNumMaxLineVertices]; - m2DLines = new Line2D[mNumMax2DLines]; - mNumVertices = 0; - mNum2DLines = 0; - mUnitSphereMesh = CreateSphere(1.0f); - mCylinderMesh = CreateCylinder(2.0f, 1.0f, 2.0f); - mArrowHeadMesh = CreateArrowHead(1.0f, 0.5f); - mUnitCubeMesh = CreateCube(1.0f); - mFont = new VectorFont(this); - - mTriangleVertices.SetMemoryCategory(MEMCATEGORY_MCOMMON); + m_vertexBuffer = new LineVertex[s_numMaxLineVertices]; + m_m2DLines = new Line2D[s_numMax2DLines]; + m_numVertices = 0; + m_num2DLines = 0; + m_unitSphereMesh = CreateSphere(1.0f); + m_cylinderMesh = CreateCylinder(2.0f, 1.0f, 2.0f); + m_arrowHeadMesh = CreateArrowHead(1.0f, 0.5f); + m_unitCubeMesh = CreateCube(1.0f); + m_font = new VectorFont(this); } // destructor RenderUtil::~RenderUtil() { - delete[] mVertexBuffer; - delete[] m2DLines; - delete mUnitSphereMesh; - delete mCylinderMesh; - delete mUnitCubeMesh; - delete mArrowHeadMesh; - delete mFont; + delete[] m_vertexBuffer; + delete[] m_m2DLines; + delete m_unitSphereMesh; + delete m_cylinderMesh; + delete m_unitCubeMesh; + delete m_arrowHeadMesh; + delete m_font; // get rid of the world space positions - mWorldSpacePositions.clear(); + m_worldSpacePositions.clear(); } @@ -76,14 +74,14 @@ namespace MCommon void RenderUtil::RenderLines() { // check if we have to render anything and skip directly in case the line vertex buffer is empty - if (mNumVertices == 0) + if (m_numVertices == 0) { return; } // render the lines and reset the number of vertices - RenderLines(mVertexBuffer, mNumVertices); - mNumVertices = 0; + RenderLines(m_vertexBuffer, m_numVertices); + m_numVertices = 0; } @@ -91,14 +89,14 @@ namespace MCommon void RenderUtil::Render2DLines() { // check if we have to render anything and skip directly in case the line buffer is empty - if (mNum2DLines == 0) + if (m_num2DLines == 0) { return; } // render the lines and reset the number of lines - Render2DLines(m2DLines, mNum2DLines); - mNum2DLines = 0; + Render2DLines(m_m2DLines, m_num2DLines); + m_num2DLines = 0; } @@ -106,14 +104,14 @@ namespace MCommon void RenderUtil::RenderTriangles() { // check if we have to render anything and skip directly in case there are no triangles - if (mTriangleVertices.GetIsEmpty()) + if (m_triangleVertices.empty()) { return; } // render the triangles and clear the array - RenderTriangles(mTriangleVertices); - mTriangleVertices.Clear(false); + RenderTriangles(m_triangleVertices); + m_triangleVertices.clear(); } @@ -198,7 +196,7 @@ namespace MCommon // render the current bounding box of the given actor instance - void RenderUtil::RenderAABB(const MCore::AABB& box, const MCore::RGBAColor& color, bool directlyRender) + void RenderUtil::RenderAabb(const AZ::Aabb& box, const MCore::RGBAColor& color, bool directlyRender) { AZ::Vector3 min = box.GetMin(); AZ::Vector3 max = box.GetMax(); @@ -238,26 +236,28 @@ namespace MCommon // render selection gizmo around the given AABB - void RenderUtil::RenderSelection(const MCore::AABB& box, const MCore::RGBAColor& color, bool directlyRender) + void RenderUtil::RenderSelection(const AZ::Aabb& box, const MCore::RGBAColor& color, bool directlyRender) { - //const Vector3 center = box.CalcMiddle(); - const AZ::Vector3 min = box.GetMin();// + (box.GetMin()-center).Normalized()*0.005f; - const AZ::Vector3 max = box.GetMax();// + (box.GetMax()-center).Normalized()*0.005f; - const float scale = box.CalcRadius() * 0.1f; + const AZ::Vector3& min = box.GetMin(); + const AZ::Vector3& max = box.GetMax(); + const float radius = AZ::Vector3(box.GetMax() - box.GetMin()).GetLength() * 0.5f; + const float scale = radius * 0.1f; const AZ::Vector3 up = AZ::Vector3(0.0f, 1.0f, 0.0f) * scale; const AZ::Vector3 right = AZ::Vector3(1.0f, 0.0f, 0.0f) * scale; const AZ::Vector3 front = AZ::Vector3(0.0f, 0.0f, 1.0f) * scale; // generate our vertices - AZ::Vector3 p[8]; - p[0].Set(min.GetX(), min.GetY(), min.GetZ()); - p[1].Set(max.GetX(), min.GetY(), min.GetZ()); - p[2].Set(max.GetX(), min.GetY(), max.GetZ()); - p[3].Set(min.GetX(), min.GetY(), max.GetZ()); - p[4].Set(min.GetX(), max.GetY(), min.GetZ()); - p[5].Set(max.GetX(), max.GetY(), min.GetZ()); - p[6].Set(max.GetX(), max.GetY(), max.GetZ()); - p[7].Set(min.GetX(), max.GetY(), max.GetZ()); + const AZStd::array p + { + AZ::Vector3{min.GetX(), min.GetY(), min.GetZ()}, + AZ::Vector3{max.GetX(), min.GetY(), min.GetZ()}, + AZ::Vector3{max.GetX(), min.GetY(), max.GetZ()}, + AZ::Vector3{min.GetX(), min.GetY(), max.GetZ()}, + AZ::Vector3{min.GetX(), max.GetY(), min.GetZ()}, + AZ::Vector3{max.GetX(), max.GetY(), min.GetZ()}, + AZ::Vector3{max.GetX(), max.GetY(), max.GetZ()}, + AZ::Vector3{min.GetX(), max.GetY(), max.GetZ()}, + }; // render the box RenderLine(p[0], p[0] + up, color); @@ -302,75 +302,58 @@ namespace MCommon // constructor RenderUtil::AABBRenderSettings::AABBRenderSettings() { - mNodeBasedAABB = true; - mMeshBasedAABB = true; - mCollisionMeshBasedAABB = true; - mStaticBasedAABB = true; - mStaticBasedColor = MCore::RGBAColor(0.0f, 0.7f, 0.7f); - mNodeBasedColor = MCore::RGBAColor(1.0f, 0.0f, 0.0f); - mCollisionMeshBasedColor = MCore::RGBAColor(0.0f, 0.7f, 0.0f); - mMeshBasedColor = MCore::RGBAColor(0.0f, 0.0f, 0.7f); + m_nodeBasedAabb = true; + m_meshBasedAabb = true; + m_staticBasedAabb = true; + m_staticBasedColor = MCore::RGBAColor(0.0f, 0.7f, 0.7f); + m_nodeBasedColor = MCore::RGBAColor(1.0f, 0.0f, 0.0f); + m_meshBasedColor = MCore::RGBAColor(0.0f, 0.0f, 0.7f); } // render the given types of AABBs of a actor instance - void RenderUtil::RenderAABBs(EMotionFX::ActorInstance* actorInstance, const AABBRenderSettings& renderSettings, bool directlyRender) + void RenderUtil::RenderAabbs(EMotionFX::ActorInstance* actorInstance, const AABBRenderSettings& renderSettings, bool directlyRender) { - // get the current LOD level - const uint32 lodLevel = actorInstance->GetLODLevel(); - - // handle the collision mesh based AABB - if (renderSettings.mCollisionMeshBasedAABB) - { - // calculate the collision mesh based AABB - MCore::AABB box; - actorInstance->CalcCollisionMeshBasedAABB(lodLevel, &box); - - // render the aabb - if (box.CheckIfIsValid()) - { - RenderAABB(box, renderSettings.mCollisionMeshBasedColor); - } - } + const size_t lodLevel = actorInstance->GetLODLevel(); // handle the node based AABB - if (renderSettings.mNodeBasedAABB) + if (renderSettings.m_nodeBasedAabb) { // calculate the node based AABB - MCore::AABB box; - actorInstance->CalcNodeBasedAABB(&box); + AZ::Aabb box; + actorInstance->CalcNodeBasedAabb(&box); // render the aabb - if (box.CheckIfIsValid()) + if (box.IsValid()) { - RenderAABB(box, renderSettings.mNodeBasedColor); + RenderAabb(box, renderSettings.m_nodeBasedColor); } } // handle the mesh based AABB - if (renderSettings.mMeshBasedAABB) + if (renderSettings.m_meshBasedAabb) { // calculate the mesh based AABB - MCore::AABB box; - actorInstance->CalcMeshBasedAABB(lodLevel, &box); + AZ::Aabb box; + actorInstance->CalcMeshBasedAabb(lodLevel, &box); // render the aabb - if (box.CheckIfIsValid()) + if (box.IsValid()) { - RenderAABB(box, renderSettings.mMeshBasedColor); + RenderAabb(box, renderSettings.m_meshBasedColor); } } - if (renderSettings.mStaticBasedAABB) + if (renderSettings.m_staticBasedAabb) { // calculate the static based AABB - MCore::AABB box; - actorInstance->CalcStaticBasedAABB(&box); + AZ::Aabb box; + actorInstance->CalcStaticBasedAabb(&box); // render the aabb - if (box.CheckIfIsValid()) + if (box.IsValid()) { - RenderAABB(box, renderSettings.mStaticBasedColor); + RenderAabb(box, renderSettings.m_staticBasedColor); } } @@ -382,31 +365,31 @@ namespace MCommon // render a simple line based skeleton - void RenderUtil::RenderSimpleSkeleton(EMotionFX::ActorInstance* actorInstance, const AZStd::unordered_set* visibleJointIndices, - const AZStd::unordered_set* selectedJointIndices, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, + void RenderUtil::RenderSimpleSkeleton(EMotionFX::ActorInstance* actorInstance, const AZStd::unordered_set* visibleJointIndices, + const AZStd::unordered_set* selectedJointIndices, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, float jointSphereRadius, bool directlyRender) { const EMotionFX::Actor* actor = actorInstance->GetActor(); const EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); const EMotionFX::Pose* pose = actorInstance->GetTransformData()->GetCurrentPose(); - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t n = 0; n < numNodes; ++n) { const EMotionFX::Node* joint = skeleton->GetNode(actorInstance->GetEnabledNode(n)); - const AZ::u32 jointIndex = joint->GetNodeIndex(); + const size_t jointIndex = joint->GetNodeIndex(); if (!visibleJointIndices || visibleJointIndices->empty() || (visibleJointIndices->find(jointIndex) != visibleJointIndices->end())) { - const AZ::Vector3 currentJointPos = pose->GetWorldSpaceTransform(jointIndex).mPosition; + const AZ::Vector3 currentJointPos = pose->GetWorldSpaceTransform(jointIndex).m_position; const bool jointSelected = selectedJointIndices->find(jointIndex) != selectedJointIndices->end(); - const AZ::u32 parentIndex = joint->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + const size_t parentIndex = joint->GetParentIndex(); + if (parentIndex != InvalidIndex) { const bool parentSelected = selectedJointIndices->find(parentIndex) != selectedJointIndices->end(); - const AZ::Vector3 parentJointPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; + const AZ::Vector3 parentJointPos = pose->GetWorldSpaceTransform(parentIndex).m_position; RenderLine(currentJointPos, parentJointPos, parentSelected ? selectedColor : color); } @@ -420,77 +403,6 @@ namespace MCommon } } - - // render object orientated bounding boxes for all enabled nodes inside the actor instance - void RenderUtil::RenderOBBs(EMotionFX::ActorInstance* actorInstance, const AZStd::unordered_set* visibleJointIndices, const AZStd::unordered_set* selectedJointIndices, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, bool directlyRender) - { - AZ::Vector3 p[8]; - - // get the actor it is an instance from - const EMotionFX::Actor* actor = actorInstance->GetActor(); - const EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); - const EMotionFX::Pose* pose = actorInstance->GetTransformData()->GetCurrentPose(); - - // iterate through all enabled nodes - MCore::RGBAColor tempColor; - const uint32 numEnabled = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabled; ++i) - { - const EMotionFX::Node* joint = skeleton->GetNode(actorInstance->GetEnabledNode(i)); - const AZ::u32 jointIndex = joint->GetNodeIndex(); - - if (!visibleJointIndices || visibleJointIndices->empty() || - (visibleJointIndices->find(jointIndex) != visibleJointIndices->end())) - { - const MCore::OBB& obb = actor->GetNodeOBB(jointIndex); - EMotionFX::Transform worldTransform = pose->GetWorldSpaceTransform(jointIndex); - - // skip the OBB if it isn't valid - if (obb.CheckIfIsValid() == false) - { - continue; - } - - // check if the current bone is selected and set the color according to it - if (selectedJointIndices && selectedJointIndices->find(jointIndex) != selectedJointIndices->end()) - { - tempColor = selectedColor; - } - else - { - tempColor = color; - } - - obb.CalcCornerPoints(p); - for (uint32 a = 0; a < 8; a++) - { - p[a] = worldTransform.TransformPoint(p[a]); - } - - // render - RenderLine(p[0], p[1], tempColor); - RenderLine(p[1], p[2], tempColor); - RenderLine(p[2], p[3], tempColor); - RenderLine(p[0], p[3], tempColor); - - RenderLine(p[1], p[5], tempColor); - RenderLine(p[3], p[7], tempColor); - RenderLine(p[2], p[6], tempColor); - RenderLine(p[0], p[4], tempColor); - - RenderLine(p[4], p[5], tempColor); - RenderLine(p[4], p[7], tempColor); - RenderLine(p[6], p[7], tempColor); - RenderLine(p[6], p[5], tempColor); - } - } - - if (directlyRender) - { - RenderLines(); - } - } - // render wireframe mesh void RenderUtil::RenderWireframe(EMotionFX::Mesh* mesh, const AZ::Transform& worldTM, const MCore::RGBAColor& color, bool directlyRender, float offsetScale) { @@ -507,7 +419,7 @@ namespace MCommon AZ::Vector3* normals = (AZ::Vector3*)mesh->FindVertexData(EMotionFX::Mesh::ATTRIB_NORMALS); MCore::RGBAColor* vertexColors = (MCore::RGBAColor*)mesh->FindVertexData(EMotionFX::Mesh::ATTRIB_COLORS128); - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); + const size_t numSubMeshes = mesh->GetNumSubMeshes(); for (uint32 subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) { EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(subMeshIndex); @@ -522,9 +434,9 @@ namespace MCommon const uint32 indexB = indices[triangleStartIndex + 1] + startVertex; const uint32 indexC = indices[triangleStartIndex + 2] + startVertex; - const AZ::Vector3 posA = mWorldSpacePositions[indexA] + normals[indexA] * scale; - const AZ::Vector3 posB = mWorldSpacePositions[indexB] + normals[indexB] * scale; - const AZ::Vector3 posC = mWorldSpacePositions[indexC] + normals[indexC] * scale; + const AZ::Vector3 posA = m_worldSpacePositions[indexA] + normals[indexA] * scale; + const AZ::Vector3 posB = m_worldSpacePositions[indexB] + normals[indexB] * scale; + const AZ::Vector3 posC = m_worldSpacePositions[indexC] + normals[indexC] * scale; if (vertexColors) { @@ -569,7 +481,7 @@ namespace MCommon // render face normals if (faceNormals) { - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); + const size_t numSubMeshes = mesh->GetNumSubMeshes(); for (uint32 subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) { EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(subMeshIndex); @@ -584,9 +496,9 @@ namespace MCommon const uint32 indexB = indices[triangleStartIndex + 1] + startVertex; const uint32 indexC = indices[triangleStartIndex + 2] + startVertex; - const AZ::Vector3& posA = mWorldSpacePositions[ indexA ]; - const AZ::Vector3& posB = mWorldSpacePositions[ indexB ]; - const AZ::Vector3& posC = mWorldSpacePositions[ indexC ]; + const AZ::Vector3& posA = m_worldSpacePositions[ indexA ]; + const AZ::Vector3& posB = m_worldSpacePositions[ indexB ]; + const AZ::Vector3& posC = m_worldSpacePositions[ indexC ]; const AZ::Vector3 normalDir = (posB - posA).Cross(posC - posA).GetNormalized(); @@ -601,7 +513,7 @@ namespace MCommon // render vertex normals if (vertexNormals) { - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); + const size_t numSubMeshes = mesh->GetNumSubMeshes(); for (uint32 subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) { EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(subMeshIndex); @@ -612,7 +524,7 @@ namespace MCommon for (uint32 j = 0; j < numVertices; ++j) { const uint32 vertexIndex = j + startVertex; - const AZ::Vector3& position = mWorldSpacePositions[vertexIndex]; + const AZ::Vector3& position = m_worldSpacePositions[vertexIndex]; const AZ::Vector3 normal = worldTM.TransformVector(normals[vertexIndex]).GetNormalizedSafe() * vertexNormalsScale; RenderLine(position, position + normal, colorVertexNormals); } @@ -666,15 +578,15 @@ namespace MCommon } bitangent = (worldTM.TransformVector(bitangent)).GetNormalizedSafe(); - RenderLine(mWorldSpacePositions[i], mWorldSpacePositions[i] + (tangent * scale), colorTangents); + RenderLine(m_worldSpacePositions[i], m_worldSpacePositions[i] + (tangent * scale), colorTangents); if (tangents[i].GetW() < 0.0f) { - RenderLine(mWorldSpacePositions[i], mWorldSpacePositions[i] + (bitangent * scale), mirroredBitangentColor); + RenderLine(m_worldSpacePositions[i], m_worldSpacePositions[i] + (bitangent * scale), mirroredBitangentColor); } else { - RenderLine(mWorldSpacePositions[i], mWorldSpacePositions[i] + (bitangent * scale), colorBitangent); + RenderLine(m_worldSpacePositions[i], m_worldSpacePositions[i] + (bitangent * scale), colorBitangent); } } @@ -689,28 +601,28 @@ namespace MCommon void RenderUtil::PrepareForMesh(EMotionFX::Mesh* mesh, const AZ::Transform& worldTM) { // check if we have already prepared for the given mesh - if (mCurrentMesh == mesh) + if (m_currentMesh == mesh) { return; } // set our new current mesh - mCurrentMesh = mesh; + m_currentMesh = mesh; // get the number of vertices and the data - const uint32 numVertices = mCurrentMesh->GetNumVertices(); - AZ::Vector3* positions = (AZ::Vector3*)mCurrentMesh->FindVertexData(EMotionFX::Mesh::ATTRIB_POSITIONS); + const uint32 numVertices = m_currentMesh->GetNumVertices(); + AZ::Vector3* positions = (AZ::Vector3*)m_currentMesh->FindVertexData(EMotionFX::Mesh::ATTRIB_POSITIONS); // check if the vertices fits in our buffer - if (mWorldSpacePositions.size() < numVertices) + if (m_worldSpacePositions.size() < numVertices) { - mWorldSpacePositions.resize(numVertices); + m_worldSpacePositions.resize(numVertices); } // pre-calculate the world space positions for (uint32 i = 0; i < numVertices; ++i) { - mWorldSpacePositions[i] = worldTM.TransformPoint(positions[i]); + m_worldSpacePositions[i] = worldTM.TransformPoint(positions[i]); } } @@ -722,13 +634,13 @@ namespace MCommon EMotionFX::TransformData* transformData = actorInstance->GetTransformData(); const EMotionFX::Pose* pose = transformData->GetCurrentPose(); - const uint32 nodeIndex = node->GetNodeIndex(); - const uint32 parentIndex = node->GetParentIndex(); - const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(nodeIndex).mPosition; + const size_t nodeIndex = node->GetNodeIndex(); + const size_t parentIndex = node->GetParentIndex(); + const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(nodeIndex).m_position; - if (parentIndex != MCORE_INVALIDINDEX32) + if (parentIndex != InvalidIndex) { - const AZ::Vector3 parentWorldPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; + const AZ::Vector3 parentWorldPos = pose->GetWorldSpaceTransform(parentIndex).m_position; const AZ::Vector3 bone = parentWorldPos - nodeWorldPos; const float boneLength = MCore::SafeLength(bone); @@ -741,7 +653,7 @@ namespace MCommon // render the advanced skeleton - void RenderUtil::RenderSkeleton(EMotionFX::ActorInstance* actorInstance, const MCore::Array& boneList, const AZStd::unordered_set* visibleJointIndices, const AZStd::unordered_set* selectedJointIndices, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor) + void RenderUtil::RenderSkeleton(EMotionFX::ActorInstance* actorInstance, const AZStd::vector& boneList, const AZStd::unordered_set* visibleJointIndices, const AZStd::unordered_set* selectedJointIndices, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor) { // check if our render util supports rendering meshes, if not render the fallback skeleton using lines only if (GetIsMeshRenderingSupported() == false) @@ -758,15 +670,15 @@ namespace MCommon // iterate through all enabled nodes MCore::RGBAColor tempColor; - const uint32 numEnabled = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabled; ++i) + const size_t numEnabled = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numEnabled; ++i) { EMotionFX::Node* joint = skeleton->GetNode(actorInstance->GetEnabledNode(i)); - const AZ::u32 jointIndex = joint->GetNodeIndex(); - const AZ::u32 parentIndex = joint->GetParentIndex(); + const size_t jointIndex = joint->GetNodeIndex(); + const size_t parentIndex = joint->GetParentIndex(); // check if this node has a parent and is a bone, if not skip it - if (parentIndex == MCORE_INVALIDINDEX32 || boneList.Find(jointIndex) == MCORE_INVALIDINDEX32) + if (parentIndex == InvalidIndex || AZStd::find(begin(boneList), end(boneList), jointIndex) == end(boneList)) { continue; } @@ -774,8 +686,8 @@ namespace MCommon if (!visibleJointIndices || visibleJointIndices->empty() || (visibleJointIndices->find(jointIndex) != visibleJointIndices->end())) { - const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(jointIndex).mPosition; - const AZ::Vector3 parentWorldPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; + const AZ::Vector3 nodeWorldPos = pose->GetWorldSpaceTransform(jointIndex).m_position; + const AZ::Vector3 parentWorldPos = pose->GetWorldSpaceTransform(parentIndex).m_position; const AZ::Vector3 bone = parentWorldPos - nodeWorldPos; const AZ::Vector3 boneDirection = MCore::SafeNormalize(bone); const float boneLength = MCore::SafeLength(bone); @@ -803,7 +715,7 @@ namespace MCommon // render node orientations - void RenderUtil::RenderNodeOrientations(EMotionFX::ActorInstance* actorInstance, const MCore::Array& boneList, const AZStd::unordered_set* visibleJointIndices, const AZStd::unordered_set* selectedJointIndices, float scale, bool scaleBonesOnLength) + void RenderUtil::RenderNodeOrientations(EMotionFX::ActorInstance* actorInstance, const AZStd::vector& boneList, const AZStd::unordered_set* visibleJointIndices, const AZStd::unordered_set* selectedJointIndices, float scale, bool scaleBonesOnLength) { // get the actor and the transform data const float unitScale = 1.0f / (float)MCore::Distance::ConvertValue(1.0f, MCore::Distance::UNITTYPE_METERS, EMotionFX::GetEMotionFX().GetUnitType()); @@ -814,38 +726,38 @@ namespace MCommon const float constPreScale = scale * unitScale * 3.0f; AxisRenderingSettings axisRenderingSettings; - const uint32 numEnabled = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabled; ++i) + const size_t numEnabled = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numEnabled; ++i) { EMotionFX::Node* joint = skeleton->GetNode(actorInstance->GetEnabledNode(i)); - const AZ::u32 jointIndex = joint->GetNodeIndex(); - const AZ::u32 parentIndex = joint->GetParentIndex(); + const size_t jointIndex = joint->GetNodeIndex(); + const size_t parentIndex = joint->GetParentIndex(); if (!visibleJointIndices || visibleJointIndices->empty() || (visibleJointIndices->find(jointIndex) != visibleJointIndices->end())) { // either scale the bones based on their length or use the normal size - if (scaleBonesOnLength && parentIndex != MCORE_INVALIDINDEX32 && boneList.Find(jointIndex) != MCORE_INVALIDINDEX32) + if (scaleBonesOnLength && parentIndex != InvalidIndex && AZStd::find(begin(boneList), end(boneList), jointIndex) != end(boneList)) { static const float axisBoneScale = 50.0f; - axisRenderingSettings.mSize = GetBoneScale(actorInstance, joint) * constPreScale * axisBoneScale; + axisRenderingSettings.m_size = GetBoneScale(actorInstance, joint) * constPreScale * axisBoneScale; } else { - axisRenderingSettings.mSize = constPreScale; + axisRenderingSettings.m_size = constPreScale; } // check if the current bone is selected and set the color according to it if (selectedJointIndices && selectedJointIndices->find(jointIndex) != selectedJointIndices->end()) { - axisRenderingSettings.mSelected = true; + axisRenderingSettings.m_selected = true; } else { - axisRenderingSettings.mSelected = false; + axisRenderingSettings.m_selected = false; } - axisRenderingSettings.mWorldTM = pose->GetWorldSpaceTransform(jointIndex).ToAZTransform(); + axisRenderingSettings.m_worldTm = pose->GetWorldSpaceTransform(jointIndex).ToAZTransform(); RenderLineAxis(axisRenderingSettings); } } @@ -863,25 +775,25 @@ namespace MCommon AxisRenderingSettings axisRenderingSettings; // iterate through all enabled nodes - const uint32 numEnabled = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabled; ++i) + const size_t numEnabled = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numEnabled; ++i) { EMotionFX::Node* node = skeleton->GetNode(actorInstance->GetEnabledNode(i)); - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); // render node orientation const EMotionFX::Transform worldTransform = pose->GetWorldSpaceTransform(nodeIndex); - axisRenderingSettings.mSize = GetBoneScale(actorInstance, node) * 5.0f; - axisRenderingSettings.mWorldTM = worldTransform.ToAZTransform(); + axisRenderingSettings.m_size = GetBoneScale(actorInstance, node) * 5.0f; + axisRenderingSettings.m_worldTm = worldTransform.ToAZTransform(); RenderLineAxis(axisRenderingSettings);// line based axis rendering // skip root nodes for the line based skeleton rendering, you could also use curNode->IsRootNode() // but we use the parent index here, as we will reuse it - uint32 parentIndex = node->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + size_t parentIndex = node->GetParentIndex(); + if (parentIndex != InvalidIndex) { - const AZ::Vector3 endPos = pose->GetWorldSpaceTransform(parentIndex).mPosition; - RenderLine(worldTransform.mPosition, endPos, color); + const AZ::Vector3 endPos = pose->GetWorldSpaceTransform(parentIndex).m_position; + RenderLine(worldTransform.m_position, endPos, color); } } @@ -909,14 +821,14 @@ namespace MCommon void RenderUtil::UtilMesh::CalculateNormals(bool counterClockWise) { // check if the normals actually got allocated - if (mNormals.empty()) + if (m_normals.empty()) { return; } // reset all normals to the zero vector - const size_t numNormals = mNormals.size(); - MCore::MemSet(&mNormals[0], 0, sizeof(AZ::Vector3) * numNormals); + const size_t numNormals = m_normals.size(); + MCore::MemSet(&m_normals[0], 0, sizeof(AZ::Vector3) * numNormals); // iterate through all vertices and sum up the face normals uint32 i; @@ -925,24 +837,24 @@ namespace MCommon for (i = 0; i < numNormals; i += 3) { - indexA = mIndices[i]; - indexB = mIndices[i + (counterClockWise ? 1 : 2)]; - indexC = mIndices[i + (counterClockWise ? 2 : 1)]; + indexA = m_indices[i]; + indexB = m_indices[i + (counterClockWise ? 1 : 2)]; + indexC = m_indices[i + (counterClockWise ? 2 : 1)]; - v1 = mPositions[indexB] - mPositions[indexA]; - v2 = mPositions[indexC] - mPositions[indexA]; + v1 = m_positions[indexB] - m_positions[indexA]; + v2 = m_positions[indexC] - m_positions[indexA]; normal = v1.Cross(v2); - mNormals[indexA] = mNormals[indexA] + normal; - mNormals[indexB] = mNormals[indexB] + normal; - mNormals[indexC] = mNormals[indexC] + normal; + m_normals[indexA] = m_normals[indexA] + normal; + m_normals[indexB] = m_normals[indexB] + normal; + m_normals[indexC] = m_normals[indexC] + normal; } // normalize all the normals for (i = 0; i < numNormals; ++i) { - mNormals[i] = mNormals[i].GetNormalized(); + m_normals[i] = m_normals[i].GetNormalized(); } } @@ -951,14 +863,14 @@ namespace MCommon void RenderUtil::UtilMesh::Allocate(uint32 numVertices, uint32 numIndices, bool hasNormals) { AZ_Assert(numVertices > 0 && numIndices % 3 == 0, "Invalid numVertices or numIndices"); - AZ_Assert(mPositions.empty() && mIndices.empty() && mNormals.empty(), "data already initialized"); + AZ_Assert(m_positions.empty() && m_indices.empty() && m_normals.empty(), "data already initialized"); // allocate the buffers - mPositions.resize(numVertices); - mIndices.resize(numIndices); + m_positions.resize(numVertices); + m_indices.resize(numIndices); if (hasNormals) { - mNormals.resize(numVertices); + m_normals.resize(numVertices); } } @@ -985,13 +897,13 @@ namespace MCommon void RenderUtil::FillCylinder(UtilMesh* mesh, float baseRadius, float topRadius, float length, bool calculateNormals) { // check if the positions and the indices have been allocated already by the CreateCylinder() function - if (mesh->mPositions.empty() || mesh->mIndices.empty()) + if (mesh->m_positions.empty() || mesh->m_indices.empty()) { return; } // number of segments/sides of the cylinder - const uint32 numSegments = static_cast(mesh->mPositions.size()) / 2; + const uint32 numSegments = static_cast(mesh->m_positions.size()) / 2; // fill in the vertices uint32 i; @@ -1001,24 +913,24 @@ namespace MCommon const float z = MCore::Math::Sin(p); const float y = MCore::Math::Cos(p); - mesh->mPositions[i] = AZ::Vector3(0.0f, y * baseRadius, z * baseRadius); - mesh->mPositions[i + numSegments] = AZ::Vector3(-length, y * topRadius, z * topRadius); + mesh->m_positions[i] = AZ::Vector3(0.0f, y * baseRadius, z * baseRadius); + mesh->m_positions[i + numSegments] = AZ::Vector3(-length, y * topRadius, z * topRadius); } // fill in the indices uint32 c = 0; for (i = 0; i < numSegments; ++i) { - mesh->mIndices[c++] = i; - mesh->mIndices[c++] = ((i + 1) % numSegments); - mesh->mIndices[c++] = i + numSegments; + mesh->m_indices[c++] = i; + mesh->m_indices[c++] = ((i + 1) % numSegments); + mesh->m_indices[c++] = i + numSegments; } for (i = 0; i < numSegments; ++i) { - mesh->mIndices[c++] = i + numSegments; - mesh->mIndices[c++] = ((i + 1) % numSegments); - mesh->mIndices[c++] = ((i + 1) % numSegments) + numSegments; + mesh->m_indices[c++] = i + numSegments; + mesh->m_indices[c++] = ((i + 1) % numSegments); + mesh->m_indices[c++] = ((i + 1) % numSegments) + numSegments; } // recalculate normals if desired @@ -1083,19 +995,19 @@ namespace MCommon const float x = r * MCore::Math::Sin(p); const float y = r * MCore::Math::Cos(p); - sphereMesh->mPositions[(i - 1) * numSegments + j] = AZ::Vector3(x, y, z * radius); + sphereMesh->m_positions[(i - 1) * numSegments + j] = AZ::Vector3(x, y, z * radius); } } // the highest and lowest vertices - sphereMesh->mPositions[(numSegments - 2) * numSegments + 0] = AZ::Vector3(0.0f, 0.0f, radius); - sphereMesh->mPositions[(numSegments - 2) * numSegments + 1] = AZ::Vector3(0.0f, 0.0f, -radius); + sphereMesh->m_positions[(numSegments - 2) * numSegments + 0] = AZ::Vector3(0.0f, 0.0f, radius); + sphereMesh->m_positions[(numSegments - 2) * numSegments + 1] = AZ::Vector3(0.0f, 0.0f, -radius); // calculate normals - const size_t numPositions = sphereMesh->mPositions.size(); + const size_t numPositions = sphereMesh->m_positions.size(); for (i = 0; i < numPositions; ++i) { - sphereMesh->mNormals[i] = -sphereMesh->mPositions[i].GetNormalized(); + sphereMesh->m_normals[i] = -sphereMesh->m_positions[i].GetNormalized(); } // fill the indices @@ -1104,46 +1016,46 @@ namespace MCommon { for (uint32 j = 0; j < numSegments - 1; j++) { - sphereMesh->mIndices[c++] = (i - 1) * numSegments + j; - sphereMesh->mIndices[c++] = (i - 1) * numSegments + j + 1; - sphereMesh->mIndices[c++] = i * numSegments + j; + sphereMesh->m_indices[c++] = (i - 1) * numSegments + j; + sphereMesh->m_indices[c++] = (i - 1) * numSegments + j + 1; + sphereMesh->m_indices[c++] = i * numSegments + j; - sphereMesh->mIndices[c++] = (i - 1) * numSegments + j + 1; - sphereMesh->mIndices[c++] = i * numSegments + j + 1; - sphereMesh->mIndices[c++] = i * numSegments + j; + sphereMesh->m_indices[c++] = (i - 1) * numSegments + j + 1; + sphereMesh->m_indices[c++] = i * numSegments + j + 1; + sphereMesh->m_indices[c++] = i * numSegments + j; } - sphereMesh->mIndices[c++] = (i - 1) * numSegments + numSegments - 1; - sphereMesh->mIndices[c++] = (i - 1) * numSegments; - sphereMesh->mIndices[c++] = i * numSegments + numSegments - 1; + sphereMesh->m_indices[c++] = (i - 1) * numSegments + numSegments - 1; + sphereMesh->m_indices[c++] = (i - 1) * numSegments; + sphereMesh->m_indices[c++] = i * numSegments + numSegments - 1; - sphereMesh->mIndices[c++] = i * numSegments; - sphereMesh->mIndices[c++] = (i - 1) * numSegments; - sphereMesh->mIndices[c++] = i * numSegments + numSegments - 1; + sphereMesh->m_indices[c++] = i * numSegments; + sphereMesh->m_indices[c++] = (i - 1) * numSegments; + sphereMesh->m_indices[c++] = i * numSegments + numSegments - 1; } // highest and deepest indices for (i = 0; i < numSegments - 1; ++i) { - sphereMesh->mIndices[c++] = i; - sphereMesh->mIndices[c++] = i + 1; - sphereMesh->mIndices[c++] = (numSegments - 2) * numSegments; + sphereMesh->m_indices[c++] = i; + sphereMesh->m_indices[c++] = i + 1; + sphereMesh->m_indices[c++] = (numSegments - 2) * numSegments; } - sphereMesh->mIndices[c++] = numSegments - 1; - sphereMesh->mIndices[c++] = 0; - sphereMesh->mIndices[c++] = (numSegments - 2) * numSegments; + sphereMesh->m_indices[c++] = numSegments - 1; + sphereMesh->m_indices[c++] = 0; + sphereMesh->m_indices[c++] = (numSegments - 2) * numSegments; for (i = 0; i < numSegments - 1; ++i) { - sphereMesh->mIndices[c++] = (numSegments - 3) * numSegments + i; - sphereMesh->mIndices[c++] = (numSegments - 3) * numSegments + i + 1; - sphereMesh->mIndices[c++] = (numSegments - 2) * numSegments + 1; + sphereMesh->m_indices[c++] = (numSegments - 3) * numSegments + i; + sphereMesh->m_indices[c++] = (numSegments - 3) * numSegments + i + 1; + sphereMesh->m_indices[c++] = (numSegments - 2) * numSegments + 1; } - sphereMesh->mIndices[c++] = (numSegments - 3) * numSegments + (numSegments - 1); - sphereMesh->mIndices[c++] = (numSegments - 3) * numSegments; - sphereMesh->mIndices[c++] = (numSegments - 2) * numSegments + 1; + sphereMesh->m_indices[c++] = (numSegments - 3) * numSegments + (numSegments - 1); + sphereMesh->m_indices[c++] = (numSegments - 3) * numSegments; + sphereMesh->m_indices[c++] = (numSegments - 2) * numSegments + 1; return sphereMesh; } @@ -1227,63 +1139,63 @@ namespace MCommon mesh->Allocate(numVertices, numTriangles * 3, true); // define the vertices - mesh->mPositions[0] = AZ::Vector3(-0.5f, -0.5f, -0.5f) * size; - mesh->mPositions[1] = AZ::Vector3(0.5f, -0.5f, -0.5f) * size; - mesh->mPositions[2] = AZ::Vector3(0.5f, 0.5f, -0.5f) * size; - mesh->mPositions[3] = AZ::Vector3(-0.5f, 0.5f, -0.5f) * size; - mesh->mPositions[4] = AZ::Vector3(-0.5f, -0.5f, 0.5f) * size; - mesh->mPositions[5] = AZ::Vector3(0.5f, -0.5f, 0.5f) * size; - mesh->mPositions[6] = AZ::Vector3(0.5f, 0.5f, 0.5f) * size; - mesh->mPositions[7] = AZ::Vector3(-0.5f, 0.5f, 0.5f) * size; + mesh->m_positions[0] = AZ::Vector3(-0.5f, -0.5f, -0.5f) * size; + mesh->m_positions[1] = AZ::Vector3(0.5f, -0.5f, -0.5f) * size; + mesh->m_positions[2] = AZ::Vector3(0.5f, 0.5f, -0.5f) * size; + mesh->m_positions[3] = AZ::Vector3(-0.5f, 0.5f, -0.5f) * size; + mesh->m_positions[4] = AZ::Vector3(-0.5f, -0.5f, 0.5f) * size; + mesh->m_positions[5] = AZ::Vector3(0.5f, -0.5f, 0.5f) * size; + mesh->m_positions[6] = AZ::Vector3(0.5f, 0.5f, 0.5f) * size; + mesh->m_positions[7] = AZ::Vector3(-0.5f, 0.5f, 0.5f) * size; // define the indices - mesh->mIndices[0] = 0; - mesh->mIndices[1] = 1; - mesh->mIndices[2] = 2; + mesh->m_indices[0] = 0; + mesh->m_indices[1] = 1; + mesh->m_indices[2] = 2; - mesh->mIndices[3] = 0; - mesh->mIndices[4] = 2; - mesh->mIndices[5] = 3; + mesh->m_indices[3] = 0; + mesh->m_indices[4] = 2; + mesh->m_indices[5] = 3; - mesh->mIndices[6] = 1; - mesh->mIndices[7] = 5; - mesh->mIndices[8] = 6; + mesh->m_indices[6] = 1; + mesh->m_indices[7] = 5; + mesh->m_indices[8] = 6; - mesh->mIndices[9] = 1; - mesh->mIndices[10] = 6; - mesh->mIndices[11] = 2; + mesh->m_indices[9] = 1; + mesh->m_indices[10] = 6; + mesh->m_indices[11] = 2; - mesh->mIndices[12] = 5; - mesh->mIndices[13] = 4; - mesh->mIndices[14] = 7; + mesh->m_indices[12] = 5; + mesh->m_indices[13] = 4; + mesh->m_indices[14] = 7; - mesh->mIndices[15] = 5; - mesh->mIndices[16] = 7; - mesh->mIndices[17] = 6; + mesh->m_indices[15] = 5; + mesh->m_indices[16] = 7; + mesh->m_indices[17] = 6; - mesh->mIndices[18] = 4; - mesh->mIndices[19] = 0; - mesh->mIndices[20] = 3; + mesh->m_indices[18] = 4; + mesh->m_indices[19] = 0; + mesh->m_indices[20] = 3; - mesh->mIndices[21] = 4; - mesh->mIndices[22] = 3; - mesh->mIndices[23] = 7; + mesh->m_indices[21] = 4; + mesh->m_indices[22] = 3; + mesh->m_indices[23] = 7; - mesh->mIndices[24] = 1; - mesh->mIndices[25] = 0; - mesh->mIndices[26] = 4; + mesh->m_indices[24] = 1; + mesh->m_indices[25] = 0; + mesh->m_indices[26] = 4; - mesh->mIndices[27] = 1; - mesh->mIndices[28] = 4; - mesh->mIndices[29] = 5; + mesh->m_indices[27] = 1; + mesh->m_indices[28] = 4; + mesh->m_indices[29] = 5; - mesh->mIndices[30] = 3; - mesh->mIndices[31] = 2; - mesh->mIndices[32] = 6; + mesh->m_indices[30] = 3; + mesh->m_indices[31] = 2; + mesh->m_indices[32] = 6; - mesh->mIndices[33] = 3; - mesh->mIndices[34] = 6; - mesh->mIndices[35] = 7; + mesh->m_indices[33] = 3; + mesh->m_indices[34] = 6; + mesh->m_indices[35] = 7; // calculate the normals mesh->CalculateNormals(); @@ -1307,7 +1219,7 @@ namespace MCommon // fill in the indices for (uint32 i = 0; i < numVertices; ++i) { - mesh->mIndices[i] = i; + mesh->m_indices[i] = i; } // fill in the vertices and recalculate the normals @@ -1322,7 +1234,7 @@ namespace MCommon { static AZ::Vector3 points[12]; size_t pointNr = 0; - const size_t numVertices = mesh->mPositions.size(); + const size_t numVertices = mesh->m_positions.size(); const size_t numTriangles = numVertices / 3; assert(numTriangles * 3 == numVertices); const size_t numSegments = numTriangles / 2; @@ -1361,14 +1273,14 @@ namespace MCommon vertexNr = i * 6; // triangle 1 - mesh->mPositions[vertexNr + 0] = segmentPoint; - mesh->mPositions[vertexNr + 1] = previousPoint; - mesh->mPositions[vertexNr + 2] = center; + mesh->m_positions[vertexNr + 0] = segmentPoint; + mesh->m_positions[vertexNr + 1] = previousPoint; + mesh->m_positions[vertexNr + 2] = center; // triangle 2 - mesh->mPositions[vertexNr + 3] = previousPoint; - mesh->mPositions[vertexNr + 4] = segmentPoint; - mesh->mPositions[vertexNr + 5] = top; + mesh->m_positions[vertexNr + 3] = previousPoint; + mesh->m_positions[vertexNr + 4] = segmentPoint; + mesh->m_positions[vertexNr + 5] = top; // postprocess data previousPoint = segmentPoint; @@ -1438,36 +1350,36 @@ namespace MCommon // constructor RenderUtil::AxisRenderingSettings::AxisRenderingSettings() { - mSize = 1.0f; - mRenderXAxis = true; - mRenderYAxis = true; - mRenderZAxis = true; - mRenderXAxisName = false; - mRenderYAxisName = false; - mRenderZAxisName = false; - mSelected = false; + m_size = 1.0f; + m_renderXAxis = true; + m_renderYAxis = true; + m_renderZAxis = true; + m_renderXAxisName = false; + m_renderYAxisName = false; + m_renderZAxisName = false; + m_selected = false; } // render line based axis void RenderUtil::RenderLineAxis(const AxisRenderingSettings& settings) { - const float size = settings.mSize; - const AZ::Transform& worldTM = settings.mWorldTM; - const AZ::Vector3& cameraRight = settings.mCameraRight; - const AZ::Vector3& cameraUp = settings.mCameraUp; + const float size = settings.m_size; + const AZ::Transform& worldTM = settings.m_worldTm; + const AZ::Vector3& cameraRight = settings.m_cameraRight; + const AZ::Vector3& cameraUp = settings.m_cameraUp; const float arrowHeadRadius = size * 0.1f; const float arrowHeadHeight = size * 0.3f; const float axisHeight = size * 0.7f; const AZ::Vector3 position = worldTM.GetTranslation(); - if (settings.mRenderXAxis) + if (settings.m_renderXAxis) { // set the color MCore::RGBAColor xAxisColor = MCore::RGBAColor(1.0f, 0.0f, 0.0f); MCore::RGBAColor xSelectedColor; - if (settings.mSelected) + if (settings.m_selected) { xSelectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f); } @@ -1481,7 +1393,7 @@ namespace MCommon RenderArrowHead(arrowHeadHeight, arrowHeadRadius, xAxisArrowStart, xAxisDir, xSelectedColor); RenderLine(position, xAxisArrowStart, xAxisColor); - if (settings.mRenderXAxisName) + if (settings.m_renderXAxisName) { const AZ::Vector3 xNamePos = position + xAxisDir * (size * 1.15f); RenderLine(xNamePos + cameraUp * (-0.15f * size) + cameraRight * (0.1f * size), xNamePos + cameraUp * (0.15f * size) + cameraRight * (-0.1f * size), xAxisColor); @@ -1489,13 +1401,13 @@ namespace MCommon } } - if (settings.mRenderYAxis) + if (settings.m_renderYAxis) { // set the color MCore::RGBAColor yAxisColor = MCore::RGBAColor(0.0f, 1.0f, 0.0f); MCore::RGBAColor ySelectedColor; - if (settings.mSelected) + if (settings.m_selected) { ySelectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f); } @@ -1509,7 +1421,7 @@ namespace MCommon RenderArrowHead(arrowHeadHeight, arrowHeadRadius, yAxisArrowStart, yAxisDir, ySelectedColor); RenderLine(position, yAxisArrowStart, yAxisColor); - if (settings.mRenderYAxisName) + if (settings.m_renderYAxisName) { const AZ::Vector3 yNamePos = position + yAxisDir * (size * 1.15f); RenderLine(yNamePos, yNamePos + cameraRight * (-0.1f * size) + cameraUp * (0.15f * size), yAxisColor); @@ -1518,13 +1430,13 @@ namespace MCommon } } - if (settings.mRenderZAxis) + if (settings.m_renderZAxis) { // set the color MCore::RGBAColor zAxisColor = MCore::RGBAColor(0.0f, 0.0f, 1.0f); MCore::RGBAColor zSelectedColor; - if (settings.mSelected) + if (settings.m_selected) { zSelectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f); } @@ -1538,7 +1450,7 @@ namespace MCommon RenderArrowHead(arrowHeadHeight, arrowHeadRadius, zAxisArrowStart, zAxisDir, zSelectedColor); RenderLine(position, zAxisArrowStart, zAxisColor); - if (settings.mRenderZAxisName) + if (settings.m_renderZAxisName) { const AZ::Vector3 zNamePos = position + zAxisDir * (size * 1.15f); RenderLine(zNamePos + cameraRight * (-0.1f * size) + cameraUp * (0.15f * size), zNamePos + cameraRight * (0.1f * size) + cameraUp * (0.15f * size), zAxisColor); @@ -1639,7 +1551,7 @@ namespace MCommon // calculate the intersection points with the ground plane and create an AABB around those // if there is no intersection point then use the ray target as point, which is the projection onto the far plane basically - MCore::AABB aabb; + AZ::Aabb aabb = AZ::Aabb::CreateNull(); AZ::Vector3 intersectionPoint; const AZ::Plane groundPlane = AZ::Plane::CreateFromNormalAndPoint(AZ::Vector3(0.0f, 0.0f, 1.0f), AZ::Vector3::CreateZero()); for (AZ::u32 i = 0; i < 4; ++i) @@ -1649,7 +1561,7 @@ namespace MCommon corners[i] = intersectionPoint; } - aabb.Encapsulate(corners[i]); + aabb.AddPoint(corners[i]); } // set the grid start and end values @@ -1665,13 +1577,13 @@ namespace MCommon // get aabb which includes all actor instances - MCore::AABB RenderUtil::CalcSceneAABB() + AZ::Aabb RenderUtil::CalcSceneAabb() { - MCore::AABB finalAABB; + AZ::Aabb finalAABB = AZ::Aabb::CreateNull(); // get the number of actor instances and iterate through them - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { // get the actor instance and update its transformations and meshes EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -1685,17 +1597,17 @@ namespace MCommon actorInstance->UpdateMeshDeformers(0.0f); // get the mesh based bounding box - MCore::AABB boundingBox; - actorInstance->CalcMeshBasedAABB(actorInstance->GetLODLevel(), &boundingBox); + AZ::Aabb boundingBox; + actorInstance->CalcMeshBasedAabb(actorInstance->GetLODLevel(), &boundingBox); // in case there aren't any meshes, use the node based bounding box - if (boundingBox.CheckIfIsValid() == false) + if (!boundingBox.IsValid()) { - actorInstance->CalcNodeBasedAABB(&boundingBox); + actorInstance->CalcNodeBasedAabb(&boundingBox); } // make sure the actor instance is covered in our world bounding box - finalAABB.Encapsulate(boundingBox); + finalAABB.AddAabb(boundingBox); } return finalAABB; @@ -1761,10 +1673,10 @@ namespace MCommon void RenderUtil::RenderTrajectory(EMotionFX::ActorInstance* actorInstance, const MCore::RGBAColor& innerColor, const MCore::RGBAColor& borderColor, float scale) { EMotionFX::Actor* actor = actorInstance->GetActor(); - const uint32 nodeIndex = actor->GetMotionExtractionNodeIndex(); + const size_t nodeIndex = actor->GetMotionExtractionNodeIndex(); // in case the motion extraction node is not set, return directly - if (nodeIndex == MCORE_INVALIDINDEX32) + if (nodeIndex == InvalidIndex) { return; } @@ -1788,7 +1700,7 @@ namespace MCommon } // get some helper variables and check if there is a motion extraction node set - EMotionFX::ActorInstance* actorInstance = trajectoryPath->mActorInstance; + EMotionFX::ActorInstance* actorInstance = trajectoryPath->m_actorInstance; EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::Node* extractionNode = actor->GetMotionExtractionNode(); if (extractionNode == NULL) @@ -1797,9 +1709,9 @@ namespace MCommon } // fast access to the trajectory trace particles - const MCore::Array& traceParticles = trajectoryPath->mTraceParticles; - const int32 numTraceParticles = traceParticles.GetLength(); - if (traceParticles.GetIsEmpty()) + const AZStd::vector& traceParticles = trajectoryPath->m_traceParticles; + const size_t numTraceParticles = traceParticles.size(); + if (traceParticles.empty()) { return; } @@ -1816,7 +1728,7 @@ namespace MCommon // Render arrow head ////////////////////////////////////////////////////////////////////////////////////////////////////// // get the position and some direction vectors of the trajectory node matrix - EMotionFX::Transform worldTM = traceParticles[numTraceParticles - 1].mWorldTM; + EMotionFX::Transform worldTM = traceParticles[numTraceParticles - 1].m_worldTm; AZ::Vector3 right = MCore::GetRight(trajectoryWorldTM).GetNormalized(); AZ::Vector3 center = trajectoryWorldTM.GetTranslation(); AZ::Vector3 forward = MCore::GetForward(trajectoryWorldTM).GetNormalized(); @@ -1869,23 +1781,23 @@ namespace MCommon MCore::RGBAColor color = innerColor; // render the path from the arrow head towards the tail - for (int32 i = numTraceParticles - 1; i > 0; i--) + for (size_t i = numTraceParticles - 1; i > 0; i--) { // calculate the normalized distance to the head, this value also represents the alpha value as it fades away while getting closer to the end float normalizedDistance = (float)i / numTraceParticles; // get the start and end point of the line segment and calculate the delta between them - worldTM = traceParticles[i].mWorldTM; - a = worldTM.mPosition; - b = traceParticles[i - 1].mWorldTM.mPosition; + worldTM = traceParticles[i].m_worldTm; + a = worldTM.m_position; + b = traceParticles[i - 1].m_worldTm.m_position; right = MCore::GetRight(worldTM.ToAZTransform()).GetNormalized(); if (i > 1 && i < numTraceParticles - 3) { - const AZ::Vector3 deltaA = traceParticles[i - 2].mWorldTM.mPosition - traceParticles[i - 1].mWorldTM.mPosition; - const AZ::Vector3 deltaB = traceParticles[i - 1].mWorldTM.mPosition - traceParticles[i ].mWorldTM.mPosition; - const AZ::Vector3 deltaC = traceParticles[i ].mWorldTM.mPosition - traceParticles[i + 1].mWorldTM.mPosition; - const AZ::Vector3 deltaD = traceParticles[i + 1].mWorldTM.mPosition - traceParticles[i + 2].mWorldTM.mPosition; + const AZ::Vector3 deltaA = traceParticles[i - 2].m_worldTm.m_position - traceParticles[i - 1].m_worldTm.m_position; + const AZ::Vector3 deltaB = traceParticles[i - 1].m_worldTm.m_position - traceParticles[i ].m_worldTm.m_position; + const AZ::Vector3 deltaC = traceParticles[i ].m_worldTm.m_position - traceParticles[i + 1].m_worldTm.m_position; + const AZ::Vector3 deltaD = traceParticles[i + 1].m_worldTm.m_position - traceParticles[i + 2].m_worldTm.m_position; AZ::Vector3 delta = deltaA + deltaB + deltaC + deltaD; delta = MCore::SafeNormalize(delta); @@ -1920,7 +1832,7 @@ namespace MCommon } // render the solid arrow - color.a = normalizedDistance; + color.m_a = normalizedDistance; RenderTriangle(vertices[0] + liftFromGround, vertices[2] + liftFromGround, vertices[1] + liftFromGround, color); RenderTriangle(vertices[1] + liftFromGround, vertices[2] + liftFromGround, vertices[3] + liftFromGround, color); @@ -1944,7 +1856,7 @@ namespace MCommon } // remove all particles while keeping the data in memory - trajectoryPath->mTraceParticles.Clear(false); + trajectoryPath->m_traceParticles.clear(); } @@ -1971,19 +1883,19 @@ namespace MCommon // render node names for all enabled nodes - void RenderUtil::RenderNodeNames(EMotionFX::ActorInstance* actorInstance, Camera* camera, uint32 screenWidth, uint32 screenHeight, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, const AZStd::unordered_set& visibleJointIndices, const AZStd::unordered_set& selectedJointIndices) + void RenderUtil::RenderNodeNames(EMotionFX::ActorInstance* actorInstance, Camera* camera, uint32 screenWidth, uint32 screenHeight, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, const AZStd::unordered_set& visibleJointIndices, const AZStd::unordered_set& selectedJointIndices) { const EMotionFX::Actor* actor = actorInstance->GetActor(); const EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); const EMotionFX::TransformData* transformData = actorInstance->GetTransformData(); const EMotionFX::Pose* pose = transformData->GetCurrentPose(); - const AZ::u32 numEnabledNodes = actorInstance->GetNumEnabledNodes(); + const size_t numEnabledNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabledNodes; ++i) + for (size_t i = 0; i < numEnabledNodes; ++i) { const EMotionFX::Node* joint = skeleton->GetNode(actorInstance->GetEnabledNode(i)); - const AZ::u32 jointIndex = joint->GetNodeIndex(); - const AZ::Vector3 worldPos = pose->GetWorldSpaceTransform(jointIndex).mPosition; + const size_t jointIndex = joint->GetNodeIndex(); + const AZ::Vector3 worldPos = pose->GetWorldSpaceTransform(jointIndex).m_position; // check if the current enabled node is along the visible nodes and render it if that is the case if (visibleJointIndices.empty() || @@ -2049,7 +1961,7 @@ namespace MCommon void RenderUtil::RenderWireframeSphere(float radius, const AZ::Transform& worldTM, const MCore::RGBAColor& color, bool directlyRender) { - const float stepSize = AZ::Constants::TwoPi / m_wireframeSphereSegmentCount; + const float stepSize = AZ::Constants::TwoPi / s_wireframeSphereSegmentCount; AZ::Vector3 pos1, pos2; float x1, y1, x2, y2; @@ -2085,7 +1997,7 @@ namespace MCommon // The end points of these half circles connect the bottom cap to the top cap (the cylinder part in the middle). void RenderUtil::RenderWireframeCapsule(float radius, float height, const AZ::Transform& worldTM, const MCore::RGBAColor& color, bool directlyRender) { - float stepSize = AZ::Constants::TwoPi / m_wireframeSphereSegmentCount; + float stepSize = AZ::Constants::TwoPi / s_wireframeSphereSegmentCount; const float cylinderHeight = height - 2.0f * radius; const float halfCylinderHeight = cylinderHeight * 0.5f; @@ -2429,73 +2341,68 @@ namespace MCommon RenderUtil::FontChar::FontChar() { - mIndexCount = 0; - mIndices = 0; - mX1 = mY1 = mX2 = mY2 = 0; + m_indexCount = 0; + m_indices = 0; + m_x1 = m_y1 = m_x2 = m_y2 = 0; } const unsigned char* RenderUtil::FontChar::Init(const unsigned char* data, const float* vertices) { - data = getUShort(data, mIndexCount); - mIndices = (const unsigned short*)data; - data += mIndexCount * sizeof(unsigned short); + data = getUShort(data, m_indexCount); + m_indices = (const unsigned short*)data; + data += m_indexCount * sizeof(unsigned short); - for (uint32 i = 0; i < mIndexCount; ++i) + for (uint32 i = 0; i < m_indexCount; ++i) { - uint32 index = mIndices[i]; + uint32 index = m_indices[i]; const float* vertex = &vertices[index * 2]; //assert( _finite(vertex[0]) ); //assert( _finite(vertex[1]) ); if (i == 0) { - mX1 = mX2 = vertex[0]; - mY1 = mY2 = vertex[1]; + m_x1 = m_x2 = vertex[0]; + m_y1 = m_y2 = vertex[1]; } else { - if (vertex[0] < mX1) + if (vertex[0] < m_x1) { - mX1 = vertex[0]; + m_x1 = vertex[0]; } - if (vertex[1] < mY1) + if (vertex[1] < m_y1) { - mY1 = vertex[1]; + m_y1 = vertex[1]; } - if (vertex[0] > mX2) + if (vertex[0] > m_x2) { - mX2 = vertex[0]; + m_x2 = vertex[0]; } - if (vertex[1] > mY2) + if (vertex[1] > m_y2) { - mY2 = vertex[1]; + m_y2 = vertex[1]; } } } - //assert( _finite(mX1) ); - //assert( _finite(mX2) ); - //assert( _finite(mY1) ); - //assert( _finite(mY2) ); - return data; } void RenderUtil::FontChar::Render(const float* vertices, RenderUtil* renderUtil, float textScale, float& x, float& y, float posX, float posY, const MCore::RGBAColor& color) { - if (mIndices) + if (m_indices) { - const uint32 lineCount = mIndexCount / 2; - const float spacing = (mX2 - mX1) + 0.05f; + const uint32 lineCount = m_indexCount / 2; + const float spacing = (m_x2 - m_x1) + 0.05f; AZ::Vector2 p1; AZ::Vector2 p2; for (uint32 i = 0; i < lineCount; ++i) { - const float* v1 = &vertices[ mIndices[i * 2 + 0] * 2 ]; - const float* v2 = &vertices[ mIndices[i * 2 + 1] * 2 ]; + const float* v1 = &vertices[ m_indices[i * 2 + 0] * 2 ]; + const float* v2 = &vertices[ m_indices[i * 2 + 1] * 2 ]; p1.SetX((v1[0] + x) * textScale + posX); p1.SetY((v1[1] + y) * textScale); p2.SetX((v2[0] + x) * textScale + posX); @@ -2515,11 +2422,11 @@ namespace MCommon RenderUtil::VectorFont::VectorFont(RenderUtil* renderUtil) { - mRenderUtil = renderUtil; - mVersion = 0; - mVcount = 0; - mCount = 0; - mVertices = NULL; + m_renderUtil = renderUtil; + m_version = 0; + m_vcount = 0; + m_count = 0; + m_vertices = NULL; Init(gFontData); } @@ -2533,10 +2440,10 @@ namespace MCommon void RenderUtil::VectorFont::Release() { - mVersion = 0; - mVcount = 0; - mCount = 0; - mVertices = NULL; + m_version = 0; + m_vcount = 0; + m_count = 0; + m_vertices = NULL; } @@ -2546,22 +2453,22 @@ namespace MCommon if (fontData[0] == 'F' && fontData[1] == 'O' && fontData[2] == 'N' && fontData[3] == 'T') { fontData += 4; - fontData = getUint(fontData, mVersion); + fontData = getUint(fontData, m_version); - if (mVersion == FONT_VERSION) + if (m_version == FONT_VERSION) { - fontData = getUint(fontData, mVcount); - fontData = getUint(fontData, mCount); - fontData = getUint(fontData, mIcount); + fontData = getUint(fontData, m_vcount); + fontData = getUint(fontData, m_count); + fontData = getUint(fontData, m_icount); - uint32 vsize = sizeof(float) * mVcount * 2; - mVertices = (float*)fontData; + uint32 vsize = sizeof(float) * m_vcount * 2; + m_vertices = (float*)fontData; fontData += vsize; - for (uint32 i = 0; i < mCount; ++i) + for (uint32 i = 0; i < m_count; ++i) { unsigned char c = *fontData++; - fontData = mCharacters[c].Init(fontData, mVertices); + fontData = m_characters[c].Init(fontData, m_vertices); } } } @@ -2575,10 +2482,7 @@ namespace MCommon while (*text) { char codeUnit = *text++; - //if (codeUnit <= 255) - textWidth += mCharacters[(int)codeUnit].GetWidth(); - //else - // textWidth += mCharacters['?'].GetWidth(); + textWidth += m_characters[(int)codeUnit].GetWidth(); } return textWidth; @@ -2599,10 +2503,7 @@ namespace MCommon while (*text) { const char c = *text++; - // if (c <= 255) - mCharacters[(int)c].Render(mVertices, mRenderUtil, fontScale, x, y, posX, posY, color); - // else - // mCharacters['?'].Render( mVertices, mRenderUtil, fontScale, x, y, posX, posY, color ); + m_characters[(int)c].Render(m_vertices, m_renderUtil, fontScale, x, y, posX, posY, color); } } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h index 8b1cd30b6c..c21c18fd07 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RenderUtil.h @@ -6,10 +6,9 @@ * */ -#ifndef __MCOMMON_RENDERUTIL_H -#define __MCOMMON_RENDERUTIL_H +#pragma once -// include required headers +#include #include #include #include @@ -34,11 +33,11 @@ namespace MCommon public: // colors - static MCore::RGBAColor mSelectionColor; - static MCore::RGBAColor mSelectionColorDarker; - static MCore::RGBAColor mRed; - static MCore::RGBAColor mGreen; - static MCore::RGBAColor mBlue; + static MCore::RGBAColor s_selectionColor; + static MCore::RGBAColor s_selectionColorDarker; + static MCore::RGBAColor s_red; + static MCore::RGBAColor s_green; + static MCore::RGBAColor s_blue; }; @@ -111,7 +110,7 @@ namespace MCommon * Render tangents and bitangents of the mesh. * @param mesh A pointer to the mesh which will be rendered. * @param worldTM The world space transformation matrix of the node to which the given mesh belongs to. - * @param scale This parameter controls the length of the tangents and bitangentss. The default size of the tangents and bitangents is one unit. + * @param scale This parameter controls the length of the tangents and bitangents. The default size of the tangents and bitangents is one unit. * @param colorTangents The color of the tangents. * @param mirroredBitangentColor The color of the mirrored bitangents, so the ones that have a w value of -1. * @param colorBitangent The color of the face bitangents. @@ -127,7 +126,7 @@ namespace MCommon * @param directlyRender Will call the RenderLines() function internally in case it is set to true. If false * you have to make sure to call RenderLines() manually at the end of your custom render frame function. */ - void RenderAABB(const MCore::AABB& box, const MCore::RGBAColor& color, bool directlyRender = false); + void RenderAabb(const AZ::Aabb& box, const MCore::RGBAColor& color, bool directlyRender = false); /** * Render a selection gizmo around the given axis aligned bounding box. @@ -136,7 +135,7 @@ namespace MCommon * @param directlyRender Will call the RenderLines() function internally in case it is set to true. If false * you have to make sure to call RenderLines() manually at the end of your custom render frame function. */ - void RenderSelection(const MCore::AABB& box, const MCore::RGBAColor& color, bool directlyRender = false); + void RenderSelection(const AZ::Aabb& box, const MCore::RGBAColor& color, bool directlyRender = false); /** * The render settings used to enable the different AABB types of an actor instance. @@ -150,14 +149,12 @@ namespace MCommon */ AABBRenderSettings(); - bool mNodeBasedAABB; /**< Enable in case you want to render the node based AABB (default=true). */ - bool mMeshBasedAABB; /**< Enable in case you want to render the mesh based AABB (default=true). */ - bool mCollisionMeshBasedAABB; /**< Enable in case you want to render the collision mesh based AABB (default=true). */ - bool mStaticBasedAABB; /**< Enable in case you want to render the static based AABB (default=true). */ - MCore::RGBAColor mNodeBasedColor; /**< The color of the node based AABB. */ - MCore::RGBAColor mMeshBasedColor; /**< The color of the mesh based AABB. */ - MCore::RGBAColor mCollisionMeshBasedColor; /**< The color of the collision mesh based AABB. */ - MCore::RGBAColor mStaticBasedColor; /**< The color of the static based AABB. */ + bool m_nodeBasedAabb; /**< Enable in case you want to render the node based AABB (default=true). */ + bool m_meshBasedAabb; /**< Enable in case you want to render the mesh based AABB (default=true). */ + bool m_staticBasedAabb; /**< Enable in case you want to render the static based AABB (default=true). */ + MCore::RGBAColor m_nodeBasedColor; /**< The color of the node based AABB. */ + MCore::RGBAColor m_meshBasedColor; /**< The color of the mesh based AABB. */ + MCore::RGBAColor m_staticBasedColor; /**< The color of the static based AABB. */ }; /** @@ -168,19 +165,7 @@ namespace MCommon * @param directlyRender Will call the RenderLines() function internally in case it is set to true. If false * you have to make sure to call RenderLines() manually at the end of your custom render frame function. */ - void RenderAABBs(EMotionFX::ActorInstance* actorInstance, const AABBRenderSettings& renderSettings = AABBRenderSettings(), bool directlyRender = false); - - /** - * Render OBB for all enabled nodes inside the actor instance. - * @param actorInstance A pointer to the actor instance which will be rendered. - * @param[in] visibleJointIndices List of visible joint indices. nullptr in case all joints should be rendered. - * @param[in] selectedJointIndices List of selected joint indices. nullptr in case selection should not be considered. - * @param[in] color The color of the OBBs. - * @param[in] selectedColor The color of the selected OBBs. - * @param[in] directlyRender Will call the RenderLines() function internally in case it is set to true. If false - * you have to make sure to call RenderLines() manually at the end of your custom render frame function. - */ - void RenderOBBs(EMotionFX::ActorInstance* actorInstance, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 0.0f, 1.0f), const MCore::RGBAColor& selectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f), bool directlyRender = false); + void RenderAabbs(EMotionFX::ActorInstance* actorInstance, const AABBRenderSettings& renderSettings = AABBRenderSettings(), bool directlyRender = false); /** * Render a simple line based skeleton for all enabled nodes of the actor instance. @@ -192,7 +177,7 @@ namespace MCommon * @param[in] directlyRender Will call the RenderLines() function internally in case it is set to true. If false * you have to make sure to call RenderLines() manually at the end of your custom render frame function. */ - void RenderSimpleSkeleton(EMotionFX::ActorInstance* actorInstance, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, + void RenderSimpleSkeleton(EMotionFX::ActorInstance* actorInstance, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 0.0f, 1.0f), const MCore::RGBAColor& selectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f), float jointSphereRadius = 0.1f, bool directlyRender = false); @@ -206,7 +191,7 @@ namespace MCommon * @param[in] color The desired skeleton color. * @param[in] selectedColor The color of the selected bones. */ - void RenderSkeleton(EMotionFX::ActorInstance* actorInstance, const MCore::Array& boneList, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 0.0f, 0.0f, 1.0f), const MCore::RGBAColor& selectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f)); + void RenderSkeleton(EMotionFX::ActorInstance* actorInstance, const AZStd::vector& boneList, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 0.0f, 0.0f, 1.0f), const MCore::RGBAColor& selectedColor = MCore::RGBAColor(1.0f, 0.647f, 0.0f)); /** * Render node orientations. @@ -217,7 +202,7 @@ namespace MCommon * @param[in] scale The scaling value in units. Axes of normal nodes will use the scaling value as unit length, skinned bones will use the scaling value as multiplier. * @param[in] scaleBonesOnLength Automatically scales the bone orientations based on the bone length. This means finger node orientations will be rendered smaller than foot bones as the bone length is a lot smaller as well. */ - void RenderNodeOrientations(EMotionFX::ActorInstance* actorInstance, const MCore::Array& boneList, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, float scale = 1.0f, bool scaleBonesOnLength = true); + void RenderNodeOrientations(EMotionFX::ActorInstance* actorInstance, const AZStd::vector& boneList, const AZStd::unordered_set* visibleJointIndices = nullptr, const AZStd::unordered_set* selectedJointIndices = nullptr, float scale = 1.0f, bool scaleBonesOnLength = true); /** * Render the bind pose of the given actor. @@ -239,7 +224,7 @@ namespace MCommon * @param[in] visibleJointIndices List of visible joint indices. nullptr in case all joints should be rendered. * @param[in] selectedJointIndices List of selected joint indices. nullptr in case selection should not be considered. */ - void RenderNodeNames(EMotionFX::ActorInstance* actorInstance, MCommon::Camera* camera, uint32 screenWidth, uint32 screenHeight, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, const AZStd::unordered_set& visibleJointIndices, const AZStd::unordered_set& selectedJointIndices); + void RenderNodeNames(EMotionFX::ActorInstance* actorInstance, MCommon::Camera* camera, uint32 screenWidth, uint32 screenHeight, const MCore::RGBAColor& color, const MCore::RGBAColor& selectedColor, const AZStd::unordered_set& visibleJointIndices, const AZStd::unordered_set& selectedJointIndices); /** * Render a sphere. @@ -254,7 +239,7 @@ namespace MCommon * @param color The desired sphere color. * @param worldTM The world space transformation matrix. */ - MCORE_INLINE void RenderSphere(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(mUnitSphereMesh, color, worldTM); } + MCORE_INLINE void RenderSphere(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(m_unitSphereMesh, color, worldTM); } /** * Render a circle, consisting of lines. @@ -270,7 +255,7 @@ namespace MCommon * @param color The desired cube color. * @param worldTM The world space transformation matrix. */ - MCORE_INLINE void RenderCube(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(mUnitCubeMesh, color, worldTM); } + MCORE_INLINE void RenderCube(const MCore::RGBAColor& color, const AZ::Transform& worldTM) { RenderUtilMesh(m_unitCubeMesh, color, worldTM); } /** * Render a cylinder. @@ -280,7 +265,7 @@ namespace MCommon * @param color The desired cylinder color. * @param worldTM The world space transformation matrix. */ - MCORE_INLINE void RenderCylinder(float baseRadius, float topRadius, float length, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillCylinder(mCylinderMesh, baseRadius, topRadius, length); RenderUtilMesh(mCylinderMesh, color, worldTM); } + MCORE_INLINE void RenderCylinder(float baseRadius, float topRadius, float length, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillCylinder(m_cylinderMesh, baseRadius, topRadius, length); RenderUtilMesh(m_cylinderMesh, color, worldTM); } /** * Render a cylinder. @@ -317,7 +302,7 @@ namespace MCommon * @param color The desired arrow head color. * @param worldTM The world space transformation matrix. */ - MCORE_INLINE void RenderArrowHead(float height, float radius, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillArrowHead(mArrowHeadMesh, height, radius); RenderUtilMesh(mArrowHeadMesh, color, worldTM); } + MCORE_INLINE void RenderArrowHead(float height, float radius, const MCore::RGBAColor& color, const AZ::Transform& worldTM) { FillArrowHead(m_arrowHeadMesh, height, radius); RenderUtilMesh(m_arrowHeadMesh, color, worldTM); } /** * Render an arrow head. @@ -351,17 +336,17 @@ namespace MCommon */ AxisRenderingSettings(); - AZ::Transform mWorldTM; /**< The world space transformation matrix to visualize. */ - AZ::Vector3 mCameraRight; /**< The inverse of the camera's right vector used for billboarding the axis names. */ - AZ::Vector3 mCameraUp; /**< The inverse of the camera's up vector used for billboarding the axis names. */ - float mSize; /**< The size value in units is used to control the scaling of the axis. */ - bool mRenderXAxis; /**< Set to true if you want to render the x axis, false if the x axis should be skipped. */ - bool mRenderYAxis; /**< Set to true if you want to render the y axis, false if the y axis should be skipped. */ - bool mRenderZAxis; /**< Set to true if you want to render the z axis, false if the z axis should be skipped. */ - bool mRenderXAxisName; /**< Set to true if you want to render the name of the x axis. The name will only be rendered if the axis itself will be rendered as well. */ - bool mRenderYAxisName; /**< Set to true if you want to render the name of the y axis. The name will only be rendered if the axis itself will be rendered as well. */ - bool mRenderZAxisName; /**< Set to true if you want to render the name of the z axis. The name will only be rendered if the axis itself will be rendered as well. */ - bool mSelected; /**< Set to true if you want to render the axis using the selection color. */ + AZ::Transform m_worldTm; /**< The world space transformation matrix to visualize. */ + AZ::Vector3 m_cameraRight; /**< The inverse of the camera's right vector used for billboarding the axis names. */ + AZ::Vector3 m_cameraUp; /**< The inverse of the camera's up vector used for billboarding the axis names. */ + float m_size; /**< The size value in units is used to control the scaling of the axis. */ + bool m_renderXAxis; /**< Set to true if you want to render the x axis, false if the x axis should be skipped. */ + bool m_renderYAxis; /**< Set to true if you want to render the y axis, false if the y axis should be skipped. */ + bool m_renderZAxis; /**< Set to true if you want to render the z axis, false if the z axis should be skipped. */ + bool m_renderXAxisName; /**< Set to true if you want to render the name of the x axis. The name will only be rendered if the axis itself will be rendered as well. */ + bool m_renderYAxisName; /**< Set to true if you want to render the name of the y axis. The name will only be rendered if the axis itself will be rendered as well. */ + bool m_renderZAxisName; /**< Set to true if you want to render the name of the z axis. The name will only be rendered if the axis itself will be rendered as well. */ + bool m_selected; /**< Set to true if you want to render the axis using the selection color. */ }; /** @@ -387,8 +372,8 @@ namespace MCommon struct MCOMMON_API LineVertex { MCORE_MEMORYOBJECTCATEGORY(RenderUtil::LineVertex, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON); - AZ::Vector3 mPosition; /**< The position of the vertex. */ - MCore::RGBAColor mColor; /**< The vertex color. */ + AZ::Vector3 m_position; /**< The position of the vertex. */ + MCore::RGBAColor m_color; /**< The vertex color. */ }; /** @@ -399,12 +384,12 @@ namespace MCommon */ MCORE_INLINE void RenderLine(const AZ::Vector3& v1, const AZ::Vector3& v2, const MCore::RGBAColor& color) { - mVertexBuffer[mNumVertices].mPosition = v1; - mVertexBuffer[mNumVertices + 1].mPosition = v2; - mVertexBuffer[mNumVertices].mColor = color; - mVertexBuffer[mNumVertices + 1].mColor = color; - mNumVertices += 2; - if (mNumVertices >= mNumMaxLineVertices) + m_vertexBuffer[m_numVertices].m_position = v1; + m_vertexBuffer[m_numVertices + 1].m_position = v2; + m_vertexBuffer[m_numVertices].m_color = color; + m_vertexBuffer[m_numVertices + 1].m_color = color; + m_numVertices += 2; + if (m_numVertices >= s_numMaxLineVertices) { RenderLines(); } @@ -431,11 +416,11 @@ namespace MCommon struct MCOMMON_API Line2D { MCORE_MEMORYOBJECTCATEGORY(RenderUtil::Line2D, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON); - float mX1; /**< The x position of the first vertex. */ - float mY1; /**< The y position of the first vertex. */ - float mX2; /**< The x position of the second vertex. */ - float mY2; /**< The y position of the second vertex. */ - MCore::RGBAColor mColor; /**< The line color. */ + float m_x1; /**< The x position of the first vertex. */ + float m_y1; /**< The y position of the first vertex. */ + float m_x2; /**< The x position of the second vertex. */ + float m_y2; /**< The y position of the second vertex. */ + MCore::RGBAColor m_color; /**< The line color. */ }; /** @@ -448,13 +433,13 @@ namespace MCommon */ MCORE_INLINE void Render2DLine(float x1, float y1, float x2, float y2, const MCore::RGBAColor& color) { - m2DLines[mNum2DLines].mX1 = x1; - m2DLines[mNum2DLines].mY1 = y1; - m2DLines[mNum2DLines].mX2 = x2; - m2DLines[mNum2DLines].mY2 = y2; - m2DLines[mNum2DLines].mColor = color; - mNum2DLines++; - if (mNum2DLines >= mNumMax2DLines) + m_m2DLines[m_num2DLines].m_x1 = x1; + m_m2DLines[m_num2DLines].m_y1 = y1; + m_m2DLines[m_num2DLines].m_x2 = x2; + m_m2DLines[m_num2DLines].m_y2 = y2; + m_m2DLines[m_num2DLines].m_color = color; + m_num2DLines++; + if (m_num2DLines >= s_numMax2DLines) { Render2DLines(); } @@ -504,9 +489,9 @@ namespace MCommon */ void Allocate(uint32 numVertices, uint32 numIndices, bool hasNormals); - AZStd::vector mPositions; /**< The vertex buffer. */ - AZStd::vector mIndices; /**< The index buffer. */ - AZStd::vector mNormals; /**< The normal buffer. */ + AZStd::vector m_positions; /**< The vertex buffer. */ + AZStd::vector m_indices; /**< The index buffer. */ + AZStd::vector m_normals; /**< The normal buffer. */ }; /** @@ -515,12 +500,12 @@ namespace MCommon struct UtilMeshVertex { MCORE_MEMORYOBJECTCATEGORY(RenderUtil::UtilMeshVertex, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON); - AZ::Vector3 mPosition; /**< The position of the vertex. */ - AZ::Vector3 mNormal; /**< The vertex normal. */ + AZ::Vector3 m_position; /**< The position of the vertex. */ + AZ::Vector3 m_normal; /**< The vertex normal. */ UtilMeshVertex(const AZ::Vector3& pos, const AZ::Vector3& normal) - : mPosition(pos) - , mNormal(normal) {} + : m_position(pos) + , m_normal(normal) {} }; /** @@ -545,57 +530,39 @@ namespace MCommon * To avoid recalculating them several times we do this at a central place. This function needs to be called before switching to a new mesh inside * the render loop as well as before an animation update, so before calling any of the render normals, face normals, tangents and bitangents functions. */ - MCORE_INLINE void ResetCurrentMesh() { mCurrentMesh = NULL; } + MCORE_INLINE void ResetCurrentMesh() { m_currentMesh = NULL; } //--------------------------------------------------------------------------------------------- - /*struct MCOMMON_API Triangle - { - MCORE_MEMORYOBJECTCATEGORY( RenderUtil::Triangle, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON ); - - AZ::Vector3 mPosA; - AZ::Vector3 mPosB; - AZ::Vector3 mPosC; - - AZ::Vector3 mNormalA; - AZ::Vector3 mNormalB; - AZ::Vector3 mNormalC; - - uint32 mColor; - - Triangle() {} - Triangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) : mPosA(posA), mPosB(posB), mPosC(posC), mNormalA(normalA), mNormalB(normalB), mNormalC(normalC), mColor(color) {} - };*/ - /** * The vertex structure to be used for rendering util meshes. */ struct TriangleVertex { MCORE_MEMORYOBJECTCATEGORY(RenderUtil::TriangleVertex, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MCOMMON); - AZ::Vector3 mPosition; /**< The position of the vertex. */ - AZ::Vector3 mNormal; /**< The vertex normal. */ - uint32 mColor; + AZ::Vector3 m_position; /**< The position of the vertex. */ + AZ::Vector3 m_normal; /**< The vertex normal. */ + uint32 m_color; MCORE_INLINE TriangleVertex(const AZ::Vector3& pos, const AZ::Vector3& normal, uint32 color) - : mPosition(pos) - , mNormal(normal) - , mColor(color) {} + : m_position(pos) + , m_normal(normal) + , m_color(color) {} }; MCORE_INLINE void AddTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) { - mTriangleVertices.Add(TriangleVertex(posA, normalA, color)); - mTriangleVertices.Add(TriangleVertex(posB, normalB, color)); - mTriangleVertices.Add(TriangleVertex(posC, normalC, color)); + m_triangleVertices.emplace_back(TriangleVertex(posA, normalA, color)); + m_triangleVertices.emplace_back(TriangleVertex(posB, normalB, color)); + m_triangleVertices.emplace_back(TriangleVertex(posC, normalC, color)); - if (mTriangleVertices.GetLength() + 2 >= mNumMaxTriangleVertices) + if (m_triangleVertices.size() + 2 >= s_numMaxTriangleVertices) { RenderTriangles(); } } - virtual void RenderTriangles(const MCore::Array& triangleVertices) { MCORE_UNUSED(triangleVertices); } + virtual void RenderTriangles(const AZStd::vector& triangleVertices) { MCORE_UNUSED(triangleVertices); } void RenderTriangles(); //--------------------------------------------------------------------------------------------- @@ -615,24 +582,24 @@ namespace MCommon * Calculate the aabb which includes all actor instances. * @return The aabb which includes all actor instances. */ - MCore::AABB CalcSceneAABB(); + AZ::Aabb CalcSceneAabb(); struct TrajectoryPathParticle { - EMotionFX::Transform mWorldTM; + EMotionFX::Transform m_worldTm; }; struct TrajectoryTracePath { - MCore::Array mTraceParticles; - EMotionFX::ActorInstance* mActorInstance; - float mTimePassed; + AZStd::vector m_traceParticles; + EMotionFX::ActorInstance* m_actorInstance; + float m_timePassed; TrajectoryTracePath() { - mTraceParticles.Reserve(250); - mTimePassed = 0.0f; - mActorInstance = NULL; + m_traceParticles.reserve(250); + m_timePassed = 0.0f; + m_actorInstance = NULL; } }; @@ -652,7 +619,7 @@ namespace MCommon /** * Render text to screen. This will only work in case the Render2DLines() function has been implemented. */ - MCORE_INLINE void RenderText(float x, float y, const char* text, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 1.0f), float fontSize = 11.0f, bool centered = false) { mFont->Render(x * m_devicePixelRatio, (y * m_devicePixelRatio) + fontSize - 1, fontSize, centered, text, color); } + MCORE_INLINE void RenderText(float x, float y, const char* text, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 1.0f), float fontSize = 11.0f, bool centered = false) { m_font->Render(x * m_devicePixelRatio, (y * m_devicePixelRatio) + fontSize - 1, fontSize, centered, text, color); } /** * Render text to screen. This will only work in case the Render2DLines() function has been implemented. @@ -722,7 +689,7 @@ namespace MCommon /** * Change the shape of a given arrow head util mesh. This method can be used to adjust an already allocated arrow head util mesh. - * For example this can be usedful if you need to change the radius or the height of an arrow head. + * For example this can be useful if you need to change the radius or the height of an arrow head. * @param mesh A pointer to the arrow head util mesh. Note that this mesh has to be created using CreateArrowHead(). * @param height The height of the arrow head from the base to the head. * @param radius The radius of the base of the arrow head. @@ -735,7 +702,7 @@ namespace MCommon * @param radius The radius of the sphere. * @return A pointer to the newly created util sphere mesh. */ - static UtilMesh* CreateSphere(float radius, uint32 numSegments = 8); + static UtilMesh* CreateSphere(float radius, uint32 numSegments = 5); /** * Create an util mesh we can use to render cubes. @@ -765,19 +732,19 @@ namespace MCommon MCORE_INLINE float GetWidth() const { float ret = 0.1f; - if (mIndexCount > 0) + if (m_indexCount > 0) { - ret = (mX2 - mX1) + 0.05f; + ret = (m_x2 - m_x1) + 0.05f; } return ret; } - float mX1; - float mX2; - float mY1; - float mY2; - unsigned short mIndexCount; - const unsigned short* mIndices; + float m_x1; + float m_x2; + float m_y1; + float m_y2; + unsigned short m_indexCount; + const unsigned short* m_indices; }; class MCOMMON_API VectorFont @@ -795,42 +762,39 @@ namespace MCommon float CalculateTextWidth(const char* text); private: - uint32 mVersion; - uint32 mVcount; - uint32 mCount; - float* mVertices; - uint32 mIcount; - FontChar mCharacters[256]; - RenderUtil* mRenderUtil; + uint32 m_version; + uint32 m_vcount; + uint32 m_count; + float* m_vertices; + uint32 m_icount; + FontChar m_characters[256]; + RenderUtil* m_renderUtil; }; - EMotionFX::Mesh* mCurrentMesh; /**< A pointer to the mesh whose world space positions are in the pre-calculated positions buffer. NULL in case we haven't pre-calculated any positions yet. */ - AZStd::vector mWorldSpacePositions; /**< The buffer used to store world space positions for rendering normals, tangents and the wireframe. */ + EMotionFX::Mesh* m_currentMesh; /**< A pointer to the mesh whose world space positions are in the pre-calculated positions buffer. NULL in case we haven't pre-calculated any positions yet. */ + AZStd::vector m_worldSpacePositions; /**< The buffer used to store world space positions for rendering normals, tangents and the wireframe. */ - LineVertex* mVertexBuffer; /**< Array of line vertices. */ - uint32 mNumVertices; /**< The current number of vertices in the array. */ - static uint32 mNumMaxLineVertices; /**< The maximum capacity of the line vertex buffer. */ + LineVertex* m_vertexBuffer; /**< Array of line vertices. */ + uint32 m_numVertices; /**< The current number of vertices in the array. */ + static uint32 s_numMaxLineVertices; /**< The maximum capacity of the line vertex buffer. */ - Line2D* m2DLines; /**< Array of 2D lines. */ - uint32 mNum2DLines; /**< The current number of 2D lines in the array. */ - static uint32 mNumMax2DLines; /**< The maximum capacity of the 2D line buffer. */ - static float m_wireframeSphereSegmentCount; + Line2D* m_m2DLines; /**< Array of 2D lines. */ + uint32 m_num2DLines; /**< The current number of 2D lines in the array. */ + static uint32 s_numMax2DLines; /**< The maximum capacity of the 2D line buffer. */ + static float s_wireframeSphereSegmentCount; float m_devicePixelRatio; - VectorFont* mFont; /**< The vector font used to render text. */ + VectorFont* m_font; /**< The vector font used to render text. */ - UtilMesh* mUnitSphereMesh; /**< The preallocated and preconstructed sphere mesh used for rendering. */ - UtilMesh* mCylinderMesh; /**< The preallocated and preconstructed cylinder mesh used for rendering. */ - UtilMesh* mUnitCubeMesh; /**< The preallocated and preconstructed cube mesh used for rendering. */ - UtilMesh* mArrowHeadMesh; /**< The preallocated and preconstructed arrow head mesh used for rendering. */ - static uint32 mNumMaxMeshVertices; /**< The maximum capacity of the util mesh vertex buffer. */ - static uint32 mNumMaxMeshIndices; /**< The maximum capacity of the util mesh index buffer */ + UtilMesh* m_unitSphereMesh; /**< The preallocated and preconstructed sphere mesh used for rendering. */ + UtilMesh* m_cylinderMesh; /**< The preallocated and preconstructed cylinder mesh used for rendering. */ + UtilMesh* m_unitCubeMesh; /**< The preallocated and preconstructed cube mesh used for rendering. */ + UtilMesh* m_arrowHeadMesh; /**< The preallocated and preconstructed arrow head mesh used for rendering. */ + static uint32 s_numMaxMeshVertices; /**< The maximum capacity of the util mesh vertex buffer. */ + static uint32 s_numMaxMeshIndices; /**< The maximum capacity of the util mesh index buffer */ // helper variables for rendering triangles - MCore::Array mTriangleVertices; - static uint32 mNumMaxTriangleVertices; /**< The maximum capacity of the triangle vertex buffer */ + AZStd::vector m_triangleVertices; + static uint32 s_numMaxTriangleVertices; /**< The maximum capacity of the triangle vertex buffer */ }; } // namespace MCommon - - -#endif diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.cpp index 123ef00333..3a978d448c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.cpp @@ -16,10 +16,10 @@ namespace MCommon RotateManipulator::RotateManipulator(float scalingFactor, bool isVisible) : TransformationManipulator(scalingFactor, isVisible) { - mMode = ROTATE_NONE; - mRotation = AZ::Vector3::CreateZero(); - mRotationQuat = AZ::Quaternion::CreateIdentity(); - mClickPosition = AZ::Vector3::CreateZero(); + m_mode = ROTATE_NONE; + m_rotation = AZ::Vector3::CreateZero(); + m_rotationQuat = AZ::Quaternion::CreateIdentity(); + m_clickPosition = AZ::Vector3::CreateZero(); } @@ -34,35 +34,35 @@ namespace MCommon { MCORE_UNUSED(camera); - // adjust the mSize when in ortho mode - mSize = mScalingFactor; - mInnerRadius = 0.15f * mSize; - mOuterRadius = 0.2f * mSize; - mArrowBaseRadius = mInnerRadius / 70.0f; - mAABBWidth = mInnerRadius / 30.0f;// previous 70.0f - mAxisSize = mSize * 0.05f; - mTextDistance = mSize * 0.05f; - mInnerQuadSize = 0.45f * MCore::Math::Sqrt(2) * mInnerRadius; + // adjust the m_size when in ortho mode + m_size = m_scalingFactor; + m_innerRadius = 0.15f * m_size; + m_outerRadius = 0.2f * m_size; + m_arrowBaseRadius = m_innerRadius / 70.0f; + m_aabbWidth = m_innerRadius / 30.0f;// previous 70.0f + m_axisSize = m_size * 0.05f; + m_textDistance = m_size * 0.05f; + m_innerQuadSize = 0.45f * MCore::Math::Sqrt(2) * m_innerRadius; // set the bounding volumes of the axes selection - mXAxisAABB.SetMax(mPosition + AZ::Vector3(mAABBWidth, mInnerRadius, mInnerRadius)); - mXAxisAABB.SetMin(mPosition - AZ::Vector3(mAABBWidth, mInnerRadius, mInnerRadius)); - mYAxisAABB.SetMax(mPosition + AZ::Vector3(mInnerRadius, mAABBWidth, mInnerRadius)); - mYAxisAABB.SetMin(mPosition - AZ::Vector3(mInnerRadius, mAABBWidth, mInnerRadius)); - mZAxisAABB.SetMax(mPosition + AZ::Vector3(mInnerRadius, mInnerRadius, mAABBWidth)); - mZAxisAABB.SetMin(mPosition - AZ::Vector3(mInnerRadius, mInnerRadius, mAABBWidth)); - mXAxisInnerAABB.SetMax(mPosition + AZ::Vector3(mAABBWidth, mInnerQuadSize, mInnerQuadSize)); - mXAxisInnerAABB.SetMin(mPosition - AZ::Vector3(mAABBWidth, mInnerQuadSize, mInnerQuadSize)); - mYAxisInnerAABB.SetMax(mPosition + AZ::Vector3(mInnerQuadSize, mAABBWidth, mInnerQuadSize)); - mYAxisInnerAABB.SetMin(mPosition - AZ::Vector3(mInnerQuadSize, mAABBWidth, mInnerQuadSize)); - mZAxisInnerAABB.SetMax(mPosition + AZ::Vector3(mInnerQuadSize, mInnerQuadSize, mAABBWidth)); - mZAxisInnerAABB.SetMin(mPosition - AZ::Vector3(mInnerQuadSize, mInnerQuadSize, mAABBWidth)); + m_xAxisAabb.SetMax(m_position + AZ::Vector3(m_aabbWidth, m_innerRadius, m_innerRadius)); + m_xAxisAabb.SetMin(m_position - AZ::Vector3(m_aabbWidth, m_innerRadius, m_innerRadius)); + m_yAxisAabb.SetMax(m_position + AZ::Vector3(m_innerRadius, m_aabbWidth, m_innerRadius)); + m_yAxisAabb.SetMin(m_position - AZ::Vector3(m_innerRadius, m_aabbWidth, m_innerRadius)); + m_zAxisAabb.SetMax(m_position + AZ::Vector3(m_innerRadius, m_innerRadius, m_aabbWidth)); + m_zAxisAabb.SetMin(m_position - AZ::Vector3(m_innerRadius, m_innerRadius, m_aabbWidth)); + m_xAxisInnerAabb.SetMax(m_position + AZ::Vector3(m_aabbWidth, m_innerQuadSize, m_innerQuadSize)); + m_xAxisInnerAabb.SetMin(m_position - AZ::Vector3(m_aabbWidth, m_innerQuadSize, m_innerQuadSize)); + m_yAxisInnerAabb.SetMax(m_position + AZ::Vector3(m_innerQuadSize, m_aabbWidth, m_innerQuadSize)); + m_yAxisInnerAabb.SetMin(m_position - AZ::Vector3(m_innerQuadSize, m_aabbWidth, m_innerQuadSize)); + m_zAxisInnerAabb.SetMax(m_position + AZ::Vector3(m_innerQuadSize, m_innerQuadSize, m_aabbWidth)); + m_zAxisInnerAabb.SetMin(m_position - AZ::Vector3(m_innerQuadSize, m_innerQuadSize, m_aabbWidth)); // set the bounding spheres for inner and outer circle modifiers - mInnerBoundingSphere.SetCenter(mPosition); - mInnerBoundingSphere.SetRadius(mInnerRadius); - mOuterBoundingSphere.SetCenter(mPosition); - mOuterBoundingSphere.SetRadius(mOuterRadius); + m_innerBoundingSphere.SetCenter(m_position); + m_innerBoundingSphere.SetRadius(m_innerRadius); + m_outerBoundingSphere.SetCenter(m_position); + m_outerBoundingSphere.SetRadius(m_outerRadius); } @@ -82,7 +82,7 @@ namespace MCommon MCore::Ray mousePosRay = camera->Unproject(mousePosX, mousePosY); // check if mouse ray hits the outer sphere of the manipulator - if (mousePosRay.Intersects(mOuterBoundingSphere)) + if (mousePosRay.Intersects(m_outerBoundingSphere)) { return true; } @@ -109,14 +109,14 @@ namespace MCommon MCore::Ray camRay = camera->Unproject(screenWidth / 2, screenHeight / 2); AZ::Vector3 camDir = camRay.GetDirection(); - mSignX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f; - mSignY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f; - mSignZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f; + m_signX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f; + m_signY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f; + m_signZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi) ? 1.0f : -1.0f; // determine the axis visibility, to disable movement for invisible axes - mXAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); - mYAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); - mZAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_xAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_yAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_zAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); // update the bounding volumes UpdateBoundingVolumes(); @@ -127,12 +127,12 @@ namespace MCommon void RotateManipulator::Render(MCommon::Camera* camera, RenderUtil* renderUtil) { // return if no render util is set - if (renderUtil == nullptr || camera == nullptr || mIsVisible == false) + if (renderUtil == nullptr || camera == nullptr || m_isVisible == false) { return; } - // set mSize variables for the gizmo + // set m_size variables for the gizmo const uint32 screenWidth = camera->GetScreenWidth(); const uint32 screenHeight = camera->GetScreenHeight(); @@ -143,14 +143,13 @@ namespace MCommon MCore::RGBAColor blueTransparent = MCore::RGBAColor(0.0, 0.0, 0.762f, 0.2f); MCore::RGBAColor greyTransparent = MCore::RGBAColor(0.5f, 0.5f, 0.5f, 0.3f); - MCore::RGBAColor xAxisColor = (mMode == ROTATE_X) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor yAxisColor = (mMode == ROTATE_Y) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor zAxisColor = (mMode == ROTATE_Z) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; - MCore::RGBAColor camRollAxisColor = (mMode == ROTATE_CAMROLL) ? ManipulatorColors::mSelectionColor : grey; - //MCore::RGBAColor camPitchYawColor = (mMode == ROTATE_CAMPITCHYAW) ? ManipulatorColors::mSelectionColor : grey; + MCore::RGBAColor xAxisColor = (m_mode == ROTATE_X) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor yAxisColor = (m_mode == ROTATE_Y) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor zAxisColor = (m_mode == ROTATE_Z) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; + MCore::RGBAColor camRollAxisColor = (m_mode == ROTATE_CAMROLL) ? ManipulatorColors::s_selectionColor : grey; // render axis in the center of the rotation gizmo - renderUtil->RenderAxis(mAxisSize, mPosition, AZ::Vector3(1.0f, 0.0f, 0.0f), AZ::Vector3(0.0f, 1.0f, 0.0f), AZ::Vector3(0.0f, 0.0f, 1.0f)); + renderUtil->RenderAxis(m_axisSize, m_position, AZ::Vector3(1.0f, 0.0f, 0.0f), AZ::Vector3(0.0f, 1.0f, 0.0f), AZ::Vector3(0.0f, 0.0f, 1.0f)); // shoot rays to the plane, to get upwards pointing vector on the plane // used for the text positioning and the angle visualization for the view rotation axis @@ -159,7 +158,7 @@ namespace MCommon AZ::Vector3 camRollAxis = originRay.GetDirection(); // calculate the plane perpendicular to the view rotation axis - MCore::PlaneEq rotationPlane(originRay.GetDirection(), mPosition); + MCore::PlaneEq rotationPlane(originRay.GetDirection(), m_position); // get the intersection points of the rays and the plane AZ::Vector3 originRayIntersect, upVecRayIntersect; @@ -177,66 +176,43 @@ namespace MCommon camViewMat.InvertFull(); // set the translation part of the matrix - camViewMat.SetTranslation(mPosition); + camViewMat.SetTranslation(m_position); // render the view axis rotation manipulator const AZ::Transform camViewTransform = AZ::Transform::CreateFromMatrix3x3AndTranslation( AZ::Matrix3x3::CreateFromMatrix4x4(camViewMat), camViewMat.GetTranslation()); - renderUtil->RenderCircle(camViewTransform, mOuterRadius, 64, camRollAxisColor); - renderUtil->RenderCircle(camViewTransform, mInnerRadius, 64, grey); + renderUtil->RenderCircle(camViewTransform, m_outerRadius, 64, camRollAxisColor); + renderUtil->RenderCircle(camViewTransform, m_innerRadius, 64, grey); - if (mMode == ROTATE_CAMPITCHYAW) + if (m_mode == ROTATE_CAMPITCHYAW) { - renderUtil->RenderCircle(camViewTransform, mInnerRadius, 64, grey, 0.0f, MCore::Math::twoPi, true, greyTransparent); + renderUtil->RenderCircle(camViewTransform, m_innerRadius, 64, grey, 0.0f, MCore::Math::twoPi, true, greyTransparent); } - // handle the rotation around the camera roll axis - /* - if (mMode == ROTATE_CAMROLL) - { - // calculate angle of the click position to the reference directions - const float angleUp = Math::ACos( mClickPosition.Dot(upVector) ); - const float angleLeft = Math::ACos( mClickPosition.Dot(leftVector) ); - - // rotate the whole circle around pi, if rotation is in the negative direction - if (mRotation.Dot(mRotationAxis) < 0) - camViewMat = camViewMat * camViewMat.RotationMatrixAxisAngle( upVector, Math::pi ); - - // handle different dot product results (necessary because dot product only handles a range of [0, pi]) - if (angleLeft > Math::halfPi) - camViewMat = camViewMat * camViewMat.RotationMatrixAxisAngle( mRotationAxis, -angleUp ); - else - camViewMat = camViewMat * camViewMat.RotationMatrixAxisAngle( mRotationAxis, angleUp ); - - // render the rotated circle segment to represent the current rotation angle around the view axis - renderUtil->RenderCircle( camViewMat, mOuterRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, mRotation.Length(), true, greyTransparent ); - } - */ - // calculate the signs of the rotation and the angle between the axes and the click position - const float signX = (mRotation.GetX() >= 0) ? 1.0f : -1.0f; - const float signY = (mRotation.GetY() >= 0) ? 1.0f : -1.0f; - const float signZ = (mRotation.GetZ() >= 0) ? 1.0f : -1.0f; - const float angleX = MCore::Math::ACos(mClickPosition.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))); - const float angleY = MCore::Math::ACos(mClickPosition.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))); - const float angleZ = MCore::Math::ACos(mClickPosition.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))); + const float signX = (m_rotation.GetX() >= 0) ? 1.0f : -1.0f; + const float signY = (m_rotation.GetY() >= 0) ? 1.0f : -1.0f; + const float signZ = (m_rotation.GetZ() >= 0) ? 1.0f : -1.0f; + const float angleX = MCore::Math::ACos(m_clickPosition.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))); + const float angleY = MCore::Math::ACos(m_clickPosition.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))); + const float angleZ = MCore::Math::ACos(m_clickPosition.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))); // transformation matrix for the circle for rotation around the x axis AZ::Transform rotMatrixX = MCore::GetRotationMatrixAxisAngle(AZ::Vector3(0.0f, 1.0f, 0.0f), signX * MCore::Math::halfPi); // set the translation part of the matrix - rotMatrixX.SetTranslation(mPosition); + rotMatrixX.SetTranslation(m_position); // render the circle for the rotation around the x axis - if (mMode == ROTATE_X) + if (m_mode == ROTATE_X) { - renderUtil->RenderCircle(rotMatrixX, mInnerRadius, 64, grey); + renderUtil->RenderCircle(rotMatrixX, m_innerRadius, 64, grey); } - renderUtil->RenderCircle(rotMatrixX, mInnerRadius, 64, xAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis); + renderUtil->RenderCircle(rotMatrixX, m_innerRadius, 64, xAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis); // draw current angle if in x rotation mode - if (mMode == ROTATE_X) + if (m_mode == ROTATE_X) { // handle different dot product results (necessary because dot product only handles a range of [0, pi]) if (angleZ > MCore::Math::halfPi) @@ -249,28 +225,28 @@ namespace MCommon } // set the translation part of the matrix - rotMatrixX.SetTranslation(mPosition); + rotMatrixX.SetTranslation(m_position); // render the rotated circle segment to represent the current rotation angle around the x axis - renderUtil->RenderCircle(rotMatrixX, mInnerRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, MCore::Math::Abs(mRotation.GetX()), true, redTransparent, true, camRollAxis); + renderUtil->RenderCircle(rotMatrixX, m_innerRadius, 64, ManipulatorColors::s_selectionColor, 0.0f, MCore::Math::Abs(m_rotation.GetX()), true, redTransparent, true, camRollAxis); } // rotation matrix for rotation around the y axis AZ::Transform rotMatrixY = MCore::GetRotationMatrixAxisAngle(AZ::Vector3(1.0f, 0.0f, 0.0f), MCore::Math::halfPi); // set the translation part of the matrix - rotMatrixY.SetTranslation(mPosition); + rotMatrixY.SetTranslation(m_position); // render the circle for rotation around the y axis - if (mMode == ROTATE_Y) + if (m_mode == ROTATE_Y) { - renderUtil->RenderCircle(rotMatrixY, mInnerRadius, 64, grey); + renderUtil->RenderCircle(rotMatrixY, m_innerRadius, 64, grey); } - renderUtil->RenderCircle(rotMatrixY, mInnerRadius, 64, yAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis); + renderUtil->RenderCircle(rotMatrixY, m_innerRadius, 64, yAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis); // draw current angle if in y rotation mode - if (mMode == ROTATE_Y) + if (m_mode == ROTATE_Y) { // render current rotation angle depending on the dot product results calculated above if (signY > 0) @@ -293,28 +269,28 @@ namespace MCommon } // set the translation part of the matrix - rotMatrixY.SetTranslation(mPosition); + rotMatrixY.SetTranslation(m_position); // render the rotated circle segment to represent the current rotation angle around the y axis - renderUtil->RenderCircle(rotMatrixY, mInnerRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, MCore::Math::Abs(mRotation.GetY()), true, greenTransparent, true, camRollAxis); + renderUtil->RenderCircle(rotMatrixY, m_innerRadius, 64, ManipulatorColors::s_selectionColor, 0.0f, MCore::Math::Abs(m_rotation.GetY()), true, greenTransparent, true, camRollAxis); } // the circle for rotation around the z axis AZ::Transform rotMatrixZ = AZ::Transform::CreateIdentity(); // set the translation part of the matrix - rotMatrixZ.SetTranslation(mPosition); + rotMatrixZ.SetTranslation(m_position); // render the circle for rotation around the z axis - if (mMode == ROTATE_Z) + if (m_mode == ROTATE_Z) { - renderUtil->RenderCircle(rotMatrixZ, mInnerRadius, 64, grey); + renderUtil->RenderCircle(rotMatrixZ, m_innerRadius, 64, grey); } - renderUtil->RenderCircle(rotMatrixZ, mInnerRadius, 64, zAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis); + renderUtil->RenderCircle(rotMatrixZ, m_innerRadius, 64, zAxisColor, 0.0f, MCore::Math::twoPi, false, MCore::RGBAColor(), true, camRollAxis); // draw current angle if in z rotation mode - if (mMode == ROTATE_Z) + if (m_mode == ROTATE_Z) { // render current rotation angle depending on the dot product results calculated above if (signZ < 0.0f) @@ -337,56 +313,56 @@ namespace MCommon } // set the translation part of the matrix - rotMatrixZ.SetTranslation(mPosition); + rotMatrixZ.SetTranslation(m_position); // render the rotated circle segment to represent the current rotation angle around the z axis - renderUtil->RenderCircle(rotMatrixZ, mInnerRadius, 64, ManipulatorColors::mSelectionColor, 0.0f, MCore::Math::Abs(mRotation.GetZ()), true, blueTransparent, true, camRollAxis); + renderUtil->RenderCircle(rotMatrixZ, m_innerRadius, 64, ManipulatorColors::s_selectionColor, 0.0f, MCore::Math::Abs(m_rotation.GetZ()), true, blueTransparent, true, camRollAxis); } // break if in different projection mode and camera roll rotation mode - if (mCurrentProjectionMode != camera->GetProjectionMode() && mMode == ROTATE_CAMROLL) + if (m_currentProjectionMode != camera->GetProjectionMode() && m_mode == ROTATE_CAMROLL) { return; } // render the absolute rotation if gizmo is hit - if (mMode != ROTATE_NONE) + if (m_mode != ROTATE_NONE) { - const AZ::Vector3 currRot = MCore::AzQuaternionToEulerAngles(mCallback->GetCurrValueQuat()); - mTempString = AZStd::string::format("Abs. Rotation X: %.3f, Y: %.3f, Z: %.3f", MCore::Math::RadiansToDegrees(currRot.GetX() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetY() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetZ() + MCore::Math::epsilon)); - renderUtil->RenderText(10, 10, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f); + const AZ::Vector3 currRot = MCore::AzQuaternionToEulerAngles(m_callback->GetCurrValueQuat()); + m_tempString = AZStd::string::format("Abs. Rotation X: %.3f, Y: %.3f, Z: %.3f", MCore::Math::RadiansToDegrees(currRot.GetX() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetY() + MCore::Math::epsilon), MCore::Math::RadiansToDegrees(currRot.GetZ() + MCore::Math::epsilon)); + renderUtil->RenderText(10, 10, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f); } // if the rotation has been changed draw the current direction of the rotation - if (mRotation.GetLength() > 0.0f) + if (m_rotation.GetLength() > 0.0f) { // render text with the rotation values of the axes - float radius = (mMode == ROTATE_CAMROLL) ? mOuterRadius : mInnerRadius; - mTempString = AZStd::string::format("[%.2f, %.2f, %.2f]", MCore::Math::RadiansToDegrees(mRotation.GetX()), MCore::Math::RadiansToDegrees(mRotation.GetY()), MCore::Math::RadiansToDegrees(mRotation.GetZ())); + float radius = (m_mode == ROTATE_CAMROLL) ? m_outerRadius : m_innerRadius; + m_tempString = AZStd::string::format("[%.2f, %.2f, %.2f]", MCore::Math::RadiansToDegrees(m_rotation.GetX()), MCore::Math::RadiansToDegrees(m_rotation.GetY()), MCore::Math::RadiansToDegrees(m_rotation.GetZ())); //String rotationValues = String() = AZStd::string::format("[%.2f, %.2f, %.2f]", camera->GetPosition().x, camera->GetPosition().y, camera->GetPosition().z); - AZ::Vector3 textPosition = MCore::Project(mPosition + (upVector * (mOuterRadius + mTextDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight); - renderUtil->RenderText(textPosition.GetX() - 2.9f * mTempString.size(), textPosition.GetY(), mTempString.c_str(), ManipulatorColors::mSelectionColor); + AZ::Vector3 textPosition = MCore::Project(m_position + (upVector * (m_outerRadius + m_textDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight); + renderUtil->RenderText(textPosition.GetX() - 2.9f * m_tempString.size(), textPosition.GetY(), m_tempString.c_str(), ManipulatorColors::s_selectionColor); // mark the click position with a small cube - AZ::Vector3 clickPosition = mPosition + mClickPosition * radius; + AZ::Vector3 clickPosition = m_position + m_clickPosition * radius; // calculate the tangent at the click position - MCore::RGBAColor rotDirColorNegative = (mRotation.Dot(mRotationAxis) > 0.0f) ? ManipulatorColors::mSelectionColor : grey; - MCore::RGBAColor rotDirColorPositive = (mRotation.Dot(mRotationAxis) < 0.0f) ? ManipulatorColors::mSelectionColor : grey; + MCore::RGBAColor rotDirColorNegative = (m_rotation.Dot(m_rotationAxis) > 0.0f) ? ManipulatorColors::s_selectionColor : grey; + MCore::RGBAColor rotDirColorPositive = (m_rotation.Dot(m_rotationAxis) < 0.0f) ? ManipulatorColors::s_selectionColor : grey; // render the tangent directions at the click positions - AZ::Vector3 tangent = mRotationAxis.Cross(mClickPosition).GetNormalized(); - renderUtil->RenderLine(clickPosition, clickPosition + 1.5f * mAxisSize * tangent, rotDirColorPositive); - renderUtil->RenderLine(clickPosition, clickPosition - 1.5f * mAxisSize * tangent, rotDirColorNegative); - renderUtil->RenderCylinder(2.0f * mArrowBaseRadius, 0.0f, 0.5f * mAxisSize, clickPosition + 1.5f * mAxisSize * tangent, tangent, rotDirColorPositive); - renderUtil->RenderCylinder(2.0f * mArrowBaseRadius, 0.0f, 0.5f * mAxisSize, clickPosition - 1.5f * mAxisSize * tangent, -tangent, rotDirColorNegative); + AZ::Vector3 tangent = m_rotationAxis.Cross(m_clickPosition).GetNormalized(); + renderUtil->RenderLine(clickPosition, clickPosition + 1.5f * m_axisSize * tangent, rotDirColorPositive); + renderUtil->RenderLine(clickPosition, clickPosition - 1.5f * m_axisSize * tangent, rotDirColorNegative); + renderUtil->RenderCylinder(2.0f * m_arrowBaseRadius, 0.0f, 0.5f * m_axisSize, clickPosition + 1.5f * m_axisSize * tangent, tangent, rotDirColorPositive); + renderUtil->RenderCylinder(2.0f * m_arrowBaseRadius, 0.0f, 0.5f * m_axisSize, clickPosition - 1.5f * m_axisSize * tangent, -tangent, rotDirColorNegative); } else { - if (mName.size() > 0) + if (m_name.size() > 0) { - AZ::Vector3 textPosition = MCore::Project(mPosition + (upVector * (mOuterRadius + mTextDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight); - renderUtil->RenderText(textPosition.GetX(), textPosition.GetY(), mName.c_str(), ManipulatorColors::mSelectionColor, 11.0f, true); + AZ::Vector3 textPosition = MCore::Project(m_position + (upVector * (m_outerRadius + m_textDistance)), camera->GetViewProjMatrix(), screenWidth, screenHeight); + renderUtil->RenderText(textPosition.GetX(), textPosition.GetY(), m_name.c_str(), ManipulatorColors::s_selectionColor, 11.0f, true); } } } @@ -399,7 +375,7 @@ namespace MCommon MCORE_UNUSED(middleButtonPressed); // check if camera has been set - if (camera == nullptr || mIsVisible == false || (leftButtonPressed && rightButtonPressed)) + if (camera == nullptr || m_isVisible == false || (leftButtonPressed && rightButtonPressed)) { return; } @@ -407,7 +383,7 @@ namespace MCommon // update the axis visibility flags UpdateAxisDirections(camera); - // get screen mSize + // get screen m_size uint32 screenWidth = camera->GetScreenWidth(); uint32 screenHeight = camera->GetScreenHeight(); @@ -416,15 +392,15 @@ namespace MCommon //MCore::Ray mousePrevPosRay = camera->Unproject( mousePosX-mouseMovementX, mousePosY-mouseMovementY ); MCore::Ray camRollRay = camera->Unproject(screenWidth / 2, screenHeight / 2); AZ::Vector3 camRollAxis = camRollRay.GetDirection(); - mRotationQuat = AZ::Quaternion::CreateIdentity(); + m_rotationQuat = AZ::Quaternion::CreateIdentity(); // check for the selected axis/plane - if (mSelectionLocked == false || mMode == ROTATE_NONE) + if (m_selectionLocked == false || m_mode == ROTATE_NONE) { // update old rotation of the callback - if (mCallback) + if (m_callback) { - mCallback->UpdateOldValues(); + m_callback->UpdateOldValues(); } // the intersection variables @@ -432,88 +408,88 @@ namespace MCommon // set rotation mode to rotation around the x axis, if the following intersection conditions are fulfilled // innerAABB not hit, outerAABB hit, innerBoundingSphere hit and angle between cameraRollAxis and clickPosition > pi/2 - if ((mousePosRay.Intersects(mXAxisInnerAABB) == false || - (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && mXAxisVisible)) && - mousePosRay.Intersects(mXAxisAABB, &intersectA, &intersectB) && - mousePosRay.Intersects(mInnerBoundingSphere) && - MCore::Math::ACos(camRollAxis.Dot((intersectA - mPosition).GetNormalized())) > MCore::Math::halfPi) + if ((mousePosRay.Intersects(m_xAxisInnerAabb) == false || + (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && m_xAxisVisible)) && + mousePosRay.Intersects(m_xAxisAabb, &intersectA, &intersectB) && + mousePosRay.Intersects(m_innerBoundingSphere) && + MCore::Math::ACos(camRollAxis.Dot((intersectA - m_position).GetNormalized())) > MCore::Math::halfPi) { - mMode = ROTATE_X; - mRotationAxis = AZ::Vector3(1.0f, 0.0f, 0.0f); - mClickPosition = (intersectA - mPosition).GetNormalized(); - mClickPosition.SetX(0.0f); + m_mode = ROTATE_X; + m_rotationAxis = AZ::Vector3(1.0f, 0.0f, 0.0f); + m_clickPosition = (intersectA - m_position).GetNormalized(); + m_clickPosition.SetX(0.0f); } // set rotation mode to rotation around the y axis, if the following intersection conditions are fulfilled // innerAABB not hit, outerAABB hit, innerBoundingSphere hit and angle between cameraRollAxis and clickPosition > pi/2 - else if ((mousePosRay.Intersects(mYAxisInnerAABB) == false || - (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && mYAxisVisible)) && - mousePosRay.Intersects(mYAxisAABB, &intersectA, &intersectB) && mousePosRay.Intersects(mInnerBoundingSphere) && - MCore::Math::ACos(camRollAxis.Dot((intersectA - mPosition).GetNormalized())) > MCore::Math::halfPi) + else if ((mousePosRay.Intersects(m_yAxisInnerAabb) == false || + (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && m_yAxisVisible)) && + mousePosRay.Intersects(m_yAxisAabb, &intersectA, &intersectB) && mousePosRay.Intersects(m_innerBoundingSphere) && + MCore::Math::ACos(camRollAxis.Dot((intersectA - m_position).GetNormalized())) > MCore::Math::halfPi) { - mMode = ROTATE_Y; - mRotationAxis = AZ::Vector3(0.0f, 1.0f, 0.0f); - mClickPosition = (intersectA - mPosition).GetNormalized(); - mClickPosition.SetY(0.0f); + m_mode = ROTATE_Y; + m_rotationAxis = AZ::Vector3(0.0f, 1.0f, 0.0f); + m_clickPosition = (intersectA - m_position).GetNormalized(); + m_clickPosition.SetY(0.0f); } // set rotation mode to rotation around the z axis, if the following intersection conditions are fulfilled // innerAABB not hit, outerAABB hit, innerBoundingSphere hit and angle between cameraRollAxis and clickPosition > pi/2 - else if ((mousePosRay.Intersects(mZAxisInnerAABB) == false || - (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && mZAxisVisible)) && - mousePosRay.Intersects(mZAxisAABB, &intersectA, &intersectB) && mousePosRay.Intersects(mInnerBoundingSphere) && - MCore::Math::ACos(camRollAxis.Dot((intersectA - mPosition).GetNormalized())) > MCore::Math::halfPi) + else if ((mousePosRay.Intersects(m_zAxisInnerAabb) == false || + (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC && m_zAxisVisible)) && + mousePosRay.Intersects(m_zAxisAabb, &intersectA, &intersectB) && mousePosRay.Intersects(m_innerBoundingSphere) && + MCore::Math::ACos(camRollAxis.Dot((intersectA - m_position).GetNormalized())) > MCore::Math::halfPi) { - mMode = ROTATE_Z; - mRotationAxis = AZ::Vector3(0.0f, 0.0f, 1.0f); - mClickPosition = (intersectA - mPosition).GetNormalized(); - mClickPosition.SetZ(0.0f); + m_mode = ROTATE_Z; + m_rotationAxis = AZ::Vector3(0.0f, 0.0f, 1.0f); + m_clickPosition = (intersectA - m_position).GetNormalized(); + m_clickPosition.SetZ(0.0f); } // set rotation mode to rotation around the pitch and yaw axis of the camera, // if the inner sphere is hit and none of the previous conditions was fulfilled - else if (mousePosRay.Intersects(mInnerBoundingSphere, &intersectA, &intersectB)) + else if (mousePosRay.Intersects(m_innerBoundingSphere, &intersectA, &intersectB)) { - mMode = ROTATE_CAMPITCHYAW; + m_mode = ROTATE_CAMPITCHYAW; // set the rotation axis to zero, because no single axis exists in this mode - mRotationAxis = AZ::Vector3::CreateZero(); + m_rotationAxis = AZ::Vector3::CreateZero(); // project the click position onto the plane which is perpendicular to the rotation direction - MCore::PlaneEq rotationPlane(camRollAxis, mPosition); - mClickPosition = (rotationPlane.Project(intersectA - mPosition)).GetNormalized(); + MCore::PlaneEq rotationPlane(camRollAxis, m_position); + m_clickPosition = (rotationPlane.Project(intersectA - m_position)).GetNormalized(); } // set rotation mode to rotation around the roll axis of the camera, // if the outer sphere is hit and none of the previous conditions was fulfilled - else if (mousePosRay.Intersects(mOuterBoundingSphere, &intersectA, &intersectB)) + else if (mousePosRay.Intersects(m_outerBoundingSphere, &intersectA, &intersectB)) { // set rotation mode to rotate around the view axis - mMode = ROTATE_CAMROLL; + m_mode = ROTATE_CAMROLL; // set the rotation axis to the look at ray direction - mRotationAxis = camRollRay.GetDirection(); + m_rotationAxis = camRollRay.GetDirection(); // project the click position onto the plane which is perpendicular to the rotation direction - MCore::PlaneEq rotationPlane(mRotationAxis, AZ::Vector3::CreateZero()); - mClickPosition = (rotationPlane.Project(intersectA - mPosition)).GetNormalized(); + MCore::PlaneEq rotationPlane(m_rotationAxis, AZ::Vector3::CreateZero()); + m_clickPosition = (rotationPlane.Project(intersectA - m_position)).GetNormalized(); } // no bounding volume is currently hit, therefore do not rotate else { - mMode = ROTATE_NONE; + m_mode = ROTATE_NONE; } } // set selection lock and current projection mode - mSelectionLocked = leftButtonPressed; - mCurrentProjectionMode = camera->GetProjectionMode(); + m_selectionLocked = leftButtonPressed; + m_currentProjectionMode = camera->GetProjectionMode(); // reset the gizmo if no rotation mode is selected - if (mSelectionLocked == false || mMode == ROTATE_NONE) + if (m_selectionLocked == false || m_mode == ROTATE_NONE) { - mRotation = AZ::Vector3::CreateZero(); + m_rotation = AZ::Vector3::CreateZero(); return; } @@ -527,13 +503,13 @@ namespace MCommon } // set the rotation depending on the rotation mode - if (mMode == ROTATE_CAMPITCHYAW) + if (m_mode == ROTATE_CAMPITCHYAW) { // the yaw axis of the camera view MCore::Ray camYawRay = camera->Unproject(screenWidth / 2, screenHeight / 2 - 10); // calculate the plane perpendicular to the view rotation axis - MCore::PlaneEq rotationPlane(camRollAxis, mPosition); + MCore::PlaneEq rotationPlane(camRollAxis, m_position); // get the intersection points of the rays and the plane AZ::Vector3 originRayIntersect, upVecRayIntersect; @@ -548,69 +524,46 @@ namespace MCommon // calculate the projected axes, used to determine the angle between click position // and the axes. This allows weighting the angles by the movement direction. - AZ::Vector3 projectedCenter = MCore::Project(mPosition, camera->GetViewProjMatrix(), screenWidth, screenHeight); - AZ::Vector3 projectedClickPosYaw = MCore::Project(mPosition - leftVector, camera->GetViewProjMatrix(), screenWidth, screenHeight); - AZ::Vector3 projectedClickPosPitch = MCore::Project(mPosition - upVector, camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 projectedCenter = MCore::Project(m_position, camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 projectedClickPosYaw = MCore::Project(m_position - leftVector, camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 projectedClickPosPitch = MCore::Project(m_position - upVector, camera->GetViewProjMatrix(), screenWidth, screenHeight); AZ::Vector3 projDirClickPosYaw = (projectedClickPosYaw - projectedCenter).GetNormalized(); AZ::Vector3 projDirClickPosPitch = (projectedClickPosPitch - projectedCenter).GetNormalized(); // calculate the angle between mouse movement and projected rotation axis - float angleYaw = projDirClickPosYaw.Dot(mouseMovementV3) * mScalingFactor * movementLength * 0.00005f; - float anglePitch = projDirClickPosPitch.Dot(mouseMovementV3) * mScalingFactor * movementLength * 0.00005f; + float angleYaw = projDirClickPosYaw.Dot(mouseMovementV3) * m_scalingFactor * movementLength * 0.00005f; + float anglePitch = projDirClickPosPitch.Dot(mouseMovementV3) * m_scalingFactor * movementLength * 0.00005f; // perform rotation arround the cam yaw and pitch axis AZ::Quaternion rotation = MCore::CreateFromAxisAndAngle(upVector, -angleYaw); rotation = rotation * MCore::CreateFromAxisAndAngle(leftVector, anglePitch); // set euler angles of the rotation variable - mRotation += MCore::AzQuaternionToEulerAngles(rotation); - mRotationQuat = rotation; + m_rotation += MCore::AzQuaternionToEulerAngles(rotation); + m_rotationQuat = rotation; } else { - /* - // HINT: uncommented stuff is the exact rotation, used in maya - // generate current translation plane and calculate mouse intersections - MCore::PlaneEq movementPlane( mRotationAxis, mPosition ); - Vector3 mousePosIntersect, mousePrevPosIntersect; - mousePosRay.Intersects( movementPlane, &mousePosIntersect ); - mousePrevPosRay.Intersects( movementPlane, &mousePrevPosIntersect ); - - // normalize the intersection points, as only the angle between them is needed - mousePosIntersect = (mousePosIntersect - mPosition).Normalize(); - mousePrevPosIntersect = (mousePrevPosIntersect - mPosition).Normalize(); - - // distance of the mouse intersections is the actual movement on the plane - float angleSign = MCore::Sgn((mRotationAxis.Cross(mousePosIntersect-mousePrevPosIntersect)).Dot(mousePosIntersect)); - float angle = MCore::Math::ACos( (mousePrevPosIntersect).Dot((mousePosIntersect)) ) * angleSign; - - mRotation += mRotationAxis * angle; - mRotation = Vector3( MCore::Clamp(mRotation.x, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.y, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.z, -Math::twoPi, Math::twoPi) ); - mRotationQuat = Quaternion( mRotationAxis, MCore::Clamp(-angle, -Math::twoPi, Math::twoPi) ); - */ // calculate the projected center and click position to determine the rotation angle - AZ::Vector3 tangent = (mRotationAxis.Cross(mClickPosition)).GetNormalized(); - AZ::Vector3 projectedCenter = MCore::Project(mPosition, camera->GetViewProjMatrix(), screenWidth, screenHeight); - AZ::Vector3 projectedClickPos = MCore::Project(mPosition - tangent, camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 tangent = (m_rotationAxis.Cross(m_clickPosition)).GetNormalized(); + AZ::Vector3 projectedCenter = MCore::Project(m_position, camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 projectedClickPos = MCore::Project(m_position - tangent, camera->GetViewProjMatrix(), screenWidth, screenHeight); AZ::Vector3 projDirClickPos = (projectedClickPos - projectedCenter); - // calculate the angle between mouse movement and projected rotation axis - //float angle = Math::DegreesToRadians(Math::Floor(Math::RadiansToDegrees((projDirClickPos.Dot( mouseMovementV3 ) * mScalingFactor * 0.00002f) * movementLength))); float angle = MCore::Math::DegreesToRadians(MCore::Sgn(projDirClickPos.Dot(mouseMovementV3)) * 0.2f * MCore::Math::Floor(movementLength + 0.5f)); // adjust rotation - mRotation += mRotationAxis * angle; - //mRotation = Vector3( MCore::Clamp(mRotation.x, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.y, -Math::twoPi, Math::twoPi), MCore::Clamp(mRotation.z, -Math::twoPi, Math::twoPi) ); - mRotationQuat = AZ::Quaternion::CreateFromAxisAngle(mRotationAxis, MCore::Math::FMod(-angle, MCore::Math::twoPi)); - mRotationQuat.Normalize(); + m_rotation += m_rotationAxis * angle; + m_rotationQuat = AZ::Quaternion::CreateFromAxisAngle(m_rotationAxis, MCore::Math::FMod(-angle, MCore::Math::twoPi)); + m_rotationQuat.Normalize(); } // update the callback - if (mCallback) + if (m_callback) { - const AZ::Quaternion curRot = mCallback->GetCurrValueQuat(); - const AZ::Quaternion newRot = (curRot * mRotationQuat).GetNormalized(); - mCallback->Update(newRot); + const AZ::Quaternion curRot = m_callback->GetCurrValueQuat(); + const AZ::Quaternion newRot = (curRot * m_rotationQuat).GetNormalized(); + m_callback->Update(newRot); } } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h index c6d719ae7c..4a664b1526 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/RotateManipulator.h @@ -8,7 +8,7 @@ #pragma once -// include the Core system +#include #include #include #include @@ -88,40 +88,40 @@ namespace MCommon void ProcessMouseInput(MCommon::Camera* camera, int32 mousePosX, int32 mousePosY, int32 mouseMovementX, int32 mouseMovementY, bool leftButtonPressed, bool middleButtonPressed, bool rightButtonPressed, uint32 keyboardKeyFlags = 0); protected: - AZ::Vector3 mRotation; - AZ::Quaternion mRotationQuat; - AZ::Vector3 mRotationAxis; - AZ::Vector3 mClickPosition; + AZ::Vector3 m_rotation; + AZ::Quaternion m_rotationQuat; + AZ::Vector3 m_rotationAxis; + AZ::Vector3 m_clickPosition; // bounding volumes for the axes - MCore::BoundingSphere mInnerBoundingSphere; - MCore::BoundingSphere mOuterBoundingSphere; - MCore::AABB mXAxisAABB; - MCore::AABB mYAxisAABB; - MCore::AABB mZAxisAABB; - MCore::AABB mXAxisInnerAABB; - MCore::AABB mYAxisInnerAABB; - MCore::AABB mZAxisInnerAABB; + MCore::BoundingSphere m_innerBoundingSphere; + MCore::BoundingSphere m_outerBoundingSphere; + MCore::AABB m_xAxisAabb; + MCore::AABB m_yAxisAabb; + MCore::AABB m_zAxisAabb; + MCore::AABB m_xAxisInnerAabb; + MCore::AABB m_yAxisInnerAabb; + MCore::AABB m_zAxisInnerAabb; // the proportions of the rotation manipulator - float mSize; - float mInnerRadius; - float mOuterRadius; - float mArrowBaseRadius; - float mAABBWidth; - float mAxisSize; - float mTextDistance; - float mInnerQuadSize; + float m_size; + float m_innerRadius; + float m_outerRadius; + float m_arrowBaseRadius; + float m_aabbWidth; + float m_axisSize; + float m_textDistance; + float m_innerQuadSize; // orientation information - float mSignX; - float mSignY; - float mSignZ; - bool mXAxisVisible; - bool mYAxisVisible; - bool mZAxisVisible; + float m_signX; + float m_signY; + float m_signZ; + bool m_xAxisVisible; + bool m_yAxisVisible; + bool m_zAxisVisible; // store the projection mode of the current render widget - MCommon::Camera::ProjectionMode mCurrentProjectionMode; + MCommon::Camera::ProjectionMode m_currentProjectionMode; }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp index 65915aec65..a1bb69110d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.cpp @@ -16,12 +16,12 @@ namespace MCommon : TransformationManipulator(scalingFactor, isVisible) { // set the initial values - mMode = SCALE_NONE; - mSelectionLocked = false; - mCallback = nullptr; - mPosition = AZ::Vector3::CreateZero(); - mScaleDirection = AZ::Vector3::CreateZero(); - mScale = AZ::Vector3::CreateZero(); + m_mode = SCALE_NONE; + m_selectionLocked = false; + m_callback = nullptr; + m_position = AZ::Vector3::CreateZero(); + m_scaleDirection = AZ::Vector3::CreateZero(); + m_scale = AZ::Vector3::CreateZero(); } @@ -40,35 +40,35 @@ namespace MCommon UpdateAxisDirections(camera); } - mSize = mScalingFactor; - mScaledSize = AZ::Vector3(mSize, mSize, mSize) + AZ::Vector3(MCore::Max(float(mScale.GetX()), -mSize), MCore::Max(float(mScale.GetY()), -mSize), MCore::Max(float(mScale.GetZ()), -mSize)); - mDiagScale = 0.5f; - mArrowLength = mSize / 10.0f; - mBaseRadius = mSize / 15.0f; + m_size = m_scalingFactor; + m_scaledSize = AZ::Vector3(m_size, m_size, m_size) + AZ::Vector3(MCore::Max(float(m_scale.GetX()), -m_size), MCore::Max(float(m_scale.GetY()), -m_size), MCore::Max(float(m_scale.GetZ()), -m_size)); + m_diagScale = 0.5f; + m_arrowLength = m_size / 10.0f; + m_baseRadius = m_size / 15.0f; // positions for the plane selectors - mFirstPlaneSelectorPos = mScaledSize * 0.3f; - mSecPlaneSelectorPos = mScaledSize * 0.6f; + m_firstPlaneSelectorPos = m_scaledSize * 0.3f; + m_secPlaneSelectorPos = m_scaledSize * 0.6f; // set the bounding volumes of the axes selection - mXAxisAABB.SetMax(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mArrowLength, mBaseRadius, mBaseRadius)); - mXAxisAABB.SetMin(mPosition - mSignX * AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); - mYAxisAABB.SetMax(mPosition + mSignY * AZ::Vector3(mBaseRadius, mScaledSize.GetY() + mArrowLength, mBaseRadius)); - mYAxisAABB.SetMin(mPosition - mSignY * AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); - mZAxisAABB.SetMax(mPosition + mSignZ * AZ::Vector3(mBaseRadius, mBaseRadius, mScaledSize.GetZ() + mArrowLength)); - mZAxisAABB.SetMin(mPosition - mSignZ * AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); + m_xAxisAabb.SetMax(m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + m_arrowLength, m_baseRadius, m_baseRadius)); + m_xAxisAabb.SetMin(m_position - m_signX * AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); + m_yAxisAabb.SetMax(m_position + m_signY * AZ::Vector3(m_baseRadius, m_scaledSize.GetY() + m_arrowLength, m_baseRadius)); + m_yAxisAabb.SetMin(m_position - m_signY * AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); + m_zAxisAabb.SetMax(m_position + m_signZ * AZ::Vector3(m_baseRadius, m_baseRadius, m_scaledSize.GetZ() + m_arrowLength)); + m_zAxisAabb.SetMin(m_position - m_signZ * AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); // set bounding volumes for the plane selectors - mXYPlaneAABB.SetMax(mPosition + AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, mSecPlaneSelectorPos.GetY() * mSignY, mBaseRadius * mSignZ)); - mXYPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, mSecPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ)); - mXZPlaneAABB.SetMax(mPosition + AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, mBaseRadius * mSignY, mSecPlaneSelectorPos.GetZ() * mSignZ)); - mXZPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ)); - mYZPlaneAABB.SetMax(mPosition + AZ::Vector3(mBaseRadius * mSignX, mSecPlaneSelectorPos.GetY() * mSignY, mSecPlaneSelectorPos.GetZ() * mSignZ)); - mYZPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ)); + m_xyPlaneAabb.SetMax(m_position + AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, m_secPlaneSelectorPos.GetY() * m_signY, m_baseRadius * m_signZ)); + m_xyPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, m_secPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ)); + m_xzPlaneAabb.SetMax(m_position + AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, m_baseRadius * m_signY, m_secPlaneSelectorPos.GetZ() * m_signZ)); + m_xzPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ)); + m_yzPlaneAabb.SetMax(m_position + AZ::Vector3(m_baseRadius * m_signX, m_secPlaneSelectorPos.GetY() * m_signY, m_secPlaneSelectorPos.GetZ() * m_signZ)); + m_yzPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ)); // set bounding volume for the box selector - mXYZBoxAABB.SetMin(mPosition - AZ::Vector3(mBaseRadius * mSignX, mBaseRadius * mSignY, mBaseRadius * mSignZ)); - mXYZBoxAABB.SetMax(mPosition + mDiagScale * AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, mFirstPlaneSelectorPos.GetY() * mSignY, mFirstPlaneSelectorPos.GetZ() * mSignZ)); + m_xyzBoxAabb.SetMin(m_position - AZ::Vector3(m_baseRadius * m_signX, m_baseRadius * m_signY, m_baseRadius * m_signZ)); + m_xyzBoxAabb.SetMax(m_position + m_diagScale * AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, m_firstPlaneSelectorPos.GetY() * m_signY, m_firstPlaneSelectorPos.GetZ() * m_signZ)); } @@ -89,14 +89,14 @@ namespace MCommon MCore::Ray camRay = camera->Unproject(screenWidth / 2, screenHeight / 2); AZ::Vector3 camDir = camRay.GetDirection(); - mSignX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f; - mSignY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f; - mSignZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f; + m_signX = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f; + m_signY = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f; + m_signZ = (MCore::Math::ACos(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) >= MCore::Math::halfPi - MCore::Math::epsilon) ? 1.0f : -1.0f; // determine the axis visibility, to disable movement for invisible axes - mXAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); - mYAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); - mZAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_xAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_yAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_zAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); } @@ -116,13 +116,13 @@ namespace MCommon MCore::Ray mouseRay = camera->Unproject(mousePosX, mousePosY); // check if one of the AABBs is hit - if (mouseRay.Intersects(mXAxisAABB) || - mouseRay.Intersects(mYAxisAABB) || - mouseRay.Intersects(mZAxisAABB) || - mouseRay.Intersects(mXYPlaneAABB) || - mouseRay.Intersects(mXZPlaneAABB) || - mouseRay.Intersects(mYZPlaneAABB) || - mouseRay.Intersects(mXYZBoxAABB)) + if (mouseRay.Intersects(m_xAxisAabb) || + mouseRay.Intersects(m_yAxisAabb) || + mouseRay.Intersects(m_zAxisAabb) || + mouseRay.Intersects(m_xyPlaneAabb) || + mouseRay.Intersects(m_xzPlaneAabb) || + mouseRay.Intersects(m_yzPlaneAabb) || + mouseRay.Intersects(m_xyzBoxAabb)) { return true; } @@ -136,12 +136,12 @@ namespace MCommon void ScaleManipulator::Render(MCommon::Camera* camera, RenderUtil* renderUtil) { // return if no render util is set - if (renderUtil == nullptr || camera == nullptr || mIsVisible == false) + if (renderUtil == nullptr || camera == nullptr || m_isVisible == false) { return; } - // set mSize variables for the gizmo + // set m_size variables for the gizmo const uint32 screenWidth = camera->GetScreenWidth(); const uint32 screenHeight = camera->GetScreenHeight(); @@ -149,131 +149,131 @@ namespace MCommon UpdateAxisDirections(camera); // set color for the axes, depending on the selection (TODO: maybe put these into the constructor.) - MCore::RGBAColor xAxisColor = (mMode == SCALE_XYZ || mMode == SCALE_X || mMode == SCALE_XY || mMode == SCALE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor yAxisColor = (mMode == SCALE_XYZ || mMode == SCALE_Y || mMode == SCALE_XY || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor zAxisColor = (mMode == SCALE_XYZ || mMode == SCALE_Z || mMode == SCALE_XZ || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; - MCore::RGBAColor xyPlaneColorX = (mMode == SCALE_XYZ || mMode == SCALE_XY) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor xyPlaneColorY = (mMode == SCALE_XYZ || mMode == SCALE_XY) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor xzPlaneColorX = (mMode == SCALE_XYZ || mMode == SCALE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor xzPlaneColorZ = (mMode == SCALE_XYZ || mMode == SCALE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; - MCore::RGBAColor yzPlaneColorY = (mMode == SCALE_XYZ || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor yzPlaneColorZ = (mMode == SCALE_XYZ || mMode == SCALE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; + MCore::RGBAColor xAxisColor = (m_mode == SCALE_XYZ || m_mode == SCALE_X || m_mode == SCALE_XY || m_mode == SCALE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor yAxisColor = (m_mode == SCALE_XYZ || m_mode == SCALE_Y || m_mode == SCALE_XY || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor zAxisColor = (m_mode == SCALE_XYZ || m_mode == SCALE_Z || m_mode == SCALE_XZ || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; + MCore::RGBAColor xyPlaneColorX = (m_mode == SCALE_XYZ || m_mode == SCALE_XY) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor xyPlaneColorY = (m_mode == SCALE_XYZ || m_mode == SCALE_XY) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor xzPlaneColorX = (m_mode == SCALE_XYZ || m_mode == SCALE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor xzPlaneColorZ = (m_mode == SCALE_XYZ || m_mode == SCALE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; + MCore::RGBAColor yzPlaneColorY = (m_mode == SCALE_XYZ || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor yzPlaneColorZ = (m_mode == SCALE_XYZ || m_mode == SCALE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; // the x axis with cube at the line end - AZ::Vector3 firstPlanePosX = mPosition + mSignX * AZ::Vector3(mFirstPlaneSelectorPos.GetX(), 0.0f, 0.0f); - AZ::Vector3 secPlanePosX = mPosition + mSignX * AZ::Vector3(mSecPlaneSelectorPos.GetX(), 0.0f, 0.0f); - if (mXAxisVisible) + AZ::Vector3 firstPlanePosX = m_position + m_signX * AZ::Vector3(m_firstPlaneSelectorPos.GetX(), 0.0f, 0.0f); + AZ::Vector3 secPlanePosX = m_position + m_signX * AZ::Vector3(m_secPlaneSelectorPos.GetX(), 0.0f, 0.0f); + if (m_xAxisVisible) { - renderUtil->RenderLine(mPosition, mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + 0.5f * mBaseRadius, 0.0f, 0.0f), xAxisColor); - AZ::Vector3 quadPos = MCore::Project(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mBaseRadius, 0, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); - renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mRed, ManipulatorColors::mRed); + renderUtil->RenderLine(m_position, m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + 0.5f * m_baseRadius, 0.0f, 0.0f), xAxisColor); + AZ::Vector3 quadPos = MCore::Project(m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + m_baseRadius, 0, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); + renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::s_red, ManipulatorColors::s_red); // render the plane selector lines - renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + mDiagScale * (AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0)), xyPlaneColorX); - renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + mDiagScale * (AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0)), xzPlaneColorX); - renderUtil->RenderLine(secPlanePosX, secPlanePosX + mDiagScale * (AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0)), xyPlaneColorX); - renderUtil->RenderLine(secPlanePosX, secPlanePosX + mDiagScale * (AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0)), xzPlaneColorX); + renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + m_diagScale * (AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0)), xyPlaneColorX); + renderUtil->RenderLine(firstPlanePosX, firstPlanePosX + m_diagScale * (AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0)), xzPlaneColorX); + renderUtil->RenderLine(secPlanePosX, secPlanePosX + m_diagScale * (AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0)), xyPlaneColorX); + renderUtil->RenderLine(secPlanePosX, secPlanePosX + m_diagScale * (AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0)), xzPlaneColorX); } // the y axis with cube at the line end - AZ::Vector3 firstPlanePosY = mPosition + mSignY * AZ::Vector3(0.0f, mFirstPlaneSelectorPos.GetY(), 0.0f); - AZ::Vector3 secPlanePosY = mPosition + mSignY * AZ::Vector3(0.0f, mSecPlaneSelectorPos.GetY(), 0.0f); - if (mYAxisVisible) + AZ::Vector3 firstPlanePosY = m_position + m_signY * AZ::Vector3(0.0f, m_firstPlaneSelectorPos.GetY(), 0.0f); + AZ::Vector3 secPlanePosY = m_position + m_signY * AZ::Vector3(0.0f, m_secPlaneSelectorPos.GetY(), 0.0f); + if (m_yAxisVisible) { - renderUtil->RenderLine(mPosition, mPosition + mSignY * AZ::Vector3(0.0f, mScaledSize.GetY(), 0.0f), yAxisColor); - AZ::Vector3 quadPos = MCore::Project(mPosition + mSignY * AZ::Vector3(0, mScaledSize.GetY() + 0.5f * mBaseRadius, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); - renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mGreen, ManipulatorColors::mGreen); + renderUtil->RenderLine(m_position, m_position + m_signY * AZ::Vector3(0.0f, m_scaledSize.GetY(), 0.0f), yAxisColor); + AZ::Vector3 quadPos = MCore::Project(m_position + m_signY * AZ::Vector3(0, m_scaledSize.GetY() + 0.5f * m_baseRadius, 0), camera->GetViewProjMatrix(), screenWidth, screenHeight); + renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::s_green, ManipulatorColors::s_green); // render the plane selector lines - renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + mDiagScale * (AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0)), xyPlaneColorY); - renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + mDiagScale * (AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0)), yzPlaneColorY); - renderUtil->RenderLine(secPlanePosY, secPlanePosY + mDiagScale * (AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0)), xyPlaneColorY); - renderUtil->RenderLine(secPlanePosY, secPlanePosY + mDiagScale * (AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ) - AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0)), yzPlaneColorY); + renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + m_diagScale * (AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0)), xyPlaneColorY); + renderUtil->RenderLine(firstPlanePosY, firstPlanePosY + m_diagScale * (AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0)), yzPlaneColorY); + renderUtil->RenderLine(secPlanePosY, secPlanePosY + m_diagScale * (AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0)), xyPlaneColorY); + renderUtil->RenderLine(secPlanePosY, secPlanePosY + m_diagScale * (AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ) - AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0)), yzPlaneColorY); } // the z axis with cube at the line end - AZ::Vector3 firstPlanePosZ = mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mFirstPlaneSelectorPos.GetZ()); - AZ::Vector3 secPlanePosZ = mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mSecPlaneSelectorPos.GetZ()); - if (mZAxisVisible) + AZ::Vector3 firstPlanePosZ = m_position + m_signZ * AZ::Vector3(0.0f, 0.0f, m_firstPlaneSelectorPos.GetZ()); + AZ::Vector3 secPlanePosZ = m_position + m_signZ * AZ::Vector3(0.0f, 0.0f, m_secPlaneSelectorPos.GetZ()); + if (m_zAxisVisible) { - renderUtil->RenderLine(mPosition, mPosition + mSignZ * AZ::Vector3(0.0f, 0.0f, mScaledSize.GetZ()), zAxisColor); - AZ::Vector3 quadPos = MCore::Project(mPosition + mSignZ * AZ::Vector3(0, 0, mScaledSize.GetZ() + 0.5f * mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); - renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::mBlue, ManipulatorColors::mBlue); + renderUtil->RenderLine(m_position, m_position + m_signZ * AZ::Vector3(0.0f, 0.0f, m_scaledSize.GetZ()), zAxisColor); + AZ::Vector3 quadPos = MCore::Project(m_position + m_signZ * AZ::Vector3(0, 0, m_scaledSize.GetZ() + 0.5f * m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); + renderUtil->RenderBorderedRect(static_cast(quadPos.GetX() - 2.0f), static_cast(quadPos.GetX() + 3.0f), static_cast(quadPos.GetY() - 2.0f), static_cast(quadPos.GetY() + 3.0f), ManipulatorColors::s_blue, ManipulatorColors::s_blue); // render the plane selector lines - renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + mDiagScale * (AZ::Vector3(mFirstPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ)), xzPlaneColorZ); - renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + mDiagScale * (AZ::Vector3(0, mFirstPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(0, 0, mFirstPlaneSelectorPos.GetZ() * mSignZ)), yzPlaneColorZ); - renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + mDiagScale * (AZ::Vector3(mSecPlaneSelectorPos.GetX() * mSignX, 0, 0) - AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ)), xzPlaneColorZ); - renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + mDiagScale * (AZ::Vector3(0, mSecPlaneSelectorPos.GetY() * mSignY, 0) - AZ::Vector3(0, 0, mSecPlaneSelectorPos.GetZ() * mSignZ)), yzPlaneColorZ); + renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + m_diagScale * (AZ::Vector3(m_firstPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ)), xzPlaneColorZ); + renderUtil->RenderLine(firstPlanePosZ, firstPlanePosZ + m_diagScale * (AZ::Vector3(0, m_firstPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(0, 0, m_firstPlaneSelectorPos.GetZ() * m_signZ)), yzPlaneColorZ); + renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + m_diagScale * (AZ::Vector3(m_secPlaneSelectorPos.GetX() * m_signX, 0, 0) - AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ)), xzPlaneColorZ); + renderUtil->RenderLine(secPlanePosZ, secPlanePosZ + m_diagScale * (AZ::Vector3(0, m_secPlaneSelectorPos.GetY() * m_signY, 0) - AZ::Vector3(0, 0, m_secPlaneSelectorPos.GetZ() * m_signZ)), yzPlaneColorZ); } // calculate projected positions for the axis labels and render the text - AZ::Vector3 textPosY = MCore::Project(mPosition + mSignY * AZ::Vector3(0.0, mScaledSize.GetY() + mArrowLength + mBaseRadius, -mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); - AZ::Vector3 textPosX = MCore::Project(mPosition + mSignX * AZ::Vector3(mScaledSize.GetX() + mArrowLength + mBaseRadius, -mBaseRadius, 0.0), camera->GetViewProjMatrix(), screenWidth, screenHeight); - AZ::Vector3 textPosZ = MCore::Project(mPosition + mSignZ * AZ::Vector3(0.0, mBaseRadius, mScaledSize.GetZ() + mArrowLength + mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 textPosY = MCore::Project(m_position + m_signY * AZ::Vector3(0.0, m_scaledSize.GetY() + m_arrowLength + m_baseRadius, -m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 textPosX = MCore::Project(m_position + m_signX * AZ::Vector3(m_scaledSize.GetX() + m_arrowLength + m_baseRadius, -m_baseRadius, 0.0), camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 textPosZ = MCore::Project(m_position + m_signZ * AZ::Vector3(0.0, m_baseRadius, m_scaledSize.GetZ() + m_arrowLength + m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderText(textPosX.GetX(), textPosX.GetY(), "X", xAxisColor); renderUtil->RenderText(textPosY.GetX(), textPosY.GetY(), "Y", yAxisColor); renderUtil->RenderText(textPosZ.GetX(), textPosZ.GetY(), "Z", zAxisColor); // Render the triangles for plane selection - if (mMode == SCALE_XY && mXAxisVisible && mYAxisVisible) + if (m_mode == SCALE_XY && m_xAxisVisible && m_yAxisVisible) { - renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosY, ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(firstPlanePosX, secPlanePosY, firstPlanePosY, ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosY, ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosX, secPlanePosY, firstPlanePosY, ManipulatorColors::s_selectionColorDarker); } - else if (mMode == SCALE_XZ && mXAxisVisible && mZAxisVisible) + else if (m_mode == SCALE_XZ && m_xAxisVisible && m_zAxisVisible) { - renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosZ, ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(firstPlanePosX, secPlanePosZ, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosX, secPlanePosX, secPlanePosZ, ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosX, secPlanePosZ, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker); } - else if (mMode == SCALE_YZ && mYAxisVisible && mZAxisVisible) + else if (m_mode == SCALE_YZ && m_yAxisVisible && m_zAxisVisible) { - renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosZ, secPlanePosY, ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosY, firstPlanePosY, ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosZ, secPlanePosY, ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosZ, secPlanePosY, firstPlanePosY, ManipulatorColors::s_selectionColorDarker); } - else if (mMode == SCALE_XYZ) + else if (m_mode == SCALE_XYZ) { - renderUtil->RenderTriangle(firstPlanePosX, firstPlanePosY, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(mPosition, firstPlanePosX, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(mPosition, firstPlanePosX, firstPlanePosY, ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(mPosition, firstPlanePosY, firstPlanePosZ, ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(firstPlanePosX, firstPlanePosY, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(m_position, firstPlanePosX, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(m_position, firstPlanePosX, firstPlanePosY, ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(m_position, firstPlanePosY, firstPlanePosZ, ManipulatorColors::s_selectionColorDarker); } // check if callback exists - if (mCallback == nullptr) + if (m_callback == nullptr) { return; } // render the current scale factor in percent if gizmo is hit - if (mMode != SCALE_NONE) + if (m_mode != SCALE_NONE) { - const AZ::Vector3& currScale = mCallback->GetCurrValueVec(); - mTempString = AZStd::string::format("Abs. Scale X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(currScale.GetX()), 0.0f), MCore::Max(float(currScale.GetY()), 0.0f), MCore::Max(float(currScale.GetZ()), 0.0f)); - renderUtil->RenderText(10, 10, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f); + const AZ::Vector3& currScale = m_callback->GetCurrValueVec(); + m_tempString = AZStd::string::format("Abs. Scale X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(currScale.GetX()), 0.0f), MCore::Max(float(currScale.GetY()), 0.0f), MCore::Max(float(currScale.GetZ()), 0.0f)); + renderUtil->RenderText(10, 10, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f); } // calculate the position offset of the relative text float yOffset = (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_PERSPECTIVE) ? 80.0f : 50.0f; // text position relative scaling or name displayed below the gizmo - AZ::Vector3 textPos = MCore::Project(mPosition + (mSize * AZ::Vector3(mSignX, mSignY, mSignZ) / 3.0f), camera->GetViewProjMatrix(), camera->GetScreenWidth(), camera->GetScreenHeight()); + AZ::Vector3 textPos = MCore::Project(m_position + (m_size * AZ::Vector3(m_signX, m_signY, m_signZ) / 3.0f), camera->GetViewProjMatrix(), camera->GetScreenWidth(), camera->GetScreenHeight()); // render the relative scale when moving - if (mSelectionLocked && mMode != SCALE_NONE) + if (m_selectionLocked && m_mode != SCALE_NONE) { // calculate the scale factor - AZ::Vector3 scaleFactor = ((AZ::Vector3(mSize, mSize, mSize) + mScale) / (float)mSize); + AZ::Vector3 scaleFactor = ((AZ::Vector3(m_size, m_size, m_size) + m_scale) / (float)m_size); // render the scaling value below the gizmo - mTempString = AZStd::string::format("X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(scaleFactor.GetX()), 0.0f), MCore::Max(float(scaleFactor.GetY()), 0.0f), MCore::Max(float(scaleFactor.GetZ()), 0.0f)); - renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f, true); + m_tempString = AZStd::string::format("X: %.3f, Y: %.3f, Z: %.3f", MCore::Max(float(scaleFactor.GetX()), 0.0f), MCore::Max(float(scaleFactor.GetY()), 0.0f), MCore::Max(float(scaleFactor.GetZ()), 0.0f)); + renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f, true); } else { - if (mName.size() > 0) + if (m_name.size() > 0) { - renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, mName.c_str(), ManipulatorColors::mSelectionColor, 9.0f, true); + renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, m_name.c_str(), ManipulatorColors::s_selectionColor, 9.0f, true); } } } @@ -286,12 +286,12 @@ namespace MCommon MCORE_UNUSED(middleButtonPressed); // check if camera has been set - if (camera == nullptr || mIsVisible == false || (leftButtonPressed && rightButtonPressed)) + if (camera == nullptr || m_isVisible == false || (leftButtonPressed && rightButtonPressed)) { return; } - // get screen mSize + // get screen m_size const uint32 screenWidth = camera->GetScreenWidth(); const uint32 screenHeight = camera->GetScreenHeight(); @@ -303,63 +303,63 @@ namespace MCommon MCore::Ray mousePrevPosRay = camera->Unproject(mousePosX - mouseMovementX, mousePosY - mouseMovementY); // check for the selected axis/plane - if (mSelectionLocked == false || mMode == SCALE_NONE) + if (m_selectionLocked == false || m_mode == SCALE_NONE) { // update old rotation of the callback - if (mCallback) + if (m_callback) { - mCallback->UpdateOldValues(); + m_callback->UpdateOldValues(); } // handle different scale cases depending on the bounding volumes - if (mousePosRay.Intersects(mXYZBoxAABB)) + if (mousePosRay.Intersects(m_xyzBoxAabb)) { - mMode = SCALE_XYZ; - mScaleDirection = AZ::Vector3(mSignX, mSignY, mSignZ); + m_mode = SCALE_XYZ; + m_scaleDirection = AZ::Vector3(m_signX, m_signY, m_signZ); } - else if (mousePosRay.Intersects(mXYPlaneAABB) && mXAxisVisible && mYAxisVisible) + else if (mousePosRay.Intersects(m_xyPlaneAabb) && m_xAxisVisible && m_yAxisVisible) { - mMode = SCALE_XY; - mScaleDirection = AZ::Vector3(mSignX, mSignY, 0.0f); + m_mode = SCALE_XY; + m_scaleDirection = AZ::Vector3(m_signX, m_signY, 0.0f); } - else if (mousePosRay.Intersects(mXZPlaneAABB) && mXAxisVisible && mZAxisVisible) + else if (mousePosRay.Intersects(m_xzPlaneAabb) && m_xAxisVisible && m_zAxisVisible) { - mMode = SCALE_XZ; - mScaleDirection = AZ::Vector3(mSignX, 0.0f, mSignZ); + m_mode = SCALE_XZ; + m_scaleDirection = AZ::Vector3(m_signX, 0.0f, m_signZ); } - else if (mousePosRay.Intersects(mYZPlaneAABB) && mYAxisVisible && mZAxisVisible) + else if (mousePosRay.Intersects(m_yzPlaneAabb) && m_yAxisVisible && m_zAxisVisible) { - mMode = SCALE_YZ; - mScaleDirection = AZ::Vector3(0.0f, mSignY, mSignZ); + m_mode = SCALE_YZ; + m_scaleDirection = AZ::Vector3(0.0f, m_signY, m_signZ); } - else if (mousePosRay.Intersects(mXAxisAABB) && mXAxisVisible) + else if (mousePosRay.Intersects(m_xAxisAabb) && m_xAxisVisible) { - mMode = SCALE_X; - mScaleDirection = AZ::Vector3(mSignX, 0.0f, 0.0f); + m_mode = SCALE_X; + m_scaleDirection = AZ::Vector3(m_signX, 0.0f, 0.0f); } - else if (mousePosRay.Intersects(mYAxisAABB) && mYAxisVisible) + else if (mousePosRay.Intersects(m_yAxisAabb) && m_yAxisVisible) { - mMode = SCALE_Y; - mScaleDirection = AZ::Vector3(0.0f, mSignY, 0.0f); + m_mode = SCALE_Y; + m_scaleDirection = AZ::Vector3(0.0f, m_signY, 0.0f); } - else if (mousePosRay.Intersects(mZAxisAABB) && mZAxisVisible) + else if (mousePosRay.Intersects(m_zAxisAabb) && m_zAxisVisible) { - mMode = SCALE_Z; - mScaleDirection = AZ::Vector3(0.0f, 0.0f, mSignZ); + m_mode = SCALE_Z; + m_scaleDirection = AZ::Vector3(0.0f, 0.0f, m_signZ); } else { - mMode = SCALE_NONE; + m_mode = SCALE_NONE; } } // set selection lock - mSelectionLocked = leftButtonPressed; + m_selectionLocked = leftButtonPressed; // move the gizmo - if (mSelectionLocked == false || mMode == SCALE_NONE) + if (m_selectionLocked == false || m_mode == SCALE_NONE) { - mScale = AZ::Vector3::CreateZero(); + m_scale = AZ::Vector3::CreateZero(); return; } @@ -369,7 +369,7 @@ namespace MCommon // calculate the movement of the mouse on a plane located at the gizmo position // and perpendicular to the camera direction MCore::Ray camRay = camera->Unproject(screenWidth / 2, screenHeight / 2); - MCore::PlaneEq movementPlane(camRay.GetDirection(), mPosition); + MCore::PlaneEq movementPlane(camRay.GetDirection(), m_position); // calculate the intersection points of the mouse positions with the previously calculated plane AZ::Vector3 mousePosIntersect, mousePrevPosIntersect; @@ -377,17 +377,17 @@ namespace MCommon mousePrevPosRay.Intersects(movementPlane, &mousePrevPosIntersect); // project the mouse movement onto the scale axis - scaleChange = (mScaleDirection * mScaleDirection.Dot(mousePosIntersect) - mScaleDirection * mScaleDirection.Dot(mousePrevPosIntersect)); + scaleChange = (m_scaleDirection * m_scaleDirection.Dot(mousePosIntersect) - m_scaleDirection * m_scaleDirection.Dot(mousePrevPosIntersect)); // update the scale of the gizmo - scaleChange = AZ::Vector3(scaleChange.GetX() * mSignX, scaleChange.GetY() * mSignY, scaleChange.GetZ() * mSignZ); - mScale += scaleChange; + scaleChange = AZ::Vector3(scaleChange.GetX() * m_signX, scaleChange.GetY() * m_signY, scaleChange.GetZ() * m_signZ); + m_scale += scaleChange; // update the callback actor instance - if (mCallback) + if (m_callback) { - AZ::Vector3 updateScale = (AZ::Vector3(mSize, mSize, mSize) + mScale) / (float)mSize; - mCallback->Update(updateScale); + AZ::Vector3 updateScale = (AZ::Vector3(m_size, m_size, m_size) + m_scale) / (float)m_size; + m_callback->Update(updateScale); } } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h index 8cfd3ec541..affee9622c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/ScaleManipulator.h @@ -8,7 +8,7 @@ #pragma once -// include the Core system +#include #include #include #include "MCommonConfig.h" @@ -90,31 +90,31 @@ namespace MCommon protected: // scale vectors - AZ::Vector3 mScaleDirection; - AZ::Vector3 mScale; + AZ::Vector3 m_scaleDirection; + AZ::Vector3 m_scale; // bounding volumes for the axes - MCore::AABB mXAxisAABB; - MCore::AABB mYAxisAABB; - MCore::AABB mZAxisAABB; - MCore::AABB mXYPlaneAABB; - MCore::AABB mXZPlaneAABB; - MCore::AABB mYZPlaneAABB; - MCore::AABB mXYZBoxAABB; + MCore::AABB m_xAxisAabb; + MCore::AABB m_yAxisAabb; + MCore::AABB m_zAxisAabb; + MCore::AABB m_xyPlaneAabb; + MCore::AABB m_xzPlaneAabb; + MCore::AABB m_yzPlaneAabb; + MCore::AABB m_xyzBoxAabb; // size properties of the scale manipulator - float mSize; - AZ::Vector3 mScaledSize; - float mDiagScale; - float mArrowLength; - float mBaseRadius; - AZ::Vector3 mFirstPlaneSelectorPos; - AZ::Vector3 mSecPlaneSelectorPos; - float mSignX; - float mSignY; - float mSignZ; - bool mXAxisVisible; - bool mYAxisVisible; - bool mZAxisVisible; + float m_size; + AZ::Vector3 m_scaledSize; + float m_diagScale; + float m_arrowLength; + float m_baseRadius; + AZ::Vector3 m_firstPlaneSelectorPos; + AZ::Vector3 m_secPlaneSelectorPos; + float m_signX; + float m_signY; + float m_signZ; + bool m_xAxisVisible; + bool m_yAxisVisible; + bool m_zAxisVisible; }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TransformationManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TransformationManipulator.h index 502c68d522..e9f5d8f72e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TransformationManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TransformationManipulator.h @@ -30,11 +30,11 @@ namespace MCommon */ ManipulatorCallback(EMotionFX::ActorInstance* actorInstance, const AZ::Vector3& oldValue) { - mActorInstance = actorInstance; - mOldValueVec = oldValue; - mCurrValueVec = oldValue; - mCurrValueQuat = AZ::Quaternion::CreateIdentity(); - mOldValueQuat = AZ::Quaternion::CreateIdentity(); + m_actorInstance = actorInstance; + m_oldValueVec = oldValue; + m_currValueVec = oldValue; + m_currValueQuat = AZ::Quaternion::CreateIdentity(); + m_oldValueQuat = AZ::Quaternion::CreateIdentity(); } /** @@ -42,11 +42,11 @@ namespace MCommon */ ManipulatorCallback(EMotionFX::ActorInstance* actorInstance, const AZ::Quaternion& oldValue) { - mActorInstance = actorInstance; - mOldValueQuat = oldValue; - mCurrValueQuat = oldValue; - mOldValueVec = AZ::Vector3::CreateZero(); - mCurrValueVec = AZ::Vector3::CreateZero(); + m_actorInstance = actorInstance; + m_oldValueQuat = oldValue; + m_currValueQuat = oldValue; + m_oldValueVec = AZ::Vector3::CreateZero(); + m_currValueVec = AZ::Vector3::CreateZero(); } /** @@ -57,8 +57,8 @@ namespace MCommon /** * Update the actor instance. */ - virtual void Update(const AZ::Vector3& value) { mCurrValueVec = value; } - virtual void Update(const AZ::Quaternion& value) { mCurrValueQuat = value; } + virtual void Update(const AZ::Vector3& value) { m_currValueVec = value; } + virtual void Update(const AZ::Quaternion& value) { m_currValueQuat = value; } /** * Update old transformation values of the callback @@ -69,35 +69,35 @@ namespace MCommon * Functions to get the current value. * @return the position/scale/rotation of the actor instance. */ - virtual AZ::Vector3 GetCurrValueVec() { return mCurrValueVec; } - virtual AZ::Quaternion GetCurrValueQuat() { return mCurrValueQuat; } + virtual AZ::Vector3 GetCurrValueVec() { return m_currValueVec; } + virtual AZ::Quaternion GetCurrValueQuat() { return m_currValueQuat; } /** * Return the old value. * @return the old value. */ - const AZ::Vector3& GetOldValueVec() const { return mOldValueVec; } - const AZ::Quaternion& GetOldValueQuat() const { return mOldValueQuat; } + const AZ::Vector3& GetOldValueVec() const { return m_oldValueVec; } + const AZ::Quaternion& GetOldValueQuat() const { return m_oldValueQuat; } /** * Apply transformation. */ - virtual void ApplyTransformation() { mOldValueVec = mCurrValueVec; mOldValueQuat = mCurrValueQuat; } + virtual void ApplyTransformation() { m_oldValueVec = m_currValueVec; m_oldValueQuat = m_currValueQuat; } /** * returns the actor instance, if there is one assigned to the callback. * @return The actor instance. */ - EMotionFX::ActorInstance* GetActorInstance() { return mActorInstance; } + EMotionFX::ActorInstance* GetActorInstance() { return m_actorInstance; } virtual bool GetResetFollowMode() const { return false; } protected: - AZ::Quaternion mOldValueQuat; - AZ::Quaternion mCurrValueQuat; - AZ::Vector3 mOldValueVec; - AZ::Vector3 mCurrValueVec; - EMotionFX::ActorInstance* mActorInstance; + AZ::Quaternion m_oldValueQuat; + AZ::Quaternion m_currValueQuat; + AZ::Vector3 m_oldValueVec; + AZ::Vector3 m_currValueVec; + EMotionFX::ActorInstance* m_actorInstance; }; /** @@ -121,12 +121,12 @@ namespace MCommon */ TransformationManipulator(float scalingFactor = 1.0f, bool isVisible = true) { - mScalingFactor = scalingFactor; - mIsVisible = isVisible; - mSelectionLocked = false; - mPosition = AZ::Vector3::CreateZero(); - mRenderOffset = AZ::Vector3::CreateZero(); - mCallback = nullptr; + m_scalingFactor = scalingFactor; + m_isVisible = isVisible; + m_selectionLocked = false; + m_position = AZ::Vector3::CreateZero(); + m_renderOffset = AZ::Vector3::CreateZero(); + m_callback = nullptr; } /** @@ -134,48 +134,48 @@ namespace MCommon */ virtual ~TransformationManipulator() { - delete mCallback; + delete m_callback; } /** * Function to init the position of the gizmo. */ - void Init(const AZ::Vector3& position) { mPosition = position + mRenderOffset; UpdateBoundingVolumes(); } + void Init(const AZ::Vector3& position) { m_position = position + m_renderOffset; UpdateBoundingVolumes(); } /** * Function to set the name of the gizmo. * @param name The name of the gizmo. (e.g. used to identify different parameters) */ - void SetName(const AZStd::string& name) { mName = name; } + void SetName(const AZStd::string& name) { m_name = name; } /** * Function to get the gizmo name. * @return The name of the gizmo. */ - const AZStd::string& GetName() const { return mName; } + const AZStd::string& GetName() const { return m_name; } /** * Get the selection lock state. * @return the selection lock state. */ - void SetSelectionLocked(bool selectionLocked) { mSelectionLocked = selectionLocked; } - bool GetSelectionLocked() { return mSelectionLocked; } + void SetSelectionLocked(bool selectionLocked) { m_selectionLocked = selectionLocked; } + bool GetSelectionLocked() { return m_selectionLocked; } /** * Set the visible state of the manipulator. */ - void SetIsVisible(bool isVisible = true) { mIsVisible = isVisible; } + void SetIsVisible(bool isVisible = true) { m_isVisible = isVisible; } /** * Set the scale of the gizmo. * @param scale The new scale value for the gizmo. */ - void SetScale(float scale, MCommon::Camera* camera = nullptr) { mScalingFactor = scale; UpdateBoundingVolumes(camera); } + void SetScale(float scale, MCommon::Camera* camera = nullptr) { m_scalingFactor = scale; UpdateBoundingVolumes(camera); } /** * Set mode of the gizmo. */ - void SetMode(uint32 mode) { mMode = mode; } + void SetMode(uint32 mode) { m_mode = mode; } /** * Set the render offset of the gizmo. @@ -185,7 +185,7 @@ namespace MCommon void SetRenderOffset(const AZ::Vector3& offset) { AZ::Vector3 oldPos = GetPosition(); - mRenderOffset = offset; + m_renderOffset = offset; Init(oldPos); } @@ -193,39 +193,39 @@ namespace MCommon * Get the position of the gizmo. * @return The position of the gizmo. */ - AZ::Vector3 GetPosition() const { return mPosition - mRenderOffset; } + AZ::Vector3 GetPosition() const { return m_position - m_renderOffset; } /** * Get the position offset of the gizmo. * Only affects rendering position of the gizmo, not the actual value it modifies. * @return The offset position of the gizmo. */ - const AZ::Vector3& GetRenderOffset() const { return mRenderOffset; } + const AZ::Vector3& GetRenderOffset() const { return m_renderOffset; } /** * Set the callback. * @param callback Pointer to the callback used to manipulate the actorinstance. */ - void SetCallback(ManipulatorCallback* callback) { delete mCallback; mCallback = callback; } + void SetCallback(ManipulatorCallback* callback) { delete m_callback; m_callback = callback; } /** * Returns the current callback of the manipulator. * Used to apply the transformation upon mouse release for example. * @return The manipulator callback. */ - ManipulatorCallback* GetCallback() { return mCallback; } + ManipulatorCallback* GetCallback() { return m_callback; } /** * Function to get the mode of the transformation manipulator. * @return The mode of the manipulator. */ - uint32 GetMode() { return mMode; } + uint32 GetMode() { return m_mode; } /** * Returns the visible state of the gizmo. - * @return mIsVisible The visible state of the gizmo. + * @return m_isVisible The visible state of the gizmo. */ - bool GetIsVisible() { return mIsVisible; } + bool GetIsVisible() { return m_isVisible; } /** * Function to get the type of a gizmo. Has to be set by the constructor of the inherited classes. @@ -270,14 +270,14 @@ namespace MCommon } protected: - AZ::Vector3 mPosition; - AZ::Vector3 mRenderOffset; - AZStd::string mName; - AZStd::string mTempString; - uint32 mMode; - float mScalingFactor; - ManipulatorCallback* mCallback; - bool mSelectionLocked; - bool mIsVisible; + AZ::Vector3 m_position; + AZ::Vector3 m_renderOffset; + AZStd::string m_name; + AZStd::string m_tempString; + uint32 m_mode; + float m_scalingFactor; + ManipulatorCallback* m_callback; + bool m_selectionLocked; + bool m_isVisible; }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.cpp index e20ae5a77e..db2cccb334 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.cpp @@ -16,8 +16,8 @@ namespace MCommon : TransformationManipulator(scalingFactor, isVisible) { // set the initial values - mMode = TRANSLATE_NONE; - mCallback = nullptr; + m_mode = TRANSLATE_NONE; + m_callback = nullptr; } @@ -33,26 +33,26 @@ namespace MCommon MCORE_UNUSED(camera); // set the new proportions - mSize = mScalingFactor; - mArrowLength = mSize / 5.0f; - mBaseRadius = mSize / 20.0f; - mPlaneSelectorPos = mSize / 2; + m_size = m_scalingFactor; + m_arrowLength = m_size / 5.0f; + m_baseRadius = m_size / 20.0f; + m_planeSelectorPos = m_size / 2; // set the bounding volumes of the axes selection - mXAxisAABB.SetMax(mPosition + AZ::Vector3(mSize + mArrowLength, mBaseRadius, mBaseRadius)); - mXAxisAABB.SetMin(mPosition - AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); - mYAxisAABB.SetMax(mPosition + AZ::Vector3(mBaseRadius, mSize + mArrowLength, mBaseRadius)); - mYAxisAABB.SetMin(mPosition - AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); - mZAxisAABB.SetMax(mPosition + AZ::Vector3(mBaseRadius, mBaseRadius, mSize + mArrowLength)); - mZAxisAABB.SetMin(mPosition - AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); + m_xAxisAabb.SetMax(m_position + AZ::Vector3(m_size + m_arrowLength, m_baseRadius, m_baseRadius)); + m_xAxisAabb.SetMin(m_position - AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); + m_yAxisAabb.SetMax(m_position + AZ::Vector3(m_baseRadius, m_size + m_arrowLength, m_baseRadius)); + m_yAxisAabb.SetMin(m_position - AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); + m_zAxisAabb.SetMax(m_position + AZ::Vector3(m_baseRadius, m_baseRadius, m_size + m_arrowLength)); + m_zAxisAabb.SetMin(m_position - AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); // set bounding volumes for the plane selectors - mXYPlaneAABB.SetMax(mPosition + AZ::Vector3(mPlaneSelectorPos, mPlaneSelectorPos, mBaseRadius)); - mXYPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(mPlaneSelectorPos, mPlaneSelectorPos, 0) - AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); - mXZPlaneAABB.SetMax(mPosition + AZ::Vector3(mPlaneSelectorPos, mBaseRadius, mPlaneSelectorPos)); - mXZPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(mPlaneSelectorPos, 0, mPlaneSelectorPos) - AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); - mYZPlaneAABB.SetMax(mPosition + AZ::Vector3(mBaseRadius, mPlaneSelectorPos, mPlaneSelectorPos)); - mYZPlaneAABB.SetMin(mPosition + 0.3f * AZ::Vector3(0, mPlaneSelectorPos, mPlaneSelectorPos) - AZ::Vector3(mBaseRadius, mBaseRadius, mBaseRadius)); + m_xyPlaneAabb.SetMax(m_position + AZ::Vector3(m_planeSelectorPos, m_planeSelectorPos, m_baseRadius)); + m_xyPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(m_planeSelectorPos, m_planeSelectorPos, 0) - AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); + m_xzPlaneAabb.SetMax(m_position + AZ::Vector3(m_planeSelectorPos, m_baseRadius, m_planeSelectorPos)); + m_xzPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(m_planeSelectorPos, 0, m_planeSelectorPos) - AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); + m_yzPlaneAabb.SetMax(m_position + AZ::Vector3(m_baseRadius, m_planeSelectorPos, m_planeSelectorPos)); + m_yzPlaneAabb.SetMin(m_position + 0.3f * AZ::Vector3(0, m_planeSelectorPos, m_planeSelectorPos) - AZ::Vector3(m_baseRadius, m_baseRadius, m_baseRadius)); } @@ -74,9 +74,9 @@ namespace MCommon AZ::Vector3 camDir = camRollRay.GetDirection(); // determine the axis visibility, to disable movement for invisible axes - mXAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); - mYAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); - mZAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_xAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(1.0f, 0.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_yAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 1.0f, 0.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); + m_zAxisVisible = (MCore::InRange(MCore::Math::Abs(camDir.Dot(AZ::Vector3(0.0f, 0.0f, 1.0f))) - 1.0f, -MCore::Math::epsilon, MCore::Math::epsilon) == false); } @@ -96,8 +96,8 @@ namespace MCommon MCore::Ray mouseRay = camera->Unproject(mousePosX, mousePosY); // check if one of the AABBs is hit - if (mouseRay.Intersects(mXAxisAABB) || mouseRay.Intersects(mYAxisAABB) || mouseRay.Intersects(mZAxisAABB) || - mouseRay.Intersects(mXYPlaneAABB) || mouseRay.Intersects(mXZPlaneAABB) || mouseRay.Intersects(mYZPlaneAABB)) + if (mouseRay.Intersects(m_xAxisAabb) || mouseRay.Intersects(m_yAxisAabb) || mouseRay.Intersects(m_zAxisAabb) || + mouseRay.Intersects(m_xyPlaneAabb) || mouseRay.Intersects(m_xzPlaneAabb) || mouseRay.Intersects(m_yzPlaneAabb)) { return true; } @@ -111,7 +111,7 @@ namespace MCommon void TranslateManipulator::Render(MCommon::Camera* camera, RenderUtil* renderUtil) { // return if no render util is set - if (renderUtil == nullptr || camera == nullptr || mIsVisible == false) + if (renderUtil == nullptr || camera == nullptr || m_isVisible == false) { return; } @@ -124,106 +124,100 @@ namespace MCommon UpdateAxisVisibility(camera); // set color for the axes, depending on the selection - MCore::RGBAColor xAxisColor = (mMode == TRANSLATE_X || mMode == TRANSLATE_XY || mMode == TRANSLATE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor yAxisColor = (mMode == TRANSLATE_Y || mMode == TRANSLATE_XY || mMode == TRANSLATE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor zAxisColor = (mMode == TRANSLATE_Z || mMode == TRANSLATE_XZ || mMode == TRANSLATE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; - MCore::RGBAColor xyPlaneColorX = (mMode == TRANSLATE_XY) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor xyPlaneColorY = (mMode == TRANSLATE_XY) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor xzPlaneColorX = (mMode == TRANSLATE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mRed; - MCore::RGBAColor xzPlaneColorZ = (mMode == TRANSLATE_XZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; - MCore::RGBAColor yzPlaneColorY = (mMode == TRANSLATE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mGreen; - MCore::RGBAColor yzPlaneColorZ = (mMode == TRANSLATE_YZ) ? ManipulatorColors::mSelectionColor : ManipulatorColors::mBlue; - - if (mXAxisVisible) + MCore::RGBAColor xAxisColor = (m_mode == TRANSLATE_X || m_mode == TRANSLATE_XY || m_mode == TRANSLATE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor yAxisColor = (m_mode == TRANSLATE_Y || m_mode == TRANSLATE_XY || m_mode == TRANSLATE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor zAxisColor = (m_mode == TRANSLATE_Z || m_mode == TRANSLATE_XZ || m_mode == TRANSLATE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; + MCore::RGBAColor xyPlaneColorX = (m_mode == TRANSLATE_XY) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor xyPlaneColorY = (m_mode == TRANSLATE_XY) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor xzPlaneColorX = (m_mode == TRANSLATE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_red; + MCore::RGBAColor xzPlaneColorZ = (m_mode == TRANSLATE_XZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; + MCore::RGBAColor yzPlaneColorY = (m_mode == TRANSLATE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_green; + MCore::RGBAColor yzPlaneColorZ = (m_mode == TRANSLATE_YZ) ? ManipulatorColors::s_selectionColor : ManipulatorColors::s_blue; + + if (m_xAxisVisible) { // the x axis consisting of a line, cylinder and plane selectors - renderUtil->RenderLine(mPosition, mPosition + AZ::Vector3(mSize, 0.0, 0.0), xAxisColor); - renderUtil->RenderCylinder(mBaseRadius, 0, mArrowLength, mPosition + AZ::Vector3(mSize, 0, 0), AZ::Vector3(1, 0, 0), ManipulatorColors::mRed); - renderUtil->RenderLine(mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0, 0.0), mPosition + AZ::Vector3(mPlaneSelectorPos, mPlaneSelectorPos, 0.0), xyPlaneColorX); - renderUtil->RenderLine(mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0, 0.0), mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0, mPlaneSelectorPos), xzPlaneColorX); + renderUtil->RenderLine(m_position, m_position + AZ::Vector3(m_size, 0.0, 0.0), xAxisColor); + renderUtil->RenderCylinder(m_baseRadius, 0, m_arrowLength, m_position + AZ::Vector3(m_size, 0, 0), AZ::Vector3(1, 0, 0), ManipulatorColors::s_red); + renderUtil->RenderLine(m_position + AZ::Vector3(m_planeSelectorPos, 0.0, 0.0), m_position + AZ::Vector3(m_planeSelectorPos, m_planeSelectorPos, 0.0), xyPlaneColorX); + renderUtil->RenderLine(m_position + AZ::Vector3(m_planeSelectorPos, 0.0, 0.0), m_position + AZ::Vector3(m_planeSelectorPos, 0.0, m_planeSelectorPos), xzPlaneColorX); // render the axis label for the x axis - AZ::Vector3 textPosX = MCore::Project(mPosition + AZ::Vector3(mSize + mArrowLength + mBaseRadius, -mBaseRadius, 0.0), camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 textPosX = MCore::Project(m_position + AZ::Vector3(m_size + m_arrowLength + m_baseRadius, -m_baseRadius, 0.0), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderText(textPosX.GetX(), textPosX.GetY(), "X", xAxisColor); } - if (mYAxisVisible) + if (m_yAxisVisible) { // the y axis consisting of a line, cylinder and plane selectors - renderUtil->RenderLine(mPosition, mPosition + AZ::Vector3(0.0, mSize, 0.0), yAxisColor); - renderUtil->RenderCylinder(mBaseRadius, 0, mArrowLength, mPosition + AZ::Vector3(0, mSize, 0), AZ::Vector3(0, 1, 0), ManipulatorColors::mGreen); - renderUtil->RenderLine(mPosition + AZ::Vector3(0.0, mPlaneSelectorPos, 0.0), mPosition + AZ::Vector3(mPlaneSelectorPos, mPlaneSelectorPos, 0.0), xyPlaneColorY); - renderUtil->RenderLine(mPosition + AZ::Vector3(0.0, mPlaneSelectorPos, 0.0), mPosition + AZ::Vector3(0.0, mPlaneSelectorPos, mPlaneSelectorPos), yzPlaneColorY); + renderUtil->RenderLine(m_position, m_position + AZ::Vector3(0.0, m_size, 0.0), yAxisColor); + renderUtil->RenderCylinder(m_baseRadius, 0, m_arrowLength, m_position + AZ::Vector3(0, m_size, 0), AZ::Vector3(0, 1, 0), ManipulatorColors::s_green); + renderUtil->RenderLine(m_position + AZ::Vector3(0.0, m_planeSelectorPos, 0.0), m_position + AZ::Vector3(m_planeSelectorPos, m_planeSelectorPos, 0.0), xyPlaneColorY); + renderUtil->RenderLine(m_position + AZ::Vector3(0.0, m_planeSelectorPos, 0.0), m_position + AZ::Vector3(0.0, m_planeSelectorPos, m_planeSelectorPos), yzPlaneColorY); // render the axis label for the y axis - AZ::Vector3 textPosY = MCore::Project(mPosition + AZ::Vector3(0.0, mSize + mArrowLength + mBaseRadius, -mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 textPosY = MCore::Project(m_position + AZ::Vector3(0.0, m_size + m_arrowLength + m_baseRadius, -m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderText(textPosY.GetX(), textPosY.GetY(), "Y", yAxisColor); } - if (mZAxisVisible) + if (m_zAxisVisible) { // the z axis consisting of a line, cylinder and plane selectors - renderUtil->RenderLine(mPosition, mPosition + AZ::Vector3(0.0, 0.0, mSize), zAxisColor); - renderUtil->RenderCylinder(mBaseRadius, 0, mArrowLength, mPosition + AZ::Vector3(0, 0, mSize), AZ::Vector3(0, 0, 1), ManipulatorColors::mBlue); - renderUtil->RenderLine(mPosition + AZ::Vector3(0.0, 0.0, mPlaneSelectorPos), mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0, mPlaneSelectorPos), xzPlaneColorZ); - renderUtil->RenderLine(mPosition + AZ::Vector3(0.0, 0.0, mPlaneSelectorPos), mPosition + AZ::Vector3(0.0, mPlaneSelectorPos, mPlaneSelectorPos), yzPlaneColorZ); + renderUtil->RenderLine(m_position, m_position + AZ::Vector3(0.0, 0.0, m_size), zAxisColor); + renderUtil->RenderCylinder(m_baseRadius, 0, m_arrowLength, m_position + AZ::Vector3(0, 0, m_size), AZ::Vector3(0, 0, 1), ManipulatorColors::s_blue); + renderUtil->RenderLine(m_position + AZ::Vector3(0.0, 0.0, m_planeSelectorPos), m_position + AZ::Vector3(m_planeSelectorPos, 0.0, m_planeSelectorPos), xzPlaneColorZ); + renderUtil->RenderLine(m_position + AZ::Vector3(0.0, 0.0, m_planeSelectorPos), m_position + AZ::Vector3(0.0, m_planeSelectorPos, m_planeSelectorPos), yzPlaneColorZ); // render the axis label for the z axis - AZ::Vector3 textPosZ = MCore::Project(mPosition + AZ::Vector3(0.0, mBaseRadius, mSize + mArrowLength + mBaseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); + AZ::Vector3 textPosZ = MCore::Project(m_position + AZ::Vector3(0.0, m_baseRadius, m_size + m_arrowLength + m_baseRadius), camera->GetViewProjMatrix(), screenWidth, screenHeight); renderUtil->RenderText(textPosZ.GetX(), textPosZ.GetY(), "Z", zAxisColor); } // draw transparent quad for the plane selectors - if (mMode == TRANSLATE_XY) + if (m_mode == TRANSLATE_XY) { - renderUtil->RenderTriangle(mPosition, mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0f, 0.0f), mPosition + AZ::Vector3(mPlaneSelectorPos, mPlaneSelectorPos, 0.0f), ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(mPosition, mPosition + AZ::Vector3(mPlaneSelectorPos, mPlaneSelectorPos, 0.0f), mPosition + AZ::Vector3(0.0f, mPlaneSelectorPos, 0.0f), ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(m_position, m_position + AZ::Vector3(m_planeSelectorPos, 0.0f, 0.0f), m_position + AZ::Vector3(m_planeSelectorPos, m_planeSelectorPos, 0.0f), ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(m_position, m_position + AZ::Vector3(m_planeSelectorPos, m_planeSelectorPos, 0.0f), m_position + AZ::Vector3(0.0f, m_planeSelectorPos, 0.0f), ManipulatorColors::s_selectionColorDarker); } - else if (mMode == TRANSLATE_XZ) + else if (m_mode == TRANSLATE_XZ) { - renderUtil->RenderTriangle(mPosition, mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0f, 0.0f), mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0f, mPlaneSelectorPos), ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(mPosition, mPosition + AZ::Vector3(mPlaneSelectorPos, 0.0f, mPlaneSelectorPos), mPosition + AZ::Vector3(0.0f, 0.0f, mPlaneSelectorPos), ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(m_position, m_position + AZ::Vector3(m_planeSelectorPos, 0.0f, 0.0f), m_position + AZ::Vector3(m_planeSelectorPos, 0.0f, m_planeSelectorPos), ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(m_position, m_position + AZ::Vector3(m_planeSelectorPos, 0.0f, m_planeSelectorPos), m_position + AZ::Vector3(0.0f, 0.0f, m_planeSelectorPos), ManipulatorColors::s_selectionColorDarker); } - else if (mMode == TRANSLATE_YZ) + else if (m_mode == TRANSLATE_YZ) { - renderUtil->RenderTriangle(mPosition + AZ::Vector3(0.0f, 0.0f, mPlaneSelectorPos), mPosition, mPosition + AZ::Vector3(0.0f, mPlaneSelectorPos, 0.0f), ManipulatorColors::mSelectionColorDarker); - renderUtil->RenderTriangle(mPosition + AZ::Vector3(0.0f, mPlaneSelectorPos, 0.0f), mPosition + AZ::Vector3(0.0f, mPlaneSelectorPos, mPlaneSelectorPos), mPosition + AZ::Vector3(0.0f, 0.0f, mPlaneSelectorPos), ManipulatorColors::mSelectionColorDarker); + renderUtil->RenderTriangle(m_position + AZ::Vector3(0.0f, 0.0f, m_planeSelectorPos), m_position, m_position + AZ::Vector3(0.0f, m_planeSelectorPos, 0.0f), ManipulatorColors::s_selectionColorDarker); + renderUtil->RenderTriangle(m_position + AZ::Vector3(0.0f, m_planeSelectorPos, 0.0f), m_position + AZ::Vector3(0.0f, m_planeSelectorPos, m_planeSelectorPos), m_position + AZ::Vector3(0.0f, 0.0f, m_planeSelectorPos), ManipulatorColors::s_selectionColorDarker); } // render the relative position when moving - if (mCallback) + if (m_callback) { // calculate the y-offset of the text position - AZ::Vector3 deltaPos = GetPosition() - mCallback->GetOldValueVec(); + AZ::Vector3 deltaPos = GetPosition() - m_callback->GetOldValueVec(); float yOffset = (camera->GetProjectionMode() == MCommon::Camera::PROJMODE_PERSPECTIVE) ? 60.0f * ((float)screenHeight / 720.0f) : 40.0f; // render the relative movement - AZ::Vector3 textPos = MCore::Project(mPosition + (AZ::Vector3(mSize, mSize, mSize) / 3.0f), camera->GetViewProjMatrix(), camera->GetScreenWidth(), camera->GetScreenHeight()); + AZ::Vector3 textPos = MCore::Project(m_position + (AZ::Vector3(m_size, m_size, m_size) / 3.0f), camera->GetViewProjMatrix(), camera->GetScreenWidth(), camera->GetScreenHeight()); // render delta position of the gizmo of the name if not dragging at the moment - if (mSelectionLocked && mMode != TRANSLATE_NONE) + if (m_selectionLocked && m_mode != TRANSLATE_NONE) { - mTempString = AZStd::string::format("X: %.3f, Y: %.3f, Z: %.3f", static_cast(deltaPos.GetX()), static_cast(deltaPos.GetY()), static_cast(deltaPos.GetZ())); - renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f, true); + m_tempString = AZStd::string::format("X: %.3f, Y: %.3f, Z: %.3f", static_cast(deltaPos.GetX()), static_cast(deltaPos.GetY()), static_cast(deltaPos.GetZ())); + renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f, true); } else { - renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, mName.c_str(), ManipulatorColors::mSelectionColor, 9.0f, true); + renderUtil->RenderText(textPos.GetX(), textPos.GetY() + yOffset, m_name.c_str(), ManipulatorColors::s_selectionColor, 9.0f, true); } } - // render aabbs (for debug issues. remove this) - /* renderUtil->RenderAABB( mXAxisAABB, ManipulatorColors::mSelectionColor, true ); - renderUtil->RenderAABB( mYAxisAABB, ManipulatorColors::mSelectionColor, true ); - renderUtil->RenderAABB( mZAxisAABB, ManipulatorColors::mSelectionColor, true ); - */ - // render the absolute position of the gizmo/actor instance - if (mMode != TRANSLATE_NONE) + if (m_mode != TRANSLATE_NONE) { const AZ::Vector3 offsetPos = GetPosition(); - mTempString = AZStd::string::format("Abs Pos X: %.3f, Y: %.3f, Z: %.3f", static_cast(offsetPos.GetX()), static_cast(offsetPos.GetY()), static_cast(offsetPos.GetZ())); - renderUtil->RenderText(10, 10, mTempString.c_str(), ManipulatorColors::mSelectionColor, 9.0f); + m_tempString = AZStd::string::format("Abs Pos X: %.3f, Y: %.3f, Z: %.3f", static_cast(offsetPos.GetX()), static_cast(offsetPos.GetY()), static_cast(offsetPos.GetZ())); + renderUtil->RenderText(10, 10, m_tempString.c_str(), ManipulatorColors::s_selectionColor, 9.0f); } } @@ -235,7 +229,7 @@ namespace MCommon MCORE_UNUSED(middleButtonPressed); // check if camera has been set - if (camera == nullptr || mIsVisible == false || (leftButtonPressed && rightButtonPressed)) + if (camera == nullptr || m_isVisible == false || (leftButtonPressed && rightButtonPressed)) { return; } @@ -252,64 +246,64 @@ namespace MCommon UpdateAxisVisibility(camera); // check for the selected axis/plane - if (mSelectionLocked == false || mMode == TRANSLATE_NONE) + if (m_selectionLocked == false || m_mode == TRANSLATE_NONE) { // update old values of the callback - if (mCallback) + if (m_callback) { - mCallback->UpdateOldValues(); + m_callback->UpdateOldValues(); } // handle different translation modes - if (mousePosRay.Intersects(mXYPlaneAABB) && mXAxisVisible && mYAxisVisible) + if (mousePosRay.Intersects(m_xyPlaneAabb) && m_xAxisVisible && m_yAxisVisible) { - mMovementDirection = AZ::Vector3(1.0f, 1.0f, 0.0f); - mMovementPlaneNormal = AZ::Vector3(0.0f, 0.0f, 1.0f); - mMode = TRANSLATE_XY; + m_movementDirection = AZ::Vector3(1.0f, 1.0f, 0.0f); + m_movementPlaneNormal = AZ::Vector3(0.0f, 0.0f, 1.0f); + m_mode = TRANSLATE_XY; } - else if (mousePosRay.Intersects(mXZPlaneAABB) && mXAxisVisible && mZAxisVisible) + else if (mousePosRay.Intersects(m_xzPlaneAabb) && m_xAxisVisible && m_zAxisVisible) { - mMovementDirection = AZ::Vector3(1.0f, 0.0f, 1.0f); - mMovementPlaneNormal = AZ::Vector3(0.0f, 1.0f, 0.0f); - mMode = TRANSLATE_XZ; + m_movementDirection = AZ::Vector3(1.0f, 0.0f, 1.0f); + m_movementPlaneNormal = AZ::Vector3(0.0f, 1.0f, 0.0f); + m_mode = TRANSLATE_XZ; } - else if (mousePosRay.Intersects(mYZPlaneAABB) && mYAxisVisible && mZAxisVisible) + else if (mousePosRay.Intersects(m_yzPlaneAabb) && m_yAxisVisible && m_zAxisVisible) { - mMovementDirection = AZ::Vector3(0.0f, 1.0f, 1.0f); - mMovementPlaneNormal = AZ::Vector3(1.0f, 0.0f, 0.0f); - mMode = TRANSLATE_YZ; + m_movementDirection = AZ::Vector3(0.0f, 1.0f, 1.0f); + m_movementPlaneNormal = AZ::Vector3(1.0f, 0.0f, 0.0f); + m_mode = TRANSLATE_YZ; } - else if (mousePosRay.Intersects(mXAxisAABB) && mXAxisVisible) + else if (mousePosRay.Intersects(m_xAxisAabb) && m_xAxisVisible) { - mMovementDirection = AZ::Vector3(1.0f, 0.0f, 0.0f); - mMovementPlaneNormal = AZ::Vector3(0.0f, 1.0f, 1.0f).GetNormalized(); - mMode = TRANSLATE_X; + m_movementDirection = AZ::Vector3(1.0f, 0.0f, 0.0f); + m_movementPlaneNormal = AZ::Vector3(0.0f, 1.0f, 1.0f).GetNormalized(); + m_mode = TRANSLATE_X; } - else if (mousePosRay.Intersects(mYAxisAABB) && mYAxisVisible) + else if (mousePosRay.Intersects(m_yAxisAabb) && m_yAxisVisible) { - mMovementDirection = AZ::Vector3(0.0f, 1.0f, 0.0f); - mMovementPlaneNormal = AZ::Vector3(1.0f, 0.0f, 1.0f).GetNormalized(); - mMode = TRANSLATE_Y; + m_movementDirection = AZ::Vector3(0.0f, 1.0f, 0.0f); + m_movementPlaneNormal = AZ::Vector3(1.0f, 0.0f, 1.0f).GetNormalized(); + m_mode = TRANSLATE_Y; } - else if (mousePosRay.Intersects(mZAxisAABB) && mZAxisVisible) + else if (mousePosRay.Intersects(m_zAxisAabb) && m_zAxisVisible) { - mMovementDirection = AZ::Vector3(0.0f, 0.0f, 1.0f); - mMovementPlaneNormal = AZ::Vector3(1.0f, 1.0f, 0.0f).GetNormalized(); - mMode = TRANSLATE_Z; + m_movementDirection = AZ::Vector3(0.0f, 0.0f, 1.0f); + m_movementPlaneNormal = AZ::Vector3(1.0f, 1.0f, 0.0f).GetNormalized(); + m_mode = TRANSLATE_Z; } else { - mMode = TRANSLATE_NONE; + m_mode = TRANSLATE_NONE; } } // set selection lock - mSelectionLocked = leftButtonPressed; + m_selectionLocked = leftButtonPressed; // move the gizmo - if (mSelectionLocked == false || mMode == TRANSLATE_NONE) + if (m_selectionLocked == false || m_mode == TRANSLATE_NONE) { - mMousePosRelative = AZ::Vector3::CreateZero(); + m_mousePosRelative = AZ::Vector3::CreateZero(); return; } @@ -317,22 +311,22 @@ namespace MCommon AZ::Vector3 movement = AZ::Vector3::CreateZero(); // handle plane movement - if (mMode == TRANSLATE_XY || mMode == TRANSLATE_XZ || mMode == TRANSLATE_YZ) + if (m_mode == TRANSLATE_XY || m_mode == TRANSLATE_XZ || m_mode == TRANSLATE_YZ) { // generate current translation plane and calculate mouse intersections - MCore::PlaneEq movementPlane(mMovementPlaneNormal, mPosition); + MCore::PlaneEq movementPlane(m_movementPlaneNormal, m_position); AZ::Vector3 mousePosIntersect, mousePrevPosIntersect; mousePosRay.Intersects(movementPlane, &mousePosIntersect); mousePrevPosRay.Intersects(movementPlane, &mousePrevPosIntersect); // calculate the mouse position relative to the gizmo - if (MCore::Math::IsFloatZero(MCore::SafeLength(mMousePosRelative))) + if (MCore::Math::IsFloatZero(MCore::SafeLength(m_mousePosRelative))) { - mMousePosRelative = mousePosIntersect - mPosition; + m_mousePosRelative = mousePosIntersect - m_position; } // distance of the mouse intersections is the actual movement on the plane - movement = mousePosIntersect - mMousePosRelative; + movement = mousePosIntersect - m_mousePosRelative; } // handle axis movement @@ -342,12 +336,12 @@ namespace MCommon // calculate the movement of the mouse on a plane located at the gizmo position // and perpendicular to the move direction AZ::Vector3 camDir = camera->Unproject(camera->GetScreenWidth() / 2, camera->GetScreenHeight() / 2).GetDirection(); - AZ::Vector3 thirdAxis = mMovementDirection.Cross(camDir).GetNormalized(); - mMovementPlaneNormal = thirdAxis.Cross(mMovementDirection).GetNormalized(); - thirdAxis = mMovementPlaneNormal.Cross(mMovementDirection).GetNormalized(); + AZ::Vector3 thirdAxis = m_movementDirection.Cross(camDir).GetNormalized(); + m_movementPlaneNormal = thirdAxis.Cross(m_movementDirection).GetNormalized(); + thirdAxis = m_movementPlaneNormal.Cross(m_movementDirection).GetNormalized(); - MCore::PlaneEq movementPlane(mMovementPlaneNormal, mPosition); - MCore::PlaneEq movementPlane2(thirdAxis, mPosition); + MCore::PlaneEq movementPlane(m_movementPlaneNormal, m_position); + MCore::PlaneEq movementPlane2(thirdAxis, m_position); // calculate the intersection points of the mouse positions with the previously calculated plane AZ::Vector3 mousePosIntersect, mousePosIntersect2; @@ -356,44 +350,44 @@ namespace MCommon if (mousePosIntersect.GetLength() < camera->GetFarClipDistance()) { - if (MCore::Math::IsFloatZero(MCore::SafeLength(mMousePosRelative))) + if (MCore::Math::IsFloatZero(MCore::SafeLength(m_mousePosRelative))) { - mMousePosRelative = movementPlane2.Project(mousePosIntersect) - mPosition; + m_mousePosRelative = movementPlane2.Project(mousePosIntersect) - m_position; } mousePosIntersect = movementPlane2.Project(mousePosIntersect); } else { - if (MCore::Math::IsFloatZero(MCore::SafeLength(mMousePosRelative))) + if (MCore::Math::IsFloatZero(MCore::SafeLength(m_mousePosRelative))) { - mMousePosRelative = movementPlane.Project(mousePosIntersect2) - mPosition; + m_mousePosRelative = movementPlane.Project(mousePosIntersect2) - m_position; } mousePosIntersect = movementPlane.Project(mousePosIntersect2); } // adjust the movement vector - movement = mousePosIntersect - mMousePosRelative; + movement = mousePosIntersect - m_mousePosRelative; } // update the position of the gizmo - movement = movement - mPosition; - movement = AZ::Vector3(movement.GetX() * mMovementDirection.GetX(), movement.GetY() * mMovementDirection.GetY(), movement.GetZ() * mMovementDirection.GetZ()); - mPosition += movement; + movement = movement - m_position; + movement = AZ::Vector3(movement.GetX() * m_movementDirection.GetX(), movement.GetY() * m_movementDirection.GetY(), movement.GetZ() * m_movementDirection.GetZ()); + m_position += movement; // update the callback - if (mCallback) + if (m_callback) { // reset the callback position, if the position is too far away from the camera float farClip = camera->GetFarClipDistance(); - if (mPosition.GetLength() >= farClip) + if (m_position.GetLength() >= farClip) { - mPosition = mCallback->GetOldValueVec() + mRenderOffset; + m_position = m_callback->GetOldValueVec() + m_renderOffset; } // update the callback - mCallback->Update(GetPosition()); + m_callback->Update(GetPosition()); } } } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h index 362f6c19be..4b916f43b7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/Common/TranslateManipulator.h @@ -9,7 +9,7 @@ #ifndef __MCOMMON_TRANSLATEMANIPULATOR_H #define __MCOMMON_TRANSLATEMANIPULATOR_H -// include the Core system +#include #include #include #include "MCommonConfig.h" @@ -91,24 +91,24 @@ namespace MCommon protected: // bounding volumes for the axes - MCore::AABB mXAxisAABB; - MCore::AABB mYAxisAABB; - MCore::AABB mZAxisAABB; - MCore::AABB mXYPlaneAABB; - MCore::AABB mXZPlaneAABB; - MCore::AABB mYZPlaneAABB; + MCore::AABB m_xAxisAabb; + MCore::AABB m_yAxisAabb; + MCore::AABB m_zAxisAabb; + MCore::AABB m_xyPlaneAabb; + MCore::AABB m_xzPlaneAabb; + MCore::AABB m_yzPlaneAabb; // the scaling factors for the translate manipulator - float mSize; - float mArrowLength; - float mBaseRadius; - float mPlaneSelectorPos; - AZ::Vector3 mMovementPlaneNormal; - AZ::Vector3 mMovementDirection; - AZ::Vector3 mMousePosRelative; - bool mXAxisVisible; - bool mYAxisVisible; - bool mZAxisVisible; + float m_size; + float m_arrowLength; + float m_baseRadius; + float m_planeSelectorPos; + AZ::Vector3 m_movementPlaneNormal; + AZ::Vector3 m_movementDirection; + AZ::Vector3 m_mousePosRelative; + bool m_xAxisVisible; + bool m_yAxisVisible; + bool m_zAxisVisible; }; } // namespace MCommon diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.cpp index c4091de594..297bf01638 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.cpp @@ -10,7 +10,7 @@ #include #include -#include +#include #include "GBuffer.h" #include "RenderTexture.h" #include "GLSLShader.h" @@ -22,20 +22,20 @@ namespace RenderGL // constructor GBuffer::GBuffer() { - mFBO = 0; - mDepthBufferID = 0; - mWidth = 100; - mHeight = 100; + m_fbo = 0; + m_depthBufferId = 0; + m_width = 100; + m_height = 100; - mRenderTargetA = nullptr; - mRenderTargetB = nullptr; - mRenderTargetC = nullptr; - mRenderTargetD = nullptr; - mRenderTargetE = nullptr; + m_renderTargetA = nullptr; + m_renderTargetB = nullptr; + m_renderTargetC = nullptr; + m_renderTargetD = nullptr; + m_renderTargetE = nullptr; for (uint32 i = 0; i < NUM_COMPONENTS; ++i) { - mComponents[i] = 0; + m_components[i] = 0; } } @@ -62,48 +62,48 @@ namespace RenderGL return false; } - mWidth = width; - mHeight = height; + m_width = width; + m_height = height; // create the FBO - glGenFramebuffers(1, &mFBO); + glGenFramebuffers(1, &m_fbo); for (uint32 i = 0; i < NUM_COMPONENTS; ++i) { - glGenTextures(1, &mComponents[i]); + glGenTextures(1, &m_components[i]); } - glGenTextures(1, &mDepthBufferID); + glGenTextures(1, &m_depthBufferId); // bind the fbo - glBindFramebuffer(GL_FRAMEBUFFER, mFBO); + glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); // init normals texture - glBindTexture(GL_TEXTURE_2D, mComponents[COMPONENT_SHADED]); + glBindTexture(GL_TEXTURE_2D, m_components[COMPONENT_SHADED]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mComponents[COMPONENT_SHADED], 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_components[COMPONENT_SHADED], 0); // init glow color texture - glBindTexture(GL_TEXTURE_2D, mComponents[COMPONENT_GLOW]); + glBindTexture(GL_TEXTURE_2D, m_components[COMPONENT_GLOW]); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, width, height, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, mComponents[COMPONENT_GLOW], 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, m_components[COMPONENT_GLOW], 0); // init the depth buffer - glBindTexture(GL_TEXTURE_2D, mDepthBufferID); + glBindTexture(GL_TEXTURE_2D, m_depthBufferId); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, width, height, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, mDepthBufferID, 0); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, mDepthBufferID, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthBufferId, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_depthBufferId, 0); // unbind glBindTexture(GL_TEXTURE_2D, 0); @@ -131,28 +131,28 @@ namespace RenderGL // release void GBuffer::Release() { - if (mFBO) + if (m_fbo) { - glDeleteFramebuffers(1, &mFBO); + glDeleteFramebuffers(1, &m_fbo); for (uint32 i = 0; i < NUM_COMPONENTS; ++i) { - glDeleteTextures(1, &mComponents[i]); + glDeleteTextures(1, &m_components[i]); } - glDeleteTextures(1, &mDepthBufferID); + glDeleteTextures(1, &m_depthBufferId); } - delete mRenderTargetA; - delete mRenderTargetB; - delete mRenderTargetC; - delete mRenderTargetD; - delete mRenderTargetE; - - mRenderTargetA = nullptr; - mRenderTargetB = nullptr; - mRenderTargetC = nullptr; - mRenderTargetD = nullptr; - mRenderTargetE = nullptr; + delete m_renderTargetA; + delete m_renderTargetB; + delete m_renderTargetC; + delete m_renderTargetD; + delete m_renderTargetE; + + m_renderTargetA = nullptr; + m_renderTargetB = nullptr; + m_renderTargetC = nullptr; + m_renderTargetD = nullptr; + m_renderTargetE = nullptr; } @@ -167,39 +167,39 @@ namespace RenderGL // resize render textures bool GBuffer::ResizeTextures(uint32 screenWidth, uint32 screenHeight) { - delete mRenderTargetA; - delete mRenderTargetB; - delete mRenderTargetC; - delete mRenderTargetD; - delete mRenderTargetE; - - mRenderTargetA = new RenderTexture(); - mRenderTargetB = new RenderTexture(); - mRenderTargetC = new RenderTexture(); - mRenderTargetD = new RenderTexture(); - mRenderTargetE = new RenderTexture(); - - if (mRenderTargetA->Init(GL_RGBA16F, screenWidth, screenHeight) == false) + delete m_renderTargetA; + delete m_renderTargetB; + delete m_renderTargetC; + delete m_renderTargetD; + delete m_renderTargetE; + + m_renderTargetA = new RenderTexture(); + m_renderTargetB = new RenderTexture(); + m_renderTargetC = new RenderTexture(); + m_renderTargetD = new RenderTexture(); + m_renderTargetE = new RenderTexture(); + + if (m_renderTargetA->Init(GL_RGBA16F, screenWidth, screenHeight) == false) { return false; } - if (mRenderTargetB->Init(GL_RGBA16F, screenWidth, screenHeight) == false) + if (m_renderTargetB->Init(GL_RGBA16F, screenWidth, screenHeight) == false) { return false; } - if (mRenderTargetC->Init(GL_RGBA16F, screenWidth, screenHeight) == false) + if (m_renderTargetC->Init(GL_RGBA16F, screenWidth, screenHeight) == false) { return false; } - if (mRenderTargetD->Init(GL_RGBA16F, screenWidth / 2, screenHeight / 2) == false) + if (m_renderTargetD->Init(GL_RGBA16F, screenWidth / 2, screenHeight / 2) == false) { return false; } - if (mRenderTargetE->Init(GL_RGBA16F, screenWidth / 2, screenHeight / 2) == false) + if (m_renderTargetE->Init(GL_RGBA16F, screenWidth / 2, screenHeight / 2) == false) { return false; } @@ -213,16 +213,10 @@ namespace RenderGL { glPushAttrib(GL_VIEWPORT_BIT | GL_COLOR_BUFFER_BIT); - // get the width and height of the current used viewport - //float glDimensions[4]; - //glGetFloatv( GL_VIEWPORT, glDimensions ); - //mPrevWidth = (uint32)glDimensions[2]; - //mPrevHeight = (uint32)glDimensions[3]; - // bind the render texture and frame buffer glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); - glBindFramebuffer(GL_FRAMEBUFFER, mFBO); + glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); GLenum bufs[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 }; glDrawBuffers(2, bufs); @@ -234,14 +228,14 @@ namespace RenderGL } // setup the new viewport - glViewport(0, 0, mWidth, mHeight); + glViewport(0, 0, m_width, m_height); } // clear void GBuffer::Clear(const MCore::RGBAColor& color) { - glClearColor(color.r, color.g, color.b, 1.0f); + glClearColor(color.m_r, color.m_g, color.m_b, 1.0f); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } @@ -252,16 +246,9 @@ namespace RenderGL { glPopAttrib(); - //GLenum bufs[] = { GL_COLOR_ATTACHMENT0 }; - //glDrawBuffers( 1, bufs); - // undbind the frame buffer glBindFramebuffer(GL_FRAMEBUFFER, 0); - // reset viewport to original dimensions - //glViewport( 0, 0, mPrevWidth, mPrevHeight ); - //GetGraphicsManager()->SetRenderTexture(nullptr); - glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE0, 0); @@ -278,12 +265,12 @@ namespace RenderGL //----------------------------- // render the main image //----------------------------- - glBindTexture(GL_TEXTURE_2D, mComponents[COMPONENT_SHADED]); + glBindTexture(GL_TEXTURE_2D, m_components[COMPONENT_SHADED]); // setup ortho projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0, mWidth, mHeight, 0, -1, 1); + glOrtho(0, m_width, m_height, 0, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); @@ -298,15 +285,15 @@ namespace RenderGL glColor3f(1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); - glVertex2f(static_cast(mWidth), 0.0f); + glVertex2f(static_cast(m_width), 0.0f); glColor3f(1.0f, 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); - glVertex2f(static_cast(mWidth), static_cast(mHeight)); + glVertex2f(static_cast(m_width), static_cast(m_height)); glColor3f(1.0f, 1.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); - glVertex2f(0.0f, static_cast(mHeight)); + glVertex2f(0.0f, static_cast(m_height)); glColor3f(1.0f, 1.0f, 1.0f); glEnd(); @@ -320,14 +307,14 @@ namespace RenderGL // render the small images //----------------------------- uint32 xStart = 10; - uint32 yStart = mHeight - 110; + uint32 yStart = m_height - 110; for (uint32 i = 0; i < NUM_COMPONENTS; ++i) { - glBindTexture(GL_TEXTURE_2D, mComponents[i]); + glBindTexture(GL_TEXTURE_2D, m_components[i]); - const float w = static_cast(mWidth); - const float h = static_cast(mHeight); + const float w = static_cast(m_width); + const float h = static_cast(m_height); // Setup ortho projection glMatrixMode(GL_PROJECTION); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.h index 40b40fea45..cce01485e0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GBuffer.h @@ -50,32 +50,30 @@ namespace RenderGL void Render(); - MCORE_INLINE uint32 GetTextureID(EComponent component) const { return mComponents[component]; } + MCORE_INLINE uint32 GetTextureID(EComponent component) const { return m_components[component]; } bool Resize(uint32 width, uint32 height); bool ResizeTextures(uint32 screenWidth, uint32 screenHeight); - MCORE_INLINE RenderTexture* GetRenderTargetA() { return mRenderTargetA; } - MCORE_INLINE RenderTexture* GetRenderTargetB() { return mRenderTargetB; } - MCORE_INLINE RenderTexture* GetRenderTargetC() { return mRenderTargetC; } - MCORE_INLINE RenderTexture* GetRenderTargetD() { return mRenderTargetD; } - MCORE_INLINE RenderTexture* GetRenderTargetE() { return mRenderTargetE; } + MCORE_INLINE RenderTexture* GetRenderTargetA() { return m_renderTargetA; } + MCORE_INLINE RenderTexture* GetRenderTargetB() { return m_renderTargetB; } + MCORE_INLINE RenderTexture* GetRenderTargetC() { return m_renderTargetC; } + MCORE_INLINE RenderTexture* GetRenderTargetD() { return m_renderTargetD; } + MCORE_INLINE RenderTexture* GetRenderTargetE() { return m_renderTargetE; } private: - uint32 mFBO; - uint32 mComponents[NUM_COMPONENTS]; - uint32 mDepthBufferID; - //uint32 mPrevWidth; - //uint32 mPrevHeight; - uint32 mWidth; - uint32 mHeight; - - RenderTexture* mRenderTargetA; /**< A temp render target. */ - RenderTexture* mRenderTargetB; /**< A temp render target. */ - RenderTexture* mRenderTargetC; /**< A temp render target. */ - RenderTexture* mRenderTargetD; /**< Render target with width and height divided by four. */ - RenderTexture* mRenderTargetE; /**< Render target with width and height divided by four. */ + uint32 m_fbo; + uint32 m_components[NUM_COMPONENTS]; + uint32 m_depthBufferId; + uint32 m_width; + uint32 m_height; + + RenderTexture* m_renderTargetA; /**< A temp render target. */ + RenderTexture* m_renderTargetB; /**< A temp render target. */ + RenderTexture* m_renderTargetC; /**< A temp render target. */ + RenderTexture* m_renderTargetD; /**< Render target with width and height divided by four. */ + RenderTexture* m_renderTargetE; /**< Render target with width and height divided by four. */ }; } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp index d727300dd5..15be9676c1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLActor.cpp @@ -23,21 +23,12 @@ namespace RenderGL // constructor GLActor::GLActor() { - mEnableGPUSkinning = true; - mActor = nullptr; - mEnableGPUSkinning = true; + m_enableGpuSkinning = true; + m_actor = nullptr; + m_enableGpuSkinning = true; - mMaterials.SetMemoryCategory(MEMCATEGORY_RENDERING); - - mHomoMaterials.SetMemoryCategory(MEMCATEGORY_RENDERING); - - for (uint32 i = 0; i < 3; i++) - { - mIndexBuffers[i].SetMemoryCategory(MEMCATEGORY_RENDERING); - } - - mSkyColor = MCore::RGBAColor(0.55f, 0.55f, 0.55f); - mGroundColor = MCore::RGBAColor(0.117f, 0.015f, 0.07f); + m_skyColor = MCore::RGBAColor(0.55f, 0.55f, 0.55f); + m_groundColor = MCore::RGBAColor(0.117f, 0.015f, 0.07f); } @@ -65,45 +56,39 @@ namespace RenderGL // get rid of the allocated memory void GLActor::Cleanup() { - uint32 i; - // get rid of all index and vertex buffers - for (uint32 a = 0; a < 3; ++a) + for (AZStd::vector& vertexBuffers : m_vertexBuffers) { - // get rid of the given vertex buffers - const uint32 numVertexBuffers = mVertexBuffers[a].GetLength(); - for (i = 0; i < numVertexBuffers; ++i) + for (VertexBuffer* vertexBuffer : vertexBuffers) { - delete mVertexBuffers[a][i]; + delete vertexBuffer; } - - // get rid of the given index buffers - const uint32 numIndexBuffers = mIndexBuffers[a].GetLength(); - for (i = 0; i < numIndexBuffers; ++i) + } + for (AZStd::vector& indexBuffers : m_indexBuffers) + { + for (IndexBuffer* indexBuffer : indexBuffers) { - delete mIndexBuffers[a][i]; + delete indexBuffer; } } // delete all materials - const uint32 numLOD = mMaterials.GetLength(); - for (uint32 l = 0; l < numLOD; l++) + for (AZStd::vector& materialsPerLod : m_materials) { - const uint32 numMaterials = mMaterials[l].GetLength(); - for (uint32 n = 0; n < numMaterials; n++) + for (MaterialPrimitives* materialPrimitives : materialsPerLod) { - delete mMaterials[l][n]->mMaterial; - delete mMaterials[l][n]; + delete materialPrimitives->m_material; + delete materialPrimitives; } } } // customize the classify mesh type function - EMotionFX::Mesh::EMeshType GLActor::ClassifyMeshType(EMotionFX::Node* node, EMotionFX::Mesh* mesh, uint32 lodLevel) + EMotionFX::Mesh::EMeshType GLActor::ClassifyMeshType(EMotionFX::Node* node, EMotionFX::Mesh* mesh, size_t lodLevel) { MCORE_ASSERT(node && mesh); - return mesh->ClassifyMeshType(lodLevel, mActor, node->GetNodeIndex(), !mEnableGPUSkinning, 4, 200); + return mesh->ClassifyMeshType(lodLevel, m_actor, node->GetNodeIndex(), !m_enableGpuSkinning, 4, 200); } @@ -117,39 +102,40 @@ namespace RenderGL AZ::Debug::Timer initTimer; initTimer.Stamp(); - mActor = actor; - mEnableGPUSkinning = gpuSkinning; - mTexturePath = texturePath; + m_actor = actor; + m_enableGpuSkinning = gpuSkinning; + m_texturePath = texturePath; // get the number of nodes and geometry LOD levels - const uint32 numGeometryLODLevels = actor->GetNumLODLevels(); - const uint32 numNodes = actor->GetNumNodes(); + const size_t numGeometryLODLevels = actor->GetNumLODLevels(); + const size_t numNodes = actor->GetNumNodes(); // set the pre-allocation amount for the number of materials - mMaterials.Resize(numGeometryLODLevels); + m_materials.resize(numGeometryLODLevels); // resize the vertex and index buffers - for (uint32 a = 0; a < 3; ++a) + for (AZStd::vector& vertexBuffers : m_vertexBuffers) { - mVertexBuffers[a].Resize(numGeometryLODLevels); - mIndexBuffers[a].Resize(numGeometryLODLevels); - mPrimitives[a].Resize(numGeometryLODLevels); - - // reset the vertex and index buffers - for (uint32 n = 0; n < numGeometryLODLevels; ++n) - { - mVertexBuffers[a][n] = nullptr; - mIndexBuffers [a][n] = nullptr; - } + vertexBuffers.resize(numGeometryLODLevels); + AZStd::fill(begin(vertexBuffers), end(vertexBuffers), nullptr); + } + for (AZStd::vector& indexBuffers : m_indexBuffers) + { + indexBuffers.resize(numGeometryLODLevels); + AZStd::fill(begin(indexBuffers), end(indexBuffers), nullptr); + } + for (MCore::Array2D& primitives : m_primitives) + { + primitives.Resize(numGeometryLODLevels); } - mHomoMaterials.Resize(numGeometryLODLevels); - mDynamicNodes.Resize (numGeometryLODLevels); + m_homoMaterials.resize(numGeometryLODLevels); + m_dynamicNodes.Resize (numGeometryLODLevels); EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); // iterate through the lod levels - for (uint32 lodLevel = 0; lodLevel < numGeometryLODLevels; ++lodLevel) + for (size_t lodLevel = 0; lodLevel < numGeometryLODLevels; ++lodLevel) { InitMaterials(lodLevel); @@ -158,7 +144,7 @@ namespace RenderGL uint32 totalNumIndices[3] = { 0, 0, 0 }; // iterate through all nodes - for (uint32 n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { // get the current node EMotionFX::Node* node = skeleton->GetNode(n); @@ -180,35 +166,35 @@ namespace RenderGL EMotionFX::Mesh::EMeshType meshType = ClassifyMeshType(node, mesh, lodLevel); // get the number of submeshes and iterate through them - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t s = 0; s < numSubMeshes; ++s) { // get the current submesh EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(s); // create and add the primitive Primitive newPrimitive; - newPrimitive.mNodeIndex = n; - newPrimitive.mNumVertices = subMesh->GetNumVertices(); - newPrimitive.mNumTriangles = subMesh->CalcNumTriangles(); // subMesh->GetNumIndices() / 3; - newPrimitive.mIndexOffset = totalNumIndices[ meshType ]; - newPrimitive.mVertexOffset = totalNumVerts[ meshType ]; - newPrimitive.mMaterialIndex = 0; // Since GL actor only uses the default material, we should only pass in 0. + newPrimitive.m_nodeIndex = n; + newPrimitive.m_numVertices = subMesh->GetNumVertices(); + newPrimitive.m_numTriangles = subMesh->CalcNumTriangles(); // subMesh->GetNumIndices() / 3; + newPrimitive.m_indexOffset = totalNumIndices[ meshType ]; + newPrimitive.m_vertexOffset = totalNumVerts[ meshType ]; + newPrimitive.m_materialIndex = 0; // Since GL actor only uses the default material, we should only pass in 0. // copy over the used bones from the submesh if (subMesh->GetNumBones() > 0) { - newPrimitive.mBoneNodeIndices = subMesh->GetBonesArray(); + newPrimitive.m_boneNodeIndices = subMesh->GetBonesArray(); } // add to primitive list - mPrimitives[meshType].Add(lodLevel, newPrimitive); + m_primitives[meshType].Add(lodLevel, newPrimitive); // add to material list - MaterialPrimitives* materialPrims = mMaterials[lodLevel][newPrimitive.mMaterialIndex]; - materialPrims->mPrimitives[meshType].Add(newPrimitive); + MaterialPrimitives* materialPrims = m_materials[lodLevel][newPrimitive.m_materialIndex]; + materialPrims->m_primitives[meshType].emplace_back(newPrimitive); - totalNumIndices[meshType] += newPrimitive.mNumTriangles * 3; + totalNumIndices[meshType] += newPrimitive.m_numTriangles * 3; totalNumVerts[meshType] += subMesh->GetNumVertices(); } @@ -216,19 +202,19 @@ namespace RenderGL // add dynamic meshes to the dynamic node list if (meshType == EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED) { - mDynamicNodes.Add(lodLevel, node->GetNodeIndex()); + m_dynamicNodes.Add(lodLevel, node->GetNodeIndex()); } } // create the dynamic vertex buffers - const uint32 numDynamicBytes = sizeof(StandardVertex) * totalNumVerts[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED]; + const size_t numDynamicBytes = sizeof(StandardVertex) * totalNumVerts[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED]; if (numDynamicBytes > 0) { - mVertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] = new VertexBuffer(); - mIndexBuffers [EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] = new IndexBuffer(); + m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] = new VertexBuffer(); + m_indexBuffers [EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] = new IndexBuffer(); - const bool vbSuccess = mVertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Init(sizeof(StandardVertex), totalNumVerts[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED], USAGE_DYNAMIC); - const bool ibSuccess = mIndexBuffers [EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Init(IndexBuffer::INDEXSIZE_32BIT, totalNumIndices[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED], USAGE_STATIC); + const bool vbSuccess = m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Init(sizeof(StandardVertex), totalNumVerts[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED], USAGE_DYNAMIC); + const bool ibSuccess = m_indexBuffers [EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Init(IndexBuffer::INDEXSIZE_32BIT, totalNumIndices[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED], USAGE_STATIC); // check if the vertex and index buffers are valid if (vbSuccess == false || ibSuccess == false) @@ -239,14 +225,14 @@ namespace RenderGL } // create the static vertex buffers - const uint32 numStaticBytes = sizeof(StandardVertex) * totalNumVerts[EMotionFX::Mesh::MESHTYPE_STATIC]; + const size_t numStaticBytes = sizeof(StandardVertex) * totalNumVerts[EMotionFX::Mesh::MESHTYPE_STATIC]; if (numStaticBytes > 0) { - mVertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] = new VertexBuffer(); - mIndexBuffers [EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] = new IndexBuffer(); + m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] = new VertexBuffer(); + m_indexBuffers [EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] = new IndexBuffer(); - const bool vbSuccess = mVertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Init(sizeof(StandardVertex), totalNumVerts[EMotionFX::Mesh::MESHTYPE_STATIC], USAGE_STATIC); - const bool ibSuccess = mIndexBuffers [EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Init(IndexBuffer::INDEXSIZE_32BIT, totalNumIndices[EMotionFX::Mesh::MESHTYPE_STATIC], USAGE_STATIC); + const bool vbSuccess = m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Init(sizeof(StandardVertex), totalNumVerts[EMotionFX::Mesh::MESHTYPE_STATIC], USAGE_STATIC); + const bool ibSuccess = m_indexBuffers [EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Init(IndexBuffer::INDEXSIZE_32BIT, totalNumIndices[EMotionFX::Mesh::MESHTYPE_STATIC], USAGE_STATIC); // check if the vertex and index buffers are valid if (vbSuccess == false || ibSuccess == false) @@ -257,14 +243,14 @@ namespace RenderGL } // create the skinned vertex buffers - const uint32 numSkinnedBytes = sizeof(SkinnedVertex) * totalNumVerts[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED]; + const size_t numSkinnedBytes = sizeof(SkinnedVertex) * totalNumVerts[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED]; if (numSkinnedBytes > 0) { - mVertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] = new VertexBuffer(); - mIndexBuffers [EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] = new IndexBuffer(); + m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] = new VertexBuffer(); + m_indexBuffers [EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] = new IndexBuffer(); - const bool vbSuccess = mVertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Init(sizeof(SkinnedVertex), totalNumVerts[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED], USAGE_STATIC); - const bool ibSuccess = mIndexBuffers [EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Init(IndexBuffer::INDEXSIZE_32BIT, totalNumIndices[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED], USAGE_STATIC); + const bool vbSuccess = m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Init(sizeof(SkinnedVertex), totalNumVerts[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED], USAGE_STATIC); + const bool ibSuccess = m_indexBuffers [EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Init(IndexBuffer::INDEXSIZE_32BIT, totalNumIndices[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED], USAGE_STATIC); // check if the vertex and index buffers are valid if (vbSuccess == false || ibSuccess == false) @@ -284,10 +270,10 @@ namespace RenderGL if (gpuSkinning) { // iterate through all geometry LOD levels - for (uint32 lodLevel = 0; lodLevel < numGeometryLODLevels; ++lodLevel) + for (size_t lodLevel = 0; lodLevel < numGeometryLODLevels; ++lodLevel) { // iterate through all nodes - for (uint32 n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { // get the current node EMotionFX::Node* node = skeleton->GetNode(n); @@ -321,8 +307,8 @@ namespace RenderGL EMotionFX::MeshDeformerStack* stack = actor->GetMeshDeformerStack(lodLevel, n); if (stack) { - const uint32 numDeformers = stack->GetNumDeformers(); - for (uint32 d=0; dGetNumDeformers(); + for (size_t d=0; dGetDeformer(d); deformer->SetIsEnabled(false); @@ -358,22 +344,22 @@ namespace RenderGL // fallback to standard material MCore::LogWarning("[OpenGL] Cannot initialize OpenGL material for material '%s'. Falling back to default material.", emfxMaterial->GetName()); StandardMaterial* material = new RenderGL::StandardMaterial(this); - material->Init((EMotionFX::StandardMaterial*)mActor->GetMaterial(0, 0)); + material->Init((EMotionFX::StandardMaterial*)m_actor->GetMaterial(0, 0)); return material; } } // initialize materials - void GLActor::InitMaterials(uint32 lodLevel) + void GLActor::InitMaterials(size_t lodLevel) { // get the number of materials and iterate through them - const uint32 numMaterials = mActor->GetNumMaterials(lodLevel); - for (uint32 m = 0; m < numMaterials; ++m) + const size_t numMaterials = m_actor->GetNumMaterials(lodLevel); + for (size_t m = 0; m < numMaterials; ++m) { - EMotionFX::Material* emfxMaterial = mActor->GetMaterial(lodLevel, m); + EMotionFX::Material* emfxMaterial = m_actor->GetMaterial(lodLevel, m); Material* material = InitMaterial(emfxMaterial); - mMaterials[lodLevel].Add( new MaterialPrimitives(material) ); + m_materials[lodLevel].emplace_back( new MaterialPrimitives(material) ); } } @@ -381,13 +367,13 @@ namespace RenderGL // render the given actor instance void GLActor::Render(EMotionFX::ActorInstance* actorInstance, uint32 renderFlags) { - if (!mActor->IsReady()) + if (!m_actor->IsReady()) { return; } // make sure our actor instance is valid and that we initialized the gl actor - assert(mActor && actorInstance); + assert(m_actor && actorInstance); // update the dynamic vertices (copy dynamic vertices from system memory into the vertex buffer) UpdateDynamicVertices(actorInstance); @@ -411,39 +397,37 @@ namespace RenderGL // render meshes of the given type void GLActor::RenderMeshes(EMotionFX::ActorInstance* actorInstance, EMotionFX::Mesh::EMeshType meshType, uint32 renderFlags) { - const uint32 lodLevel = actorInstance->GetLODLevel(); - const uint32 numMaterials = mMaterials[lodLevel].GetLength(); + const size_t lodLevel = actorInstance->GetLODLevel(); + const size_t numMaterials = m_materials[lodLevel].size(); if (numMaterials == 0) { return; } - if (mVertexBuffers[meshType][lodLevel] == nullptr || mIndexBuffers[meshType][lodLevel] == nullptr) + if (m_vertexBuffers[meshType][lodLevel] == nullptr || m_indexBuffers[meshType][lodLevel] == nullptr) { return; } - if (mVertexBuffers[meshType][lodLevel]->GetBufferID() == MCORE_INVALIDINDEX32) + if (m_vertexBuffers[meshType][lodLevel]->GetBufferID() == MCORE_INVALIDINDEX32) { return; } // activate vertex and index buffers - mVertexBuffers[meshType][lodLevel]->Activate(); - mIndexBuffers[meshType][lodLevel]->Activate(); + m_vertexBuffers[meshType][lodLevel]->Activate(); + m_indexBuffers[meshType][lodLevel]->Activate(); // render all the primitives in each material - for (uint32 n = 0; n < numMaterials; n++) + for (const MaterialPrimitives* materialPrims : m_materials[lodLevel]) { - const MaterialPrimitives* materialPrims = mMaterials[lodLevel][n]; - const uint32 numPrimitives = materialPrims->mPrimitives[meshType].GetLength(); - if (numPrimitives == 0) + if (materialPrims->m_primitives[meshType].empty()) { continue; } - Material* material = materialPrims->mMaterial; + Material* material = materialPrims->m_material; if (material == nullptr) { continue; @@ -459,9 +443,9 @@ namespace RenderGL material->Activate(activationFlags); // render all primitives - for (uint32 i = 0; i < numPrimitives; ++i) + for (const Primitive& primitive : materialPrims->m_primitives[meshType]) { - material->Render(actorInstance, &materialPrims->mPrimitives[meshType][i]); + material->Render(actorInstance, &primitive); } material->Deactivate(); @@ -473,20 +457,20 @@ namespace RenderGL void GLActor::UpdateDynamicVertices(EMotionFX::ActorInstance* actorInstance) { // get the number of dynamic nodes - const uint32 lodLevel = actorInstance->GetLODLevel(); - const size_t numNodes = mDynamicNodes.GetNumElements(lodLevel); + const size_t lodLevel = actorInstance->GetLODLevel(); + const size_t numNodes = m_dynamicNodes.GetNumElements(lodLevel); if (numNodes == 0) { return; } - if (mVertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] == nullptr) + if (m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] == nullptr) { return; } // lock the dynamic vertex buffer - StandardVertex* dynamicVertices = (StandardVertex*)mVertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); + StandardVertex* dynamicVertices = (StandardVertex*)m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); if (dynamicVertices == nullptr) { return; @@ -499,8 +483,8 @@ namespace RenderGL for (size_t n = 0; n < numNodes; ++n) { // get the node and its mesh - const size_t nodeIndex = mDynamicNodes.GetElement(lodLevel, n); - EMotionFX::Mesh* mesh = mActor->GetMesh(lodLevel, aznumeric_cast(nodeIndex)); + const size_t nodeIndex = m_dynamicNodes.GetElement(lodLevel, n); + EMotionFX::Mesh* mesh = m_actor->GetMesh(lodLevel, nodeIndex); // is the mesh valid? if (mesh == nullptr) @@ -519,10 +503,10 @@ namespace RenderGL { for (uint32 v = 0; v < numVertices; ++v) { - dynamicVertices[globalVert].mPosition = positions[v]; - dynamicVertices[globalVert].mNormal = normals[v]; - dynamicVertices[globalVert].mUV = uvsA[v]; - dynamicVertices[globalVert].mTangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); + dynamicVertices[globalVert].m_position = positions[v]; + dynamicVertices[globalVert].m_normal = normals[v]; + dynamicVertices[globalVert].m_uv = uvsA[v]; + dynamicVertices[globalVert].m_tangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); globalVert++; } } @@ -530,22 +514,22 @@ namespace RenderGL { for (uint32 v = 0; v < numVertices; ++v) { - dynamicVertices[globalVert].mPosition = positions[v]; - dynamicVertices[globalVert].mNormal = normals[v]; - dynamicVertices[globalVert].mUV = AZ::Vector2(0.0f, 0.0f); - dynamicVertices[globalVert].mTangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); + dynamicVertices[globalVert].m_position = positions[v]; + dynamicVertices[globalVert].m_normal = normals[v]; + dynamicVertices[globalVert].m_uv = AZ::Vector2(0.0f, 0.0f); + dynamicVertices[globalVert].m_tangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); globalVert++; } } } // unlock the vertex buffer - mVertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Unlock(); + m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Unlock(); } // fill the index buffers with data - void GLActor::FillIndexBuffers(uint32 lodLevel) + void GLActor::FillIndexBuffers(size_t lodLevel) { // initialize the index buffers uint32* staticIndices = nullptr; @@ -553,23 +537,23 @@ namespace RenderGL uint32* skinnedIndices = nullptr; // lock the index buffers - if (mIndexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]) + if (m_indexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]) { - staticIndices = (uint32*)mIndexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Lock(LOCK_WRITEONLY); + staticIndices = (uint32*)m_indexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Lock(LOCK_WRITEONLY); } - if (mIndexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]) + if (m_indexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]) { - dynamicIndices = (uint32*)mIndexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); + dynamicIndices = (uint32*)m_indexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); } - if (mIndexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]) + if (m_indexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]) { - skinnedIndices = (uint32*)mIndexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); + skinnedIndices = (uint32*)m_indexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); } //if (staticIndices == nullptr || dynamicIndices == nullptr || skinnedIndices == nullptr) - if ((mIndexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] && staticIndices == nullptr) || - (mIndexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] && dynamicIndices == nullptr) || - (mIndexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] && skinnedIndices == nullptr)) + if ((m_indexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] && staticIndices == nullptr) || + (m_indexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel] && dynamicIndices == nullptr) || + (m_indexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] && skinnedIndices == nullptr)) { MCore::LogWarning("[OpenGL] Cannot lock index buffers in GLActor::FillIndexBuffers."); return; @@ -583,17 +567,17 @@ namespace RenderGL uint32 staticOffset = 0; uint32 gpuSkinnedOffset = 0; - EMotionFX::Skeleton* skeleton = mActor->GetSkeleton(); + EMotionFX::Skeleton* skeleton = m_actor->GetSkeleton(); // get the number of nodes and iterate through them - const uint32 numNodes = mActor->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = m_actor->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { // get the current node EMotionFX::Node* node = skeleton->GetNode(n); // get the mesh for the node, if there is any - EMotionFX::Mesh* mesh = mActor->GetMesh(lodLevel, n); + EMotionFX::Mesh* mesh = m_actor->GetMesh(lodLevel, n); if (mesh == nullptr) { continue; @@ -606,7 +590,6 @@ namespace RenderGL } // get the mesh type and the indices - //const uint32 numIndices = mesh->GetNumIndices(); uint32* indices = mesh->GetIndices(); uint8* vertCounts = mesh->GetPolygonVertexCounts(); EMotionFX::Mesh::EMeshType meshType = ClassifyMeshType(node, mesh, lodLevel); @@ -630,9 +613,6 @@ namespace RenderGL polyStartIndex += numPolyVerts; } - //for (uint32 i=0; iGetNumVertices(); break; } @@ -653,10 +633,6 @@ namespace RenderGL polyStartIndex += numPolyVerts; } - // fill in static index buffers - //for (uint32 i=0; iGetNumVertices(); break; } @@ -677,10 +653,6 @@ namespace RenderGL polyStartIndex += numPolyVerts; } - // fill in gpu skinned index buffers - //for (uint32 i=0; iGetNumVertices(); break; } @@ -690,38 +662,38 @@ namespace RenderGL // unlock the buffers if (staticIndices) { - mIndexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Unlock(); + m_indexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Unlock(); } if (dynamicIndices) { - mIndexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Unlock(); + m_indexBuffers[EMotionFX::Mesh::MESHTYPE_CPU_DEFORMED][lodLevel]->Unlock(); } if (skinnedIndices) { - mIndexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Unlock(); + m_indexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Unlock(); } } // fill the static vertex buffer - void GLActor::FillStaticVertexBuffers(uint32 lodLevel) + void GLActor::FillStaticVertexBuffers(size_t lodLevel) { - if (mVertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] == nullptr) + if (m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel] == nullptr) { return; } // get the number of nodes - const uint32 numNodes = mActor->GetNumNodes(); + const size_t numNodes = m_actor->GetNumNodes(); if (numNodes == 0) { return; } - EMotionFX::Skeleton* skeleton = mActor->GetSkeleton(); + EMotionFX::Skeleton* skeleton = m_actor->GetSkeleton(); // lock the static vertex buffer - StandardVertex* staticVertices = (StandardVertex*)mVertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Lock(LOCK_WRITEONLY); + StandardVertex* staticVertices = (StandardVertex*)m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Lock(LOCK_WRITEONLY); if (staticVertices == nullptr) { return; @@ -731,13 +703,13 @@ namespace RenderGL uint32 globalVert = 0; // iterate through all nodes - for (uint32 n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { // get the current node EMotionFX::Node* node = skeleton->GetNode(n); // get the mesh for the node, if there is any - EMotionFX::Mesh* mesh = mActor->GetMesh(lodLevel, n); + EMotionFX::Mesh* mesh = m_actor->GetMesh(lodLevel, n); if (mesh == nullptr) { continue; @@ -767,10 +739,10 @@ namespace RenderGL const uint32 numVerts = mesh->GetNumVertices(); for (uint32 v = 0; v < numVerts; ++v) { - staticVertices[globalVert].mPosition = positions[v]; - staticVertices[globalVert].mNormal = normals[v]; - staticVertices[globalVert].mUV = uvsA[v]; - staticVertices[globalVert].mTangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); + staticVertices[globalVert].m_position = positions[v]; + staticVertices[globalVert].m_normal = normals[v]; + staticVertices[globalVert].m_uv = uvsA[v]; + staticVertices[globalVert].m_tangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); globalVert++; } } @@ -779,39 +751,39 @@ namespace RenderGL const uint32 numVerts = mesh->GetNumVertices(); for (uint32 v = 0; v < numVerts; ++v) { - staticVertices[globalVert].mPosition = positions[v]; - staticVertices[globalVert].mNormal = normals[v]; - staticVertices[globalVert].mUV = AZ::Vector2(0.0f, 0.0f); - staticVertices[globalVert].mTangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); + staticVertices[globalVert].m_position = positions[v]; + staticVertices[globalVert].m_normal = normals[v]; + staticVertices[globalVert].m_uv = AZ::Vector2(0.0f, 0.0f); + staticVertices[globalVert].m_tangent = (tangents) ? tangents[v] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); globalVert++; } } } // unlock the vertex buffer - mVertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Unlock(); + m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_STATIC][lodLevel]->Unlock(); } // fill the GPU skinned vertex buffer - void GLActor::FillGPUSkinnedVertexBuffers(uint32 lodLevel) + void GLActor::FillGPUSkinnedVertexBuffers(size_t lodLevel) { - if (mVertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] == nullptr) + if (m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel] == nullptr) { return; } // get the number of dynamic nodes - const uint32 numNodes = mActor->GetNumNodes(); + const size_t numNodes = m_actor->GetNumNodes(); if (numNodes == 0) { return; } - EMotionFX::Skeleton* skeleton = mActor->GetSkeleton(); + EMotionFX::Skeleton* skeleton = m_actor->GetSkeleton(); // lock the GPU skinned vertex buffer - SkinnedVertex* skinnedVertices = (SkinnedVertex*)mVertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); + SkinnedVertex* skinnedVertices = (SkinnedVertex*)m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Lock(LOCK_WRITEONLY); if (skinnedVertices == nullptr) { return; @@ -821,13 +793,13 @@ namespace RenderGL uint32 globalVert = 0; // iterate through all nodes - for (uint32 n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { // get the current node EMotionFX::Node* node = skeleton->GetNode(n); // get the mesh for the node, if there is any - EMotionFX::Mesh* mesh = mActor->GetMesh(lodLevel, n); + EMotionFX::Mesh* mesh = m_actor->GetMesh(lodLevel, n); if (mesh == nullptr) { continue; @@ -858,8 +830,8 @@ namespace RenderGL assert(skinningInfo); // get the number of submeshes and iterate through them - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t s = 0; s < numSubMeshes; ++s) { // get the current submesh and the start vertex EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(s); @@ -873,10 +845,10 @@ namespace RenderGL const uint32 orgVertex = orgVerts[meshVertexNr]; // copy position and normal - skinnedVertices[globalVert].mPosition = positions[meshVertexNr]; - skinnedVertices[globalVert].mNormal = normals[meshVertexNr]; - skinnedVertices[globalVert].mTangent = (tangents) ? tangents[meshVertexNr] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); - skinnedVertices[globalVert].mUV = (uvsA == nullptr) ? AZ::Vector2(0.0f, 0.0f) : uvsA[meshVertexNr]; + skinnedVertices[globalVert].m_position = positions[meshVertexNr]; + skinnedVertices[globalVert].m_normal = normals[meshVertexNr]; + skinnedVertices[globalVert].m_tangent = (tangents) ? tangents[meshVertexNr] : AZ::Vector4(0.0f, 0.0f, 1.0f, 1.0f); + skinnedVertices[globalVert].m_uv = (uvsA == nullptr) ? AZ::Vector2(0.0f, 0.0f) : uvsA[meshVertexNr]; // get the number of influences and iterate through them const size_t numInfluences = skinningInfo->GetNumInfluences(orgVertex); @@ -885,17 +857,17 @@ namespace RenderGL { // get the influence and its weight and set the indices EMotionFX::SkinInfluence* influence = skinningInfo->GetInfluence(orgVertex, i); - skinnedVertices[globalVert].mWeights[i] = influence->GetWeight(); - const uint32 boneIndex = subMesh->FindBoneIndex(influence->GetNodeNr()); - skinnedVertices[globalVert].mBoneIndices[i] = static_cast(boneIndex); - MCORE_ASSERT(boneIndex != MCORE_INVALIDINDEX32); + skinnedVertices[globalVert].m_weights[i] = influence->GetWeight(); + const size_t boneIndex = subMesh->FindBoneIndex(influence->GetNodeNr()); + skinnedVertices[globalVert].m_boneIndices[i] = static_cast(boneIndex); + MCORE_ASSERT(boneIndex != InvalidIndex); } // reset remaining weights and offsets for (size_t a = i; a < 4; ++a) { - skinnedVertices[globalVert].mWeights[a] = 0.0f; - skinnedVertices[globalVert].mBoneIndices[a] = 0; + skinnedVertices[globalVert].m_weights[a] = 0.0f; + skinnedVertices[globalVert].m_boneIndices[a] = 0; } globalVert++; @@ -904,6 +876,6 @@ namespace RenderGL } // unlock the vertex buffer - mVertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Unlock(); + m_vertexBuffers[EMotionFX::Mesh::MESHTYPE_GPU_DEFORMED][lodLevel]->Unlock(); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.cpp index 83ae498682..91ee24876e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.cpp @@ -17,7 +17,7 @@ namespace RenderGL { bool ok = true; - ok &= bool((glMapBuffer = (_glMapBuffer)context->getProcAddress(QByteArray("glMapBuffer")))); + ok &= bool((m_glMapBuffer = (_glMapBuffer)context->getProcAddress(QByteArray("glMapBuffer")))); return ok; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h index 1eea2209ec..934d73b29e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLExtensions.h @@ -21,7 +21,7 @@ namespace RenderGL { bool resolve(const QOpenGLContext* context); - _glMapBuffer glMapBuffer; + _glMapBuffer m_glMapBuffer; }; } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp index feb2cd22ee..734b57e96b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.cpp @@ -26,66 +26,61 @@ namespace RenderGL : RenderUtil() { // set/reset the member variables - mGraphicsManager = graphicsManager; - mLineShader = nullptr; - mMeshShader = nullptr; - mMeshVertexBuffer = nullptr; - mMeshIndexBuffer = nullptr; + m_graphicsManager = graphicsManager; + m_lineShader = nullptr; + m_meshShader = nullptr; + m_meshVertexBuffer = nullptr; + m_meshIndexBuffer = nullptr; - mTriangleVertexBuffer = nullptr; - mTriangleIndexBuffer = nullptr; + m_triangleVertexBuffer = nullptr; + m_triangleIndexBuffer = nullptr; - mCurrentLineVB = 0; - - for (uint32 i = 0; i < MAX_LINE_VERTEXBUFFERS; ++i) - { - mLineVertexBuffers[i] = nullptr; - } + m_currentLineVb = 0; // initialize the vertex buffers and the shader used for line rendering - for (uint32 i = 0; i < MAX_LINE_VERTEXBUFFERS; ++i) + for (VertexBuffer*& lineVertexBuffer : m_lineVertexBuffers) { - mLineVertexBuffers[i] = new VertexBuffer(); - if (mLineVertexBuffers[i]->Init(sizeof(LineVertex), mNumMaxLineVertices, USAGE_DYNAMIC) == false) + lineVertexBuffer = new VertexBuffer(); + if (lineVertexBuffer->Init(sizeof(LineVertex), s_numMaxLineVertices, USAGE_DYNAMIC) == false) { MCore::LogError("[OpenGL] Failed to create render utility line vertex buffer."); CleanUp(); } } - mLineShader = graphicsManager->LoadShader("Line_VS.glsl", "Line_PS.glsl"); + m_lineShader = graphicsManager->LoadShader("Line_VS.glsl", "Line_PS.glsl"); // initialize the vertex and the index buffers as well as the shader used for rendering util meshes - mMeshVertexBuffer = new VertexBuffer(); - mMeshIndexBuffer = new IndexBuffer(); + m_meshVertexBuffer = new VertexBuffer(); + m_meshIndexBuffer = new IndexBuffer(); - if (mMeshVertexBuffer->Init(sizeof(UtilMeshVertex), mNumMaxMeshVertices, USAGE_DYNAMIC) == false) + if (m_meshVertexBuffer->Init(sizeof(UtilMeshVertex), s_numMaxMeshVertices, USAGE_DYNAMIC) == false) { MCore::LogError("[OpenGL] Failed to create render utility mesh vertex buffer."); CleanUp(); return; } - if (mMeshIndexBuffer->Init(IndexBuffer::INDEXSIZE_32BIT, mNumMaxMeshIndices, USAGE_DYNAMIC) == false) + if (m_meshIndexBuffer->Init(IndexBuffer::INDEXSIZE_32BIT, s_numMaxMeshIndices, USAGE_DYNAMIC) == false) { MCore::LogError("[OpenGL] Failed to create render utility mesh index buffer."); CleanUp(); return; } - mMeshShader = graphicsManager->LoadShader("RenderUtil_VS.glsl", "RenderUtil_PS.glsl"); + m_meshShader = graphicsManager->LoadShader("RenderUtil_VS.glsl", "RenderUtil_PS.glsl"); // initialize the triangle rendering buffers - mTriangleVertexBuffer = new VertexBuffer(); - if (mTriangleVertexBuffer->Init(sizeof(TriangleVertex), mNumMaxTriangleVertices, USAGE_DYNAMIC) == false) + m_triangleVertexBuffer = new VertexBuffer(); + if (m_triangleVertexBuffer->Init(sizeof(TriangleVertex), s_numMaxTriangleVertices, USAGE_DYNAMIC) == false) { MCore::LogError("[OpenGL] Failed to create triangle vertex buffer."); CleanUp(); return; } - mTriangleIndexBuffer = new IndexBuffer(); - if (mTriangleIndexBuffer->Init(IndexBuffer::INDEXSIZE_32BIT, mNumMaxTriangleVertices, USAGE_STATIC) == false) + m_triangleIndexBuffer = new IndexBuffer(); + if (m_triangleIndexBuffer->Init(IndexBuffer::INDEXSIZE_32BIT, s_numMaxTriangleVertices, USAGE_STATIC) == false) { MCore::LogError("[OpenGL] Failed to create triangle index buffer."); CleanUp(); @@ -93,24 +88,23 @@ namespace RenderGL } // lock the index buffer and fill in the static indices - uint32* indices = (uint32*)mTriangleIndexBuffer->Lock(); + uint32* indices = (uint32*)m_triangleIndexBuffer->Lock(); if (indices) { - for (uint32 i = 0; i < mNumMaxTriangleVertices; ++i) + for (uint32 i = 0; i < s_numMaxTriangleVertices; ++i) { indices[i] = i; } - mTriangleIndexBuffer->Unlock(); + m_triangleIndexBuffer->Unlock(); } // texture rendering - mMaxNumTextures = 256; - mNumTextures = 0; - mTextures = new TextureEntry[mMaxNumTextures]; + m_maxNumTextures = 256; + m_numTextures = 0; + m_textures = new TextureEntry[m_maxNumTextures]; // text rendering - mTextEntries.SetMemoryCategory(MEMCATEGORY_RENDERING); } @@ -127,60 +121,59 @@ namespace RenderGL void GLRenderUtil::Validate() { - if (mLineShader) + if (m_lineShader) { - mLineShader->Validate(); + m_lineShader->Validate(); } - if (mMeshShader) + if (m_meshShader) { - mMeshShader->Validate(); + m_meshShader->Validate(); } } // destroy the allocated memory void GLRenderUtil::CleanUp() { - for (uint32 i = 0; i < MAX_LINE_VERTEXBUFFERS; ++i) + for (VertexBuffer*& lineVertexBuffer : m_lineVertexBuffers) { - delete mLineVertexBuffers[i]; - mLineVertexBuffers[i] = nullptr; + delete lineVertexBuffer; + lineVertexBuffer = nullptr; } - delete mMeshVertexBuffer; - delete mMeshIndexBuffer; + delete m_meshVertexBuffer; + delete m_meshIndexBuffer; - delete mTriangleVertexBuffer; - delete mTriangleIndexBuffer; + delete m_triangleVertexBuffer; + delete m_triangleIndexBuffer; - mMeshVertexBuffer = nullptr; - mMeshIndexBuffer = nullptr; + m_meshVertexBuffer = nullptr; + m_meshIndexBuffer = nullptr; - mTriangleVertexBuffer = nullptr; - mTriangleIndexBuffer = nullptr; + m_triangleVertexBuffer = nullptr; + m_triangleIndexBuffer = nullptr; - mCurrentLineVB = 0; + m_currentLineVb = 0; // get rid of the texture entries - delete[] mTextures; + delete[] m_textures; // get rid of texture entries - const uint32 numTextEntries = mTextEntries.GetLength(); - for (uint32 i = 0; i < numTextEntries; ++i) + for (TextEntry* textEntry : m_textEntries) { - delete mTextEntries[i]; + delete textEntry; } - mTextEntries.Clear(); + m_textEntries.clear(); } // render texture void GLRenderUtil::RenderTexture(Texture* texture, const AZ::Vector2& pos) { - mTextures[mNumTextures].pos = pos; - mTextures[mNumTextures].texture = texture; - mNumTextures++; + m_textures[m_numTextures].m_pos = pos; + m_textures[m_numTextures].m_texture = texture; + m_numTextures++; - if (mNumTextures >= mMaxNumTextures) + if (m_numTextures >= m_maxNumTextures) { RenderTextures(); } @@ -190,7 +183,7 @@ namespace RenderGL // render textures void GLRenderUtil::RenderTextures() { - if (mNumTextures == 0) + if (m_numTextures == 0) { return; } @@ -223,44 +216,41 @@ namespace RenderGL glColor3f(1.0f, 1.0f, 1.0f); // iterate through the textures and render them - for (uint32 i = 0; i < mNumTextures; ++i) + for (uint32 i = 0; i < m_numTextures; ++i) { - TextureEntry& e = mTextures[i]; - float w = static_cast(e.texture->GetWidth()); - float h = static_cast(e.texture->GetHeight()); + TextureEntry& e = m_textures[i]; + float w = static_cast(e.m_texture->GetWidth()); + float h = static_cast(e.m_texture->GetHeight()); - glBindTexture(GL_TEXTURE_2D, e.texture->GetID()); + glBindTexture(GL_TEXTURE_2D, e.m_texture->GetID()); glBegin(GL_QUADS); glTexCoord2f(0.0f, 0.0f); - glVertex3f(e.pos.GetX(), e.pos.GetY(), -1.0f); + glVertex3f(e.m_pos.GetX(), e.m_pos.GetY(), -1.0f); glTexCoord2f(1.0f, 0.0f); - glVertex3f(e.pos.GetX() + w, e.pos.GetY(), -1.0f); + glVertex3f(e.m_pos.GetX() + w, e.m_pos.GetY(), -1.0f); glTexCoord2f(1.0f, 1.0f); - glVertex3f(e.pos.GetX() + w, e.pos.GetY() + h, -1.0f); + glVertex3f(e.m_pos.GetX() + w, e.m_pos.GetY() + h, -1.0f); glTexCoord2f(0.0f, 1.0f); - glVertex3f(e.pos.GetX(), e.pos.GetY() + h, -1.0f); + glVertex3f(e.m_pos.GetX(), e.m_pos.GetY() + h, -1.0f); glEnd(); } glPopAttrib(); - //const float renderTime = time.GetTime(); - //LOG("numTextures=%i, renderTime=%.3fms", mNumTextures, renderTime*1000); - - mNumTextures = 0; + m_numTextures = 0; } // overloaded render lines function void GLRenderUtil::RenderLines(LineVertex* vertices, uint32 numVertices) { - if (mLineShader == nullptr) + if (m_lineShader == nullptr) { return; } - VertexBuffer* vertexBuffer = mLineVertexBuffers[mCurrentLineVB]; + VertexBuffer* vertexBuffer = m_lineVertexBuffers[m_currentLineVb]; // copy the vertices into the OpenGL vertex buffer LineVertex* lineVertices = (LineVertex*)vertexBuffer->Lock(); @@ -275,23 +265,23 @@ namespace RenderGL glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // setup the shader and render the lines - mLineShader->Activate(); + m_lineShader->Activate(); - mLineShader->SetAttribute("inPosition", 4, GL_FLOAT, sizeof(LineVertex), 0); - mLineShader->SetAttribute("inColor", 4, GL_FLOAT, sizeof(LineVertex), sizeof(AZ::Vector3)); - mLineShader->SetUniform("matViewProj", mGraphicsManager->GetCamera()->GetViewProjMatrix(), false); + m_lineShader->SetAttribute("inPosition", 4, GL_FLOAT, sizeof(LineVertex), 0); + m_lineShader->SetAttribute("inColor", 4, GL_FLOAT, sizeof(LineVertex), sizeof(AZ::Vector3)); + m_lineShader->SetUniform("matViewProj", m_graphicsManager->GetCamera()->GetViewProjMatrix(), false); glDrawArrays(GL_LINES, 0, numVertices); - mLineShader->Deactivate(); + m_lineShader->Deactivate(); GetGraphicsManager()->SetShader(nullptr); // if only lines are rendered, we need to unbind this shader totally // otherwise it will stay active and another context can't use it vertexBuffer->Deactivate(); - mCurrentLineVB++; - if (mCurrentLineVB >= MAX_LINE_VERTEXBUFFERS) + m_currentLineVb++; + if (m_currentLineVb >= MAX_LINE_VERTEXBUFFERS) { - mCurrentLineVB = 0; + m_currentLineVb = 0; } } @@ -321,14 +311,14 @@ namespace RenderGL glLoadIdentity(); // use the fixed function pipeline - mGraphicsManager->SetShader(nullptr); + m_graphicsManager->SetShader(nullptr); glBegin(GL_LINES); for (uint32 i = 0; i < numLines; ++i) { - glColor3f(lines[i].mColor.r, lines[i].mColor.g, lines[i].mColor.b); - glVertex3f(lines[i].mX1, lines[i].mY1, 0.0); - glVertex3f(lines[i].mX2, lines[i].mY2, 0.0); + glColor3f(lines[i].m_color.m_r, lines[i].m_color.m_g, lines[i].m_color.m_b); + glVertex3f(lines[i].m_x1, lines[i].m_y1, 0.0); + glVertex3f(lines[i].m_x2, lines[i].m_y2, 0.0); } glEnd(); @@ -360,9 +350,9 @@ namespace RenderGL glLoadIdentity(); // use the fixed function pipeline - mGraphicsManager->SetShader(nullptr); + m_graphicsManager->SetShader(nullptr); - glColor3f(fillColor.r, fillColor.g, fillColor.b); + glColor3f(fillColor.m_r, fillColor.m_g, fillColor.m_b); glBegin(GL_QUADS); glVertex3i(left, top, 0); glVertex3i(left, bottom, 0); @@ -382,65 +372,65 @@ namespace RenderGL // overloaded render util mesh function void GLRenderUtil::RenderUtilMesh(UtilMesh* mesh, const MCore::RGBAColor& color, const AZ::Transform& globalTM) { - if (mMeshShader == nullptr) + if (m_meshShader == nullptr) { return; } // lock the vertex and the index buffer - UtilMeshVertex* vertices = (UtilMeshVertex*)mMeshVertexBuffer->Lock(); - uint32* indices = (uint32*)mMeshIndexBuffer->Lock(); + UtilMeshVertex* vertices = (UtilMeshVertex*)m_meshVertexBuffer->Lock(); + uint32* indices = (uint32*)m_meshIndexBuffer->Lock(); // copy the vertices and the indices into the OpenGL buffers - MCORE_ASSERT(mesh->mPositions.size() <= mNumMaxMeshVertices); - MCore::MemCopy(indices, mesh->mIndices.data(), mesh->mIndices.size() * sizeof(uint32)); + MCORE_ASSERT(mesh->m_positions.size() <= s_numMaxMeshVertices); + MCore::MemCopy(indices, mesh->m_indices.data(), mesh->m_indices.size() * sizeof(uint32)); - if (mesh->mNormals.empty()) + if (mesh->m_normals.empty()) { - const size_t numVertices = mesh->mPositions.size(); + const size_t numVertices = mesh->m_positions.size(); for (size_t i = 0; i < numVertices; ++i) { - vertices[i].mPosition = mesh->mPositions[i]; - vertices[i].mNormal = AZ::Vector3(1.0f, 0.0f, 0.0f); + vertices[i].m_position = mesh->m_positions[i]; + vertices[i].m_normal = AZ::Vector3(1.0f, 0.0f, 0.0f); } } else { - const size_t numVertices = mesh->mPositions.size(); + const size_t numVertices = mesh->m_positions.size(); for (size_t i = 0; i < numVertices; ++i) { - vertices[i].mPosition = mesh->mPositions[i]; - vertices[i].mNormal = mesh->mNormals[i]; + vertices[i].m_position = mesh->m_positions[i]; + vertices[i].m_normal = mesh->m_normals[i]; } } // unlock and activate the vertex and the index buffer - mMeshVertexBuffer->Unlock(); - mMeshIndexBuffer->Unlock(); - mMeshVertexBuffer->Activate(); - mMeshIndexBuffer->Activate(); + m_meshVertexBuffer->Unlock(); + m_meshIndexBuffer->Unlock(); + m_meshVertexBuffer->Activate(); + m_meshIndexBuffer->Activate(); // setup shader - mMeshShader->Activate(); + m_meshShader->Activate(); - MCommon::Camera* camera = mGraphicsManager->GetCamera(); + MCommon::Camera* camera = m_graphicsManager->GetCamera(); const AZ::Matrix4x4 globalMatrix = AZ::Matrix4x4::CreateFromTransform(globalTM); - mMeshShader->SetUniform("worldViewProjectionMatrix", camera->GetViewProjMatrix() * globalMatrix); - mMeshShader->SetUniform("cameraPosition", camera->GetPosition()); - mMeshShader->SetUniform("lightDirection", MCore::GetUp(camera->GetViewMatrix().GetTranspose()).GetNormalized()); // This is GetUp() now, as lookat matrices always seem to use the z axis to point forward - mMeshShader->SetUniform("diffuseColor", color); - mMeshShader->SetUniform("specularColor", AZ::Vector3::CreateOne() * 0.3f); - mMeshShader->SetUniform("specularPower", 8.0f); + m_meshShader->SetUniform("worldViewProjectionMatrix", camera->GetViewProjMatrix() * globalMatrix); + m_meshShader->SetUniform("cameraPosition", camera->GetPosition()); + m_meshShader->SetUniform("lightDirection", MCore::GetUp(camera->GetViewMatrix().GetTranspose()).GetNormalized()); // This is GetUp() now, as lookat matrices always seem to use the z axis to point forward + m_meshShader->SetUniform("diffuseColor", color); + m_meshShader->SetUniform("specularColor", AZ::Vector3::CreateOne() * 0.3f); + m_meshShader->SetUniform("specularPower", 8.0f); // setup shader attributes and draw the mesh const uint32 stride = sizeof(UtilMeshVertex); - mMeshShader->SetAttribute("inPosition", 4, GL_FLOAT, stride, 0); - mMeshShader->SetAttribute("inNormal", 4, GL_FLOAT, stride, sizeof(AZ::Vector3)); - mMeshShader->SetUniform("worldMatrix", globalMatrix); + m_meshShader->SetAttribute("inPosition", 4, GL_FLOAT, stride, 0); + m_meshShader->SetAttribute("inNormal", 4, GL_FLOAT, stride, sizeof(AZ::Vector3)); + m_meshShader->SetUniform("worldMatrix", globalMatrix); - glDrawElements(GL_TRIANGLES, (GLsizei)mesh->mIndices.size(), GL_UNSIGNED_INT, (GLvoid*)nullptr); + glDrawElements(GL_TRIANGLES, (GLsizei)mesh->m_indices.size(), GL_UNSIGNED_INT, (GLvoid*)nullptr); - mMeshShader->Deactivate(); + m_meshShader->Deactivate(); } @@ -451,7 +441,7 @@ namespace RenderGL // load the camera view projection matrix glMatrixMode(GL_PROJECTION); - MCommon::Camera* camera = mGraphicsManager->GetCamera(); + MCommon::Camera* camera = m_graphicsManager->GetCamera(); const AZ::Matrix4x4 transposedProjMatrix = camera->GetViewProjMatrix().GetTranspose(); glLoadMatrixf((float*)&transposedProjMatrix); @@ -460,14 +450,14 @@ namespace RenderGL glLoadIdentity(); // disable the shaders - mGraphicsManager->SetShader(nullptr); + m_graphicsManager->SetShader(nullptr); // set up blending properties glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // render the triangle - glColor4f(color.r, color.g, color.b, color.a); + glColor4f(color.m_r, color.m_g, color.m_b, color.m_a); glBegin(GL_TRIANGLES); glVertex3f(v1.GetX(), v1.GetY(), v1.GetZ()); glVertex3f(v2.GetX(), v2.GetY(), v2.GetZ()); @@ -481,10 +471,10 @@ namespace RenderGL } - void GLRenderUtil::RenderTriangles(const MCore::Array& triangleVertices) + void GLRenderUtil::RenderTriangles(const AZStd::vector& triangleVertices) { // check if there are any triangles to render, if not return directly - if (triangleVertices.GetIsEmpty()) + if (triangleVertices.empty()) { return; } @@ -492,67 +482,67 @@ namespace RenderGL glDisable(GL_CULL_FACE); // get the number of vertices to render - const uint32 numVertices = triangleVertices.GetLength(); - MCORE_ASSERT(numVertices <= mNumMaxTriangleVertices); + const uint32 numVertices = aznumeric_caster(triangleVertices.size()); + MCORE_ASSERT(numVertices <= s_numMaxTriangleVertices); // lock the vertex buffer - TriangleVertex* vertices = (TriangleVertex*)mTriangleVertexBuffer->Lock(); + TriangleVertex* vertices = (TriangleVertex*)m_triangleVertexBuffer->Lock(); if (vertices == nullptr) { return; } // TODO: Not nice yet, get the color from the first vertex and use if for all triangles - MCore::RGBAColor color((uint32)triangleVertices[0].mColor); + MCore::RGBAColor color((uint32)triangleVertices[0].m_color); // fill in the vertex buffer for (uint32 i = 0; i < numVertices; ++i) { - vertices[i].mPosition = triangleVertices[i].mPosition; - vertices[i].mNormal = triangleVertices[i].mNormal; + vertices[i].m_position = triangleVertices[i].m_position; + vertices[i].m_normal = triangleVertices[i].m_normal; } // unlock and activate the vertex buffer and index buffer - mTriangleVertexBuffer->Unlock(); - mTriangleVertexBuffer->Activate(); - mTriangleIndexBuffer->Activate(); + m_triangleVertexBuffer->Unlock(); + m_triangleVertexBuffer->Activate(); + m_triangleIndexBuffer->Activate(); // setup shader - mMeshShader->Activate(); + m_meshShader->Activate(); - MCommon::Camera* camera = mGraphicsManager->GetCamera(); + MCommon::Camera* camera = m_graphicsManager->GetCamera(); - mMeshShader->SetUniform("worldViewProjectionMatrix", camera->GetViewProjMatrix()); - mMeshShader->SetUniform("cameraPosition", camera->GetPosition()); - mMeshShader->SetUniform("lightDirection", MCore::GetUp(camera->GetViewMatrix().GetTranspose()).GetNormalized()); - mMeshShader->SetUniform("diffuseColor", color); - mMeshShader->SetUniform("specularColor", AZ::Vector3::CreateOne()); - mMeshShader->SetUniform("specularPower", 30.0f); + m_meshShader->SetUniform("worldViewProjectionMatrix", camera->GetViewProjMatrix()); + m_meshShader->SetUniform("cameraPosition", camera->GetPosition()); + m_meshShader->SetUniform("lightDirection", MCore::GetUp(camera->GetViewMatrix().GetTranspose()).GetNormalized()); + m_meshShader->SetUniform("diffuseColor", color); + m_meshShader->SetUniform("specularColor", AZ::Vector3::CreateOne()); + m_meshShader->SetUniform("specularPower", 30.0f); // setup shader attributes and draw the mesh const uint32 stride = sizeof(TriangleVertex); - mMeshShader->SetAttribute("inPosition", 4, GL_FLOAT, stride, 0); - mMeshShader->SetAttribute("inNormal", 4, GL_FLOAT, stride, sizeof(AZ::Vector3)); - mMeshShader->SetUniform("worldMatrix", AZ::Matrix4x4::CreateIdentity()); + m_meshShader->SetAttribute("inPosition", 4, GL_FLOAT, stride, 0); + m_meshShader->SetAttribute("inNormal", 4, GL_FLOAT, stride, sizeof(AZ::Vector3)); + m_meshShader->SetUniform("worldMatrix", AZ::Matrix4x4::CreateIdentity()); glDrawElements(GL_TRIANGLES, numVertices, GL_UNSIGNED_INT, (GLvoid*)nullptr); - mMeshShader->Deactivate(); + m_meshShader->Deactivate(); } void GLRenderUtil::RenderTextPeriod(uint32 x, uint32 y, const char* text, float lifeTime, const MCore::RGBAColor& color, float fontSize, bool centered) { TextEntry* textEntry = new TextEntry(); - textEntry->mX = x; - textEntry->mY = y; - textEntry->mText = text; - textEntry->mLifeTime = lifeTime; - textEntry->mColor = color; - textEntry->mFontSize = fontSize; - textEntry->mCentered = centered; - - mTextEntries.Add(textEntry); + textEntry->m_x = x; + textEntry->m_y = y; + textEntry->m_text = text; + textEntry->m_lifeTime = lifeTime; + textEntry->m_color = color; + textEntry->m_fontSize = fontSize; + textEntry->m_centered = centered; + + m_textEntries.emplace_back(textEntry); } @@ -560,16 +550,16 @@ namespace RenderGL { static AZ::Debug::Timer timer; const float timeDelta = static_cast(timer.StampAndGetDeltaTimeInSeconds()); - for (uint32 i = 0; i < mTextEntries.GetLength(); ) + for (uint32 i = 0; i < m_textEntries.size(); ) { - TextEntry* textEntry = mTextEntries[i]; - RenderText(static_cast(textEntry->mX), static_cast(textEntry->mY), textEntry->mText.c_str(), textEntry->mColor, textEntry->mFontSize, textEntry->mCentered); + TextEntry* textEntry = m_textEntries[i]; + RenderText(static_cast(textEntry->m_x), static_cast(textEntry->m_y), textEntry->m_text.c_str(), textEntry->m_color, textEntry->m_fontSize, textEntry->m_centered); - textEntry->mLifeTime -= timeDelta; - if (textEntry->mLifeTime < 0.0f) + textEntry->m_lifeTime -= timeDelta; + if (textEntry->m_lifeTime < 0.0f) { delete textEntry; - mTextEntries.Remove(i); + m_textEntries.erase(AZStd::next(begin(m_textEntries), i)); } else { diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h index c8888bc527..aa64581449 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLRenderUtil.h @@ -54,7 +54,7 @@ namespace RenderGL // triangle rendering void RenderTriangle(const AZ::Vector3& v1, const AZ::Vector3& v2, const AZ::Vector3& v3, const MCore::RGBAColor& color) override; - void RenderTriangles(const MCore::Array& triangleVertices) override; + void RenderTriangles(const AZStd::vector& triangleVertices) override; // text rendering (do not use until really needed, needs to do runtime allocations) void RenderTextPeriod(uint32 x, uint32 y, const char* text, float lifeTime, const MCore::RGBAColor& color = MCore::RGBAColor(1.0f, 1.0f, 1.0f), float fontSize = 11.0f, bool centered = false); @@ -73,45 +73,45 @@ namespace RenderGL void CleanUp(); #define MAX_LINE_VERTEXBUFFERS 2 - GraphicsManager* mGraphicsManager; - VertexBuffer* mLineVertexBuffers[MAX_LINE_VERTEXBUFFERS]; - uint16 mCurrentLineVB; - GLSLShader* mLineShader; - GLSLShader* mMeshShader; - VertexBuffer* mMeshVertexBuffer; - IndexBuffer* mMeshIndexBuffer; + GraphicsManager* m_graphicsManager; + VertexBuffer* m_lineVertexBuffers[MAX_LINE_VERTEXBUFFERS]{}; + uint16 m_currentLineVb; + GLSLShader* m_lineShader; + GLSLShader* m_meshShader; + VertexBuffer* m_meshVertexBuffer; + IndexBuffer* m_meshIndexBuffer; // vertex and index buffers for rendering triangles - VertexBuffer* mTriangleVertexBuffer; - IndexBuffer* mTriangleIndexBuffer; + VertexBuffer* m_triangleVertexBuffer; + IndexBuffer* m_triangleIndexBuffer; // texture rendering struct TextureEntry { MCORE_MEMORYOBJECTCATEGORY(GLRenderUtil::TextureEntry, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_RENDERING); - Texture* texture; - AZ::Vector2 pos; + Texture* m_texture; + AZ::Vector2 m_pos; TextureEntry() - : pos(0.0f, 0.0f) - , texture(nullptr) {} + : m_pos(0.0f, 0.0f) + , m_texture(nullptr) {} }; struct TextEntry { MCORE_MEMORYOBJECTCATEGORY(GLRenderUtil::TextEntry, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_RENDERING); - uint32 mX; - uint32 mY; - AZStd::string mText; - float mLifeTime; - MCore::RGBAColor mColor; - float mFontSize; - bool mCentered; + uint32 m_x; + uint32 m_y; + AZStd::string m_text; + float m_lifeTime; + MCore::RGBAColor m_color; + float m_fontSize; + bool m_centered; }; - MCore::Array mTextEntries; - TextureEntry* mTextures; - uint32 mNumTextures; - uint32 mMaxNumTextures; + AZStd::vector m_textEntries; + TextureEntry* m_textures; + uint32 m_numTextures; + uint32 m_maxNumTextures; }; } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp index 02aad3aa04..72a28a5d11 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include "GLSLShader.h" @@ -19,44 +20,39 @@ namespace RenderGL // constructor GLSLShader::ShaderParameter::ShaderParameter(const char* name, GLint loc, bool isAttrib) { - mName = name; - mType = 0; - mSize = 0; - mLocation = loc; - mIsAttribute = isAttrib; - mTextureUnit = MCORE_INVALIDINDEX32; + m_name = name; + m_type = 0; + m_size = 0; + m_location = loc; + m_isAttribute = isAttrib; + m_textureUnit = MCORE_INVALIDINDEX32; } // constructor GLSLShader::GLSLShader() { - mProgram = 0; - mVertexShader = 0; - mPixelShader = 0; - mTextureUnit = 0; - - mUniforms.SetMemoryCategory(MEMCATEGORY_RENDERING); - mAttributes.SetMemoryCategory(MEMCATEGORY_RENDERING); - mActivatedAttribs.SetMemoryCategory(MEMCATEGORY_RENDERING); - mActivatedTextures.SetMemoryCategory(MEMCATEGORY_RENDERING); + m_program = 0; + m_vertexShader = 0; + m_pixelShader = 0; + m_textureUnit = 0; // pre-alloc data for uniforms and attributes - mUniforms.Reserve(10); - mAttributes.Reserve(10); - mActivatedAttribs.Reserve(10); - mActivatedTextures.Reserve(10); + m_uniforms.reserve(10); + m_attributes.reserve(10); + m_activatedAttribs.reserve(10); + m_activatedTextures.reserve(10); } // destructor GLSLShader::~GLSLShader() { - glDetachShader(mProgram, mVertexShader); - glDetachShader(mProgram, mPixelShader); - glDeleteShader(mVertexShader); - glDeleteShader(mPixelShader); - glDeleteShader(mProgram); + glDetachShader(m_program, m_vertexShader); + glDetachShader(m_program, m_pixelShader); + glDeleteShader(m_vertexShader); + glDeleteShader(m_pixelShader); + glDeleteShader(m_program); } @@ -70,36 +66,32 @@ namespace RenderGL // Deactivate void GLSLShader::Deactivate() { - const uint32 numAttribs = mActivatedAttribs.GetLength(); - for (uint32 i = 0; i < numAttribs; ++i) + for (const size_t index : m_activatedAttribs) { - const uint32 index = mActivatedAttribs[i]; - glDisableVertexAttribArray(mAttributes[index].mLocation); + glDisableVertexAttribArray(m_attributes[index].m_location); } - const uint32 numTextures = mActivatedTextures.GetLength(); - for (uint32 i = 0; i < numTextures; ++i) + for (const size_t index : m_activatedTextures) { - const uint32 index = mActivatedTextures[i]; - assert(mUniforms[index].mType == GL_SAMPLER_2D); - glActiveTexture(GL_TEXTURE0 + mUniforms[index].mTextureUnit); + assert(m_uniforms[index].m_type == GL_SAMPLER_2D); + glActiveTexture(GL_TEXTURE0 + m_uniforms[index].m_textureUnit); glBindTexture(GL_TEXTURE_2D, 0); } - mActivatedAttribs.Clear(false); - mActivatedTextures.Clear(false); + m_activatedAttribs.clear(); + m_activatedTextures.clear(); } bool GLSLShader::Validate() { int success = 0; - glValidateProgram(mProgram); - glGetProgramiv(mProgram, GL_VALIDATE_STATUS, &success); + glValidateProgram(m_program); + glGetProgramiv(m_program, GL_VALIDATE_STATUS, &success); if (success == 0) { - MCore::LogInfo("Failed to validate program '%s'", mFileName.c_str()); - InfoLog(mProgram, &QOpenGLExtraFunctions::glGetProgramInfoLog); + MCore::LogInfo("Failed to validate program '%s'", m_fileName.c_str()); + InfoLog(m_program, &QOpenGLExtraFunctions::glGetProgramInfoLog); return false; } return true; @@ -122,17 +114,16 @@ namespace RenderGL return false; } - mFileName = filename; + m_fileName = filename; AZStd::string text; text.reserve(4096); text = "#version 120\n"; // build define string - const uint32 numDefines = mDefines.GetLength(); - for (uint32 n = 0; n < numDefines; ++n) + for (const AZStd::string& define : m_defines) { - text += AZStd::string::format("#define %s\n", mDefines[n].c_str()); + text += AZStd::string::format("#define %s\n", define.c_str()); } // read file into a big string @@ -180,27 +171,23 @@ namespace RenderGL AZStd::invoke(func, static_cast(this), object, logLen, &logWritten, text.data()); // if there are any defines, print that out too - if (mDefines.GetLength() > 0) + if (!m_defines.empty()) { AZStd::string dStr; - const uint32 numDefines = mDefines.GetLength(); - for (uint32 n = 0; n < numDefines; ++n) + for (const AZStd::string& define : m_defines) { - if (n < numDefines - 1) - { - dStr += mDefines[n] + " "; - } - else + if (!dStr.empty()) { - dStr += mDefines[n]; + dStr.append(" "); } + dStr.append(define); } - MCore::LogDetailedInfo("[GLSL] Compiling shader '%s', with defines %s", mFileName.c_str(), dStr.c_str()); + MCore::LogDetailedInfo("[GLSL] Compiling shader '%s', with defines %s", m_fileName.c_str(), dStr.c_str()); } else { - MCore::LogDetailedInfo("[GLSL] Compiling shader '%s'", mFileName.c_str()); + MCore::LogDetailedInfo("[GLSL] Compiling shader '%s'", m_fileName.c_str()); } MCore::LogDetailedInfo(text.c_str()); @@ -209,7 +196,7 @@ namespace RenderGL // Init - bool GLSLShader::Init(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, MCore::Array& defines) + bool GLSLShader::Init(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, AZStd::vector& defines) { initializeOpenGLFunctions(); /*const char* args[] = { "unroll all", @@ -217,44 +204,44 @@ namespace RenderGL "O3", nullptr };*/ - mDefines = defines; + m_defines = defines; glUseProgram(0); // compile shaders - if (!vertexFileName.empty() && CompileShader(GL_VERTEX_SHADER, &mVertexShader, vertexFileName) == false) + if (!vertexFileName.empty() && CompileShader(GL_VERTEX_SHADER, &m_vertexShader, vertexFileName) == false) { return false; } - if (!pixelFileName.empty() && CompileShader(GL_FRAGMENT_SHADER, &mPixelShader, pixelFileName) == false) + if (!pixelFileName.empty() && CompileShader(GL_FRAGMENT_SHADER, &m_pixelShader, pixelFileName) == false) { return false; } // create program - mProgram = glCreateProgram(); + m_program = glCreateProgram(); if (!vertexFileName.empty()) { - glAttachShader(mProgram, mVertexShader); + glAttachShader(m_program, m_vertexShader); } if (!pixelFileName.empty()) { - glAttachShader(mProgram, mPixelShader); + glAttachShader(m_program, m_pixelShader); } // link - glLinkProgram(mProgram); + glLinkProgram(m_program); // check for linking errors GLint success = 0; - glGetProgramiv(mProgram, GL_LINK_STATUS, &success); + glGetProgramiv(m_program, GL_LINK_STATUS, &success); if (!success) { MCore::LogInfo("[OpenGL] Failed to link shaders '%.*s' and '%.*s' ", AZ_STRING_ARG(vertexFileName.Native()), AZ_STRING_ARG(pixelFileName.Native())); - InfoLog(mProgram, &QOpenGLExtraFunctions::glGetProgramInfoLog); + InfoLog(m_program, &QOpenGLExtraFunctions::glGetProgramInfoLog); return false; } @@ -265,119 +252,111 @@ namespace RenderGL // FindAttribute GLSLShader::ShaderParameter* GLSLShader::FindAttribute(const char* name) { - const uint32 index = FindAttributeIndex(name); - if (index == MCORE_INVALIDINDEX32) + const size_t index = FindAttributeIndex(name); + if (index == InvalidIndex) { return nullptr; } - return &mAttributes[index]; + return &m_attributes[index]; } // FindAttributeIndex - uint32 GLSLShader::FindAttributeIndex(const char* name) + size_t GLSLShader::FindAttributeIndex(const char* name) { - const uint32 numAttribs = mAttributes.GetLength(); - for (uint32 i = 0; i < numAttribs; ++i) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [name](const auto& attribute) { - if (AzFramework::StringFunc::Equal(mAttributes[i].mName.c_str(), name, false /* no case */)) - { + return AzFramework::StringFunc::Equal(attribute.m_name.c_str(), name, false /* no case */) && // if we don't have a valid parameter location, an attribute by this name doesn't exist // we just cached the fact that it doesn't exist, instead of failing glGetAttribLocation every time - if (mAttributes[i].mLocation >= 0) - { - return i; - } - - return MCORE_INVALIDINDEX32; - } + attribute.m_location >= 0; + }); + if (foundAttribute != end(m_attributes)) + { + return AZStd::distance(begin(m_attributes), foundAttribute); } // the parameter wasn't cached, try to retrieve it - const GLint loc = glGetAttribLocation(mProgram, name); - mAttributes.Add(ShaderParameter(name, loc, true)); + const GLint loc = glGetAttribLocation(m_program, name); + m_attributes.emplace_back(name, loc, true); if (loc < 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - return mAttributes.GetLength() - 1; + return m_attributes.size() - 1; } // FindAttributeLocation - uint32 GLSLShader::FindAttributeLocation(const char* name) + size_t GLSLShader::FindAttributeLocation(const char* name) { ShaderParameter* p = FindAttribute(name); if (p == nullptr) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - return p->mLocation; + return p->m_location; } // FindUniform GLSLShader::ShaderParameter* GLSLShader::FindUniform(const char* name) { - const uint32 index = FindUniformIndex(name); - if (index == MCORE_INVALIDINDEX32) + const size_t index = FindUniformIndex(name); + if (index == InvalidIndex) { return nullptr; } - return &mUniforms[index]; + return &m_uniforms[index]; } // FindUniformIndex - uint32 GLSLShader::FindUniformIndex(const char* name) + size_t GLSLShader::FindUniformIndex(const char* name) { - const uint32 numUniforms = mUniforms.GetLength(); - for (uint32 i = 0; i < numUniforms; ++i) + const auto foundUniform = AZStd::find_if(begin(m_uniforms), end(m_uniforms), [name](const auto& uniform) { - if (AzFramework::StringFunc::Equal(mUniforms[i].mName.c_str(), name, false /* no case */)) - { - if (mUniforms[i].mLocation >= 0) - { - return i; - } - - return MCORE_INVALIDINDEX32; - } + return AzFramework::StringFunc::Equal(uniform.m_name.c_str(), name, false /* no case */) && + uniform.m_location >= 0; + }); + if (foundUniform != end(m_uniforms)) + { + return AZStd::distance(begin(m_uniforms), foundUniform); } // the parameter wasn't cached, try to retrieve it - const GLint loc = glGetUniformLocation(mProgram, name); - mUniforms.Add(ShaderParameter(name, loc, false)); + const GLint loc = glGetUniformLocation(m_program, name); + m_uniforms.emplace_back(name, loc, false); if (loc < 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - return mUniforms.GetLength() - 1; + return m_uniforms.size() - 1; } // SetAttribute void GLSLShader::SetAttribute(const char* name, uint32 dim, uint32 type, uint32 stride, size_t offset) { - const uint32 index = FindAttributeIndex(name); - if (index == MCORE_INVALIDINDEX32) + const size_t index = FindAttributeIndex(name); + if (index == InvalidIndex) { return; } - ShaderParameter* param = &mAttributes[index]; + ShaderParameter* param = &m_attributes[index]; - glEnableVertexAttribArray(param->mLocation); - glVertexAttribPointer(param->mLocation, dim, type, GL_FALSE, stride, (GLvoid*)offset); + glEnableVertexAttribArray(param->m_location); + glVertexAttribPointer(param->m_location, dim, type, GL_FALSE, stride, (GLvoid*)offset); - mActivatedAttribs.Add(index); + m_activatedAttribs.emplace_back(index); } @@ -390,7 +369,7 @@ namespace RenderGL return; } - glUniform1f(param->mLocation, value); + glUniform1f(param->m_location, value); } @@ -403,7 +382,7 @@ namespace RenderGL return; } - glUniform1f(param->mLocation, (float)value); + glUniform1f(param->m_location, (float)value); } @@ -416,7 +395,7 @@ namespace RenderGL return; } - glUniform4fv(param->mLocation, 1, (float*)&color); + glUniform4fv(param->m_location, 1, (float*)&color); } @@ -429,7 +408,7 @@ namespace RenderGL return; } - glUniform2fv(param->mLocation, 1, (float*)&vector); + glUniform2fv(param->m_location, 1, (float*)&vector); } @@ -442,7 +421,7 @@ namespace RenderGL return; } - glUniform3fv(param->mLocation, 1, (float*)&vector); + glUniform3fv(param->m_location, 1, (float*)&vector); } @@ -455,7 +434,7 @@ namespace RenderGL return; } - glUniform4fv(param->mLocation, 1, (float*)&vector); + glUniform4fv(param->m_location, 1, (float*)&vector); } @@ -475,7 +454,7 @@ namespace RenderGL return; } - glUniformMatrix4fv(param->mLocation, 1, !transpose, (float*)&matrix); + glUniformMatrix4fv(param->m_location, 1, !transpose, (float*)&matrix); } @@ -488,7 +467,7 @@ namespace RenderGL return; } - glUniformMatrix4fv(param->mLocation, count, GL_FALSE, (float*)matrices); + glUniformMatrix4fv(param->m_location, count, GL_FALSE, (float*)matrices); } @@ -501,26 +480,26 @@ namespace RenderGL } // update the value - glUniform1fv(param->mLocation, numFloats, values); + glUniform1fv(param->m_location, numFloats, values); } // SetUniform void GLSLShader::SetUniform(const char* name, Texture* texture) { - const uint32 index = FindUniformIndex(name); - if (index == MCORE_INVALIDINDEX32) + const size_t index = FindUniformIndex(name); + if (index == InvalidIndex) { return; } - mUniforms[index].mType = GL_SAMPLER_2D; // why is this being set here? + m_uniforms[index].m_type = GL_SAMPLER_2D; // why is this being set here? // if the texture doesn't have a sampler unit assigned, give it one - if (mUniforms[index].mTextureUnit == MCORE_INVALIDINDEX32) + if (m_uniforms[index].m_textureUnit == MCORE_INVALIDINDEX32) { - mUniforms[index].mTextureUnit = mTextureUnit; - mTextureUnit++; + m_uniforms[index].m_textureUnit = m_textureUnit; + m_textureUnit++; } if (texture == nullptr) @@ -528,30 +507,30 @@ namespace RenderGL texture = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); } - glActiveTexture(GL_TEXTURE0 + mUniforms[index].mTextureUnit); + glActiveTexture(GL_TEXTURE0 + m_uniforms[index].m_textureUnit); glBindTexture(GL_TEXTURE_2D, texture->GetID()); - glUniform1i(mUniforms[index].mLocation, mUniforms[index].mTextureUnit); + glUniform1i(m_uniforms[index].m_location, m_uniforms[index].m_textureUnit); - mActivatedTextures.Add(index); + m_activatedTextures.emplace_back(index); } // link a texture to a given uniform void GLSLShader::SetUniformTextureID(const char* name, uint32 textureID) { - const uint32 index = FindUniformIndex(name); - if (index == MCORE_INVALIDINDEX32) + const size_t index = FindUniformIndex(name); + if (index == InvalidIndex) { return; } - mUniforms[index].mType = GL_SAMPLER_2D; // why is this being set here? + m_uniforms[index].m_type = GL_SAMPLER_2D; // why is this being set here? // if the texture doesn't have a sampler unit assigned, give it one - if (mUniforms[index].mTextureUnit == MCORE_INVALIDINDEX32) + if (m_uniforms[index].m_textureUnit == MCORE_INVALIDINDEX32) { - mUniforms[index].mTextureUnit = mTextureUnit; - mTextureUnit++; + m_uniforms[index].m_textureUnit = m_textureUnit; + m_textureUnit++; } if (textureID == MCORE_INVALIDINDEX32) @@ -559,29 +538,21 @@ namespace RenderGL textureID = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture()->GetID(); } - glActiveTexture(GL_TEXTURE0 + mUniforms[index].mTextureUnit); + glActiveTexture(GL_TEXTURE0 + m_uniforms[index].m_textureUnit); glBindTexture(GL_TEXTURE_2D, textureID); - glUniform1i(mUniforms[index].mLocation, mUniforms[index].mTextureUnit); + glUniform1i(m_uniforms[index].m_location, m_uniforms[index].m_textureUnit); - mActivatedTextures.Add(index); + m_activatedTextures.emplace_back(index); } // check if the given attribute string is defined in the shader - bool GLSLShader::CheckIfIsDefined(const char* attributeName) + bool GLSLShader::CheckIfIsDefined(const char* attributeName) const { // get the number of defines and iterate through them - const uint32 numDefines = mDefines.GetLength(); - for (uint32 i = 0; i < numDefines; ++i) + return AZStd::any_of(begin(m_defines), end(m_defines), [attributeName](const AZStd::string& define) { - // compare the given attribute with the current define and return if they are equal - if (AzFramework::StringFunc::Equal(mDefines[i].c_str(), attributeName, false /* no case */)) - { - return true; - } - } - - // we haven't found the attribute, return failure - return false; + return AzFramework::StringFunc::Equal(define.c_str(), attributeName, false /* no case */); + }); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h index 6a6854e29f..5975470f86 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GLSLShader.h @@ -14,7 +14,7 @@ #include "Shader.h" // include OpenGL -#include +#include #include #include @@ -36,13 +36,13 @@ namespace RenderGL void Deactivate() override; bool Validate() override; - uint32 FindAttributeLocation(const char* name); + size_t FindAttributeLocation(const char* name); uint32 GetType() const override; - MCORE_INLINE unsigned int GetProgram() const { return mProgram; } - bool CheckIfIsDefined(const char* attributeName); + MCORE_INLINE unsigned int GetProgram() const { return m_program; } + bool CheckIfIsDefined(const char* attributeName) const; - bool Init(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, MCore::Array& defines); + bool Init(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, AZStd::vector& defines); void SetAttribute(const char* name, uint32 dim, uint32 type, uint32 stride, size_t offset) override; void SetUniform(const char* name, float value) override; @@ -65,16 +65,16 @@ namespace RenderGL { ShaderParameter(const char* name, GLint loc, bool isAttrib); - AZStd::string mName; - GLint mLocation; - GLenum mType; - uint32 mSize; - uint32 mTextureUnit; - bool mIsAttribute; + AZStd::string m_name; + GLint m_location; + GLenum m_type; + uint32 m_size; + uint32 m_textureUnit; + bool m_isAttribute; }; - uint32 FindAttributeIndex(const char* name); - uint32 FindUniformIndex(const char* name); + size_t FindAttributeIndex(const char* name); + size_t FindUniformIndex(const char* name); ShaderParameter* FindAttribute(const char* name); ShaderParameter* FindUniform(const char* name); @@ -82,19 +82,19 @@ namespace RenderGL template void InfoLog(GLuint object, T func); - AZ::IO::Path mFileName; + AZ::IO::Path m_fileName; - MCore::Array mActivatedAttribs; - MCore::Array mActivatedTextures; - MCore::Array mUniforms; - MCore::Array mAttributes; - MCore::Array mDefines; + AZStd::vector m_activatedAttribs; + AZStd::vector m_activatedTextures; + AZStd::vector m_uniforms; + AZStd::vector m_attributes; + AZStd::vector m_defines; - unsigned int mVertexShader; - unsigned int mPixelShader; - unsigned int mProgram; + unsigned int m_vertexShader; + unsigned int m_pixelShader; + unsigned int m_program; - uint32 mTextureUnit; + uint32 m_textureUnit; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp index db03a694a8..1ccb8650aa 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.cpp @@ -24,7 +24,7 @@ namespace RenderGL { - size_t GraphicsManager::mNumRandomOffsets = 64; + size_t GraphicsManager::s_numRandomOffsets = 64; GraphicsManager* gGraphicsManager = nullptr; @@ -39,60 +39,60 @@ namespace RenderGL GraphicsManager::GraphicsManager() { gGraphicsManager = this; - mPostProcessing = false; + m_postProcessing = false; // render background - mUseGradientBackground = true; - mClearColor = MCore::RGBAColor(0.359f, 0.3984f, 0.4492f); - mGradientSourceColor = MCore::RGBAColor(0.4941f, 0.5686f, 0.6470f); - mGradientTargetColor = MCore::RGBAColor(0.0941f, 0.1019f, 0.1098f); - - mGBuffer = nullptr; - mHBloom = nullptr; - mVBloom = nullptr; - mHBlur = nullptr; - mVBlur = nullptr; - mDownSample = nullptr; - mDOF = nullptr; - mSSDO = nullptr; - mHSmartBlur = nullptr; - mVSmartBlur = nullptr; - mRenderTexture = nullptr; - mActiveShader = nullptr; - mCamera = nullptr; - mRenderUtil = nullptr; - - mMainLightIntensity = 1.00f; - mMainLightAngleA = -30.0f; - mMainLightAngleB = 18.0f; - mSpecularIntensity = 1.0f; - - mBloomEnabled = true; - mBloomRadius = 4.0f; - mBloomIntensity = 0.85f; - mBloomThreshold = 0.80f; - - mDOFEnabled = false; - mDOFBlurRadius = 2.0f; - mDOFFocalDistance = 500.0f; - mDOFNear = 0.001f; - mDOFFar = 1000.0f; - - mRimAngle = 60.0f; - mRimWidth = 0.65f; - mRimIntensity = 1.5f; - mRimColor = MCore::RGBAColor(1.0f, 0.70f, 0.109f); - - mRandomVectorTexture = nullptr; - mCreateMipMaps = true; - mSkipLoadingTextures = false; + m_useGradientBackground = true; + m_clearColor = MCore::RGBAColor(0.359f, 0.3984f, 0.4492f); + m_gradientSourceColor = MCore::RGBAColor(0.4941f, 0.5686f, 0.6470f); + m_gradientTargetColor = MCore::RGBAColor(0.0941f, 0.1019f, 0.1098f); + + m_gBuffer = nullptr; + m_hBloom = nullptr; + m_vBloom = nullptr; + m_hBlur = nullptr; + m_vBlur = nullptr; + m_downSample = nullptr; + m_dof = nullptr; + m_ssdo = nullptr; + m_hSmartBlur = nullptr; + m_vSmartBlur = nullptr; + m_renderTexture = nullptr; + m_activeShader = nullptr; + m_camera = nullptr; + m_renderUtil = nullptr; + + m_mainLightIntensity = 1.00f; + m_mainLightAngleA = -30.0f; + m_mainLightAngleB = 18.0f; + m_specularIntensity = 1.0f; + + m_bloomEnabled = true; + m_bloomRadius = 4.0f; + m_bloomIntensity = 0.85f; + m_bloomThreshold = 0.80f; + + m_dofEnabled = false; + m_dofBlurRadius = 2.0f; + m_dofFocalDistance = 500.0f; + m_dofNear = 0.001f; + m_dofFar = 1000.0f; + + m_rimAngle = 60.0f; + m_rimWidth = 0.65f; + m_rimIntensity = 1.5f; + m_rimColor = MCore::RGBAColor(1.0f, 0.70f, 0.109f); + + m_randomVectorTexture = nullptr; + m_createMipMaps = true; + m_skipLoadingTextures = false; // init random offsets - mRandomOffsets.resize(mNumRandomOffsets); - AZStd::vector samples = MCore::Random::RandomDirVectorsHalton(AZ::Vector3(0.0f, 1.0f, 0.0f), MCore::Math::twoPi, mNumRandomOffsets); - for (size_t i = 0; i < mNumRandomOffsets; ++i) + m_randomOffsets.resize(s_numRandomOffsets); + AZStd::vector samples = MCore::Random::RandomDirVectorsHalton(AZ::Vector3(0.0f, 1.0f, 0.0f), MCore::Math::twoPi, s_numRandomOffsets); + for (size_t i = 0; i < s_numRandomOffsets; ++i) { - mRandomOffsets[i] = samples[i] * MCore::Random::RandF(0.1f, 1.0f); + m_randomOffsets[i] = samples[i] * MCore::Random::RandF(0.1f, 1.0f); } } @@ -101,38 +101,37 @@ namespace RenderGL GraphicsManager::~GraphicsManager() { // shutdown the texture cache - mTextureCache.Release(); + m_textureCache.Release(); // delete all shaders - mShaderCache.Release(); + m_shaderCache.Release(); // get rid of the OpenGL render utility - delete mRenderUtil; + delete m_renderUtil; // release random vector texture memory - delete mRandomVectorTexture; + delete m_randomVectorTexture; // clear the string memory - mShaderPath.clear(); + m_shaderPath.clear(); } // setup sunset color style rim lighting void GraphicsManager::SetupSunsetRim() { - mRimWidth = 0.65f; - mRimIntensity = 1.5f; - mRimColor = MCore::RGBAColor(1.0f, 0.70f, 0.109f); - //mRimColor = MCore::RGBAColor(1.0f, 0.77f, 0.30f); + m_rimWidth = 0.65f; + m_rimIntensity = 1.5f; + m_rimColor = MCore::RGBAColor(1.0f, 0.70f, 0.109f); } // setup blue color style rim lighting void GraphicsManager::SetupBlueRim() { - mRimWidth = 0.65f; - mRimIntensity = 1.5f; - mRimColor = MCore::RGBAColor(81.0f / 255.0f, 160.0f / 255.0f, 1.0f); + m_rimWidth = 0.65f; + m_rimIntensity = 1.5f; + m_rimColor = MCore::RGBAColor(81.0f / 255.0f, 160.0f / 255.0f, 1.0f); } @@ -152,12 +151,12 @@ namespace RenderGL glBegin(GL_QUADS); // bottom - glColor3f(bottomColor.r, bottomColor.g, bottomColor.b); + glColor3f(bottomColor.m_r, bottomColor.m_g, bottomColor.m_b); glVertex2f(-1.0, -1.0); glVertex2f(1.0, -1.0); // top - glColor3f(topColor.r, topColor.g, topColor.b); + glColor3f(topColor.m_r, topColor.m_g, topColor.m_b); glVertex2f(1.0, 1.0); glVertex2f(-1.0, 1.0); @@ -176,13 +175,13 @@ namespace RenderGL //glPushAttrib( GL_ALL_ATTRIB_BITS ); // Activate render targets - glClearColor(mClearColor.r, mClearColor.g, mClearColor.b, 1.0f); + glClearColor(m_clearColor.m_r, m_clearColor.m_g, m_clearColor.m_b, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // render the gradient background - if (mUseGradientBackground) + if (m_useGradientBackground) { - RenderGradientBackground(mGradientSourceColor, mGradientTargetColor); + RenderGradientBackground(m_gradientSourceColor, m_gradientTargetColor); } return true; @@ -192,9 +191,9 @@ namespace RenderGL // end a frame (perform the swap) void GraphicsManager::EndRender() { - mRenderUtil->RenderTextPeriods(); - mRenderUtil->RenderTextures(); - ((MCommon::RenderUtil*)mRenderUtil)->Render2DLines(); + m_renderUtil->RenderTextPeriods(); + m_renderUtil->RenderTextures(); + ((MCommon::RenderUtil*)m_renderUtil)->Render2DLines(); } @@ -207,7 +206,7 @@ namespace RenderGL SetShaderPath(shaderPath); // texture cache - if (mTextureCache.Init() == false) + if (m_textureCache.Init() == false) { return false; } @@ -218,7 +217,7 @@ namespace RenderGL glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); - glClearColor(mClearColor.r, mClearColor.g, mClearColor.b, 1.0f); + glClearColor(m_clearColor.m_r, m_clearColor.m_g, m_clearColor.m_b, 1.0f); glHint(GL_POINT_SMOOTH_HINT, GL_NICEST); glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); @@ -228,15 +227,15 @@ namespace RenderGL glDisable(GL_BLEND); // initialize utility rendering - mRenderUtil = new GLRenderUtil(this); - mRenderUtil->Init(); + m_renderUtil = new GLRenderUtil(this); + m_renderUtil->Init(); // post processing - if (mPostProcessing) + if (m_postProcessing) { if (InitPostProcessing() == false) { - mPostProcessing = false; + m_postProcessing = false; } } @@ -275,86 +274,52 @@ namespace RenderGL ResizeTextures(screenWidth, screenHeight); // load horizontal bloom - mHBloom = LoadPostProcessShader("HBloom.glsl"); - if (mHBloom == nullptr) + m_hBloom = LoadPostProcessShader("HBloom.glsl"); + if (m_hBloom == nullptr) { MCore::LogWarning("[OpenGL] Failed to load HBloom shader, disabling post processing."); return false; } // load vertical bloom - mVBloom = LoadPostProcessShader("VBloom.glsl"); - if (mVBloom == nullptr) + m_vBloom = LoadPostProcessShader("VBloom.glsl"); + if (m_vBloom == nullptr) { MCore::LogWarning("[OpenGL] Failed to load VBloom shader, disabling post processing."); return false; } // load vertical bloom - mDownSample = LoadPostProcessShader("DownSample.glsl"); - if (mDownSample == nullptr) + m_downSample = LoadPostProcessShader("DownSample.glsl"); + if (m_downSample == nullptr) { MCore::LogWarning("[OpenGL] Failed to load DownSample shader, disabling post processing."); return false; } // load horizontal blur - mHBlur = LoadPostProcessShader("HBlur.glsl"); - if (mHBlur == nullptr) + m_hBlur = LoadPostProcessShader("HBlur.glsl"); + if (m_hBlur == nullptr) { MCore::LogWarning("[OpenGL] Failed to load HBlur shader, disabling post processing."); return false; } // load vertical blur - mVBlur = LoadPostProcessShader("VBlur.glsl"); - if (mVBlur == nullptr) + m_vBlur = LoadPostProcessShader("VBlur.glsl"); + if (m_vBlur == nullptr) { MCore::LogWarning("[OpenGL] Failed to load VBlur shader, disabling post processing."); return false; } // load DOF shader - mDOF = LoadPostProcessShader("DepthOfField.glsl"); - if (mDOF == nullptr) + m_dof = LoadPostProcessShader("DepthOfField.glsl"); + if (m_dof == nullptr) { MCore::LogWarning("[OpenGL] Failed to load DOF shader, disabling post processing."); return false; } - /* - // load screen space directional occlusion shader - mSSDO = LoadPostProcessShader("SSDO.glsl"); - if (mSSDO == nullptr) - { - MCore::LogWarning("[OpenGL] Failed to load SSDO shader, disabling post processing."); - return false; - } - - // horizontal smartblur - mHSmartBlur = LoadPostProcessShader("HSmartBlur.glsl"); - if (mHSmartBlur == nullptr) - { - MCore::LogWarning("[OpenGL] Failed to load HSmartBlur shader, disabling post processing."); - return false; - } - - // vertical smartblur - mVSmartBlur = LoadPostProcessShader("VSmartBlur.glsl"); - if (mVSmartBlur == nullptr) - { - MCore::LogWarning("[OpenGL] Failed to load VSmartBlur shader, disabling post processing."); - return false; - } - */ - /* - // create the post processing shaders - mSSAO = LoadPostProcessShader("SSAO.glsl"); - if (mSSAO == nullptr) - { - MCore::LogWarning("[OpenGL] Failed to load SSAO shader, disabling post processing."); - return false; - } - */ return true; } @@ -371,17 +336,17 @@ namespace RenderGL // try to load a texture Texture* GraphicsManager::LoadTexture(AZ::IO::PathView filename) { - return LoadTexture(filename, mCreateMipMaps); + return LoadTexture(filename, m_createMipMaps); } // LoadPostProcessShader PostProcessShader* GraphicsManager::LoadPostProcessShader(AZ::IO::PathView cFileName) { - AZ::IO::PathView filename = mShaderPath / cFileName; + AZ::IO::PathView filename = m_shaderPath / cFileName; // check if the shader is already in the cache - Shader* s = mShaderCache.FindShader(filename.Native()); + Shader* s = m_shaderCache.FindShader(filename.Native()); if (s) { return (PostProcessShader*)s; @@ -395,7 +360,7 @@ namespace RenderGL return nullptr; } - mShaderCache.AddShader(filename.Native(), shader); + m_shaderCache.AddShader(filename.Native(), shader); return shader; } @@ -403,27 +368,26 @@ namespace RenderGL // LoadShader GLSLShader* GraphicsManager::LoadShader(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName) { - MCore::Array defines; + AZStd::vector defines; return LoadShader(vertexFileName, pixelFileName, defines); } // LoadShader - GLSLShader* GraphicsManager::LoadShader(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, MCore::Array& defines) + GLSLShader* GraphicsManager::LoadShader(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, AZStd::vector& defines) { - const AZ::IO::Path vertexPath {vertexFileName.empty() ? AZ::IO::Path{} : mShaderPath / vertexFileName}; - const AZ::IO::Path pixelPath {pixelFileName.empty() ? AZ::IO::Path{} : mShaderPath / pixelFileName}; + const AZ::IO::Path vertexPath {vertexFileName.empty() ? AZ::IO::Path{} : m_shaderPath / vertexFileName}; + const AZ::IO::Path pixelPath {pixelFileName.empty() ? AZ::IO::Path{} : m_shaderPath / pixelFileName}; // construct the lookup string for the shader cache AZStd::string cacheLookupStr = vertexPath.Native() + pixelPath.Native(); - const uint32 numDefines = defines.GetLength(); - for (uint32 n = 0; n < numDefines; n++) + for (const AZStd::string& define : defines) { - cacheLookupStr += AZStd::string::format("#%s", defines[n].c_str()); + cacheLookupStr += AZStd::string::format("#%s", define.c_str()); } // check if the shader is already in the cache - Shader* cShader = mShaderCache.FindShader(cacheLookupStr); + Shader* cShader = m_shaderCache.FindShader(cacheLookupStr); if (cShader) { return (GLSLShader*)cShader; @@ -437,7 +401,7 @@ namespace RenderGL return nullptr; } - mShaderCache.AddShader(cacheLookupStr, shader); + m_shaderCache.AddShader(cacheLookupStr, shader); return shader; } @@ -464,7 +428,7 @@ namespace RenderGL // SetShader void GraphicsManager::SetShader(Shader* shader) { - if (mActiveShader == shader) + if (m_activeShader == shader) { return; } @@ -472,7 +436,7 @@ namespace RenderGL if (shader == nullptr) { glUseProgram(0); - mActiveShader = nullptr; + m_activeShader = nullptr; return; } @@ -482,7 +446,7 @@ namespace RenderGL glUseProgram(g->GetProgram()); } - mActiveShader = shader; + m_activeShader = shader; } @@ -530,7 +494,7 @@ namespace RenderGL } // create Texture object - mRandomVectorTexture = new Texture(textureID, width, height); + m_randomVectorTexture = new Texture(textureID, width, height); glDisable(GL_TEXTURE_2D); return true; diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h index 674d428382..67ebbd9441 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/GraphicsManager.h @@ -49,91 +49,91 @@ namespace RenderGL bool BeginRender(); void EndRender(); - MCORE_INLINE MCommon::Camera* GetCamera() const { return mCamera; } - MCORE_INLINE GLRenderUtil* GetRenderUtil() { return mRenderUtil; } + MCORE_INLINE MCommon::Camera* GetCamera() const { return m_camera; } + MCORE_INLINE GLRenderUtil* GetRenderUtil() { return m_renderUtil; } const char* GetDeviceName(); const char* GetDeviceVendor(); - MCORE_INLINE RenderTexture* GetRenderTexture() { return mRenderTexture; } - MCORE_INLINE AZ::IO::PathView GetShaderPath() const { return mShaderPath; } - MCORE_INLINE TextureCache* GetTextureCache() { return &mTextureCache; } + MCORE_INLINE RenderTexture* GetRenderTexture() { return m_renderTexture; } + MCORE_INLINE AZ::IO::PathView GetShaderPath() const { return m_shaderPath; } + MCORE_INLINE TextureCache* GetTextureCache() { return &m_textureCache; } bool Init(AZ::IO::PathView shaderPath = "Shaders"); - bool GetIsPostProcessingEnabled() const { return mPostProcessing; } + bool GetIsPostProcessingEnabled() const { return m_postProcessing; } PostProcessShader* LoadPostProcessShader(AZ::IO::PathView filename); GLSLShader* LoadShader(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName); - GLSLShader* LoadShader(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, MCore::Array& defines); + GLSLShader* LoadShader(AZ::IO::PathView vertexFileName, AZ::IO::PathView pixelFileName, AZStd::vector& defines); - MCORE_INLINE void SetGBuffer(GBuffer* gBuffer) { mGBuffer = gBuffer; } - MCORE_INLINE GBuffer* GetGBuffer() { return mGBuffer; } + MCORE_INLINE void SetGBuffer(GBuffer* gBuffer) { m_gBuffer = gBuffer; } + MCORE_INLINE GBuffer* GetGBuffer() { return m_gBuffer; } Texture* LoadTexture(AZ::IO::PathView filename, bool createMipMaps); Texture* LoadTexture(AZ::IO::PathView filename); - void SetCreateMipMaps(bool createMipMaps) { mCreateMipMaps = createMipMaps; } - MCORE_INLINE bool GetCreateMipMaps() const { return mCreateMipMaps; } + void SetCreateMipMaps(bool createMipMaps) { m_createMipMaps = createMipMaps; } + MCORE_INLINE bool GetCreateMipMaps() const { return m_createMipMaps; } - void SetSkipLoadingTextures(bool skipTextures) { mSkipLoadingTextures = skipTextures; } - MCORE_INLINE bool GetSkipLoadingTextures() const { return mSkipLoadingTextures; } + void SetSkipLoadingTextures(bool skipTextures) { m_skipLoadingTextures = skipTextures; } + MCORE_INLINE bool GetSkipLoadingTextures() const { return m_skipLoadingTextures; } void Resize(uint32 width, uint32 height); - MCORE_INLINE void SetCamera(MCommon::Camera* camera) { mCamera = camera; } + MCORE_INLINE void SetCamera(MCommon::Camera* camera) { m_camera = camera; } // background rendering and colors - MCORE_INLINE void SetClearColor(const MCore::RGBAColor& color) { mClearColor = color; } - MCORE_INLINE void SetGradientSourceColor(const MCore::RGBAColor& color) { mGradientSourceColor = color; } - MCORE_INLINE void SetGradientTargetColor(const MCore::RGBAColor& color) { mGradientTargetColor = color; } - MCORE_INLINE void SetUseGradientBackground(bool enabled) { mUseGradientBackground = enabled; } - MCORE_INLINE MCore::RGBAColor GetClearColor() const { return mClearColor; } - MCORE_INLINE MCore::RGBAColor GetGradientSourceColor() const { return mGradientSourceColor; } - MCORE_INLINE MCore::RGBAColor GetGradientTargetColor() const { return mGradientTargetColor; } + MCORE_INLINE void SetClearColor(const MCore::RGBAColor& color) { m_clearColor = color; } + MCORE_INLINE void SetGradientSourceColor(const MCore::RGBAColor& color) { m_gradientSourceColor = color; } + MCORE_INLINE void SetGradientTargetColor(const MCore::RGBAColor& color) { m_gradientTargetColor = color; } + MCORE_INLINE void SetUseGradientBackground(bool enabled) { m_useGradientBackground = enabled; } + MCORE_INLINE MCore::RGBAColor GetClearColor() const { return m_clearColor; } + MCORE_INLINE MCore::RGBAColor GetGradientSourceColor() const { return m_gradientSourceColor; } + MCORE_INLINE MCore::RGBAColor GetGradientTargetColor() const { return m_gradientTargetColor; } void RenderGradientBackground(const MCore::RGBAColor& topColor, const MCore::RGBAColor& bottomColor); void SetShader(Shader* shader); - MCORE_INLINE void SetRenderTexture(RenderTexture* texture) { mRenderTexture = texture; } - MCORE_INLINE void SetShaderPath(AZ::IO::PathView shaderPath) { mShaderPath = shaderPath; } - - MCORE_INLINE void SetBloomEnabled(bool enabled) { mBloomEnabled = enabled; } - MCORE_INLINE void SetBloomThreshold(float threshold) { mBloomThreshold = threshold; } - MCORE_INLINE void SetBloomIntensity(float intensity) { mBloomIntensity = intensity; } - MCORE_INLINE void SetBloomRadius(float radius) { mBloomRadius = radius; } - MCORE_INLINE void SetDOFEnabled(bool enabled) { mDOFEnabled = enabled; } - MCORE_INLINE void SetDOFFocalDistance(float dist) { mDOFFocalDistance = dist; } - MCORE_INLINE void SetDOFNear(float dist) { mDOFNear = dist; } - MCORE_INLINE void SetDOFFar(float dist) { mDOFFar = dist; } - MCORE_INLINE void SetDOFBlurRadius(float radius) { mDOFBlurRadius = radius; } - - MCORE_INLINE void SetRimColor(const MCore::RGBAColor& color) { mRimColor = color; } - MCORE_INLINE void SetRimIntensity(float intensity) { mRimIntensity = intensity; } - MCORE_INLINE void SetRimWidth(float width) { mRimWidth = width; } - MCORE_INLINE void SetRimAngle(float angleInDegrees) { mRimAngle = angleInDegrees; } - - MCORE_INLINE void SetMainLightIntensity(float intensity) { mMainLightIntensity = intensity; } - MCORE_INLINE void SetMainLightAngleA(float angleInDegrees) { mMainLightAngleA = angleInDegrees; } - MCORE_INLINE void SetMainLightAngleB(float angleInDegrees) { mMainLightAngleB = angleInDegrees; } - MCORE_INLINE void SetSpecularIntensity(float intensity) { mSpecularIntensity = intensity; } - - MCORE_INLINE bool GetBloomEnabled() const { return mBloomEnabled; } - MCORE_INLINE float GetBloomThreshold() const { return mBloomThreshold; } - MCORE_INLINE float GetBloomIntensity() const { return mBloomIntensity; } - MCORE_INLINE float GetBloomRadius() const { return mBloomRadius; } - MCORE_INLINE bool GetDOFEnabled() const { return mDOFEnabled; } - MCORE_INLINE float GetDOFBlurRadius() const { return mDOFBlurRadius; } - MCORE_INLINE float GetDOFFocalDistance() const { return mDOFFocalDistance; } - MCORE_INLINE float GetDOFNear() const { return mDOFNear; } - MCORE_INLINE float GetDOFFar() const { return mDOFFar; } - - MCORE_INLINE const MCore::RGBAColor& GetRimColor() const { return mRimColor; } - MCORE_INLINE float GetRimIntensity() const { return mRimIntensity; } - MCORE_INLINE float GetRimWidth() const { return mRimWidth; } - MCORE_INLINE float GetRimAngle() const { return mRimAngle; } - - MCORE_INLINE float GetMainLightIntensity() const { return mMainLightIntensity; } - MCORE_INLINE float GetMainLightAngleA() const { return mMainLightAngleA; } - MCORE_INLINE float GetMainLightAngleB() const { return mMainLightAngleB; } - MCORE_INLINE float GetSpecularIntensity() const { return mSpecularIntensity; } + MCORE_INLINE void SetRenderTexture(RenderTexture* texture) { m_renderTexture = texture; } + MCORE_INLINE void SetShaderPath(AZ::IO::PathView shaderPath) { m_shaderPath = shaderPath; } + + MCORE_INLINE void SetBloomEnabled(bool enabled) { m_bloomEnabled = enabled; } + MCORE_INLINE void SetBloomThreshold(float threshold) { m_bloomThreshold = threshold; } + MCORE_INLINE void SetBloomIntensity(float intensity) { m_bloomIntensity = intensity; } + MCORE_INLINE void SetBloomRadius(float radius) { m_bloomRadius = radius; } + MCORE_INLINE void SetDOFEnabled(bool enabled) { m_dofEnabled = enabled; } + MCORE_INLINE void SetDOFFocalDistance(float dist) { m_dofFocalDistance = dist; } + MCORE_INLINE void SetDOFNear(float dist) { m_dofNear = dist; } + MCORE_INLINE void SetDOFFar(float dist) { m_dofFar = dist; } + MCORE_INLINE void SetDOFBlurRadius(float radius) { m_dofBlurRadius = radius; } + + MCORE_INLINE void SetRimColor(const MCore::RGBAColor& color) { m_rimColor = color; } + MCORE_INLINE void SetRimIntensity(float intensity) { m_rimIntensity = intensity; } + MCORE_INLINE void SetRimWidth(float width) { m_rimWidth = width; } + MCORE_INLINE void SetRimAngle(float angleInDegrees) { m_rimAngle = angleInDegrees; } + + MCORE_INLINE void SetMainLightIntensity(float intensity) { m_mainLightIntensity = intensity; } + MCORE_INLINE void SetMainLightAngleA(float angleInDegrees) { m_mainLightAngleA = angleInDegrees; } + MCORE_INLINE void SetMainLightAngleB(float angleInDegrees) { m_mainLightAngleB = angleInDegrees; } + MCORE_INLINE void SetSpecularIntensity(float intensity) { m_specularIntensity = intensity; } + + MCORE_INLINE bool GetBloomEnabled() const { return m_bloomEnabled; } + MCORE_INLINE float GetBloomThreshold() const { return m_bloomThreshold; } + MCORE_INLINE float GetBloomIntensity() const { return m_bloomIntensity; } + MCORE_INLINE float GetBloomRadius() const { return m_bloomRadius; } + MCORE_INLINE bool GetDOFEnabled() const { return m_dofEnabled; } + MCORE_INLINE float GetDOFBlurRadius() const { return m_dofBlurRadius; } + MCORE_INLINE float GetDOFFocalDistance() const { return m_dofFocalDistance; } + MCORE_INLINE float GetDOFNear() const { return m_dofNear; } + MCORE_INLINE float GetDOFFar() const { return m_dofFar; } + + MCORE_INLINE const MCore::RGBAColor& GetRimColor() const { return m_rimColor; } + MCORE_INLINE float GetRimIntensity() const { return m_rimIntensity; } + MCORE_INLINE float GetRimWidth() const { return m_rimWidth; } + MCORE_INLINE float GetRimAngle() const { return m_rimAngle; } + + MCORE_INLINE float GetMainLightIntensity() const { return m_mainLightIntensity; } + MCORE_INLINE float GetMainLightAngleA() const { return m_mainLightAngleA; } + MCORE_INLINE float GetMainLightAngleB() const { return m_mainLightAngleB; } + MCORE_INLINE float GetSpecularIntensity() const { return m_specularIntensity; } void SetupSunsetRim(); void SetupBlueRim(); @@ -143,58 +143,58 @@ namespace RenderGL bool ResizeTextures(uint32 screenWidth, uint32 screenHeight); bool CreateRandomVectorTexture(uint32 width, uint32 height); - bool mPostProcessing; - RenderTexture* mRenderTexture; // Active RT + bool m_postProcessing; + RenderTexture* m_renderTexture; // Active RT - GBuffer* mGBuffer; /**< The g-buffer. */ + GBuffer* m_gBuffer; /**< The g-buffer. */ - MCommon::Camera* mCamera; /**< The camera used for rendering. */ + MCommon::Camera* m_camera; /**< The camera used for rendering. */ - ShaderCache mShaderCache; /**< The shader manager used to load and manage vertex and pixel shaders. */ - AZ::IO::Path mShaderPath; /**< The absolute path to the directory where the shaders are located. This string will be added as prefix to each shader file the user tries to load. */ - MCore::RGBAColor mClearColor; /**< The scene background color. */ - MCore::RGBAColor mGradientSourceColor; /**< The background gradient source color. */ - MCore::RGBAColor mGradientTargetColor; /**< The background gradient target color. */ - bool mUseGradientBackground; - Shader* mActiveShader; /**< The currently used shader. */ + ShaderCache m_shaderCache; /**< The shader manager used to load and manage vertex and pixel shaders. */ + AZ::IO::Path m_shaderPath; /**< The absolute path to the directory where the shaders are located. This string will be added as prefix to each shader file the user tries to load. */ + MCore::RGBAColor m_clearColor; /**< The scene background color. */ + MCore::RGBAColor m_gradientSourceColor; /**< The background gradient source color. */ + MCore::RGBAColor m_gradientTargetColor; /**< The background gradient target color. */ + bool m_useGradientBackground; + Shader* m_activeShader; /**< The currently used shader. */ // post process shaders - PostProcessShader* mHBloom; - PostProcessShader* mVBloom; - PostProcessShader* mDownSample; - PostProcessShader* mHBlur; - PostProcessShader* mVBlur; - PostProcessShader* mDOF; - PostProcessShader* mSSDO; - PostProcessShader* mHSmartBlur; - PostProcessShader* mVSmartBlur; - - Texture* mRandomVectorTexture; - AZStd::vector mRandomOffsets; - static size_t mNumRandomOffsets; - - GLRenderUtil* mRenderUtil; /**< The rendering utility. */ - TextureCache mTextureCache; /**< The texture manager used to load and manage textures. */ - - bool mBloomEnabled; - float mBloomThreshold; - float mBloomIntensity; - float mBloomRadius; - bool mDOFEnabled; - float mDOFFocalDistance; - float mDOFNear; - float mDOFFar; - float mDOFBlurRadius; - float mRimAngle; - float mRimWidth; - float mRimIntensity; - MCore::RGBAColor mRimColor; - float mMainLightIntensity; - float mMainLightAngleA; - float mMainLightAngleB; - float mSpecularIntensity; - bool mCreateMipMaps; - bool mSkipLoadingTextures; + PostProcessShader* m_hBloom; + PostProcessShader* m_vBloom; + PostProcessShader* m_downSample; + PostProcessShader* m_hBlur; + PostProcessShader* m_vBlur; + PostProcessShader* m_dof; + PostProcessShader* m_ssdo; + PostProcessShader* m_hSmartBlur; + PostProcessShader* m_vSmartBlur; + + Texture* m_randomVectorTexture; + AZStd::vector m_randomOffsets; + static size_t s_numRandomOffsets; + + GLRenderUtil* m_renderUtil; /**< The rendering utility. */ + TextureCache m_textureCache; /**< The texture manager used to load and manage textures. */ + + bool m_bloomEnabled; + float m_bloomThreshold; + float m_bloomIntensity; + float m_bloomRadius; + bool m_dofEnabled; + float m_dofFocalDistance; + float m_dofNear; + float m_dofFar; + float m_dofBlurRadius; + float m_rimAngle; + float m_rimWidth; + float m_rimIntensity; + MCore::RGBAColor m_rimColor; + float m_mainLightIntensity; + float m_mainLightAngleA; + float m_mainLightAngleB; + float m_specularIntensity; + bool m_createMipMaps; + bool m_skipLoadingTextures; }; GraphicsManager* GetGraphicsManager(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.cpp index 279858aba7..01d1e7ef20 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.cpp @@ -17,23 +17,23 @@ namespace RenderGL // default constructor IndexBuffer::IndexBuffer() { - mBufferID = MCORE_INVALIDINDEX32; - mNumIndices = 0; + m_bufferId = MCORE_INVALIDINDEX32; + m_numIndices = 0; } // destructor IndexBuffer::~IndexBuffer() { - glDeleteBuffers(1, &mBufferID); + glDeleteBuffers(1, &m_bufferId); } // activate void IndexBuffer::Activate() { - assert(mBufferID != MCORE_INVALIDINDEX32); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID); + assert(m_bufferId != MCORE_INVALIDINDEX32); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_bufferId); } @@ -64,8 +64,8 @@ namespace RenderGL } // generate the buffer ID and bind it - glGenBuffers(1, &mBufferID); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID); + glGenBuffers(1, &m_bufferId); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_bufferId); glBufferData(GL_ELEMENT_ARRAY_BUFFER, (uint32)indexSize * numIndices, indexData, usageGL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); /* @@ -103,7 +103,7 @@ namespace RenderGL } */ // adjust the number of indices - mNumIndices = numIndices; + m_numIndices = numIndices; return true; } @@ -112,7 +112,7 @@ namespace RenderGL // lock the buffer void* IndexBuffer::Lock(ELockMode lockMode) { - if (mNumIndices == 0) + if (m_numIndices == 0) { return nullptr; } @@ -135,8 +135,8 @@ namespace RenderGL } // lock the buffer - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID); - void* data = glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, lockModeGL); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_bufferId); + void* data = m_glMapBuffer(GL_ELEMENT_ARRAY_BUFFER, lockModeGL); // check for failure if (data == nullptr) @@ -165,12 +165,12 @@ namespace RenderGL // unlock the buffer void IndexBuffer::Unlock() { - if (mNumIndices == 0) + if (m_numIndices == 0) { return; } - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mBufferID); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_bufferId); glUnmapBuffer(GL_ELEMENT_ARRAY_BUFFER); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.h index eef0ff1d7a..b09e5f394d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/IndexBuffer.h @@ -35,8 +35,8 @@ namespace RenderGL void Activate(); - MCORE_INLINE uint32 GetBufferID() const { return mBufferID; } - MCORE_INLINE uint32 GetNumIndices() const { return mNumIndices; } + MCORE_INLINE uint32 GetBufferID() const { return m_bufferId; } + MCORE_INLINE uint32 GetNumIndices() const { return m_numIndices; } bool Init(EIndexSize indexSize, uint32 numIndices, EUsageMode usage, void* indexData = nullptr); @@ -44,8 +44,8 @@ namespace RenderGL void Unlock(); private: - uint32 mBufferID; // the buffer ID - uint32 mNumIndices; // the number of indices + uint32 m_bufferId; // the buffer ID + uint32 m_numIndices; // the number of indices // helpers bool GetIsSuccess(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.cpp index 0cdaa6d327..f79f8c3edd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.cpp @@ -17,7 +17,7 @@ namespace RenderGL // constructor Material::Material(GLActor* actor) { - mActor = actor; + m_actor = actor; } @@ -52,7 +52,7 @@ namespace RenderGL Texture* Material::LoadTexture(const char* fileName, bool genMipMaps) { Texture* result = nullptr; - AZStd::string filename = mActor->GetTexturePath() + fileName; + AZStd::string filename = m_actor->GetTexturePath() + fileName; AZStd::string extension; AzFramework::StringFunc::Path::GetExtension(fileName, extension, false /* include dot */); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h index 1cebe2d87b..825fa4c7b0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/Material.h @@ -24,45 +24,45 @@ namespace RenderGL { Primitive() { - mVertexOffset = 0; - mIndexOffset = 0; - mNumTriangles = 0; - mNumVertices = 0; + m_vertexOffset = 0; + m_indexOffset = 0; + m_numTriangles = 0; + m_numVertices = 0; - mNodeIndex = MCORE_INVALIDINDEX32; - mMaterialIndex = MCORE_INVALIDINDEX32; + m_nodeIndex = InvalidIndex; + m_materialIndex = MCORE_INVALIDINDEX32; } - uint32 mNodeIndex; /**< The index of the node to which this primitive belongs to. */ - uint32 mVertexOffset; - uint32 mIndexOffset; /**< The starting index. */ - uint32 mNumTriangles; /**< The number of triangles in the primitive. */ - uint32 mNumVertices; /**< The number of vertices in the primitive. */ - uint32 mMaterialIndex; /**< The material index which is mapped to the primitive. */ + size_t m_nodeIndex; /**< The index of the node to which this primitive belongs to. */ + uint32 m_vertexOffset; + uint32 m_indexOffset; /**< The starting index. */ + uint32 m_numTriangles; /**< The number of triangles in the primitive. */ + uint32 m_numVertices; /**< The number of vertices in the primitive. */ + uint32 m_materialIndex; /**< The material index which is mapped to the primitive. */ - MCore::Array mBoneNodeIndices;/**< Mapping from local bones 0-50 to nodes. */ + AZStd::vector m_boneNodeIndices;/**< Mapping from local bones 0-50 to nodes. */ }; // StandardVertex struct RENDERGL_API StandardVertex { - AZ::Vector3 mPosition; - AZ::Vector3 mNormal; - AZ::Vector4 mTangent; - AZ::Vector2 mUV; + AZ::Vector3 m_position; + AZ::Vector3 m_normal; + AZ::Vector4 m_tangent; + AZ::Vector2 m_uv; }; // SkinnedVertex struct RENDERGL_API SkinnedVertex { - AZ::Vector3 mPosition; - AZ::Vector3 mNormal; - AZ::Vector4 mTangent; - AZ::Vector2 mUV; - float mWeights[4]; - float mBoneIndices[4]; + AZ::Vector3 m_position; + AZ::Vector3 m_normal; + AZ::Vector4 m_tangent; + AZ::Vector2 m_uv; + float m_weights[4]; + float m_boneIndices[4]; }; @@ -103,7 +103,7 @@ namespace RenderGL Texture* LoadTexture(const char* fileName); const char* AttributeToString(const EAttribute attribute); - GLActor* mActor; + GLActor* m_actor; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp index 7492f3e845..a3ca0f33c4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.cpp @@ -17,7 +17,7 @@ namespace RenderGL // default constructor PostProcessShader::PostProcessShader() { - mRT = nullptr; + m_rt = nullptr; } @@ -30,8 +30,8 @@ namespace RenderGL void PostProcessShader::ActivateRT(RenderTexture* target) { // Activate rt - mRT = target; - mRT->Activate(); + m_rt = target; + m_rt->Activate(); GLSLShader::Activate(); } @@ -73,15 +73,15 @@ namespace RenderGL { GLSLShader::Deactivate(); - mRT->Deactivate(); - mRT = nullptr; + m_rt->Deactivate(); + m_rt = nullptr; } // Init bool PostProcessShader::Init(AZ::IO::PathView filename) { - MCore::Array defines; + AZStd::vector defines; return GLSLShader::Init(nullptr, filename, defines); } @@ -89,8 +89,8 @@ namespace RenderGL // Render void PostProcessShader::Render() { - const float w = static_cast(mRT->GetWidth()); - const float h = static_cast(mRT->GetHeight()); + const float w = static_cast(m_rt->GetWidth()); + const float h = static_cast(m_rt->GetHeight()); // Setup ortho projection glMatrixMode(GL_PROJECTION); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.h index 9e976d599e..644e47b9b9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/PostProcessShader.h @@ -36,7 +36,7 @@ namespace RenderGL private: - RenderTexture* mRT; + RenderTexture* m_rt; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.cpp index d0285c457d..ac85fcf7d7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.cpp @@ -19,21 +19,21 @@ namespace RenderGL // constructor RenderTexture::RenderTexture() { - mFormat = 0; - mWidth = 0; - mHeight = 0; - mFrameBuffer = 0; - mDepthBuffer = 0; - mTexture = 0; + m_format = 0; + m_width = 0; + m_height = 0; + m_frameBuffer = 0; + m_depthBuffer = 0; + m_texture = 0; } // destructor RenderTexture::~RenderTexture() { - glDeleteTextures(1, &mTexture); - glDeleteRenderbuffers(1, &mDepthBuffer); - glDeleteFramebuffers(1, &mFrameBuffer); + glDeleteTextures(1, &m_texture); + glDeleteRenderbuffers(1, &m_depthBuffer); + glDeleteFramebuffers(1, &m_frameBuffer); } @@ -47,15 +47,15 @@ namespace RenderGL // get the width and height of the current used viewport float glDimensions[4]; glGetFloatv(GL_VIEWPORT, glDimensions); - mPrevWidth = (uint32)glDimensions[2]; - mPrevHeight = (uint32)glDimensions[3]; + m_prevWidth = (uint32)glDimensions[2]; + m_prevHeight = (uint32)glDimensions[3]; // bind the render texture and frame buffer glBindTexture(GL_TEXTURE_2D, 0); - glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer); // setup the new viewport - glViewport(0, 0, mWidth, mHeight); + glViewport(0, 0, m_width, m_height); GetGraphicsManager()->SetRenderTexture(this); } @@ -63,7 +63,7 @@ namespace RenderGL // clear the render texture void RenderTexture::Clear(const MCore::RGBAColor& color) { - glClearColor(color.r, color.g, color.b, color.a); + glClearColor(color.m_r, color.m_g, color.m_b, color.m_a); glClearDepth(1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } @@ -76,7 +76,7 @@ namespace RenderGL glBindFramebuffer(GL_FRAMEBUFFER, 0); // reset viewport to original dimensions - glViewport(0, 0, mPrevWidth, mPrevHeight); + glViewport(0, 0, m_prevWidth, m_prevHeight); GetGraphicsManager()->SetRenderTexture(nullptr); } @@ -84,10 +84,10 @@ namespace RenderGL // initialize the render texture bool RenderTexture::Init(int32 format, uint32 width, uint32 height, AZ::u32 depthBuffer) { - mFormat = format; - mWidth = width; - mHeight = height; - mDepthBuffer = depthBuffer; + m_format = format; + m_width = width; + m_height = height; + m_depthBuffer = depthBuffer; // check if the graphics hardware is capable of rendering to textures, return false if not if (hasOpenGLFeature(Framebuffers)) @@ -96,51 +96,51 @@ namespace RenderGL } // create surface IDs - glGenFramebuffers(1, &mFrameBuffer); - glGenTextures(1, &mTexture); + glGenFramebuffers(1, &m_frameBuffer); + glGenTextures(1, &m_texture); // if the depth buffer was not specified, generate it - if (mDepthBuffer == 0) + if (m_depthBuffer == 0) { - glGenRenderbuffers(1, &mDepthBuffer); + glGenRenderbuffers(1, &m_depthBuffer); } // check if initalization of the texture, the frame buffer and the depth buffer worked okay - if (mFrameBuffer == 0 || mDepthBuffer == 0 || mTexture == 0) + if (m_frameBuffer == 0 || m_depthBuffer == 0 || m_texture == 0) { - MCore::LogWarning("[OpenGL] RenderTexture failed to init (5d, %d, %d)", mFrameBuffer, mDepthBuffer, mTexture); + MCore::LogWarning("[OpenGL] RenderTexture failed to init (5d, %d, %d)", m_frameBuffer, m_depthBuffer, m_texture); return false; } // create the frame buffer object - glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer); + glBindFramebuffer(GL_FRAMEBUFFER, m_frameBuffer); // setup channels GLenum glChannels = GL_RGBA; - if (mFormat == GL_ALPHA16F_ARB || mFormat == GL_ALPHA32F_ARB) + if (m_format == GL_ALPHA16F_ARB || m_format == GL_ALPHA32F_ARB) { glChannels = GL_ALPHA; } // create render target - glBindTexture(GL_TEXTURE_2D, mTexture); - glTexImage2D(GL_TEXTURE_2D, 0, mFormat, mWidth, mHeight, 0, glChannels, GL_FLOAT, nullptr); + glBindTexture(GL_TEXTURE_2D, m_texture); + glTexImage2D(GL_TEXTURE_2D, 0, m_format, m_width, m_height, 0, glChannels, GL_FLOAT, nullptr); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTexture, 0); + glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_texture, 0); // create depth buffer if (depthBuffer == 0) { - glBindRenderbuffer(GL_RENDERBUFFER, mDepthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, mWidth, mHeight); + glBindRenderbuffer(GL_RENDERBUFFER, m_depthBuffer); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, m_width, m_height); } - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, mDepthBuffer); + glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthBuffer); if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.h index 51797e5c38..9839ca0a5f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/RenderTexture.h @@ -49,8 +49,8 @@ namespace RenderGL void Render(); - AZ::u32 GetDepthBuffer() const { return mDepthBuffer; } - int32 GetFormat() const { return mFormat; } + AZ::u32 GetDepthBuffer() const { return m_depthBuffer; } + int32 GetFormat() const { return m_format; } /** * Formats: GL_RGBA32F_ARB @@ -60,11 +60,11 @@ namespace RenderGL bool Init(int32 format, uint32 width, uint32 height, AZ::u32 depthBuffer = 0); private: - int32 mFormat; /*< . */ - uint32 mPrevHeight; /*< . */ - uint32 mPrevWidth; /*< . */ - AZ::u32 mFrameBuffer; - AZ::u32 mDepthBuffer; + int32 m_format; /*< . */ + uint32 m_prevHeight; /*< . */ + uint32 m_prevWidth; /*< . */ + AZ::u32 m_frameBuffer; + AZ::u32 m_depthBuffer; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp index 604ad4dcaf..4d25017831 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/ShaderCache.cpp @@ -15,8 +15,7 @@ namespace RenderGL // constructor ShaderCache::ShaderCache() { - mEntries.SetMemoryCategory(MEMCATEGORY_RENDERING); - mEntries.Reserve(128); + m_entries.reserve(128); } @@ -31,56 +30,41 @@ namespace RenderGL void ShaderCache::Release() { // delete all shaders - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + for (Entry& entry : m_entries) { - mEntries[i].mName.clear(); - delete mEntries[i].mShader; + entry.m_name.clear(); + delete entry.m_shader; } // clear all entries - mEntries.Clear(); + m_entries.clear(); } // add the shader to the cache (assume there are no duplicate names) void ShaderCache::AddShader(AZStd::string_view filename, Shader* shader) { - mEntries.AddEmpty(); - mEntries.GetLast().mName = filename; - mEntries.GetLast().mShader = shader; + m_entries.emplace_back(Entry{filename, shader}); } // try to locate a shader based on its name Shader* ShaderCache::FindShader(AZStd::string_view filename) const { - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundShader = AZStd::find_if(begin(m_entries), end(m_entries), [filename](const Entry& entry) { - if (AzFramework::StringFunc::Equal(mEntries[i].mName, filename, false /* no case */)) // non-case-sensitive name compare - { - return mEntries[i].mShader; - } - } - - // not found - return nullptr; + return AzFramework::StringFunc::Equal(entry.m_name, filename, false /* no case */); + }); + return foundShader != end(m_entries) ? foundShader->m_shader : nullptr; } // check if we have a given shader in the cache bool ShaderCache::CheckIfHasShader(Shader* shader) const { - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + return AZStd::any_of(begin(m_entries), end(m_entries), [shader](const Entry& entry) { - if (mEntries[i].mShader == shader) - { - return true; - } - } - - return false; + return entry.m_shader == shader; + }); } } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp index a782cfcd42..c2537e4948 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.cpp @@ -20,15 +20,13 @@ namespace RenderGL StandardMaterial::StandardMaterial(GLActor* actor) : Material(actor) { - mMaterial = nullptr; - mActiveShader = nullptr; - mAttributesUpdated = true; + m_material = nullptr; + m_activeShader = nullptr; + m_attributesUpdated = true; - mDiffuseMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); - mSpecularMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); - mNormalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); - - mShaders.SetMemoryCategory(MEMCATEGORY_RENDERING); + m_diffuseMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); + m_specularMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); + m_normalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); SetAttribute(LIGHTING, true); SetAttribute(SKINNING, false); @@ -50,7 +48,7 @@ namespace RenderGL UpdateShader(); // check if the shader is valid and return in case it's not - if (mActiveShader == nullptr) + if (m_activeShader == nullptr) { return; } @@ -60,103 +58,99 @@ namespace RenderGL if (flags & GLOBAL) { - mActiveShader->Activate(); + m_activeShader->Activate(); // vertex attributes - uint32 stride = mAttributes[SKINNING] ? sizeof(SkinnedVertex) : sizeof(StandardVertex); + uint32 stride = m_attributes[SKINNING] ? sizeof(SkinnedVertex) : sizeof(StandardVertex); static char* structStart = reinterpret_cast(reinterpret_cast(static_cast(0))); - static size_t offsetOfNormal = static_cast((reinterpret_cast(&static_cast(0)->mNormal)) - structStart); - static size_t offsetOfTangent = static_cast((reinterpret_cast(&static_cast(0)->mTangent)) - structStart); - static size_t offsetOfUV = static_cast((reinterpret_cast(&static_cast(0)->mUV)) - structStart); - static size_t offsetOfWeights = static_cast((reinterpret_cast(&static_cast(0)->mWeights)) - structStart); - static size_t offsetOfBoneIndices = static_cast((reinterpret_cast(&static_cast(0)->mBoneIndices)) - structStart); + static size_t offsetOfNormal = static_cast((reinterpret_cast(&static_cast(0)->m_normal)) - structStart); + static size_t offsetOfTangent = static_cast((reinterpret_cast(&static_cast(0)->m_tangent)) - structStart); + static size_t offsetOfUV = static_cast((reinterpret_cast(&static_cast(0)->m_uv)) - structStart); + static size_t offsetOfWeights = static_cast((reinterpret_cast(&static_cast(0)->m_weights)) - structStart); + static size_t offsetOfBoneIndices = static_cast((reinterpret_cast(&static_cast(0)->m_boneIndices)) - structStart); - mActiveShader->SetAttribute("inPosition", 4, GL_FLOAT, stride, 0); - mActiveShader->SetAttribute("inNormal", 4, GL_FLOAT, stride, offsetOfNormal); - mActiveShader->SetAttribute("inTangent", 4, GL_FLOAT, stride, offsetOfTangent); - mActiveShader->SetAttribute("inUV", 2, GL_FLOAT, stride, offsetOfUV); + m_activeShader->SetAttribute("inPosition", 4, GL_FLOAT, stride, 0); + m_activeShader->SetAttribute("inNormal", 4, GL_FLOAT, stride, offsetOfNormal); + m_activeShader->SetAttribute("inTangent", 4, GL_FLOAT, stride, offsetOfTangent); + m_activeShader->SetAttribute("inUV", 2, GL_FLOAT, stride, offsetOfUV); // vertex weights & indices - if (mAttributes[SKINNING]) + if (m_attributes[SKINNING]) { - mActiveShader->SetAttribute("inWeights", 4, GL_FLOAT, stride, offsetOfWeights); - mActiveShader->SetAttribute("inIndices", 4, GL_FLOAT, stride, offsetOfBoneIndices); + m_activeShader->SetAttribute("inWeights", 4, GL_FLOAT, stride, offsetOfWeights); + m_activeShader->SetAttribute("inIndices", 4, GL_FLOAT, stride, offsetOfBoneIndices); } // set the view projection matrix MCommon::Camera* camera = GetGraphicsManager()->GetCamera(); - mActiveShader->SetUniform("matViewProj", camera->GetViewProjMatrix()); - mActiveShader->SetUniform("matView", camera->GetViewMatrix()); + m_activeShader->SetUniform("matViewProj", camera->GetViewProjMatrix()); + m_activeShader->SetUniform("matView", camera->GetViewMatrix()); - // lights - // if (mAttributes[LIGHTING]) { AZ::Vector3 mainLightDir(0.0f, -1.0f, 0.0f); mainLightDir = AZ::Matrix3x3::CreateRotationX(MCore::Math::DegreesToRadians(gfx->GetMainLightAngleB())) * AZ::Matrix3x3::CreateRotationZ(MCore::Math::DegreesToRadians(gfx->GetMainLightAngleA())) * mainLightDir; mainLightDir.Normalize(); - mActiveShader->SetUniform("mainLightDir", mainLightDir); - mActiveShader->SetUniform("skyColor", mActor->GetSkyColor() * gfx->GetMainLightIntensity()); - mActiveShader->SetUniform("groundColor", mActor->GetGroundColor()); - mActiveShader->SetUniform("eyePoint", camera->GetPosition()); + m_activeShader->SetUniform("mainLightDir", mainLightDir); + m_activeShader->SetUniform("skyColor", m_actor->GetSkyColor() * gfx->GetMainLightIntensity()); + m_activeShader->SetUniform("groundColor", m_actor->GetGroundColor()); + m_activeShader->SetUniform("eyePoint", camera->GetPosition()); AZ::Vector3 rimLightDir = MCore::GetUp(camera->GetViewMatrix()); rimLightDir = AZ::Matrix3x3::CreateRotationZ(MCore::Math::DegreesToRadians(gfx->GetRimAngle())) * rimLightDir; rimLightDir.Normalize(); - mActiveShader->SetUniform("rimLightDir", rimLightDir); + m_activeShader->SetUniform("rimLightDir", rimLightDir); - mActiveShader->SetUniform("rimLightFactor", gfx->GetRimIntensity()); - mActiveShader->SetUniform("rimWidth", gfx->GetRimWidth()); - mActiveShader->SetUniform("rimLightColor", gfx->GetRimColor()); + m_activeShader->SetUniform("rimLightFactor", gfx->GetRimIntensity()); + m_activeShader->SetUniform("rimWidth", gfx->GetRimWidth()); + m_activeShader->SetUniform("rimLightColor", gfx->GetRimColor()); } } // Local settings if (flags & LOCAL) { - EMotionFX::StandardMaterial* stdMaterial = (mMaterial->GetType() == EMotionFX::StandardMaterial::TYPE_ID) ? static_cast(mMaterial) : nullptr; + EMotionFX::StandardMaterial* stdMaterial = (m_material->GetType() == EMotionFX::StandardMaterial::TYPE_ID) ? static_cast(m_material) : nullptr; - if (mDiffuseMap == nullptr || mDiffuseMap == gfx->GetTextureCache()->GetWhiteTexture() && stdMaterial) + if (m_diffuseMap == nullptr || m_diffuseMap == gfx->GetTextureCache()->GetWhiteTexture() && stdMaterial) { - mActiveShader->SetUniform("diffuseColor", stdMaterial->GetDiffuse()); + m_activeShader->SetUniform("diffuseColor", stdMaterial->GetDiffuse()); } else { - mActiveShader->SetUniform("diffuseColor", MCore::RGBAColor(1.0f, 1.0f, 1.0f, 1.0f)); + m_activeShader->SetUniform("diffuseColor", MCore::RGBAColor(1.0f, 1.0f, 1.0f, 1.0f)); } - //if (mAttributes[LIGHTING]) { if (stdMaterial) { MCore::RGBAColor specularColor = stdMaterial->GetSpecular() * (stdMaterial->GetShineStrength() * gfx->GetMainLightIntensity() * gfx->GetSpecularIntensity()); - mActiveShader->SetUniform("specularPower", stdMaterial->GetShine()); - mActiveShader->SetUniform("lightSpecular", specularColor); + m_activeShader->SetUniform("specularPower", stdMaterial->GetShine()); + m_activeShader->SetUniform("lightSpecular", specularColor); } else { MCore::RGBAColor specularColor = MCore::RGBAColor(1.0f, 1.0f, 1.0f) * (1.0f * gfx->GetMainLightIntensity() * gfx->GetSpecularIntensity()); - mActiveShader->SetUniform("specularPower", 25.0f); - mActiveShader->SetUniform("lightSpecular", specularColor); + m_activeShader->SetUniform("specularPower", 25.0f); + m_activeShader->SetUniform("lightSpecular", specularColor); } - mActiveShader->SetUniform("normalMap", mNormalMap); + m_activeShader->SetUniform("normalMap", m_normalMap); } - //if (mAttributes[TEXTURING]) { - mActiveShader->SetUniform("diffuseMap", mDiffuseMap); - mActiveShader->SetUniform("specularMap", mSpecularMap); + m_activeShader->SetUniform("diffuseMap", m_diffuseMap); + m_activeShader->SetUniform("specularMap", m_specularMap); } } // update the advanced rendering settings - mActiveShader->SetUniform("glowThreshold", gfx->GetBloomThreshold()); - mActiveShader->SetUniform("focalPlaneDepth", gfx->GetDOFFocalDistance()); - mActiveShader->SetUniform("nearPlaneDepth", gfx->GetDOFNear()); - mActiveShader->SetUniform("farPlaneDepth", gfx->GetDOFFar()); - mActiveShader->SetUniform("blurCutoff", 1.0f); + m_activeShader->SetUniform("glowThreshold", gfx->GetBloomThreshold()); + m_activeShader->SetUniform("focalPlaneDepth", gfx->GetDOFFocalDistance()); + m_activeShader->SetUniform("nearPlaneDepth", gfx->GetDOFNear()); + m_activeShader->SetUniform("farPlaneDepth", gfx->GetDOFFar()); + m_activeShader->SetUniform("blurCutoff", 1.0f); } @@ -164,13 +158,13 @@ namespace RenderGL void StandardMaterial::Deactivate() { // check if the shader is valid and return in case it's not - if (mActiveShader == nullptr) + if (m_activeShader == nullptr) { return; } // deactivate the active shader - mActiveShader->Deactivate(); + m_activeShader->Deactivate(); } @@ -178,49 +172,49 @@ namespace RenderGL bool StandardMaterial::Init(EMotionFX::Material* material) { initializeOpenGLFunctions(); - mMaterial = material; + m_material = material; if (material->GetType() == EMotionFX::StandardMaterial::TYPE_ID) { EMotionFX::StandardMaterial* stdMaterial = static_cast(material); // get the number of material layers and iterate through them - const uint32 numLayers = stdMaterial->GetNumLayers(); - for (uint32 i = 0; i < numLayers; ++i) + const size_t numLayers = stdMaterial->GetNumLayers(); + for (size_t i = 0; i < numLayers; ++i) { EMotionFX::StandardMaterialLayer* layer = stdMaterial->GetLayer(i); switch (layer->GetType()) { case EMotionFX::StandardMaterialLayer::LAYERTYPE_DIFFUSE: { - mDiffuseMap = LoadTexture(layer->GetFileName()); - if (mDiffuseMap == nullptr) + m_diffuseMap = LoadTexture(layer->GetFileName()); + if (m_diffuseMap == nullptr) { - mDiffuseMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); + m_diffuseMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); } } break; case EMotionFX::StandardMaterialLayer::LAYERTYPE_SHINESTRENGTH: { - mSpecularMap = LoadTexture(layer->GetFileName()); - if (mSpecularMap == nullptr) + m_specularMap = LoadTexture(layer->GetFileName()); + if (m_specularMap == nullptr) { - mSpecularMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); + m_specularMap = GetGraphicsManager()->GetTextureCache()->GetWhiteTexture(); } } break; case EMotionFX::StandardMaterialLayer::LAYERTYPE_BUMP: { - mNormalMap = LoadTexture(layer->GetFileName()); - if (mNormalMap == nullptr) + m_normalMap = LoadTexture(layer->GetFileName()); + if (m_normalMap == nullptr) { - mNormalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); + m_normalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); } } break; case EMotionFX::StandardMaterialLayer::LAYERTYPE_NORMALMAP: { - mNormalMap = LoadTexture(layer->GetFileName()); - if (mNormalMap == nullptr) + m_normalMap = LoadTexture(layer->GetFileName()); + if (m_normalMap == nullptr) { - mNormalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); + m_normalMap = GetGraphicsManager()->GetTextureCache()->GetDefaultNormalTexture(); } } break; } @@ -234,12 +228,10 @@ namespace RenderGL // void StandardMaterial::SetAttribute(EAttribute attribute, bool enabled) { - const uint32 index = (uint32)attribute; - - if (mAttributes[index] != enabled) + if (m_attributes[attribute] != enabled) { - mAttributes[index] = enabled; - mAttributesUpdated = true; + m_attributes[attribute] = enabled; + m_attributesUpdated = true; } } @@ -248,7 +240,7 @@ namespace RenderGL void StandardMaterial::Render(EMotionFX::ActorInstance* actorInstance, const Primitive* primitive) { // check if the shader is valid and return in case it's not - if (mActiveShader == nullptr) + if (m_activeShader == nullptr) { return; } @@ -261,20 +253,20 @@ namespace RenderGL const EMotionFX::TransformData* transformData = actorInstance->GetTransformData(); - if (mAttributes[SKINNING]) + if (m_attributes[SKINNING]) { const AZ::Matrix3x4* skinningMatrices = transformData->GetSkinningMatrices(); // multiple each transform by its inverse bind pose - const uint32 numBones = primitive->mBoneNodeIndices.GetLength(); - for (uint32 i = 0; i < numBones; ++i) + const size_t numBones = primitive->m_boneNodeIndices.size(); + for (size_t i = 0; i < numBones; ++i) { - const uint32 nodeNr = primitive->mBoneNodeIndices[i]; + const size_t nodeNr = primitive->m_boneNodeIndices[i]; const AZ::Matrix3x4& skinTransform = skinningMatrices[nodeNr]; - mBoneMatrices[i] = AZ::Matrix4x4::CreateFromMatrix3x4(skinTransform); + m_boneMatrices[i] = AZ::Matrix4x4::CreateFromMatrix3x4(skinTransform); } - mActiveShader->SetUniform("matBones", mBoneMatrices, numBones); + m_activeShader->SetUniform("matBones", m_boneMatrices, aznumeric_caster(numBones)); } const MCommon::Camera* camera = GetGraphicsManager()->GetCamera(); @@ -284,13 +276,13 @@ namespace RenderGL const AZ::Matrix4x4 worldViewProj = camera->GetViewProjMatrix() * world; const AZ::Matrix4x4 worldIT = world.GetInverseFull().GetTranspose(); - mActiveShader->SetUniform("matWorld", world); - mActiveShader->SetUniform("matWorldIT", worldIT); - mActiveShader->SetUniform("matWorldView", worldView); - mActiveShader->SetUniform("matWorldViewProj", worldViewProj); + m_activeShader->SetUniform("matWorld", world); + m_activeShader->SetUniform("matWorldIT", worldIT); + m_activeShader->SetUniform("matWorldView", worldView); + m_activeShader->SetUniform("matWorldViewProj", worldViewProj); // render the primitive - glDrawElementsBaseVertex(GL_TRIANGLES, primitive->mNumTriangles * 3, GL_UNSIGNED_INT, (GLvoid*)(primitive->mIndexOffset * sizeof(uint32)), primitive->mVertexOffset); + glDrawElementsBaseVertex(GL_TRIANGLES, primitive->m_numTriangles * 3, GL_UNSIGNED_INT, (GLvoid*)(primitive->m_indexOffset * sizeof(uint32)), primitive->m_vertexOffset); } @@ -298,19 +290,18 @@ namespace RenderGL void StandardMaterial::UpdateShader() { // check if any attibutes have changed and skip directly if not - if (mAttributesUpdated == false) + if (m_attributesUpdated == false) { return; } // reset the active shader - mActiveShader = nullptr; + m_activeShader = nullptr; // get the number of shaders and iterate through them - const uint32 numShaders = mShaders.GetLength(); - for (uint32 i = 0; i < numShaders; ++i) + for (GLSLShader* shader : m_shaders) { - if (mShaders[i] == nullptr) + if (shader == nullptr) { continue; } @@ -319,9 +310,9 @@ namespace RenderGL bool match = true; for (uint32 n = 0; n < NUM_ATTRIBUTES; ++n) { - if (mAttributes[n]) + if (m_attributes[n]) { - if (mShaders[i]->CheckIfIsDefined(AttributeToString((EAttribute)n)) == false) + if (shader->CheckIfIsDefined(AttributeToString((EAttribute)n)) == false) { match = false; break; @@ -329,7 +320,7 @@ namespace RenderGL } else { - if (mShaders[i]->CheckIfIsDefined(AttributeToString((EAttribute)n))) + if (shader->CheckIfIsDefined(AttributeToString((EAttribute)n))) { match = false; break; @@ -340,31 +331,31 @@ namespace RenderGL // in case we have found a matching shader update the active shader if (match) { - mActiveShader = mShaders[i]; + m_activeShader = shader; break; } } // if we didn't find a matching shader, compile it new - if (mActiveShader == nullptr) + if (m_activeShader == nullptr) { // if this function gets called at runtime something is wrong, go bug hunting! // construct an array of string attributes - MCore::Array defines; + AZStd::vector defines; for (uint32 n = 0; n < NUM_ATTRIBUTES; ++n) { - if (mAttributes[n]) + if (m_attributes[n]) { - defines.Add(AttributeToString((EAttribute)n)); + defines.emplace_back(AttributeToString((EAttribute)n)); } } // compile shader and add it to the list of shaders - mActiveShader = GetGraphicsManager()->LoadShader("StandardMaterial_VS.glsl", "StandardMaterial_PS.glsl", defines); - mShaders.Add(mActiveShader); + m_activeShader = GetGraphicsManager()->LoadShader("StandardMaterial_VS.glsl", "StandardMaterial_PS.glsl", defines); + m_shaders.emplace_back(m_activeShader); } - mAttributesUpdated = false; + m_attributesUpdated = false; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.h index 34386c7241..528269765c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/StandardMaterial.h @@ -41,17 +41,17 @@ namespace RenderGL protected: void UpdateShader(); - bool mAttributes[NUM_ATTRIBUTES]; - bool mAttributesUpdated; + bool m_attributes[NUM_ATTRIBUTES]; + bool m_attributesUpdated; - GLSLShader* mActiveShader; - MCore::Array mShaders; - AZ::Matrix4x4 mBoneMatrices[200]; - EMotionFX::Material* mMaterial; + GLSLShader* m_activeShader; + AZStd::vector m_shaders; + AZ::Matrix4x4 m_boneMatrices[200]; + EMotionFX::Material* m_material; - Texture* mDiffuseMap; - Texture* mSpecularMap; - Texture* mNormalMap; + Texture* m_diffuseMap; + Texture* m_specularMap; + Texture* m_normalMap; }; } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp index 4723d166a7..b2e0f46b53 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.cpp @@ -18,9 +18,9 @@ namespace RenderGL Texture::Texture() { initializeOpenGLFunctions(); - mTexture = 0; - mWidth = 0; - mHeight = 0; + m_texture = 0; + m_width = 0; + m_height = 0; } @@ -28,27 +28,26 @@ namespace RenderGL Texture::Texture(GLuint texID, uint32 width, uint32 height) { initializeOpenGLFunctions(); - mTexture = texID; - mWidth = width; - mHeight = height; + m_texture = texID; + m_width = width; + m_height = height; } // destructor Texture::~Texture() { - glDeleteTextures(1, &mTexture); + glDeleteTextures(1, &m_texture); } // constructor TextureCache::TextureCache() { - mWhiteTexture = nullptr; - mDefaultNormalTexture = nullptr; + m_whiteTexture = nullptr; + m_defaultNormalTexture = nullptr; - mEntries.SetMemoryCategory(MEMCATEGORY_RENDERING); - mEntries.Reserve(128); + m_entries.reserve(128); } @@ -74,30 +73,27 @@ namespace RenderGL void TextureCache::Release() { // delete all textures - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + for (Entry& entry : m_entries) { - delete mEntries[i].mTexture; + delete entry.m_texture; } // clear all entries - mEntries.Clear(); + m_entries.clear(); // delete the white texture - delete mWhiteTexture; - mWhiteTexture = nullptr; + delete m_whiteTexture; + m_whiteTexture = nullptr; - delete mDefaultNormalTexture; - mDefaultNormalTexture = nullptr; + delete m_defaultNormalTexture; + m_defaultNormalTexture = nullptr; } // add the texture to the cache (assume there are no duplicate names) void TextureCache::AddTexture(const char* filename, Texture* texture) { - mEntries.AddEmpty(); - mEntries.GetLast().mName = filename; - mEntries.GetLast().mTexture = texture; + m_entries.emplace_back(Entry{filename, texture}); } @@ -105,17 +101,11 @@ namespace RenderGL Texture* TextureCache::FindTexture(const char* filename) const { // get the number of entries and iterate through them - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [filename](const Entry& entry) { - if (AzFramework::StringFunc::Equal(mEntries[i].mName.c_str(), filename, false /* no case */)) // non-case-sensitive name compare - { - return mEntries[i].mTexture; - } - } - - // not found - return nullptr; + return AzFramework::StringFunc::Equal(entry.m_name.c_str(), filename, false /* no case */); + }); + return foundEntry != end(m_entries) ? foundEntry->m_texture : nullptr; } @@ -123,31 +113,25 @@ namespace RenderGL bool TextureCache::CheckIfHasTexture(Texture* texture) const { // get the number of entries and iterate through them - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + return AZStd::any_of(begin(m_entries), end(m_entries), [texture](const Entry& entry) { - if (mEntries[i].mTexture == texture) - { - return true; - } - } - - return false; + return entry.m_texture == texture; + }); } // remove an item from the cache void TextureCache::RemoveTexture(Texture* texture) { - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [texture](const Entry& entry) + { + return entry.m_texture == texture; + }); + + if (foundEntry != end(m_entries)) { - if (mEntries[i].mTexture == texture) - { - delete mEntries[i].mTexture; - mEntries.Remove(i); - return; - } + delete foundEntry->m_texture; + m_entries.erase(foundEntry); } } @@ -157,12 +141,12 @@ namespace RenderGL GLuint textureID; glGenTextures(1, &textureID); - uint32 width = 2; - uint32 height = 2; + constexpr GLsizei width = 2; + constexpr GLsizei height = 2; uint32 imageBuffer[4]; - for (uint32 i = 0; i < 4; ++i) { - imageBuffer[i] = MCore::RGBA(255, 255, 255, 255); // actually abgr + using AZStd::begin, AZStd::end; + AZStd::fill(begin(imageBuffer), end(imageBuffer), MCore::RGBA(255, 255, 255, 255)); // actually abgr } glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); @@ -172,7 +156,7 @@ namespace RenderGL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageBuffer); glBindTexture(GL_TEXTURE_2D, 0); - mWhiteTexture = new Texture(textureID, width, height); + m_whiteTexture = new Texture(textureID, width, height); return true; } @@ -183,12 +167,12 @@ namespace RenderGL GLuint textureID; glGenTextures(1, &textureID); - uint32 width = 2; - uint32 height = 2; + constexpr GLsizei width = 2; + constexpr GLsizei height = 2; uint32 imageBuffer[4]; - for (uint32 i = 0; i < 4; ++i) { - imageBuffer[i] = MCore::RGBA(255, 128, 128, 255); // opengl wants abgr + using AZStd::begin, AZStd::end; + AZStd::fill(begin(imageBuffer), end(imageBuffer), MCore::RGBA(255, 128, 128, 255)); // opengl wants abgr } glBindTexture(GL_TEXTURE_2D, textureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); @@ -198,7 +182,7 @@ namespace RenderGL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageBuffer); glBindTexture(GL_TEXTURE_2D, 0); - mDefaultNormalTexture = new Texture(textureID, width, height); + m_defaultNormalTexture = new Texture(textureID, width, height); return true; } } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h index bae46bd75b..4350cd67c7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/TextureCache.h @@ -10,7 +10,7 @@ #define __RENDERGL_TEXTURECACHE_H #include -#include +#include #include "RenderGLConfig.h" #include @@ -28,14 +28,14 @@ namespace RenderGL Texture(AZ::u32 texID, uint32 width, uint32 height); ~Texture(); - MCORE_INLINE uint32 GetHeight() const { return mHeight; } - MCORE_INLINE AZ::u32 GetID() const { return mTexture; } - MCORE_INLINE uint32 GetWidth() const { return mWidth; } + MCORE_INLINE uint32 GetHeight() const { return m_height; } + MCORE_INLINE AZ::u32 GetID() const { return m_texture; } + MCORE_INLINE uint32 GetWidth() const { return m_width; } protected: - AZ::u32 mTexture; - uint32 mWidth; - uint32 mHeight; + AZ::u32 m_texture; + uint32 m_width; + uint32 m_height; }; @@ -56,8 +56,8 @@ namespace RenderGL void AddTexture(const char* filename, Texture* texture); Texture* FindTexture(const char* filename) const; - MCORE_INLINE Texture* GetWhiteTexture() { return mWhiteTexture; } - MCORE_INLINE Texture* GetDefaultNormalTexture() { return mDefaultNormalTexture; } + MCORE_INLINE Texture* GetWhiteTexture() { return m_whiteTexture; } + MCORE_INLINE Texture* GetDefaultNormalTexture() { return m_defaultNormalTexture; } bool CheckIfHasTexture(Texture* texture) const; bool Init(); void RemoveTexture(Texture* texture); @@ -68,13 +68,13 @@ namespace RenderGL struct Entry { - AZStd::string mName; // the search key (unique for each texture) - Texture* mTexture; + AZStd::string m_name; // the search key (unique for each texture) + Texture* m_texture; }; - MCore::Array mEntries; - Texture* mWhiteTexture; - Texture* mDefaultNormalTexture; + AZStd::vector m_entries; + Texture* m_whiteTexture; + Texture* m_defaultNormalTexture; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.cpp b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.cpp index ef062bca0b..8c1587a00e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.cpp @@ -17,15 +17,15 @@ namespace RenderGL // constructor VertexBuffer::VertexBuffer() { - mBufferID = MCORE_INVALIDINDEX32; - mNumVertices = 0; + m_bufferId = MCORE_INVALIDINDEX32; + m_numVertices = 0; } // destructor VertexBuffer::~VertexBuffer() { - glDeleteBuffers(1, &mBufferID); + glDeleteBuffers(1, &m_bufferId); glBindBuffer(GL_ARRAY_BUFFER, 0); } @@ -33,8 +33,8 @@ namespace RenderGL // activate void VertexBuffer::Activate() { - MCORE_ASSERT(mBufferID != MCORE_INVALIDINDEX32); - glBindBuffer(GL_ARRAY_BUFFER, mBufferID); + MCORE_ASSERT(m_bufferId != MCORE_INVALIDINDEX32); + glBindBuffer(GL_ARRAY_BUFFER, m_bufferId); } @@ -71,13 +71,13 @@ namespace RenderGL } // generate the buffer and bind it - glGenBuffers(1, &mBufferID); - glBindBuffer(GL_ARRAY_BUFFER, mBufferID); + glGenBuffers(1, &m_bufferId); + glBindBuffer(GL_ARRAY_BUFFER, m_bufferId); glBufferData(GL_ARRAY_BUFFER, numBytesPerVertex * numVertices, vertexData, usageGL); glBindBuffer(GL_ARRAY_BUFFER, 0); // adjust the number of vertices - mNumVertices = numVertices; + m_numVertices = numVertices; return true; } @@ -85,7 +85,7 @@ namespace RenderGL // lock the buffer void* VertexBuffer::Lock(ELockMode lockMode) { - if (mNumVertices == 0) + if (m_numVertices == 0) { return nullptr; } @@ -107,8 +107,8 @@ namespace RenderGL lockModeGL = GL_WRITE_ONLY; } - glBindBuffer(GL_ARRAY_BUFFER, mBufferID); - void* data = glMapBuffer(GL_ARRAY_BUFFER, lockModeGL); + glBindBuffer(GL_ARRAY_BUFFER, m_bufferId); + void* data = m_glMapBuffer(GL_ARRAY_BUFFER, lockModeGL); // is the data valid? if (data == nullptr) @@ -138,12 +138,12 @@ namespace RenderGL // unlock the buffer void VertexBuffer::Unlock() { - if (mNumVertices == 0) + if (m_numVertices == 0) { return; } - glBindBuffer(GL_ARRAY_BUFFER, mBufferID); + glBindBuffer(GL_ARRAY_BUFFER, m_bufferId); glUnmapBuffer(GL_ARRAY_BUFFER); glBindBuffer(GL_ARRAY_BUFFER, 0); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.h index 1579a89226..c76cf5137a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/VertexBuffer.h @@ -50,8 +50,8 @@ namespace RenderGL void Activate(); void Deactivate(); - MCORE_INLINE uint32 GetBufferID() const { return mBufferID; } - MCORE_INLINE uint32 GetNumVertices() const { return mNumVertices; } + MCORE_INLINE uint32 GetBufferID() const { return m_bufferId; } + MCORE_INLINE uint32 GetNumVertices() const { return m_numVertices; } bool Init(uint32 numBytesPerVertex, uint32 numVertices, EUsageMode usage, void* vertexData = nullptr); @@ -59,8 +59,8 @@ namespace RenderGL void Unlock(); private: - uint32 mBufferID; // the buffer ID - uint32 mNumVertices; // the number of vertices + uint32 m_bufferId; // the buffer ID + uint32 m_numVertices; // the number of vertices bool GetIsSuccess(); bool GetHasError(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h index ff20861c08..36158306a1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/glactor.h @@ -47,52 +47,52 @@ namespace RenderGL bool Init(EMotionFX::Actor* actor, const char* texturePath, bool gpuSkinning = true, bool removeGPUSkinnedMeshes = true); - MCORE_INLINE EMotionFX::Actor* GetActor() { return mActor; } - MCORE_INLINE const AZStd::string& GetTexturePath() const { return mTexturePath; } + MCORE_INLINE EMotionFX::Actor* GetActor() { return m_actor; } + MCORE_INLINE const AZStd::string& GetTexturePath() const { return m_texturePath; } void Render(EMotionFX::ActorInstance* actorInstance, uint32 renderFlags = RENDER_LIGHTING | RENDER_TEXTURING); - const MCore::RGBAColor& GetSkyColor() const { return mSkyColor; } - const MCore::RGBAColor& GetGroundColor() const { return mGroundColor; } - void SetGroundColor(const MCore::RGBAColor& color) { mGroundColor = color; } - void SetSkyColor(const MCore::RGBAColor& color) { mSkyColor = color; } + const MCore::RGBAColor& GetSkyColor() const { return m_skyColor; } + const MCore::RGBAColor& GetGroundColor() const { return m_groundColor; } + void SetGroundColor(const MCore::RGBAColor& color) { m_groundColor = color; } + void SetSkyColor(const MCore::RGBAColor& color) { m_skyColor = color; } private: struct RENDERGL_API MaterialPrimitives { - Material* mMaterial; - MCore::Array mPrimitives[3]; + Material* m_material; + AZStd::vector m_primitives[3]; - MaterialPrimitives() { mMaterial = nullptr; mPrimitives[0].Reserve(64); mPrimitives[1].Reserve(64); mPrimitives[2].Reserve(64); } - MaterialPrimitives(Material* mat) { mMaterial = mat; mPrimitives[0].Reserve(64); mPrimitives[1].Reserve(64); mPrimitives[2].Reserve(64); } + MaterialPrimitives() { m_material = nullptr; m_primitives[0].reserve(64); m_primitives[1].reserve(64); m_primitives[2].reserve(64); } + MaterialPrimitives(Material* mat) { m_material = mat; m_primitives[0].reserve(64); m_primitives[1].reserve(64); m_primitives[2].reserve(64); } }; - AZStd::string mTexturePath; - EMotionFX::Actor* mActor; - bool mEnableGPUSkinning; + AZStd::string m_texturePath; + EMotionFX::Actor* m_actor; + bool m_enableGpuSkinning; void Cleanup(); void RenderMeshes(EMotionFX::ActorInstance* actorInstance, EMotionFX::Mesh::EMeshType meshType, uint32 renderFlags); void RenderShadowMap(EMotionFX::Mesh::EMeshType meshType); - void InitMaterials(uint32 lodLevel); + void InitMaterials(size_t lodLevel); Material* InitMaterial(EMotionFX::Material* emfxMaterial); - void FillIndexBuffers(uint32 lodLevel); - void FillStaticVertexBuffers(uint32 lodLevel); - void FillGPUSkinnedVertexBuffers(uint32 lodLevel); + void FillIndexBuffers(size_t lodLevel); + void FillStaticVertexBuffers(size_t lodLevel); + void FillGPUSkinnedVertexBuffers(size_t lodLevel); void UpdateDynamicVertices(EMotionFX::ActorInstance* actorInstance); - EMotionFX::Mesh::EMeshType ClassifyMeshType(EMotionFX::Node* node, EMotionFX::Mesh* mesh, uint32 lodLevel); + EMotionFX::Mesh::EMeshType ClassifyMeshType(EMotionFX::Node* node, EMotionFX::Mesh* mesh, size_t lodLevel); - MCore::Array< MCore::Array > mMaterials; - MCore::Array2D mDynamicNodes; - MCore::Array2D mPrimitives[3]; - MCore::Array mHomoMaterials; - MCore::Array mVertexBuffers[3]; - MCore::Array mIndexBuffers[3]; - MCore::RGBAColor mGroundColor; - MCore::RGBAColor mSkyColor; + AZStd::vector< AZStd::vector > m_materials; + MCore::Array2D m_dynamicNodes; + MCore::Array2D m_primitives[3]; + AZStd::vector m_homoMaterials; + AZStd::vector m_vertexBuffers[3]; + AZStd::vector m_indexBuffers[3]; + MCore::RGBAColor m_groundColor; + MCore::RGBAColor m_skyColor; GLActor(); ~GLActor(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h index 25a91026f8..d33cfcfd7d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h +++ b/Gems/EMotionFX/Code/EMotionFX/Rendering/OpenGL2/Source/shadercache.h @@ -11,7 +11,7 @@ #include "Shader.h" #include -#include +#include namespace RenderGL @@ -37,12 +37,12 @@ namespace RenderGL // a cache entry struct Entry { - AZStd::string mName; // the search key (unique for each shader) - Shader* mShader; + AZStd::string m_name; // the search key (unique for each shader) + Shader* m_shader; }; // - MCore::Array mEntries; // the shader cache entries + AZStd::vector m_entries; // the shader cache entries }; } // namespace RenderGL diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index a6368ac088..df039b7186 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -42,7 +42,6 @@ #include #include #include -#include #include @@ -50,31 +49,22 @@ namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(Actor, ActorAllocator, 0) - Actor::NodeInfo::NodeInfo() - { - mOBB.Init(); - } - - Actor::LODLevel::LODLevel() - { - } - Actor::MeshLODData::MeshLODData() { // Create the default LOD level - m_lodLevels.push_back({}); + m_lodLevels.emplace_back(); } Actor::NodeLODInfo::NodeLODInfo() { - mMesh = nullptr; - mStack = nullptr; + m_mesh = nullptr; + m_stack = nullptr; } Actor::NodeLODInfo::~NodeLODInfo() { - MCore::Destroy(mMesh); - MCore::Destroy(mStack); + MCore::Destroy(m_mesh); + MCore::Destroy(m_stack); } //---------------------------------------------------- @@ -83,38 +73,33 @@ namespace EMotionFX { SetName(name); - // setup the array memory categories - mMaterials.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - mDependencies.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - mMorphSetups.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - - mSkeleton = Skeleton::Create(); + m_skeleton = Skeleton::Create(); - mMotionExtractionNode = MCORE_INVALIDINDEX32; - mRetargetRootNode = MCORE_INVALIDINDEX32; - mThreadIndex = 0; - mCustomData = nullptr; - mID = MCore::GetIDGenerator().GenerateID(); - mUnitType = GetEMotionFX().GetUnitType(); - mFileUnitType = mUnitType; + m_motionExtractionNode = InvalidIndex; + m_retargetRootNode = InvalidIndex; + m_threadIndex = 0; + m_customData = nullptr; + m_id = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); + m_unitType = GetEMotionFX().GetUnitType(); + m_fileUnitType = m_unitType; + m_staticAabb = AZ::Aabb::CreateNull(); - mUsedForVisualization = false; - mDirtyFlag = false; + m_usedForVisualization = false; + m_dirtyFlag = false; m_physicsSetup = AZStd::make_shared(); m_simulatedObjectSetup = AZStd::make_shared(this); m_optimizeSkeleton = false; #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = false; + m_isOwnedByRuntime = false; #endif // EMFX_DEVELOPMENT_BUILD // make sure we have at least allocated the first LOD of materials and facial setups - mMaterials.Reserve(4); // reserve space for 4 lods - mMorphSetups.Reserve(4); // - mMaterials.AddEmpty(); - mMaterials[0].SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - mMorphSetups.Add(nullptr); + m_materials.reserve(4); // reserve space for 4 lods + m_morphSetups.reserve(4); // + m_materials.emplace_back(); + m_morphSetups.emplace_back(nullptr); GetEventManager().OnCreateActor(this); ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorCreated, this); @@ -125,15 +110,15 @@ namespace EMotionFX ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnActorDestroyed, this); GetEventManager().OnDeleteActor(this); - mNodeMirrorInfos.Clear(true); + m_nodeMirrorInfos.clear(); RemoveAllMaterials(); RemoveAllMorphSetups(); RemoveAllNodeGroups(); - mInvBindPoseTransforms.clear(); + m_invBindPoseTransforms.clear(); - MCore::Destroy(mSkeleton); + MCore::Destroy(m_skeleton); } // creates a clone of the actor (a copy). @@ -145,50 +130,41 @@ namespace EMotionFX result->SetFileName(GetFileName()); // copy the actor attributes - result->mMotionExtractionNode = mMotionExtractionNode; - result->mUnitType = mUnitType; - result->mFileUnitType = mFileUnitType; - result->mStaticAABB = mStaticAABB; - result->mRetargetRootNode = mRetargetRootNode; - result->mInvBindPoseTransforms = mInvBindPoseTransforms; + result->m_motionExtractionNode = m_motionExtractionNode; + result->m_unitType = m_unitType; + result->m_fileUnitType = m_fileUnitType; + result->m_staticAabb = m_staticAabb; + result->m_retargetRootNode = m_retargetRootNode; + result->m_invBindPoseTransforms = m_invBindPoseTransforms; result->m_optimizeSkeleton = m_optimizeSkeleton; result->m_skinToSkeletonIndexMap = m_skinToSkeletonIndexMap; result->RecursiveAddDependencies(this); // clone all nodes groups - for (uint32 i = 0; i < mNodeGroups.GetLength(); ++i) + for (uint32 i = 0; i < m_nodeGroups.GetLength(); ++i) { - result->AddNodeGroup(aznew NodeGroup(*mNodeGroups[i])); + result->AddNodeGroup(aznew NodeGroup(*m_nodeGroups[i])); } // clone the materials - result->mMaterials.Resize(mMaterials.GetLength()); - for (uint32 i = 0; i < mMaterials.GetLength(); ++i) + result->m_materials.resize(m_materials.size()); + for (size_t i = 0; i < m_materials.size(); ++i) { // get the number of materials in the current LOD - const uint32 numMaterials = mMaterials[i].GetLength(); - result->mMaterials[i].Reserve(numMaterials); - for (uint32 m = 0; m < numMaterials; ++m) + result->m_materials[i].reserve(m_materials[i].size()); + for (const Material* material : m_materials[i]) { - // retrieve the current material - Material* material = mMaterials[i][m]; - - // clone the material - Material* clone = material->Clone(); - - // add the cloned material to the cloned actor - result->AddMaterial(i, clone); + result->AddMaterial(i, material->Clone()); } } // clone the skeleton - MCore::Destroy(result->mSkeleton); - result->mSkeleton = mSkeleton->Clone(); + MCore::Destroy(result->m_skeleton); + result->m_skeleton = m_skeleton->Clone(); // clone lod data - result->mNodeInfos = mNodeInfos; - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); const size_t numLodLevels = m_meshLodData.m_lodLevels.size(); MeshLODData& resultMeshLodData = result->m_meshLodData; @@ -196,26 +172,26 @@ namespace EMotionFX result->SetNumLODLevels(static_cast(numLodLevels)); for (size_t lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) { - const MCore::Array& nodeInfos = m_meshLodData.m_lodLevels[lodLevel].mNodeInfos; - MCore::Array& resultNodeInfos = resultMeshLodData.m_lodLevels[lodLevel].mNodeInfos; + const AZStd::vector& nodeInfos = m_meshLodData.m_lodLevels[lodLevel].m_nodeInfos; + AZStd::vector& resultNodeInfos = resultMeshLodData.m_lodLevels[lodLevel].m_nodeInfos; - resultNodeInfos.Resize(numNodes); - for (uint32 n = 0; n < numNodes; ++n) + resultNodeInfos.resize(numNodes); + for (size_t n = 0; n < numNodes; ++n) { NodeLODInfo& resultNodeInfo = resultNodeInfos[n]; const NodeLODInfo& sourceNodeInfo = nodeInfos[n]; - resultNodeInfo.mMesh = (sourceNodeInfo.mMesh) ? sourceNodeInfo.mMesh->Clone() : nullptr; - resultNodeInfo.mStack = (sourceNodeInfo.mStack) ? sourceNodeInfo.mStack->Clone(resultNodeInfo.mMesh) : nullptr; + resultNodeInfo.m_mesh = (sourceNodeInfo.m_mesh) ? sourceNodeInfo.m_mesh->Clone() : nullptr; + resultNodeInfo.m_stack = (sourceNodeInfo.m_stack) ? sourceNodeInfo.m_stack->Clone(resultNodeInfo.m_mesh) : nullptr; } } // clone the morph setups - result->mMorphSetups.Resize(mMorphSetups.GetLength()); - for (uint32 i = 0; i < mMorphSetups.GetLength(); ++i) + result->m_morphSetups.resize(m_morphSetups.size()); + for (size_t i = 0; i < m_morphSetups.size(); ++i) { - if (mMorphSetups[i]) + if (m_morphSetups[i]) { - result->SetMorphSetup(i, mMorphSetups[i]->Clone()); + result->SetMorphSetup(i, m_morphSetups[i]->Clone()); } else { @@ -224,12 +200,12 @@ namespace EMotionFX } // make sure the number of root nodes is still the same - MCORE_ASSERT(result->GetSkeleton()->GetNumRootNodes() == mSkeleton->GetNumRootNodes()); + MCORE_ASSERT(result->GetSkeleton()->GetNumRootNodes() == m_skeleton->GetNumRootNodes()); // copy the transform data result->CopyTransformsFrom(this); - result->mNodeMirrorInfos = mNodeMirrorInfos; + result->m_nodeMirrorInfos = m_nodeMirrorInfos; result->m_physicsSetup = m_physicsSetup; result->SetSimulatedObjectSetup(m_simulatedObjectSetup->Clone(result.get())); @@ -246,42 +222,38 @@ namespace EMotionFX // init node mirror info void Actor::AllocateNodeMirrorInfos() { - const uint32 numNodes = mSkeleton->GetNumNodes(); - mNodeMirrorInfos.Resize(numNodes); + const size_t numNodes = m_skeleton->GetNumNodes(); + m_nodeMirrorInfos.resize(numNodes); // init the data - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { - mNodeMirrorInfos[i].mSourceNode = static_cast(i); - mNodeMirrorInfos[i].mAxis = MCORE_INVALIDINDEX8; - mNodeMirrorInfos[i].mFlags = 0; + m_nodeMirrorInfos[i].m_sourceNode = static_cast(i); + m_nodeMirrorInfos[i].m_axis = MCORE_INVALIDINDEX8; + m_nodeMirrorInfos[i].m_flags = 0; } } // remove the node mirror info void Actor::RemoveNodeMirrorInfos() { - mNodeMirrorInfos.Clear(true); + m_nodeMirrorInfos.clear(); + m_nodeMirrorInfos.shrink_to_fit(); } // check if we have our axes detected bool Actor::GetHasMirrorAxesDetected() const { - if (mNodeMirrorInfos.GetLength() == 0) + if (m_nodeMirrorInfos.empty()) { return false; } - for (uint32 i = 0; i < mNodeMirrorInfos.GetLength(); ++i) + return AZStd::all_of(begin(m_nodeMirrorInfos), end(m_nodeMirrorInfos), [](const NodeMirrorInfo& nodeMirrorInfo) { - if (mNodeMirrorInfos[i].mAxis == MCORE_INVALIDINDEX8) - { - return false; - } - } - - return true; + return nodeMirrorInfo.m_axis != MCORE_INVALIDINDEX8; + }); } @@ -289,17 +261,16 @@ namespace EMotionFX void Actor::RemoveAllMaterials() { // for all LODs - for (uint32 i = 0; i < mMaterials.GetLength(); ++i) + for (AZStd::vector& materials : m_materials) { // delete all materials - const uint32 numMats = mMaterials[i].GetLength(); - for (uint32 m = 0; m < numMats; ++m) + for (Material* material : materials) { - mMaterials[i][m]->Destroy(); + material->Destroy(); } } - mMaterials.Clear(); + m_materials.clear(); } @@ -310,9 +281,8 @@ namespace EMotionFX lodLevels.emplace_back(); LODLevel& newLOD = lodLevels.back(); - const uint32 numNodes = mSkeleton->GetNumNodes(); - newLOD.mNodeInfos.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - newLOD.mNodeInfos.Resize(numNodes); + const size_t numNodes = m_skeleton->GetNumNodes(); + newLOD.m_nodeInfos.resize(numNodes); const size_t numLODs = lodLevels.size(); const size_t lodIndex = numLODs - 1; @@ -320,26 +290,25 @@ namespace EMotionFX // get the number of nodes, iterate through them, create a new LOD level and copy over the meshes from the last LOD level for (size_t i = 0; i < numNodes; ++i) { - NodeLODInfo& newLODInfo = lodLevels[lodIndex].mNodeInfos[static_cast(i)]; + NodeLODInfo& newLODInfo = lodLevels[lodIndex].m_nodeInfos[static_cast(i)]; if (copyFromLastLODLevel && lodIndex > 0) { - const NodeLODInfo& prevLODInfo = lodLevels[lodIndex - 1].mNodeInfos[static_cast(i)]; - newLODInfo.mMesh = (prevLODInfo.mMesh) ? prevLODInfo.mMesh->Clone() : nullptr; - newLODInfo.mStack = (prevLODInfo.mStack) ? prevLODInfo.mStack->Clone(newLODInfo.mMesh) : nullptr; + const NodeLODInfo& prevLODInfo = lodLevels[lodIndex - 1].m_nodeInfos[static_cast(i)]; + newLODInfo.m_mesh = (prevLODInfo.m_mesh) ? prevLODInfo.m_mesh->Clone() : nullptr; + newLODInfo.m_stack = (prevLODInfo.m_stack) ? prevLODInfo.m_stack->Clone(newLODInfo.m_mesh) : nullptr; } else { - newLODInfo.mMesh = nullptr; - newLODInfo.mStack = nullptr; + newLODInfo.m_mesh = nullptr; + newLODInfo.m_stack = nullptr; } } // create a new material array for the new LOD level - mMaterials.Resize(static_cast(lodLevels.size())); - mMaterials[static_cast(lodIndex)].SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); + m_materials.resize(lodLevels.size()); // create an empty morph setup for the new LOD level - mMorphSetups.Add(nullptr); + m_morphSetups.emplace_back(nullptr); // copy data from the previous LOD level if wanted if (copyFromLastLODLevel && numLODs > 0) @@ -349,35 +318,33 @@ namespace EMotionFX } // insert a LOD level at a given position - void Actor::InsertLODLevel(uint32 insertAt) + void Actor::InsertLODLevel(size_t insertAt) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; - lodLevels.insert(lodLevels.begin()+insertAt, {}); + lodLevels.emplace(lodLevels.begin()+insertAt); LODLevel& newLOD = lodLevels[insertAt]; - const uint32 lodIndex = insertAt; - const uint32 numNodes = mSkeleton->GetNumNodes(); - newLOD.mNodeInfos.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - newLOD.mNodeInfos.Resize(numNodes); + const size_t lodIndex = insertAt; + const size_t numNodes = m_skeleton->GetNumNodes(); + newLOD.m_nodeInfos.resize(numNodes); // get the number of nodes, iterate through them, create a new LOD level and copy over the meshes from the last LOD level - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { - NodeLODInfo& lodInfo = lodLevels[lodIndex].mNodeInfos[i]; - lodInfo.mMesh = nullptr; - lodInfo.mStack = nullptr; + NodeLODInfo& lodInfo = lodLevels[lodIndex].m_nodeInfos[i]; + lodInfo.m_mesh = nullptr; + lodInfo.m_stack = nullptr; } // create a new material array for the new LOD level - mMaterials.Insert(insertAt); - mMaterials[lodIndex].SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); + m_materials.emplace(AZStd::next(begin(m_materials), insertAt)); // create an empty morph setup for the new LOD level - mMorphSetups.Insert(insertAt, nullptr); + m_morphSetups.emplace(AZStd::next(begin(m_morphSetups), insertAt), nullptr); } // replace existing LOD level with the current actor - void Actor::CopyLODLevel(Actor* copyActor, uint32 copyLODLevel, uint32 replaceLODLevel, bool copySkeletalLODFlags) + void Actor::CopyLODLevel(Actor* copyActor, size_t copyLODLevel, size_t replaceLODLevel, bool copySkeletalLODFlags) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; AZStd::vector& copyLodLevels = copyActor->m_meshLodData.m_lodLevels; @@ -385,10 +352,10 @@ namespace EMotionFX const LODLevel& sourceLOD = copyLodLevels[copyLODLevel]; LODLevel& targetLOD = lodLevels[replaceLODLevel]; - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - Node* node = mSkeleton->GetNode(i); + Node* node = m_skeleton->GetNode(i); Node* copyNode = copyActor->GetSkeleton()->FindNodeByID(node->GetID()); if (copyNode == nullptr) @@ -396,28 +363,28 @@ namespace EMotionFX MCore::LogWarning("Actor::CopyLODLevel() - Failed to find node '%s' in the actor we want to copy from.", node->GetName()); } - const NodeLODInfo& sourceNodeInfo = sourceLOD.mNodeInfos[ copyNode->GetNodeIndex() ]; - NodeLODInfo& targetNodeInfo = targetLOD.mNodeInfos[i]; + const NodeLODInfo& sourceNodeInfo = sourceLOD.m_nodeInfos[ copyNode->GetNodeIndex() ]; + NodeLODInfo& targetNodeInfo = targetLOD.m_nodeInfos[i]; // first get rid of existing data - MCore::Destroy(targetNodeInfo.mMesh); - targetNodeInfo.mMesh = nullptr; - MCore::Destroy(targetNodeInfo.mStack); - targetNodeInfo.mStack = nullptr; + MCore::Destroy(targetNodeInfo.m_mesh); + targetNodeInfo.m_mesh = nullptr; + MCore::Destroy(targetNodeInfo.m_stack); + targetNodeInfo.m_stack = nullptr; // if the node exists in both models if (copyNode) { // copy over the mesh and collision mesh - if (sourceNodeInfo.mMesh) + if (sourceNodeInfo.m_mesh) { - targetNodeInfo.mMesh = sourceNodeInfo.mMesh->Clone(); + targetNodeInfo.m_mesh = sourceNodeInfo.m_mesh->Clone(); } // handle the stacks - if (sourceNodeInfo.mStack) + if (sourceNodeInfo.m_stack) { - targetNodeInfo.mStack = sourceNodeInfo.mStack->Clone(targetNodeInfo.mMesh); + targetNodeInfo.m_stack = sourceNodeInfo.m_stack->Clone(targetNodeInfo.m_mesh); } // copy the skeletal LOD flag @@ -429,84 +396,77 @@ namespace EMotionFX } // copy the materials - const uint32 numMaterials = copyActor->GetNumMaterials(copyLODLevel); - for (uint32 i = 0; i < mMaterials[replaceLODLevel].GetLength(); ++i) + const size_t numMaterials = copyActor->GetNumMaterials(copyLODLevel); + for (Material* i : m_materials[replaceLODLevel]) { - mMaterials[replaceLODLevel][i]->Destroy(); + i->Destroy(); } - mMaterials[replaceLODLevel].Clear(); - mMaterials[replaceLODLevel].Reserve(numMaterials); - for (uint32 i = 0; i < numMaterials; ++i) + m_materials[replaceLODLevel].clear(); + m_materials[replaceLODLevel].reserve(numMaterials); + for (size_t i = 0; i < numMaterials; ++i) { AddMaterial(replaceLODLevel, copyActor->GetMaterial(copyLODLevel, i)->Clone()); } // copy the morph setup - if (mMorphSetups[replaceLODLevel]) + if (m_morphSetups[replaceLODLevel]) { - mMorphSetups[replaceLODLevel]->Destroy(); + m_morphSetups[replaceLODLevel]->Destroy(); } if (copyActor->GetMorphSetup(copyLODLevel)) { - mMorphSetups[replaceLODLevel] = copyActor->GetMorphSetup(copyLODLevel)->Clone(); + m_morphSetups[replaceLODLevel] = copyActor->GetMorphSetup(copyLODLevel)->Clone(); } else { - mMorphSetups[replaceLODLevel] = nullptr; + m_morphSetups[replaceLODLevel] = nullptr; } } // preallocate memory for all LOD levels - void Actor::SetNumLODLevels(uint32 numLODs, bool adjustMorphSetup) + void Actor::SetNumLODLevels(size_t numLODs, bool adjustMorphSetup) { m_meshLodData.m_lodLevels.resize(numLODs); // reserve space for the materials - mMaterials.Resize(numLODs); - for (uint32 i = 0; i < numLODs; ++i) - { - mMaterials[i].SetMemoryCategory(EMFX_MEMCATEGORY_ACTORS); - } + m_materials.resize(numLODs); if (adjustMorphSetup) { - mMorphSetups.Resize(numLODs); - for (uint32 i = 0; i < numLODs; ++i) - { - mMorphSetups[i] = nullptr; - } + m_morphSetups.resize(numLODs); + AZStd::fill(begin(m_morphSetups), AZStd::next(begin(m_morphSetups), numLODs), nullptr); } } // removes all node meshes and stacks void Actor::RemoveAllNodeMeshes() { - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { - NodeLODInfo& info = lodLevel.mNodeInfos[i]; - MCore::Destroy(info.mMesh); - info.mMesh = nullptr; - MCore::Destroy(info.mStack); - info.mStack = nullptr; + NodeLODInfo& info = lodLevel.m_nodeInfos[i]; + MCore::Destroy(info.m_mesh); + info.m_mesh = nullptr; + MCore::Destroy(info.m_stack); + info.m_stack = nullptr; } } } - void Actor::CalcMeshTotals(uint32 lodLevel, uint32* outNumPolygons, uint32* outNumVertices, uint32* outNumIndices) const + void Actor::CalcMeshTotals(size_t lodLevel, uint32* outNumPolygons, uint32* outNumVertices, uint32* outNumIndices) const { uint32 totalPolys = 0; uint32 totalVerts = 0; uint32 totalIndices = 0; - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); if (!mesh) @@ -536,15 +496,15 @@ namespace EMotionFX } - void Actor::CalcStaticMeshTotals(uint32 lodLevel, uint32* outNumVertices, uint32* outNumIndices) + void Actor::CalcStaticMeshTotals(size_t lodLevel, uint32* outNumVertices, uint32* outNumIndices) { // the totals uint32 totalVerts = 0; uint32 totalIndices = 0; // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -580,15 +540,15 @@ namespace EMotionFX } - void Actor::CalcDeformableMeshTotals(uint32 lodLevel, uint32* outNumVertices, uint32* outNumIndices) + void Actor::CalcDeformableMeshTotals(size_t lodLevel, uint32* outNumVertices, uint32* outNumIndices) { // the totals uint32 totalVerts = 0; uint32 totalIndices = 0; // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); @@ -624,12 +584,12 @@ namespace EMotionFX } - uint32 Actor::CalcMaxNumInfluences(uint32 lodLevel) const + size_t Actor::CalcMaxNumInfluences(size_t lodLevel) const { - uint32 maxInfluences = 0; + size_t maxInfluences = 0; - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); if (!mesh) @@ -637,7 +597,7 @@ namespace EMotionFX continue; } - maxInfluences = MCore::Max(maxInfluences, mesh->CalcMaxNumInfluences()); + maxInfluences = AZStd::max(maxInfluences, mesh->CalcMaxNumInfluences()); } return maxInfluences; @@ -645,27 +605,25 @@ namespace EMotionFX // verify if the skinning will look correctly in the given geometry LOD for a given skeletal LOD level - void Actor::VerifySkinning(MCore::Array& conflictNodeFlags, uint32 skeletalLODLevel, uint32 geometryLODLevel) + void Actor::VerifySkinning(AZStd::vector& conflictNodeFlags, size_t skeletalLODLevel, size_t geometryLODLevel) { - uint32 n; - // get the number of nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t numNodes = m_skeleton->GetNumNodes(); // check if the conflict node flag array's size is set to the number of nodes inside the actor - if (conflictNodeFlags.GetLength() != numNodes) + if (conflictNodeFlags.size() != numNodes) { - conflictNodeFlags.Resize(numNodes); + conflictNodeFlags.resize(numNodes); } // reset the conflict node array to zero which means we don't have any conflicting nodes yet - MCore::MemSet(conflictNodeFlags.GetPtr(), 0, numNodes * sizeof(int8)); + MCore::MemSet(conflictNodeFlags.data(), 0, numNodes * sizeof(int8)); // iterate over the all nodes in the actor - for (n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { // get the current node and the pointer to the mesh for the given lod level - Node* node = mSkeleton->GetNode(n); + Node* node = m_skeleton->GetNode(n); Mesh* mesh = GetMesh(geometryLODLevel, n); // skip nodes without meshes @@ -704,21 +662,17 @@ namespace EMotionFX } - uint32 Actor::CalcMaxNumInfluences(uint32 lodLevel, AZStd::vector& outVertexCounts) const + size_t Actor::CalcMaxNumInfluences(size_t lodLevel, AZStd::vector& outVertexCounts) const { - uint32 maxInfluences = 0; - // Reset the values. outVertexCounts.resize(CalcMaxNumInfluences(lodLevel) + 1); - for (size_t k = 0; k < outVertexCounts.size(); ++k) - { - outVertexCounts[k] = 0; - } + AZStd::fill(begin(outVertexCounts), end(outVertexCounts), 0); // Get the vertex counts for the influences. (e.g. 500 vertices have 1 skinning influence, 300 vertices have 2 skinning influences etc.) - AZStd::vector meshVertexCounts; - const uint32 numNodes = GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + size_t maxInfluences = 0; + AZStd::vector meshVertexCounts; + const size_t numNodes = GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lodLevel, i); if (!mesh) @@ -726,8 +680,8 @@ namespace EMotionFX continue; } - const uint32 meshMaxInfluences = mesh->CalcMaxNumInfluences(meshVertexCounts); - maxInfluences = MCore::Max(maxInfluences, meshMaxInfluences); + const size_t meshMaxInfluences = mesh->CalcMaxNumInfluences(meshVertexCounts); + maxInfluences = AZStd::max(maxInfluences, meshMaxInfluences); for (size_t j = 0; j < meshVertexCounts.size(); ++j) { @@ -739,11 +693,11 @@ namespace EMotionFX } // check if there is any mesh available - bool Actor::CheckIfHasMeshes(uint32 lodLevel) const + bool Actor::CheckIfHasMeshes(size_t lodLevel) const { // check if any of the nodes has a mesh - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { if (GetMesh(lodLevel, i)) { @@ -756,10 +710,10 @@ namespace EMotionFX } - bool Actor::CheckIfHasSkinnedMeshes(AZ::u32 lodLevel) const + bool Actor::CheckIfHasSkinnedMeshes(size_t lodLevel) const { - const AZ::u32 numNodes = mSkeleton->GetNumNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { const Mesh* mesh = GetMesh(lodLevel, i); if (mesh && mesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID)) @@ -791,31 +745,29 @@ namespace EMotionFX // remove all morph setups void Actor::RemoveAllMorphSetups(bool deleteMeshDeformers) { - uint32 i; - // get the number of lod levels - const uint32 numLODs = GetNumLODLevels(); + const size_t numLODs = GetNumLODLevels(); // for all LODs, get rid of all the morph setups for each geometry LOD - for (i = 0; i < mMorphSetups.GetLength(); ++i) + for (MorphSetup* morphSetup : m_morphSetups) { - if (mMorphSetups[i]) + if (morphSetup) { - mMorphSetups[i]->Destroy(); + morphSetup->Destroy(); } - mMorphSetups[i] = nullptr; + morphSetup = nullptr; } // remove all modifiers from the stacks for each lod in all nodes if (deleteMeshDeformers) { // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // process all LOD levels - for (uint32 lod = 0; lod < numLODs; ++lod) + for (size_t lod = 0; lod < numLODs; ++lod) { // if we have a modifier stack MeshDeformerStack* stack = GetMeshDeformerStack(lod, i); @@ -839,7 +791,7 @@ namespace EMotionFX // check if the material is used by the given mesh - bool Actor::CheckIfIsMaterialUsed(Mesh* mesh, uint32 materialIndex) const + bool Actor::CheckIfIsMaterialUsed(Mesh* mesh, size_t materialIndex) const { // check if the mesh is valid if (mesh == nullptr) @@ -848,8 +800,8 @@ namespace EMotionFX } // iterate through the submeshes - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t s = 0; s < numSubMeshes; ++s) { // if the submesh material index is the same as the material index we search for, then it is being used if (mesh->GetSubMesh(s)->GetMaterial() == materialIndex) @@ -863,21 +815,17 @@ namespace EMotionFX // check if the material is used by a mesh of this actor - bool Actor::CheckIfIsMaterialUsed(uint32 lodLevel, uint32 index) const + bool Actor::CheckIfIsMaterialUsed(size_t lodLevel, size_t index) const { // iterate through all nodes of the actor and check its meshes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // if the mesh is in LOD range check if it uses the material if (CheckIfIsMaterialUsed(GetMesh(lodLevel, i), index)) { return true; } - - // same for the collision mesh - //if (CheckIfIsMaterialUsed( GetCollisionMesh(lodLevel, i), index )) - //return true; } // return false, this means that no mesh uses the given material @@ -886,13 +834,13 @@ namespace EMotionFX // remove the given material and reassign all material numbers of the submeshes - void Actor::RemoveMaterial(uint32 lodLevel, uint32 index) + void Actor::RemoveMaterial(size_t lodLevel, size_t index) { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); + MCORE_ASSERT(lodLevel < m_materials.size()); // first of all remove the given material - mMaterials[lodLevel][index]->Destroy(); - mMaterials[lodLevel].Remove(index); + m_materials[lodLevel][index]->Destroy(); + m_materials[lodLevel].erase(AZStd::next(begin(m_materials[lodLevel]), index)); } @@ -903,17 +851,17 @@ namespace EMotionFX // the maximum number of children of a root node, the node with the most children // will become our repositioning node - uint32 maxNumChilds = 0; + size_t maxNumChilds = 0; // traverse through all root nodes - const uint32 numRootNodes = mSkeleton->GetNumRootNodes(); - for (uint32 i = 0; i < numRootNodes; ++i) + const size_t numRootNodes = m_skeleton->GetNumRootNodes(); + for (size_t i = 0; i < numRootNodes; ++i) { // get the given root node from the actor - Node* rootNode = mSkeleton->GetNode(mSkeleton->GetRootNodeIndex(i)); + Node* rootNode = m_skeleton->GetNode(m_skeleton->GetRootNodeIndex(i)); // get the number of child nodes recursively - const uint32 numChildNodes = rootNode->GetNumChildNodesRecursive(); + const size_t numChildNodes = rootNode->GetNumChildNodesRecursive(); // if the number of child nodes of this node is bigger than the current max number // this is our new candidate for the repositioning node @@ -936,14 +884,14 @@ namespace EMotionFX // extract a bone list - void Actor::ExtractBoneList(uint32 lodLevel, MCore::Array* outBoneList) const + void Actor::ExtractBoneList(size_t lodLevel, AZStd::vector* outBoneList) const { // clear the existing items - outBoneList->Clear(); + outBoneList->clear(); // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { Mesh* mesh = GetMesh(lodLevel, n); @@ -965,16 +913,16 @@ namespace EMotionFX for (uint32 v = 0; v < numOrgVerts; ++v) { // for all influences for this vertex - const uint32 numInfluences = aznumeric_cast(skinningLayer->GetNumInfluences(v)); - for (uint32 i = 0; i < numInfluences; ++i) + const size_t numInfluences = skinningLayer->GetNumInfluences(v); + for (size_t i = 0; i < numInfluences; ++i) { // get the node number of the bone - uint32 nodeNr = skinningLayer->GetInfluence(v, i)->GetNodeNr(); + uint16 nodeNr = skinningLayer->GetInfluence(v, i)->GetNodeNr(); // check if it is already in the bone list, if not, add it - if (outBoneList->Contains(nodeNr) == false) + if (AZStd::find(begin(*outBoneList), end(*outBoneList), nodeNr) == end(*outBoneList)) { - outBoneList->Add(nodeNr); + outBoneList->emplace_back(nodeNr); } } } @@ -986,38 +934,26 @@ namespace EMotionFX void Actor::RecursiveAddDependencies(const Actor* actor) { // process all dependencies of the given actor - const uint32 numDependencies = actor->GetNumDependencies(); - for (uint32 i = 0; i < numDependencies; ++i) + const size_t numDependencies = actor->GetNumDependencies(); + for (size_t i = 0; i < numDependencies; ++i) { // add it to the actor instance - mDependencies.Add(*actor->GetDependency(i)); + m_dependencies.emplace_back(*actor->GetDependency(i)); // recursive into the actor we are dependent on - RecursiveAddDependencies(actor->GetDependency(i)->mActor); - } - } - - // update the bounding volumes - void Actor::UpdateNodeBindPoseOBBs(uint32 lodLevel) - { - // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) - { - CalcOBBFromBindPose(lodLevel, i); + RecursiveAddDependencies(actor->GetDependency(i)->m_actor); } } - // remove all node groups void Actor::RemoveAllNodeGroups() { - const uint32 numGroups = mNodeGroups.GetLength(); + const uint32 numGroups = m_nodeGroups.GetLength(); for (uint32 i = 0; i < numGroups; ++i) { - delete mNodeGroups[i]; + delete m_nodeGroups[i]; } - mNodeGroups.Clear(); + m_nodeGroups.Clear(); } @@ -1030,11 +966,11 @@ namespace EMotionFX AZStd::string nameB; // search through all nodes to find the best match - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { // get the node name - const char* name = mSkeleton->GetNode(n)->GetName(); + const char* name = m_skeleton->GetNode(n)->GetName(); // check if a substring appears inside this node's name if (strstr(name, subStringB)) @@ -1087,28 +1023,28 @@ namespace EMotionFX bool Actor::MapNodeMotionSource(const char* sourceNodeName, const char* destNodeName) { // find the source node index - const uint32 sourceNodeIndex = mSkeleton->FindNodeByNameNoCase(sourceNodeName)->GetNodeIndex(); - if (sourceNodeIndex == MCORE_INVALIDINDEX32) + const size_t sourceNodeIndex = m_skeleton->FindNodeByNameNoCase(sourceNodeName)->GetNodeIndex(); + if (sourceNodeIndex == InvalidIndex) { return false; } // find the dest node index - const uint32 destNodeIndex = mSkeleton->FindNodeByNameNoCase(destNodeName)->GetNodeIndex(); - if (destNodeIndex == MCORE_INVALIDINDEX32) + const size_t destNodeIndex = m_skeleton->FindNodeByNameNoCase(destNodeName)->GetNodeIndex(); + if (destNodeIndex == InvalidIndex) { return false; } // allocate the data if we haven't already - if (mNodeMirrorInfos.GetLength() == 0) + if (m_nodeMirrorInfos.empty()) { AllocateNodeMirrorInfos(); } // apply the mapping - mNodeMirrorInfos[ destNodeIndex ].mSourceNode = static_cast(sourceNodeIndex); - mNodeMirrorInfos[ sourceNodeIndex ].mSourceNode = static_cast(destNodeIndex); + m_nodeMirrorInfos[ destNodeIndex ].m_sourceNode = static_cast(sourceNodeIndex); + m_nodeMirrorInfos[ sourceNodeIndex ].m_sourceNode = static_cast(destNodeIndex); // we succeeded, because both source and dest have been found return true; @@ -1119,14 +1055,14 @@ namespace EMotionFX bool Actor::MapNodeMotionSource(uint16 sourceNodeIndex, uint16 targetNodeIndex) { // allocate the data if we haven't already - if (mNodeMirrorInfos.GetLength() == 0) + if (m_nodeMirrorInfos.empty()) { AllocateNodeMirrorInfos(); } // apply the mapping - mNodeMirrorInfos[ targetNodeIndex ].mSourceNode = static_cast(sourceNodeIndex); - mNodeMirrorInfos[ sourceNodeIndex ].mSourceNode = static_cast(targetNodeIndex); + m_nodeMirrorInfos[ targetNodeIndex ].m_sourceNode = static_cast(sourceNodeIndex); + m_nodeMirrorInfos[ sourceNodeIndex ].m_sourceNode = static_cast(targetNodeIndex); // we succeeded, because both source and dest have been found return true; @@ -1139,10 +1075,10 @@ namespace EMotionFX void Actor::MatchNodeMotionSources(const char* subStringA, const char* subStringB) { // try to map all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - Node* node = mSkeleton->GetNode(i); + Node* node = m_skeleton->GetNode(i); // find the best match const uint16 bestIndex = FindBestMatchForNode(node->GetName(), subStringA, subStringB); @@ -1150,8 +1086,8 @@ namespace EMotionFX // if a best match has been found if (bestIndex != MCORE_INVALIDINDEX16) { - MCore::LogDetailedInfo("%s <---> %s", node->GetName(), mSkeleton->GetNode(bestIndex)->GetName()); - MapNodeMotionSource(node->GetName(), mSkeleton->GetNode(bestIndex)->GetName()); + MCore::LogDetailedInfo("%s <---> %s", node->GetName(), m_skeleton->GetNode(bestIndex)->GetName()); + MapNodeMotionSource(node->GetName(), m_skeleton->GetNode(bestIndex)->GetName()); } } } @@ -1160,37 +1096,37 @@ namespace EMotionFX // set the name of the actor void Actor::SetName(const char* name) { - mName = name; + m_name = name; } // set the filename of the actor void Actor::SetFileName(const char* filename) { - mFileName = filename; + m_fileName = filename; } // find the first active parent node in a given skeletal LOD - uint32 Actor::FindFirstActiveParentBone(uint32 skeletalLOD, uint32 startNodeIndex) const + size_t Actor::FindFirstActiveParentBone(size_t skeletalLOD, size_t startNodeIndex) const { - uint32 curNodeIndex = startNodeIndex; + size_t curNodeIndex = startNodeIndex; do { - curNodeIndex = mSkeleton->GetNode(curNodeIndex)->GetParentIndex(); - if (curNodeIndex == MCORE_INVALIDINDEX32) + curNodeIndex = m_skeleton->GetNode(curNodeIndex)->GetParentIndex(); + if (curNodeIndex == InvalidIndex) { return curNodeIndex; } - if (mSkeleton->GetNode(curNodeIndex)->GetSkeletalLODStatus(skeletalLOD)) + if (m_skeleton->GetNode(curNodeIndex)->GetSkeletalLODStatus(skeletalLOD)) { return curNodeIndex; } - } while (curNodeIndex != MCORE_INVALIDINDEX32); + } while (curNodeIndex != InvalidIndex); - return MCORE_INVALIDINDEX32; + return InvalidIndex; } // make the geometry LOD levels compatible with the skeletal LOD levels @@ -1204,10 +1140,10 @@ namespace EMotionFX for (size_t geomLod = 0; geomLod < numGeomLODs; ++geomLod) { // for all nodes - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { - Node* node = mSkeleton->GetNode(n); + Node* node = m_skeleton->GetNode(n); // check if this node has a mesh, if not we can skip it Mesh* mesh = GetMesh(static_cast(geomLod), n); @@ -1227,8 +1163,8 @@ namespace EMotionFX const uint32* orgVertices = (uint32*)mesh->FindOriginalVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); // for all submeshes - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t s = 0; s < numSubMeshes; ++s) { SubMesh* subMesh = mesh->GetSubMesh(s); @@ -1246,11 +1182,11 @@ namespace EMotionFX { // if the bone is disabled SkinInfluence* influence = layer->GetInfluence(orgVertex, i); - if (mSkeleton->GetNode(influence->GetNodeNr())->GetSkeletalLODStatus(static_cast(geomLod)) == false) + if (m_skeleton->GetNode(influence->GetNodeNr())->GetSkeletalLODStatus(static_cast(geomLod)) == false) { // find the first parent bone that is enabled in this LOD - const uint32 newNodeIndex = FindFirstActiveParentBone(static_cast(geomLod), influence->GetNodeNr()); - if (newNodeIndex == MCORE_INVALIDINDEX32) + const size_t newNodeIndex = FindFirstActiveParentBone(geomLod, influence->GetNodeNr()); + if (newNodeIndex == InvalidIndex) { MCore::LogWarning("EMotionFX::Actor::MakeGeomLODsCompatibleWithSkeletalLODs() - Failed to find an enabled parent for node '%s' in skeletal LOD %d of actor '%s' (0x%x)", node->GetName(), geomLod, GetFileName(), this); continue; @@ -1285,17 +1221,17 @@ namespace EMotionFX // generate a path from the current node towards the root - void Actor::GenerateUpdatePathToRoot(uint32 endNodeIndex, MCore::Array& outPath) const + void Actor::GenerateUpdatePathToRoot(size_t endNodeIndex, AZStd::vector& outPath) const { - outPath.Clear(false); - outPath.Reserve(32); + outPath.clear(); + outPath.reserve(32); // start at the end effector - Node* currentNode = mSkeleton->GetNode(endNodeIndex); + Node* currentNode = m_skeleton->GetNode(endNodeIndex); while (currentNode) { // add the current node to the update list - outPath.Add(currentNode->GetNodeIndex()); + outPath.emplace_back(currentNode->GetNodeIndex()); // move up the hierarchy, towards the root and end node currentNode = currentNode->GetParentNode(); @@ -1314,18 +1250,18 @@ namespace EMotionFX } } - void Actor::SetMotionExtractionNodeIndex(uint32 nodeIndex) + void Actor::SetMotionExtractionNodeIndex(size_t nodeIndex) { - mMotionExtractionNode = nodeIndex; + m_motionExtractionNode = nodeIndex; ActorNotificationBus::Broadcast(&ActorNotificationBus::Events::OnMotionExtractionNodeChanged, this, GetMotionExtractionNode()); } Node* Actor::GetMotionExtractionNode() const { - if (mMotionExtractionNode != MCORE_INVALIDINDEX32 && - mMotionExtractionNode < mSkeleton->GetNumNodes()) + if (m_motionExtractionNode != InvalidIndex && + m_motionExtractionNode < m_skeleton->GetNumNodes()) { - return mSkeleton->GetNode(mMotionExtractionNode); + return m_skeleton->GetNode(m_motionExtractionNode); } return nullptr; @@ -1333,14 +1269,14 @@ namespace EMotionFX void Actor::ReinitializeMeshDeformers() { - const uint32 numLODLevels = GetNumLODLevels(); - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numLODLevels = GetNumLODLevels(); + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - Node* node = mSkeleton->GetNode(i); + Node* node = m_skeleton->GetNode(i); // iterate through all LOD levels - for (uint32 lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) + for (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) { // reinit the mesh deformer stacks MeshDeformerStack* stack = GetMeshDeformerStack(lodLevel, i); @@ -1352,22 +1288,21 @@ namespace EMotionFX } } - // post init - void Actor::PostCreateInit(bool makeGeomLodsCompatibleWithSkeletalLODs, bool generateOBBs, bool convertUnitType) + void Actor::PostCreateInit(bool makeGeomLodsCompatibleWithSkeletalLODs, bool convertUnitType) { - if (mThreadIndex == MCORE_INVALIDINDEX32) + if (m_threadIndex == MCORE_INVALIDINDEX32) { - mThreadIndex = 0; + m_threadIndex = 0; } // calculate the inverse bind pose matrices const Pose* bindPose = GetBindPose(); - const uint32 numNodes = mSkeleton->GetNumNodes(); - mInvBindPoseTransforms.resize(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + m_invBindPoseTransforms.resize(numNodes); + for (size_t i = 0; i < numNodes; ++i) { - mInvBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); + m_invBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); } // make sure the skinning info doesn't use any disabled bones @@ -1380,17 +1315,12 @@ namespace EMotionFX ReinitializeMeshDeformers(); // make sure our world space bind pose is updated too - if (mMorphSetups.GetLength() > 0 && mMorphSetups[0]) + if (m_morphSetups.size() > 0 && m_morphSetups[0]) { - mSkeleton->GetBindPose()->ResizeNumMorphs(mMorphSetups[0]->GetNumMorphTargets()); - } - mSkeleton->GetBindPose()->ForceUpdateFullModelSpacePose(); - mSkeleton->GetBindPose()->ZeroMorphWeights(); - - if (generateOBBs) - { - UpdateNodeBindPoseOBBs(0); + m_skeleton->GetBindPose()->ResizeNumMorphs(m_morphSetups[0]->GetNumMorphTargets()); } + m_skeleton->GetBindPose()->ForceUpdateFullModelSpacePose(); + m_skeleton->GetBindPose()->ZeroMorphWeights(); if (!GetHasMirrorInfo()) { @@ -1405,10 +1335,6 @@ namespace EMotionFX m_simulatedObjectSetup->InitAfterLoad(this); - // build the static axis aligned bounding box by creating an actor instance (needed to perform cpu skinning mesh deforms and mesh scaling etc) - // then copy it over to the actor - UpdateStaticAABB(); - // rescale all content if needed if (convertUnitType) { @@ -1520,12 +1446,16 @@ namespace EMotionFX { // Optional, not all actors have morph targets. const size_t numLODLevels = m_meshAsset->GetLodAssets().size(); - mMorphSetups.Resize(static_cast(numLODLevels)); - for (AZ::u32 i = 0; i < numLODLevels; ++i) + m_morphSetups.resize(numLODLevels); + for (size_t i = 0; i < numLODLevels; ++i) { - mMorphSetups[i] = nullptr; + m_morphSetups[i] = nullptr; } } + + // build the static axis aligned bounding box by creating an actor instance (needed to perform cpu skinning mesh deforms and mesh scaling etc) + // then copy it over to the actor + UpdateStaticAabb(); } m_isReady = true; @@ -1534,16 +1464,13 @@ namespace EMotionFX } // update the static AABB (very heavy as it has to create an actor instance, update mesh deformers, calculate the mesh based bounds etc) - void Actor::UpdateStaticAABB() + void Actor::UpdateStaticAabb() { - if (!mStaticAABB.CheckIfIsValid()) - { - ActorInstance* actorInstance = ActorInstance::Create(this, nullptr, mThreadIndex); - //actorInstance->UpdateMeshDeformers(0.0f); - //actorInstance->UpdateStaticBasedAABBDimensions(); - actorInstance->GetStaticBasedAABB(&mStaticAABB); - actorInstance->Destroy(); - } + ActorInstance* actorInstance = ActorInstance::Create(this, nullptr, m_threadIndex); + actorInstance->UpdateMeshDeformers(0.0f); + actorInstance->UpdateStaticBasedAabbDimensions(); + actorInstance->GetStaticBasedAabb(&m_staticAabb); + actorInstance->Destroy(); } @@ -1552,10 +1479,10 @@ namespace EMotionFX { outPoints.clear(); - const uint32 geomLODLevel = 0; - const uint32 numNodes = mSkeleton->GetNumNodes(); + const size_t geomLODLevel = 0; + const size_t numNodes = m_skeleton->GetNumNodes(); - for (uint32 nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) + for (size_t nodeIndex = 0; nodeIndex < numNodes; nodeIndex++) { // check if this node has a mesh, if not we can skip it Mesh* mesh = GetMesh(geomLODLevel, nodeIndex); @@ -1576,8 +1503,8 @@ namespace EMotionFX AZ::Vector3* positions = (AZ::Vector3*)mesh->FindVertexData(EMotionFX::Mesh::ATTRIB_POSITIONS); // for all submeshes - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) { SubMesh* subMesh = mesh->GetSubMesh(subMeshIndex); @@ -1589,10 +1516,10 @@ namespace EMotionFX const uint32 orgVertex = orgVertices[startVertex + vertexIndex]; // for all skinning influences of the vertex - const uint32 numInfluences = static_cast(layer->GetNumInfluences(orgVertex)); + const size_t numInfluences = layer->GetNumInfluences(orgVertex); float maxWeight = 0.0f; - uint32 maxWeightNodeIndex = 0; - for (uint32 i = 0; i < numInfluences; ++i) + size_t maxWeightNodeIndex = 0; + for (size_t i = 0; i < numInfluences; ++i) { SkinInfluence* influence = layer->GetInfluence(orgVertex, i); float weight = influence->GetWeight(); @@ -1621,17 +1548,17 @@ namespace EMotionFX Pose pose; pose.LinkToActor(this); - const uint32 numNodes = mNodeMirrorInfos.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_nodeMirrorInfos.size(); + for (size_t i = 0; i < numNodes; ++i) { - const uint16 motionSource = (GetHasMirrorInfo()) ? GetNodeMirrorInfo(i).mSourceNode : static_cast(i); + const uint16 motionSource = (GetHasMirrorInfo()) ? GetNodeMirrorInfo(i).m_sourceNode : static_cast(i); // displace the local transform a bit, and calculate its mirrored model space position pose.InitFromBindPose(this); Transform localTransform = pose.GetLocalSpaceTransform(motionSource); Transform orgDelta = Transform::CreateIdentity(); - orgDelta.mPosition.Set(1.1f, 2.2f, 3.3f); - orgDelta.mRotation = MCore::AzEulerAnglesToAzQuat(0.1f, 0.2f, 0.3f); + orgDelta.m_position.Set(1.1f, 2.2f, 3.3f); + orgDelta.m_rotation = MCore::AzEulerAnglesToAzQuat(0.1f, 0.2f, 0.3f); Transform delta = orgDelta; delta.Multiply(localTransform); pose.SetLocalSpaceTransform(motionSource, delta); @@ -1657,12 +1584,11 @@ namespace EMotionFX const Transform& modelSpaceResult = pose.GetModelSpaceTransform(i); // check if we have a matching distance in model space - const float dist = MCore::SafeLength(modelSpaceResult.mPosition - endModelSpaceTransform.mPosition); + const float dist = MCore::SafeLength(modelSpaceResult.m_position - endModelSpaceTransform.m_position); if (dist <= MCore::Math::epsilon) { - //MCore::LogInfo("%s = %f (axis=%d)", mNodes[i]->GetName(), dist, a); - mNodeMirrorInfos[i].mAxis = a; - mNodeMirrorInfos[i].mFlags = 0; + m_nodeMirrorInfos[i].m_axis = a; + m_nodeMirrorInfos[i].m_flags = 0; found = true; break; } @@ -1710,12 +1636,11 @@ namespace EMotionFX const Transform& modelSpaceResult = pose.GetModelSpaceTransform(i); // check if we have a matching distance in world space - const float dist = MCore::SafeLength(modelSpaceResult.mPosition - endModelSpaceTransform.mPosition); + const float dist = MCore::SafeLength(modelSpaceResult.m_position - endModelSpaceTransform.m_position); if (dist <= MCore::Math::epsilon) { - //MCore::LogInfo("*** %s = %f (axis=%d) (flip=%d)", mNodes[i]->GetName(), dist, a, f); - mNodeMirrorInfos[i].mAxis = a; - mNodeMirrorInfos[i].mFlags = flags; + m_nodeMirrorInfos[i].m_axis = a; + m_nodeMirrorInfos[i].m_flags = flags; found = true; break; } @@ -1738,35 +1663,31 @@ namespace EMotionFX if (found == false) { - mNodeMirrorInfos[i].mAxis = bestAxis; - mNodeMirrorInfos[i].mFlags = bestFlags; - //MCore::LogInfo("best for %s = %f (axis=%d) (flags=%d)", mNodes[i]->GetName(), minDist, bestAxis, bestFlags); + m_nodeMirrorInfos[i].m_axis = bestAxis; + m_nodeMirrorInfos[i].m_flags = bestFlags; } } - - //for (uint32 i=0; iGetName(), mNodeMirrorInfos[i].mAxis, mNodeMirrorInfos[i].mFlags); } // get the array of node mirror infos - const MCore::Array& Actor::GetNodeMirrorInfos() const + const AZStd::vector& Actor::GetNodeMirrorInfos() const { - return mNodeMirrorInfos; + return m_nodeMirrorInfos; } // get the array of node mirror infos - MCore::Array& Actor::GetNodeMirrorInfos() + AZStd::vector& Actor::GetNodeMirrorInfos() { - return mNodeMirrorInfos; + return m_nodeMirrorInfos; } // set the node mirror infos directly - void Actor::SetNodeMirrorInfos(const MCore::Array& mirrorInfos) + void Actor::SetNodeMirrorInfos(const AZStd::vector& mirrorInfos) { - mNodeMirrorInfos = mirrorInfos; + m_nodeMirrorInfos = mirrorInfos; } @@ -1776,11 +1697,9 @@ namespace EMotionFX Pose pose; pose.InitFromBindPose(this); - const uint16 numNodes = static_cast(mSkeleton->GetNumNodes()); + const uint16 numNodes = static_cast(m_skeleton->GetNumNodes()); for (uint16 i = 0; i < numNodes; ++i) { - //Node* node = mNodes[i]; - // find the best match const uint16 bestIndex = FindBestMirrorMatchForNode(i, pose); @@ -1797,7 +1716,7 @@ namespace EMotionFX // find the best matching node index uint16 Actor::FindBestMirrorMatchForNode(uint16 nodeIndex, Pose& pose) const { - if (mSkeleton->GetNode(nodeIndex)->GetIsRootNode()) + if (m_skeleton->GetNode(nodeIndex)->GetIsRootNode()) { return MCORE_INVALIDINDEX16; } @@ -1806,25 +1725,25 @@ namespace EMotionFX const Transform nodeTransform = pose.GetModelSpaceTransform(nodeIndex); const Transform mirroredTransform = nodeTransform.Mirrored(AZ::Vector3(1.0f, 0.0f, 0.0f)); - uint32 numMatches = 0; + size_t numMatches = 0; uint16 result = MCORE_INVALIDINDEX16; // find nodes that have the mirrored transform - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const Transform curNodeTransform = pose.GetModelSpaceTransform(i); + const Transform& curNodeTransform = pose.GetModelSpaceTransform(i); if (i != nodeIndex) { // only check the translation for now #ifndef EMFX_SCALE_DISABLED if (MCore::Compare::CheckIfIsClose( - curNodeTransform.mPosition, - mirroredTransform.mPosition, MCore::Math::epsilon) && - MCore::Compare::CheckIfIsClose(MCore::SafeLength(curNodeTransform.mScale), - MCore::SafeLength(mirroredTransform.mScale), MCore::Math::epsilon)) + curNodeTransform.m_position, + mirroredTransform.m_position, MCore::Math::epsilon) && + MCore::Compare::CheckIfIsClose(MCore::SafeLength(curNodeTransform.m_scale), + MCore::SafeLength(mirroredTransform.m_scale), MCore::Math::epsilon)) #else - if (MCore::Compare::CheckIfIsClose(curNodeTransform.mPosition, mirroredTransform.mPosition, MCore::Math::epsilon)) + if (MCore::Compare::CheckIfIsClose(curNodeTransform.m_position, mirroredTransform.m_position, MCore::Math::epsilon)) #endif { numMatches++; @@ -1835,8 +1754,8 @@ namespace EMotionFX if (numMatches == 1) { - const uint32 hierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(nodeIndex); - const uint32 matchingHierarchyDepth = mSkeleton->CalcHierarchyDepthForNode(result); + const size_t hierarchyDepth = m_skeleton->CalcHierarchyDepthForNode(nodeIndex); + const size_t matchingHierarchyDepth = m_skeleton->CalcHierarchyDepthForNode(result); if (hierarchyDepth != matchingHierarchyDepth) { return MCORE_INVALIDINDEX16; @@ -1852,75 +1771,73 @@ namespace EMotionFX // resize the transform arrays to the current number of nodes void Actor::ResizeTransformData() { - Pose& bindPose = *mSkeleton->GetBindPose(); + Pose& bindPose = *m_skeleton->GetBindPose(); bindPose.LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); - const AZ::u32 numMorphs = bindPose.GetNumMorphWeights(); - for (AZ::u32 i = 0; i < numMorphs; ++i) + const size_t numMorphs = bindPose.GetNumMorphWeights(); + for (size_t i = 0; i < numMorphs; ++i) { bindPose.SetMorphWeight(i, 0.0f); } - mInvBindPoseTransforms.resize(mSkeleton->GetNumNodes()); + m_invBindPoseTransforms.resize(m_skeleton->GetNumNodes()); } // release any transform data void Actor::ReleaseTransformData() { - mSkeleton->GetBindPose()->Clear(); - mInvBindPoseTransforms.clear(); + m_skeleton->GetBindPose()->Clear(); + m_invBindPoseTransforms.clear(); } // copy transforms from another actor void Actor::CopyTransformsFrom(const Actor* other) { - MCORE_ASSERT(other->GetNumNodes() == mSkeleton->GetNumNodes()); + MCORE_ASSERT(other->GetNumNodes() == m_skeleton->GetNumNodes()); ResizeTransformData(); - mInvBindPoseTransforms = other->mInvBindPoseTransforms; - *mSkeleton->GetBindPose() = *other->GetSkeleton()->GetBindPose(); + m_invBindPoseTransforms = other->m_invBindPoseTransforms; + *m_skeleton->GetBindPose() = *other->GetSkeleton()->GetBindPose(); } - void Actor::SetNumNodes(uint32 numNodes) + void Actor::SetNumNodes(size_t numNodes) { - mSkeleton->SetNumNodes(numNodes); - mNodeInfos.resize(numNodes); + m_skeleton->SetNumNodes(numNodes); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.Resize(numNodes); + lodLevel.m_nodeInfos.resize(numNodes); } - Pose* bindPose = mSkeleton->GetBindPose(); + Pose* bindPose = m_skeleton->GetBindPose(); bindPose->LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); } void Actor::AddNode(Node* node) { - mSkeleton->AddNode(node); - mSkeleton->GetBindPose()->LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); + m_skeleton->AddNode(node); + m_skeleton->GetBindPose()->LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); // initialize the LOD data - mNodeInfos.emplace_back(); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.AddEmpty(); + lodLevel.m_nodeInfos.emplace_back(); } - mSkeleton->GetBindPose()->LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); - mSkeleton->GetBindPose()->SetLocalSpaceTransform(mSkeleton->GetNumNodes() - 1, Transform::CreateIdentity()); + m_skeleton->GetBindPose()->LinkToActor(this, Pose::FLAG_LOCALTRANSFORMREADY, false); + m_skeleton->GetBindPose()->SetLocalSpaceTransform(m_skeleton->GetNumNodes() - 1, Transform::CreateIdentity()); } - Node* Actor::AddNode(uint32 nodeIndex, const char* name, uint32 parentIndex) + Node* Actor::AddNode(size_t nodeIndex, const char* name, size_t parentIndex) { Node* node = Node::Create(name, GetSkeleton()); node->SetNodeIndex(nodeIndex); node->SetParentIndex(parentIndex); AddNode(node); - if (parentIndex == MCORE_INVALIDINDEX32) + if (parentIndex == InvalidIndex) { GetSkeleton()->AddRootNode(node->GetNodeIndex()); } @@ -1931,153 +1848,138 @@ namespace EMotionFX return node; } - void Actor::RemoveNode(uint32 nr, bool delMem) + void Actor::RemoveNode(size_t nr, bool delMem) { - mSkeleton->RemoveNode(nr, delMem); - mNodeInfos.erase(mNodeInfos.begin() + nr); + m_skeleton->RemoveNode(nr, delMem); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.Remove(nr); + lodLevel.m_nodeInfos.erase(AZStd::next(begin(lodLevel.m_nodeInfos), nr)); } } void Actor::DeleteAllNodes() { - mSkeleton->RemoveAllNodes(); - mNodeInfos.clear(); + m_skeleton->RemoveAllNodes(); AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; for (LODLevel& lodLevel : lodLevels) { - lodLevel.mNodeInfos.Clear(); + lodLevel.m_nodeInfos.clear(); } } - void Actor::ReserveMaterials(uint32 lodLevel, uint32 numMaterials) + void Actor::ReserveMaterials(size_t lodLevel, size_t numMaterials) { - mMaterials[lodLevel].Reserve(numMaterials); + m_materials[lodLevel].reserve(numMaterials); } // get a material - Material* Actor::GetMaterial(uint32 lodLevel, uint32 nr) const + Material* Actor::GetMaterial(size_t lodLevel, size_t nr) const { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - MCORE_ASSERT(nr < mMaterials[lodLevel].GetLength()); - return mMaterials[lodLevel][nr]; + MCORE_ASSERT(lodLevel < m_materials.size()); + MCORE_ASSERT(nr < m_materials[lodLevel].size()); + return m_materials[lodLevel][nr]; } // get a material by name - uint32 Actor::FindMaterialIndexByName(uint32 lodLevel, const char* name) const + size_t Actor::FindMaterialIndexByName(size_t lodLevel, const char* name) const { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - // search through all materials - const uint32 numMaterials = mMaterials[lodLevel].GetLength(); - for (uint32 i = 0; i < numMaterials; ++i) + const auto foundMaterial = AZStd::find_if(m_materials[lodLevel].begin(), m_materials[lodLevel].end(), [name](const Material* material) { - if (mMaterials[lodLevel][i]->GetNameString() == name) - { - return i; - } - } - - // no material found - return MCORE_INVALIDINDEX32; + return material->GetNameString() == name; + }); + return foundMaterial != m_materials[lodLevel].end() ? AZStd::distance(m_materials[lodLevel].begin(), foundMaterial) : InvalidIndex; } // set a material - void Actor::SetMaterial(uint32 lodLevel, uint32 nr, Material* mat) + void Actor::SetMaterial(size_t lodLevel, size_t nr, Material* mat) { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - MCORE_ASSERT(nr < mMaterials[lodLevel].GetLength()); - mMaterials[lodLevel][nr] = mat; + m_materials[lodLevel][nr] = mat; } - void Actor::AddMaterial(uint32 lodLevel, Material* mat) + void Actor::AddMaterial(size_t lodLevel, Material* mat) { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - mMaterials[lodLevel].Add(mat); + m_materials[lodLevel].emplace_back(mat); } - uint32 Actor::GetNumMaterials(uint32 lodLevel) const + size_t Actor::GetNumMaterials(size_t lodLevel) const { - MCORE_ASSERT(lodLevel < mMaterials.GetLength()); - return mMaterials[lodLevel].GetLength(); + return m_materials[lodLevel].size(); } - uint32 Actor::GetNumLODLevels() const + size_t Actor::GetNumLODLevels() const { - const AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; - return static_cast(lodLevels.size()); + return m_meshLodData.m_lodLevels.size(); } void* Actor::GetCustomData() const { - return mCustomData; + return m_customData; } void Actor::SetCustomData(void* dataPointer) { - mCustomData = dataPointer; + m_customData = dataPointer; } const char* Actor::GetName() const { - return mName.c_str(); + return m_name.c_str(); } const AZStd::string& Actor::GetNameString() const { - return mName; + return m_name; } const char* Actor::GetFileName() const { - return mFileName.c_str(); + return m_fileName.c_str(); } const AZStd::string& Actor::GetFileNameString() const { - return mFileName; + return m_fileName; } void Actor::AddDependency(const Dependency& dependency) { - mDependencies.Add(dependency); + m_dependencies.emplace_back(dependency); } - void Actor::SetMorphSetup(uint32 lodLevel, MorphSetup* setup) + void Actor::SetMorphSetup(size_t lodLevel, MorphSetup* setup) { - mMorphSetups[lodLevel] = setup; + m_morphSetups[lodLevel] = setup; } uint32 Actor::GetNumNodeGroups() const { - return mNodeGroups.GetLength(); + return m_nodeGroups.GetLength(); } NodeGroup* Actor::GetNodeGroup(uint32 index) const { - return mNodeGroups[index]; + return m_nodeGroups[index]; } void Actor::AddNodeGroup(NodeGroup* newGroup) { - mNodeGroups.Add(newGroup); + m_nodeGroups.Add(newGroup); } @@ -2085,16 +1987,16 @@ namespace EMotionFX { if (delFromMem) { - delete mNodeGroups[index]; + delete m_nodeGroups[index]; } - mNodeGroups.Remove(index); + m_nodeGroups.Remove(index); } void Actor::RemoveNodeGroup(NodeGroup* group, bool delFromMem) { - mNodeGroups.RemoveByValue(group); + m_nodeGroups.RemoveByValue(group); if (delFromMem) { delete group; @@ -2105,10 +2007,10 @@ namespace EMotionFX // find a group index by its name uint32 Actor::FindNodeGroupIndexByName(const char* groupName) const { - const uint32 numGroups = mNodeGroups.GetLength(); + const uint32 numGroups = m_nodeGroups.GetLength(); for (uint32 i = 0; i < numGroups; ++i) { - if (mNodeGroups[i]->GetNameString() == groupName) + if (m_nodeGroups[i]->GetNameString() == groupName) { return i; } @@ -2121,10 +2023,10 @@ namespace EMotionFX // find a group index by its name, but not case sensitive uint32 Actor::FindNodeGroupIndexByNameNoCase(const char* groupName) const { - const uint32 numGroups = mNodeGroups.GetLength(); + const uint32 numGroups = m_nodeGroups.GetLength(); for (uint32 i = 0; i < numGroups; ++i) { - if (AzFramework::StringFunc::Equal(mNodeGroups[i]->GetNameString().c_str(), groupName, false /* no case */)) + if (AzFramework::StringFunc::Equal(m_nodeGroups[i]->GetNameString().c_str(), groupName, false /* no case */)) { return i; } @@ -2137,12 +2039,12 @@ namespace EMotionFX // find a group by its name NodeGroup* Actor::FindNodeGroupByName(const char* groupName) const { - const uint32 numGroups = mNodeGroups.GetLength(); + const uint32 numGroups = m_nodeGroups.GetLength(); for (uint32 i = 0; i < numGroups; ++i) { - if (mNodeGroups[i]->GetNameString() == groupName) + if (m_nodeGroups[i]->GetNameString() == groupName) { - return mNodeGroups[i]; + return m_nodeGroups[i]; } } return nullptr; @@ -2152,12 +2054,12 @@ namespace EMotionFX // find a group by its name, but without case sensitivity NodeGroup* Actor::FindNodeGroupByNameNoCase(const char* groupName) const { - const uint32 numGroups = mNodeGroups.GetLength(); + const uint32 numGroups = m_nodeGroups.GetLength(); for (uint32 i = 0; i < numGroups; ++i) { - if (AzFramework::StringFunc::Equal(mNodeGroups[i]->GetNameString().c_str(), groupName, false /* no case */)) + if (AzFramework::StringFunc::Equal(m_nodeGroups[i]->GetNameString().c_str(), groupName, false /* no case */)) { - return mNodeGroups[i]; + return m_nodeGroups[i]; } } return nullptr; @@ -2166,31 +2068,31 @@ namespace EMotionFX void Actor::SetDirtyFlag(bool dirty) { - mDirtyFlag = dirty; + m_dirtyFlag = dirty; } bool Actor::GetDirtyFlag() const { - return mDirtyFlag; + return m_dirtyFlag; } void Actor::SetIsUsedForVisualization(bool flag) { - mUsedForVisualization = flag; + m_usedForVisualization = flag; } bool Actor::GetIsUsedForVisualization() const { - return mUsedForVisualization; + return m_usedForVisualization; } void Actor::SetIsOwnedByRuntime(bool isOwnedByRuntime) { #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = isOwnedByRuntime; + m_isOwnedByRuntime = isOwnedByRuntime; #else AZ_UNUSED(isOwnedByRuntime); #endif @@ -2200,53 +2102,53 @@ namespace EMotionFX bool Actor::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif } - const MCore::AABB& Actor::GetStaticAABB() const + const AZ::Aabb& Actor::GetStaticAabb() const { - return mStaticAABB; + return m_staticAabb; } - void Actor::SetStaticAABB(const MCore::AABB& box) + void Actor::SetStaticAabb(const AZ::Aabb& aabb) { - mStaticAABB = box; + m_staticAabb = aabb; } //--------------------------------- - Mesh* Actor::GetMesh(uint32 lodLevel, uint32 nodeIndex) const + Mesh* Actor::GetMesh(size_t lodLevel, size_t nodeIndex) const { const AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; - return lodLevels[lodLevel].mNodeInfos[nodeIndex].mMesh; + return lodLevels[lodLevel].m_nodeInfos[nodeIndex].m_mesh; } - MeshDeformerStack* Actor::GetMeshDeformerStack(uint32 lodLevel, uint32 nodeIndex) const + MeshDeformerStack* Actor::GetMeshDeformerStack(size_t lodLevel, size_t nodeIndex) const { const AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; - return lodLevels[lodLevel].mNodeInfos[nodeIndex].mStack; + return lodLevels[lodLevel].m_nodeInfos[nodeIndex].m_stack; } // set the mesh for a given node in a given LOD - void Actor::SetMesh(uint32 lodLevel, uint32 nodeIndex, Mesh* mesh) + void Actor::SetMesh(size_t lodLevel, size_t nodeIndex, Mesh* mesh) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; - lodLevels[lodLevel].mNodeInfos[nodeIndex].mMesh = mesh; + lodLevels[lodLevel].m_nodeInfos[nodeIndex].m_mesh = mesh; } // set the mesh deformer stack for a given node in a given LOD - void Actor::SetMeshDeformerStack(uint32 lodLevel, uint32 nodeIndex, MeshDeformerStack* stack) + void Actor::SetMeshDeformerStack(size_t lodLevel, size_t nodeIndex, MeshDeformerStack* stack) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; - lodLevels[lodLevel].mNodeInfos[nodeIndex].mStack = stack; + lodLevels[lodLevel].m_nodeInfos[nodeIndex].m_stack = stack; } // check if the mesh has a skinning deformer (either linear or dual quat) - bool Actor::CheckIfHasSkinningDeformer(uint32 lodLevel, uint32 nodeIndex) const + bool Actor::CheckIfHasSkinningDeformer(size_t lodLevel, size_t nodeIndex) const { // check if there is a mesh Mesh* mesh = GetMesh(lodLevel, nodeIndex); @@ -2265,125 +2167,49 @@ namespace EMotionFX return (stack->CheckIfHasDeformerOfType(SoftSkinDeformer::TYPE_ID) || stack->CheckIfHasDeformerOfType(DualQuatSkinDeformer::TYPE_ID)); } - - // calculate the OBB for a given node - void Actor::CalcOBBFromBindPose(uint32 lodLevel, uint32 nodeIndex) - { - AZStd::vector points; - - // if there is a mesh - Mesh* mesh = GetMesh(lodLevel, nodeIndex); - if (mesh) - { - // if the mesh is not skinned - if (mesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID) == nullptr) - { - mesh->ExtractOriginalVertexPositions(points); - } - } - else // there is no mesh, so maybe this is a bone - { - const Transform& invBindPoseTransform = GetInverseBindPoseTransform(nodeIndex); - - // for all nodes inside the actor where this node belongs to - const uint32 numNodes = mSkeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) - { - Mesh* loopMesh = GetMesh(lodLevel, n); - if (loopMesh == nullptr) - { - continue; - } - - // get the vertex positions in bind pose - const uint32 numVerts = loopMesh->GetNumVertices(); - points.reserve(numVerts * 2); - AZ::Vector3* positions = (AZ::Vector3*)loopMesh->FindOriginalVertexData(Mesh::ATTRIB_POSITIONS); - - SkinningInfoVertexAttributeLayer* skinLayer = (SkinningInfoVertexAttributeLayer*)loopMesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); - if (skinLayer) - { - // iterate over all skinning influences and see if this node number is used - // if so, add it to the list of points - const uint32* orgVertices = (uint32*)loopMesh->FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); - for (uint32 v = 0; v < numVerts; ++v) - { - // get the original vertex number - const uint32 orgVtx = orgVertices[v]; - - // for all skinning influences for this vertex - const size_t numInfluences = skinLayer->GetNumInfluences(orgVtx); - for (size_t i = 0; i < numInfluences; ++i) - { - // get the node used by this influence - const uint32 nodeNr = skinLayer->GetInfluence(orgVtx, i)->GetNodeNr(); - - // if this is the same node as we are updating the bounds for, add the vertex position to the list - if (nodeNr == nodeIndex) - { - const AZ::Vector3 tempPos(positions[v]); - points.emplace_back(invBindPoseTransform.TransformPoint(tempPos)); - } - } // for all influences - } // for all vertices - } // if there is skinning info - } // for all nodes - } - - // init from the set of points - if (!points.empty()) - { - GetNodeOBB(nodeIndex).InitFromPoints(&points[0], static_cast(points.size())); - } - else - { - GetNodeOBB(nodeIndex).Init(); - } - } - // remove the mesh for a given node in a given LOD - void Actor::RemoveNodeMeshForLOD(uint32 lodLevel, uint32 nodeIndex, bool destroyMesh) + void Actor::RemoveNodeMeshForLOD(size_t lodLevel, size_t nodeIndex, bool destroyMesh) { AZStd::vector& lodLevels = m_meshLodData.m_lodLevels; LODLevel& lod = lodLevels[lodLevel]; - NodeLODInfo& nodeInfo = lod.mNodeInfos[nodeIndex]; + NodeLODInfo& nodeInfo = lod.m_nodeInfos[nodeIndex]; - if (destroyMesh && nodeInfo.mMesh) + if (destroyMesh && nodeInfo.m_mesh) { - MCore::Destroy(nodeInfo.mMesh); + MCore::Destroy(nodeInfo.m_mesh); } - if (destroyMesh && nodeInfo.mStack) + if (destroyMesh && nodeInfo.m_stack) { - MCore::Destroy(nodeInfo.mStack); + MCore::Destroy(nodeInfo.m_stack); } - nodeInfo.mMesh = nullptr; - nodeInfo.mStack = nullptr; + nodeInfo.m_mesh = nullptr; + nodeInfo.m_stack = nullptr; } void Actor::SetUnitType(MCore::Distance::EUnitType unitType) { - mUnitType = unitType; + m_unitType = unitType; } MCore::Distance::EUnitType Actor::GetUnitType() const { - return mUnitType; + return m_unitType; } void Actor::SetFileUnitType(MCore::Distance::EUnitType unitType) { - mFileUnitType = unitType; + m_fileUnitType = unitType; } MCore::Distance::EUnitType Actor::GetFileUnitType() const { - return mFileUnitType; + return m_fileUnitType; } @@ -2398,38 +2224,30 @@ namespace EMotionFX // scale the bind pose positions Pose* bindPose = GetBindPose(); - const uint32 numNodes = GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Transform transform = bindPose->GetLocalSpaceTransform(i); - transform.mPosition *= scaleFactor; + transform.m_position *= scaleFactor; bindPose->SetLocalSpaceTransform(i, transform); } bindPose->ForceUpdateFullModelSpacePose(); // calculate the inverse bind pose matrices - for (uint32 i = 0; i < numNodes; ++i) - { - mInvBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); - } - - // update node obbs - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { - MCore::OBB& box = GetNodeOBB(i); - box.SetExtents(box.GetExtents() * scaleFactor); - box.SetCenter(box.GetCenter() * scaleFactor); + m_invBindPoseTransforms[i] = bindPose->GetModelSpaceTransform(i).Inversed(); } // update static aabb - mStaticAABB.SetMin(mStaticAABB.GetMin() * scaleFactor); - mStaticAABB.SetMax(mStaticAABB.GetMax() * scaleFactor); + m_staticAabb.SetMin(m_staticAabb.GetMin() * scaleFactor); + m_staticAabb.SetMax(m_staticAabb.GetMax() * scaleFactor); // update mesh data for all LOD levels - const uint32 numLODs = GetNumLODLevels(); - for (uint32 lod = 0; lod < numLODs; ++lod) + const size_t numLODs = GetNumLODLevels(); + for (size_t lod = 0; lod < numLODs; ++lod) { - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { Mesh* mesh = GetMesh(lod, i); if (mesh) @@ -2440,7 +2258,7 @@ namespace EMotionFX } // scale morph target data - for (uint32 lod = 0; lod < numLODs; ++lod) + for (size_t lod = 0; lod < numLODs; ++lod) { MorphSetup* morphSetup = GetMorphSetup(lod); if (morphSetup) @@ -2460,32 +2278,32 @@ namespace EMotionFX // scale everything to the given unit type void Actor::ScaleToUnitType(MCore::Distance::EUnitType targetUnitType) { - if (mUnitType == targetUnitType) + if (m_unitType == targetUnitType) { return; } // calculate the scale factor and scale - const float scaleFactor = static_cast(MCore::Distance::GetConversionFactor(mUnitType, targetUnitType)); + const float scaleFactor = static_cast(MCore::Distance::GetConversionFactor(m_unitType, targetUnitType)); Scale(scaleFactor); // update the unit type - mUnitType = targetUnitType; + m_unitType = targetUnitType; } // Try to figure out which axis points "up" for the motion extraction node. Actor::EAxis Actor::FindBestMatchingMotionExtractionAxis() const { - MCORE_ASSERT(mMotionExtractionNode != MCORE_INVALIDINDEX32); - if (mMotionExtractionNode == MCORE_INVALIDINDEX32) + MCORE_ASSERT(m_motionExtractionNode != InvalidIndex); + if (m_motionExtractionNode == InvalidIndex) { return AXIS_Y; } // Get the local space rotation matrix of the motion extraction node. - const Transform& localTransform = GetBindPose()->GetLocalSpaceTransform(mMotionExtractionNode); - const AZ::Matrix3x3 rotationMatrix = AZ::Matrix3x3::CreateFromQuaternion(localTransform.mRotation); + const Transform& localTransform = GetBindPose()->GetLocalSpaceTransform(m_motionExtractionNode); + const AZ::Matrix3x3 rotationMatrix = AZ::Matrix3x3::CreateFromQuaternion(localTransform.m_rotation); // Calculate angles between the up axis and each of the rotation's basis vectors. const AZ::Vector3 globalUpAxis(0.0f, 0.0f, 1.0f); @@ -2513,18 +2331,18 @@ namespace EMotionFX } - void Actor::SetRetargetRootNodeIndex(uint32 nodeIndex) + void Actor::SetRetargetRootNodeIndex(size_t nodeIndex) { - mRetargetRootNode = nodeIndex; + m_retargetRootNode = nodeIndex; } void Actor::SetRetargetRootNode(Node* node) { - mRetargetRootNode = node ? node->GetNodeIndex() : MCORE_INVALIDINDEX32; + m_retargetRootNode = node ? node->GetNodeIndex() : InvalidIndex; } - void Actor::InsertJointAndParents(AZ::u32 jointIndex, AZStd::unordered_set& includedJointIndices) + void Actor::InsertJointAndParents(size_t jointIndex, AZStd::unordered_set& includedJointIndices) { // If our joint is already in, then we can skip things. if (includedJointIndices.find(jointIndex) != includedJointIndices.end()) @@ -2533,8 +2351,8 @@ namespace EMotionFX } // Add the parent. - const AZ::u32 parentIndex = mSkeleton->GetNode(jointIndex)->GetParentIndex(); - if (parentIndex != InvalidIndex32) + const size_t parentIndex = m_skeleton->GetNode(jointIndex)->GetParentIndex(); + if (parentIndex != InvalidIndex) { InsertJointAndParents(parentIndex, includedJointIndices); } @@ -2545,10 +2363,10 @@ namespace EMotionFX void Actor::AutoSetupSkeletalLODsBasedOnSkinningData(const AZStd::vector& alwaysIncludeJoints) { - AZStd::unordered_set includedJointIndices; + AZStd::unordered_set includedJointIndices; - const AZ::u32 numLODs = GetNumLODLevels(); - for (AZ::u32 lod = 0; lod < numLODs; ++lod) + const size_t numLODs = GetNumLODLevels(); + for (size_t lod = 0; lod < numLODs; ++lod) { includedJointIndices.clear(); @@ -2558,8 +2376,8 @@ namespace EMotionFX continue; } - const AZ::u32 numJoints = mSkeleton->GetNumNodes(); - for (AZ::u32 jointIndex = 0; jointIndex < numJoints; ++jointIndex) + const size_t numJoints = m_skeleton->GetNumNodes(); + for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { const Mesh* mesh = GetMesh(lod, jointIndex); if (!mesh) @@ -2571,14 +2389,13 @@ namespace EMotionFX InsertJointAndParents(jointIndex, includedJointIndices); // Look at the joints registered in the submeshes. - const AZ::u32 numSubMeshes = mesh->GetNumSubMeshes(); - for (AZ::u32 subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t subMeshIndex = 0; subMeshIndex < numSubMeshes; ++subMeshIndex) { - const MCore::Array& subMeshJoints = mesh->GetSubMesh(subMeshIndex)->GetBonesArray(); - const AZ::u32 numSubMeshJoints = subMeshJoints.GetLength(); - for (AZ::u32 i = 0; i < numSubMeshJoints; ++i) + const AZStd::vector& subMeshJoints = mesh->GetSubMesh(subMeshIndex)->GetBonesArray(); + for (size_t subMeshJoint : subMeshJoints) { - InsertJointAndParents(subMeshJoints[i], includedJointIndices); + InsertJointAndParents(subMeshJoint, includedJointIndices); } } } // for all joints @@ -2589,8 +2406,8 @@ namespace EMotionFX // Force joints in our "always include list" to be included. for (const AZStd::string& jointName : alwaysIncludeJoints) { - AZ::u32 jointIndex = InvalidIndex32; - if (!mSkeleton->FindNodeAndIndexByName(jointName, jointIndex)) + size_t jointIndex = InvalidIndex; + if (!m_skeleton->FindNodeAndIndexByName(jointName, jointIndex)) { if (!jointName.empty()) { @@ -2603,24 +2420,24 @@ namespace EMotionFX } // Disable all joints first. - for (AZ::u32 jointIndex = 0; jointIndex < numJoints; ++jointIndex) + for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { - mSkeleton->GetNode(jointIndex)->SetSkeletalLODStatus(lod, false); + m_skeleton->GetNode(jointIndex)->SetSkeletalLODStatus(lod, false); } // Enable all our included joints in this skeletal LOD. AZ_TracePrintf("EMotionFX", "[LOD %d] Enabled joints = %zd\n", lod, includedJointIndices.size()); - for (AZ::u32 jointIndex : includedJointIndices) + for (size_t jointIndex : includedJointIndices) { - mSkeleton->GetNode(jointIndex)->SetSkeletalLODStatus(lod, true); + m_skeleton->GetNode(jointIndex)->SetSkeletalLODStatus(lod, true); } } else // When we have an empty include list, enable everything. { - AZ_TracePrintf("EMotionFX", "[LOD %d] Enabled joints = %zd\n", lod, mSkeleton->GetNumNodes()); - for (AZ::u32 i = 0; i < mSkeleton->GetNumNodes(); ++i) + AZ_TracePrintf("EMotionFX", "[LOD %d] Enabled joints = %zd\n", lod, m_skeleton->GetNumNodes()); + for (size_t i = 0; i < m_skeleton->GetNumNodes(); ++i) { - mSkeleton->GetNode(i)->SetSkeletalLODStatus(lod, true); + m_skeleton->GetNode(i)->SetSkeletalLODStatus(lod, true); } } } // for each LOD @@ -2629,17 +2446,17 @@ namespace EMotionFX void Actor::PrintSkeletonLODs() { - const AZ::u32 numLODs = GetNumLODLevels(); - for (AZ::u32 lod = 0; lod < numLODs; ++lod) + const size_t numLODs = GetNumLODLevels(); + for (size_t lod = 0; lod < numLODs; ++lod) { AZ_TracePrintf("EMotionFX", "[LOD %d]:", lod); - const AZ::u32 numJoints = mSkeleton->GetNumNodes(); - for (AZ::u32 jointIndex = 0; jointIndex < numJoints; ++jointIndex) + const size_t numJoints = m_skeleton->GetNumNodes(); + for (size_t jointIndex = 0; jointIndex < numJoints; ++jointIndex) { - const Node* joint = mSkeleton->GetNode(jointIndex); + const Node* joint = m_skeleton->GetNode(jointIndex); if (joint->GetSkeletalLODStatus(lod)) { - AZ_TracePrintf("EMotionFX", "\t%s (index=%d)", joint->GetName(), jointIndex); + AZ_TracePrintf("EMotionFX", "\t%s (index=%zu)", joint->GetName(), jointIndex); } } } @@ -2663,7 +2480,7 @@ namespace EMotionFX // 3) In actor skeleton, remove every node that hasn't been marked. // 4) Meanwhile, build a map that represent the child-parent relationship. // 5) After the node index changed, we use the map in 4) to restore the child-parent relationship. - AZ::u32 numNodes = mSkeleton->GetNumNodes(); + size_t numNodes = m_skeleton->GetNumNodes(); AZStd::vector flags; AZStd::unordered_map childParentMap; flags.resize(numNodes); @@ -2672,7 +2489,7 @@ namespace EMotionFX // Search the hit detection config to find and keep all the hit detection nodes. for (const Physics::CharacterColliderNodeConfiguration& nodeConfig : m_physicsSetup->GetHitDetectionConfig().m_nodes) { - Node* node = mSkeleton->FindNodeByName(nodeConfig.m_name); + Node* node = m_skeleton->FindNodeByName(nodeConfig.m_name); if (node && nodesToKeep.find(node) == nodesToKeep.end()) { nodesToKeep.emplace(node); @@ -2687,9 +2504,9 @@ namespace EMotionFX } // Search the actor skeleton to find all the critical nodes. - for (AZ::u32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { - Node* node = mSkeleton->GetNode(i); + Node* node = m_skeleton->GetNode(i); if (node->GetIsCritical() && nodesToKeep.find(node) == nodesToKeep.end()) { nodesToKeep.emplace(node); @@ -2717,30 +2534,30 @@ namespace EMotionFX } // Remove all the nodes that haven't been marked - for (AZ::u32 nodeIndex = numNodes - 1; nodeIndex > 0; nodeIndex--) + for (size_t nodeIndex = numNodes - 1; nodeIndex > 0; nodeIndex--) { if (!flags[nodeIndex]) { - mSkeleton->RemoveNode(nodeIndex); + m_skeleton->RemoveNode(nodeIndex); } } // Update the node index. - mSkeleton->UpdateNodeIndexValues(); + m_skeleton->UpdateNodeIndexValues(); // After the node index changed, the parent index become invalid. First, clear all information about children because // it's not valid anymore. - for (AZ::u32 nodeIndex = 0; nodeIndex < mSkeleton->GetNumNodes(); ++nodeIndex) + for (size_t nodeIndex = 0; nodeIndex < m_skeleton->GetNumNodes(); ++nodeIndex) { - Node* node = mSkeleton->GetNode(nodeIndex); + Node* node = m_skeleton->GetNode(nodeIndex); node->RemoveAllChildNodes(); } // Then build the child-parent relationship using the prebuild map. for (auto& pair : childParentMap) { - Node* child = mSkeleton->FindNodeByName(pair.first); - Node* parent = mSkeleton->FindNodeByName(pair.second); + Node* child = m_skeleton->FindNodeByName(pair.first); + Node* parent = m_skeleton->FindNodeByName(pair.second); child->SetParentIndex(parent->GetNodeIndex()); parent->AddChild(child->GetNodeIndex()); } @@ -2774,8 +2591,8 @@ namespace EMotionFX } // In case neither of the mesh joints are present in the actor, just use the root node as fallback. - AZ_Assert(mSkeleton->GetNode(0), "Actor needs to have at least a single joint."); - return mSkeleton->GetNode(0); + AZ_Assert(m_skeleton->GetNode(0), "Actor needs to have at least a single joint."); + return m_skeleton->GetNode(0); } void Actor::ConstructMeshes() @@ -2787,19 +2604,19 @@ namespace EMotionFX const size_t numLODLevels = lodAssets.size(); lodLevels.clear(); - SetNumLODLevels(static_cast(numLODLevels), /*adjustMorphSetup=*/false); - const uint32 numNodes = mSkeleton->GetNumNodes(); + SetNumLODLevels(numLODLevels, /*adjustMorphSetup=*/false); + const size_t numNodes = m_skeleton->GetNumNodes(); // Remove all the materials and add them back based on the meshAsset. Eventually we will remove all the material from Actor and // GLActor. RemoveAllMaterials(); - mMaterials.Resize(static_cast(numLODLevels)); + m_materials.resize(numLODLevels); for (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) { const AZ::Data::Asset& lodAsset = lodAssets[lodLevel]; - lodLevels[lodLevel].mNodeInfos.Resize(numNodes); + lodLevels[lodLevel].m_nodeInfos.resize(numNodes); // Create a single mesh for the actor. Mesh* mesh = Mesh::CreateFromModelLod(lodAsset, m_skinToSkeletonIndexMap); @@ -2812,19 +2629,19 @@ namespace EMotionFX continue; } - const AZ::u32 jointIndex = meshJoint->GetNodeIndex(); - NodeLODInfo& jointInfo = lodLevels[lodLevel].mNodeInfos[jointIndex]; + const size_t jointIndex = meshJoint->GetNodeIndex(); + NodeLODInfo& jointInfo = lodLevels[lodLevel].m_nodeInfos[jointIndex]; - jointInfo.mMesh = mesh; + jointInfo.m_mesh = mesh; - if (!jointInfo.mStack) + if (!jointInfo.m_stack) { - jointInfo.mStack = MeshDeformerStack::Create(mesh); + jointInfo.m_stack = MeshDeformerStack::Create(mesh); } // Add the skinning deformers - const AZ::u32 numLayers = mesh->GetNumSharedVertexAttributeLayers(); - for (AZ::u32 layerNr = 0; layerNr < numLayers; ++layerNr) + const size_t numLayers = mesh->GetNumSharedVertexAttributeLayers(); + for (size_t layerNr = 0; layerNr < numLayers; ++layerNr) { EMotionFX::VertexAttributeLayer* vertexAttributeLayer = mesh->GetSharedVertexAttributeLayer(layerNr); if (vertexAttributeLayer->GetType() != EMotionFX::SkinningInfoVertexAttributeLayer::TYPE_ID) @@ -2835,8 +2652,7 @@ namespace EMotionFX EMotionFX::SkinningInfoVertexAttributeLayer* skinLayer = static_cast(vertexAttributeLayer); const AZ::u32 numOrgVerts = skinLayer->GetNumAttributes(); - AZStd::set localJointIndices = skinLayer->CalcLocalJointIndices(numOrgVerts); - const AZ::u32 numLocalJoints = static_cast(localJointIndices.size()); + const size_t numLocalJoints = skinLayer->CalcLocalJointIndices(numOrgVerts).size(); // The information about if we want to use dual quat skinning is baked into the mesh chunk and we don't have access to that // anymore. Default to dual quat skinning. @@ -2844,14 +2660,14 @@ namespace EMotionFX if (dualQuatSkinning) { DualQuatSkinDeformer* skinDeformer = DualQuatSkinDeformer::Create(mesh); - jointInfo.mStack->AddDeformer(skinDeformer); + jointInfo.m_stack->AddDeformer(skinDeformer); skinDeformer->ReserveLocalBones(numLocalJoints); skinDeformer->Reinitialize(this, meshJoint, static_cast(lodLevel)); } else { SoftSkinDeformer* skinDeformer = GetSoftSkinManager().CreateDeformer(mesh); - jointInfo.mStack->AddDeformer(skinDeformer); + jointInfo.m_stack->AddDeformer(skinDeformer); skinDeformer->ReserveLocalBones(numLocalJoints); // pre-alloc data to prevent reallocs skinDeformer->Reinitialize(this, meshJoint, static_cast(lodLevel)); } @@ -2864,7 +2680,7 @@ namespace EMotionFX Node* Actor::FindJointByMeshName(const AZStd::string_view meshName) const { - Node* joint = mSkeleton->FindNodeByName(meshName.data()); + Node* joint = m_skeleton->FindNodeByName(meshName.data()); if (!joint) { // When mesh merging in the model builder is enabled, the name of the mesh is the concatenated version @@ -2874,7 +2690,7 @@ namespace EMotionFX AZ::StringFunc::Tokenize(meshName, tokens, '+'); for (const AZStd::string& token : tokens) { - joint = mSkeleton->FindNodeByName(token); + joint = m_skeleton->FindNodeByName(token); if (joint) { break; @@ -2893,13 +2709,13 @@ namespace EMotionFX AZStd::unordered_map result; for (const auto& pair : skinMetaAsset->GetJointNameToIndexMap()) { - const Node* node = mSkeleton->FindNodeByName(pair.first.c_str()); + const Node* node = m_skeleton->FindNodeByName(pair.first.c_str()); if (!node) { AZ_Assert(node, "Cannot find joint named %s in the skeleton while it is used by the skin.", pair.first.c_str()); continue; } - result.emplace(pair.second, node->GetNodeIndex()); + result.emplace(pair.second, aznumeric_caster(node->GetNodeIndex())); } return result; @@ -2913,14 +2729,14 @@ namespace EMotionFX const AZStd::array_view>& lodAssets = m_meshAsset->GetLodAssets(); const size_t numLODLevels = lodAssets.size(); - AZ_Assert(mMorphSetups.GetLength() == numLODLevels, "There needs to be a morph setup for every single LOD level."); + AZ_Assert(m_morphSetups.size() == numLODLevels, "There needs to be a morph setup for every single LOD level."); for (size_t lodLevel = 0; lodLevel < numLODLevels; ++lodLevel) { const AZ::Data::Asset& lodAsset = lodAssets[lodLevel]; const AZStd::array_view& sourceMeshes = lodAsset->GetMeshes(); - MorphSetup* morphSetup = mMorphSetups[static_cast(lodLevel)]; + MorphSetup* morphSetup = m_morphSetups[static_cast(lodLevel)]; if (!morphSetup) { continue; @@ -2934,22 +2750,22 @@ namespace EMotionFX continue; } - const AZ::u32 jointIndex = meshJoint->GetNodeIndex(); - NodeLODInfo& jointInfo = lodLevels[lodLevel].mNodeInfos[jointIndex]; - Mesh* mesh = jointInfo.mMesh; + const size_t jointIndex = meshJoint->GetNodeIndex(); + NodeLODInfo& jointInfo = lodLevels[lodLevel].m_nodeInfos[jointIndex]; + Mesh* mesh = jointInfo.m_mesh; - if (!jointInfo.mStack) + if (!jointInfo.m_stack) { - jointInfo.mStack = MeshDeformerStack::Create(mesh); + jointInfo.m_stack = MeshDeformerStack::Create(mesh); } // Add the morph deformer to the mesh deformer stack (in case there is none yet). - MorphMeshDeformer* morphTargetDeformer = (MorphMeshDeformer*)jointInfo.mStack->FindDeformerByType(MorphMeshDeformer::TYPE_ID); + MorphMeshDeformer* morphTargetDeformer = (MorphMeshDeformer*)jointInfo.m_stack->FindDeformerByType(MorphMeshDeformer::TYPE_ID); if (!morphTargetDeformer) { morphTargetDeformer = MorphMeshDeformer::Create(mesh); // Add insert the deformer at the first position to make sure we apply morph targets before skinning. - jointInfo.mStack->InsertDeformer(/*deformerPosition=*/0, morphTargetDeformer); + jointInfo.m_stack->InsertDeformer(/*deformerPosition=*/0, morphTargetDeformer); } // The lod has shared buffers that combine the data from each submesh. In case any of the submeshes has a @@ -2971,8 +2787,8 @@ namespace EMotionFX AZ_Assert(morphTargetDeltaView.data(), "Unable to find MORPHTARGET_VERTEXDELTAS buffer"); const AZ::RPI::PackedCompressedMorphTargetDelta* vertexDeltas = reinterpret_cast(morphTargetDeltaView.data()); - const AZ::u32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (AZ::u32 mtIndex = 0; mtIndex < numMorphTargets; ++mtIndex) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t mtIndex = 0; mtIndex < numMorphTargets; ++mtIndex) { MorphTargetStandard* morphTarget = static_cast(morphSetup->GetMorphTarget(mtIndex)); @@ -2988,8 +2804,8 @@ namespace EMotionFX MorphTargetStandard::DeformData* deformData = aznew MorphTargetStandard::DeformData(jointIndex, numDeformedVertices); // Set the compression/quantization range for the positions. - deformData->mMinValue = metaData.m_minPositionDelta; - deformData->mMaxValue = metaData.m_maxPositionDelta; + deformData->m_minValue = metaData.m_minPositionDelta; + deformData->m_maxValue = metaData.m_maxPositionDelta; for (AZ::u32 deformVtx = 0; deformVtx < numDeformedVertices; ++deformVtx) { @@ -3001,24 +2817,24 @@ namespace EMotionFX AZ::RPI::CompressedMorphTargetDelta unpackedCompressedDelta = AZ::RPI::UnpackMorphTargetDelta(packedCompressedDelta); // Set the EMotionFX deform data from the CmopressedMorphTargetDelta - deformData->mDeltas[deformVtx].mVertexNr = unpackedCompressedDelta.m_morphedVertexIndex; + deformData->m_deltas[deformVtx].m_vertexNr = unpackedCompressedDelta.m_morphedVertexIndex; - deformData->mDeltas[deformVtx].mPosition = MCore::Compressed16BitVector3( + deformData->m_deltas[deformVtx].m_position = MCore::Compressed16BitVector3( unpackedCompressedDelta.m_positionX, unpackedCompressedDelta.m_positionY, unpackedCompressedDelta.m_positionZ); - deformData->mDeltas[deformVtx].mNormal = MCore::Compressed8BitVector3( + deformData->m_deltas[deformVtx].m_normal = MCore::Compressed8BitVector3( unpackedCompressedDelta.m_normalX, unpackedCompressedDelta.m_normalY, unpackedCompressedDelta.m_normalZ); - deformData->mDeltas[deformVtx].mTangent = MCore::Compressed8BitVector3( + deformData->m_deltas[deformVtx].m_tangent = MCore::Compressed8BitVector3( unpackedCompressedDelta.m_tangentX, unpackedCompressedDelta.m_tangentY, unpackedCompressedDelta.m_tangentZ); - deformData->mDeltas[deformVtx].mBitangent = MCore::Compressed8BitVector3( + deformData->m_deltas[deformVtx].m_bitangent = MCore::Compressed8BitVector3( unpackedCompressedDelta.m_bitangentX, unpackedCompressedDelta.m_bitangentY, unpackedCompressedDelta.m_bitangentZ); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h index 6c3ab6bf29..5c4a15e2d8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.h @@ -16,15 +16,14 @@ #include #include #include +#include #include #include // include MCore related files -#include #include -#include +#include #include -#include #include // include required headers @@ -69,8 +68,8 @@ namespace EMotionFX */ struct EMFX_API Dependency { - Actor* mActor; /**< The actor where the instance is dependent on. */ - AnimGraph* mAnimGraph; /**< The anim graph we depend on. */ + Actor* m_actor; /**< The actor where the instance is dependent on. */ + AnimGraph* m_animGraph; /**< The anim graph we depend on. */ }; // @@ -91,9 +90,9 @@ namespace EMotionFX // per node mirror info struct EMFX_API NodeMirrorInfo { - uint16 mSourceNode; // from which node to extract the motion - uint8 mAxis; // X=0, Y=1, Z=2 - uint8 mFlags; // bitfield with MIRRORFLAG_ prefix + uint16 m_sourceNode; // from which node to extract the motion + uint8 m_axis; // X=0, Y=1, Z=2 + uint8 m_flags; // bitfield with MIRRORFLAG_ prefix }; enum class LoadRequirement : bool @@ -115,13 +114,13 @@ namespace EMotionFX * Get the unique identification number for the actor. * @return The unique identification number. */ - MCORE_INLINE uint32 GetID() const { return mID; } + MCORE_INLINE uint32 GetID() const { return m_id; } /** * Set the unique identification number for the actor instance. * @param[in] id The unique identification number. */ - MCORE_INLINE void SetID(uint32 id) { mID = id; } + MCORE_INLINE void SetID(uint32 id) { m_id = id; } /** * Add a node to this actor. @@ -132,14 +131,14 @@ namespace EMotionFX /** * Add a node to this actor. */ - Node* AddNode(uint32 nodeIndex, const char* name, uint32 parentIndex = MCORE_INVALIDINDEX32); + Node* AddNode(size_t nodeIndex, const char* name, size_t parentIndex = InvalidIndex); /** * Remove a given node. * @param nr The node to remove. * @param delMem If true the allocated memory of the node will be deleted. */ - void RemoveNode(uint32 nr, bool delMem = true); + void RemoveNode(size_t nr, bool delMem = true); /** * Remove all nodes from memory. @@ -189,7 +188,7 @@ namespace EMotionFX * @param endNodeIndex The node index to generate the path to. * @param outPath the array that will contain the path. */ - void GenerateUpdatePathToRoot(uint32 endNodeIndex, MCore::Array& outPath) const; + void GenerateUpdatePathToRoot(size_t endNodeIndex, AZStd::vector& outPath) const; /** * Set the motion extraction node. @@ -207,7 +206,7 @@ namespace EMotionFX * You can set the node to MCORE_INVALIDINDEX32 in case you want to disable motion extraction. * @param nodeIndex The motion extraction node, or MCORE_INVALIDINDEX32 to disable it. */ - void SetMotionExtractionNodeIndex(uint32 nodeIndex); + void SetMotionExtractionNodeIndex(size_t nodeIndex); /** * Get the motion extraction node. @@ -219,7 +218,7 @@ namespace EMotionFX * Get the motion extraction node index. * @result The motion extraction node index, or MCORE_INVALIDINDEX32 when it has not been set. */ - MCORE_INLINE uint32 GetMotionExtractionNodeIndex() const { return mMotionExtractionNode; } + MCORE_INLINE size_t GetMotionExtractionNodeIndex() const { return m_motionExtractionNode; } //--------------------------------------------------------------------- @@ -228,14 +227,14 @@ namespace EMotionFX * @param lodLevel The LOD level to check for. * @result Returns true when this actor contains nodes that have meshes in the given LOD, otherwise false is returned. */ - bool CheckIfHasMeshes(uint32 lodLevel) const; + bool CheckIfHasMeshes(size_t lodLevel) const; /** * Check if we have skinned meshes. * @param lodLevel The LOD level to check for. * @result Returns true when skinned meshes are present in the specified LOD level, otherwise false is returned. */ - bool CheckIfHasSkinnedMeshes(AZ::u32 lodLevel) const; + bool CheckIfHasSkinnedMeshes(size_t lodLevel) const; /** * Extract a list with nodes that represent bones. @@ -246,7 +245,7 @@ namespace EMotionFX * @param outBoneList The array of indices to nodes that will be filled with the nodes that are bones. When the outBoneList array * already contains items, the array will first be cleared, so all existing contents will be lost. */ - void ExtractBoneList(uint32 lodLevel, MCore::Array* outBoneList) const; + void ExtractBoneList(size_t lodLevel, AZStd::vector* outBoneList) const; //------------------------------------------------ void SetPhysicsSetup(const AZStd::shared_ptr& physicsSetup); @@ -262,7 +261,7 @@ namespace EMotionFX * @param lodLevel The geometry LOD level to work on. * @param numMaterials The amount of materials to pre-allocate space for. */ - void ReserveMaterials(uint32 lodLevel, uint32 numMaterials); + void ReserveMaterials(size_t lodLevel, size_t numMaterials); /** * Get a given material. @@ -270,7 +269,7 @@ namespace EMotionFX * @param nr The material number to get. * @result A pointer to the material. */ - Material* GetMaterial(uint32 lodLevel, uint32 nr) const; + Material* GetMaterial(size_t lodLevel, size_t nr) const; /** * Find the material number/index of the material with the specified name. @@ -280,7 +279,7 @@ namespace EMotionFX * @result Returns the material number/index, which you can use to GetMaterial. When no material with the given name * can be found, a value of MCORE_INVALIDINDEX32 is returned. */ - uint32 FindMaterialIndexByName(uint32 lodLevel, const char* name) const; + size_t FindMaterialIndexByName(size_t lodLevel, const char* name) const; /** * Set a given material. @@ -288,14 +287,14 @@ namespace EMotionFX * @param nr The material number to set. * @param mat The material to set at this index. */ - void SetMaterial(uint32 lodLevel, uint32 nr, Material* mat); + void SetMaterial(size_t lodLevel, size_t nr, Material* mat); /** * Add a material to the back of the material list. * @param lodLevel The LOD level add the material to. * @param mat The material to add to the back of the list. */ - void AddMaterial(uint32 lodLevel, Material* mat); + void AddMaterial(size_t lodLevel, Material* mat); /** * Remove the given material from the material list and reassign all material numbers of the sub meshes @@ -307,14 +306,14 @@ namespace EMotionFX * @param lodLevel The LOD level add the material to. * @param index The material index of the material to remove. */ - void RemoveMaterial(uint32 lodLevel, uint32 index); + void RemoveMaterial(size_t lodLevel, size_t index); /** * Get the number of materials. * @param lodLevel The LOD level to get the number of material from. * @result The number of materials this actor has/uses. */ - uint32 GetNumMaterials(uint32 lodLevel) const; + size_t GetNumMaterials(size_t lodLevel) const; /** * Removes all materials from this actor. @@ -330,7 +329,7 @@ namespace EMotionFX * @param index The material number to check. * @result Returns true when there are meshes using the material, otherwise false is returned. */ - bool CheckIfIsMaterialUsed(uint32 lodLevel, uint32 index) const; + bool CheckIfIsMaterialUsed(size_t lodLevel, size_t index) const; //------------------------------------------------ @@ -349,26 +348,26 @@ namespace EMotionFX * @param[in] copySkeletalLODFlags Copy over the skeletal LOD flags in case of true, skip them in case of false. * @param[in] delLODActorFromMem When set to true, the method will automatically delete the given copyActor from memory. */ - void CopyLODLevel(Actor* copyActor, uint32 copyLODLevel, uint32 replaceLODLevel, bool copySkeletalLODFlags); + void CopyLODLevel(Actor* copyActor, size_t copyLODLevel, size_t replaceLODLevel, bool copySkeletalLODFlags); /** * Insert LOD level at the given position. * This function will not copy any meshes, deformer, morph targets or materials but just insert an empty LOD level. * @param[in] insertAt The position to insert the new LOD level. */ - void InsertLODLevel(uint32 insertAt); + void InsertLODLevel(size_t insertAt); /** * Set the number of LOD levels. * This will be called by the importer. Do not use manually. */ - void SetNumLODLevels(uint32 numLODs, bool adjustMorphSetup = true); + void SetNumLODLevels(size_t numLODs, bool adjustMorphSetup = true); /** * Get the number of LOD levels inside this actor. * @result The number of LOD levels. This value is at least 1, since the full detail LOD is always there. */ - uint32 GetNumLODLevels() const; + size_t GetNumLODLevels() const; //-------------------------------------------------------------------------- @@ -386,7 +385,7 @@ namespace EMotionFX * @param outNumVertices The integer to write the number of vertices in. * @param outNumIndices The integer to write the number of indices in. */ - void CalcMeshTotals(uint32 lodLevel, uint32* outNumPolygons, uint32* outNumVertices, uint32* outNumIndices) const; + void CalcMeshTotals(size_t lodLevel, uint32* outNumPolygons, uint32* outNumVertices, uint32* outNumIndices) const; /** * Calculates the total number of vertices and indices of all STATIC node meshes for the given LOD. @@ -395,7 +394,7 @@ namespace EMotionFX * @param outNumVertices The integer to write the number of vertices in. * @param outNumIndices The integer to write the number of indices in. */ - void CalcStaticMeshTotals(uint32 lodLevel, uint32* outNumVertices, uint32* outNumIndices); + void CalcStaticMeshTotals(size_t lodLevel, uint32* outNumVertices, uint32* outNumIndices); /** * Calculates the total number of vertices and indices of all DEFORMABLE node meshes for the given LOD. @@ -405,7 +404,7 @@ namespace EMotionFX * @param outNumVertices The integer to write the number of vertices in. * @param outNumIndices The integer to write the number of indices in. */ - void CalcDeformableMeshTotals(uint32 lodLevel, uint32* outNumVertices, uint32* outNumIndices); + void CalcDeformableMeshTotals(size_t lodLevel, uint32* outNumVertices, uint32* outNumIndices); /** * Calculates the maximum number of bone influences. @@ -413,7 +412,7 @@ namespace EMotionFX * @param lodLevel The LOD level, where 0 is the highest detail LOD level. This value must be in range of [0..GetNumLODLevels()-1]. * @result The maximum number of influences. This will be 0 for non-softskinned objects. */ - uint32 CalcMaxNumInfluences(uint32 lodLevel) const; + size_t CalcMaxNumInfluences(size_t lodLevel) const; /** * Calculates the maximum number of bone influences. @@ -425,7 +424,7 @@ namespace EMotionFX * @param lodLevel The detail level to calculate the results for. A value of 0 is the highest detail. * @result The maximum number of vertex/bone influences. This will be 0 for rigid, non-skinned objects. */ - uint32 CalcMaxNumInfluences(uint32 lodLevel, AZStd::vector& outVertexCounts) const; + size_t CalcMaxNumInfluences(size_t lodLevel, AZStd::vector& outVertexCounts) const; /** * Verify if the skinning will look correctly in the given geometry LOD for a given skeletal LOD level. @@ -439,7 +438,7 @@ namespace EMotionFX * disabled nodes from the given skeletal LOD level. * @param geometryLODLevel The geometry LOD level to test the skeletal LOD against with. */ - void VerifySkinning(MCore::Array& conflictNodeFlags, uint32 skeletalLODLevel, uint32 geometryLODLevel); + void VerifySkinning(AZStd::vector& conflictNodeFlags, size_t skeletalLODLevel, size_t geometryLODLevel); /** * Checks if the given material is used by a given mesh. @@ -447,7 +446,7 @@ namespace EMotionFX * @param materialIndex The index of the material to check. * @return True if one of the submeshes of the given mesh uses the given material, false if not. */ - bool CheckIfIsMaterialUsed(Mesh* mesh, uint32 materialIndex) const; + bool CheckIfIsMaterialUsed(Mesh* mesh, size_t materialIndex) const; //------------------ @@ -523,15 +522,15 @@ namespace EMotionFX * Get the number of dependencies. * @result The number of dependencies that this actor has on other actors. */ - MCORE_INLINE uint32 GetNumDependencies() const { return mDependencies.GetLength(); } + MCORE_INLINE size_t GetNumDependencies() const { return m_dependencies.size(); } /** * Get a given dependency. * @param nr The dependency number, which must be in range of [0..GetNumDependencies()-1]. * @result A pointer to the dependency. */ - MCORE_INLINE Dependency* GetDependency(uint32 nr) { return &mDependencies[nr]; } - MCORE_INLINE const Dependency* GetDependency(uint32 nr) const { return &mDependencies[nr]; } + MCORE_INLINE Dependency* GetDependency(size_t nr) { return &m_dependencies[nr]; } + MCORE_INLINE const Dependency* GetDependency(size_t nr) const { return &m_dependencies[nr]; } /** * Recursively add dependencies that this actor has on other actors. @@ -547,7 +546,7 @@ namespace EMotionFX * @result A smart pointer object to the morph setup. Use the MCore::Pointer::GetPointer() to get the actual pointer. * That GetPointer() method will return nullptr when there is no morph setup for the given LOD level. */ - MCORE_INLINE MorphSetup* GetMorphSetup(uint32 geomLODLevel) const { return mMorphSetups[geomLODLevel]; } + MCORE_INLINE MorphSetup* GetMorphSetup(size_t geomLODLevel) const { return m_morphSetups[geomLODLevel]; } /** * Remove all morph setups. Morph setups contain all morph targtets. @@ -562,18 +561,7 @@ namespace EMotionFX * @param lodLevel The LOD level, which must be in range of [0..GetNumLODLevels()-1]. * @param setup The morph setup for this LOD. */ - void SetMorphSetup(uint32 lodLevel, MorphSetup* setup); - - /** - * Update the oriented bounding volumes (OBB) of all the nodes inside this actor. - * This is a very heavy calculation and must NOT be performed on a per-frame basis but only as pre-process step. - * The OBBs of the nodes are already being calculated at export time, so you shouldn't really need to use this method. - * Only when the bind pose geometry has changed you can update the node OBBs by calling this method. - * For more information about how the bounds are calculated please see the Node::GetOBB() and Node::CalcOBBFromBindPose() methods. - * The calculations performed by this method are automatically spread over multiple threads to improve the performance. - * @param lodLevel The geometry LOD level to use while calculating the object oriented bounds per node. - */ - void UpdateNodeBindPoseOBBs(uint32 lodLevel); + void SetMorphSetup(size_t lodLevel, MorphSetup* setup); /** * Get the number of node groups inside this actor object. @@ -661,16 +649,16 @@ namespace EMotionFX * @param nodeIndex The node index to get the info for. * @result A reference to the mirror info. */ - MCORE_INLINE NodeMirrorInfo& GetNodeMirrorInfo(uint32 nodeIndex) { return mNodeMirrorInfos[nodeIndex]; } + MCORE_INLINE NodeMirrorInfo& GetNodeMirrorInfo(size_t nodeIndex) { return m_nodeMirrorInfos[nodeIndex]; } /** * Get the mirror info for a given node. * @param nodeIndex The node index to get the info for. * @result A reference to the mirror info. */ - MCORE_INLINE const NodeMirrorInfo& GetNodeMirrorInfo(uint32 nodeIndex) const { return mNodeMirrorInfos[nodeIndex]; } + MCORE_INLINE const NodeMirrorInfo& GetNodeMirrorInfo(size_t nodeIndex) const { return m_nodeMirrorInfos[nodeIndex]; } - MCORE_INLINE bool GetHasMirrorInfo() const { return (mNodeMirrorInfos.GetLength() != 0); } + MCORE_INLINE bool GetHasMirrorInfo() const { return (m_nodeMirrorInfos.size() != 0); } //--------------------------------------------------------------- @@ -747,7 +735,7 @@ namespace EMotionFX * @param startNodeIndex The node to start looking at, for example the node index of the finger bone. * @result Returns the index of the first active node, when moving up the hierarchy towards the root node. Returns MCORE_INVALIDINDEX32 when not found. */ - uint32 FindFirstActiveParentBone(uint32 skeletalLOD, uint32 startNodeIndex) const; + size_t FindFirstActiveParentBone(size_t skeletalLOD, size_t startNodeIndex) const; /** * Make the geometry LOD levels compatible with the skinning LOD levels. @@ -758,38 +746,38 @@ namespace EMotionFX void MakeGeomLODsCompatibleWithSkeletalLODs(); void ReinitializeMeshDeformers(); - void PostCreateInit(bool makeGeomLodsCompatibleWithSkeletalLODs = true, bool generateOBBs = true, bool convertUnitType = true); + void PostCreateInit(bool makeGeomLodsCompatibleWithSkeletalLODs = true, bool convertUnitType = true); void AutoDetectMirrorAxes(); - const MCore::Array& GetNodeMirrorInfos() const; - MCore::Array& GetNodeMirrorInfos(); - void SetNodeMirrorInfos(const MCore::Array& mirrorInfos); + const AZStd::vector& GetNodeMirrorInfos() const; + AZStd::vector& GetNodeMirrorInfos(); + void SetNodeMirrorInfos(const AZStd::vector& mirrorInfos); bool GetHasMirrorAxesDetected() const; - MCORE_INLINE const AZStd::vector& GetInverseBindPoseTransforms() const { return mInvBindPoseTransforms; } - MCORE_INLINE Pose* GetBindPose() { return mSkeleton->GetBindPose(); } - MCORE_INLINE const Pose* GetBindPose() const { return mSkeleton->GetBindPose(); } + MCORE_INLINE const AZStd::vector& GetInverseBindPoseTransforms() const { return m_invBindPoseTransforms; } + MCORE_INLINE Pose* GetBindPose() { return m_skeleton->GetBindPose(); } + MCORE_INLINE const Pose* GetBindPose() const { return m_skeleton->GetBindPose(); } /** * Get the inverse bind pose (in world space) transform of a given joint. * @param jointIndex The joint number, which must be in range of [0..GetNumNodes()-1]. * @result The inverse of the bind pose transform. */ - MCORE_INLINE const Transform& GetInverseBindPoseTransform(uint32 nodeIndex) const { return mInvBindPoseTransforms[nodeIndex]; } + MCORE_INLINE const Transform& GetInverseBindPoseTransform(size_t nodeIndex) const { return m_invBindPoseTransforms[nodeIndex]; } void ReleaseTransformData(); void ResizeTransformData(); void CopyTransformsFrom(const Actor* other); - const MCore::AABB& GetStaticAABB() const; - void SetStaticAABB(const MCore::AABB& box); - void UpdateStaticAABB(); // VERY heavy operation, you shouldn't call this ever (internally creates an actor instance, updates mesh deformers, calcs a mesh based aabb, destroys the actor instance again) + const AZ::Aabb& GetStaticAabb() const; + void SetStaticAabb(const AZ::Aabb& aabb); + void UpdateStaticAabb(); // VERY heavy operation, you shouldn't call this ever (internally creates an actor instance, updates mesh deformers, calcs a mesh based aabb, destroys the actor instance again) - void SetThreadIndex(uint32 index) { mThreadIndex = index; } - uint32 GetThreadIndex() const { return mThreadIndex; } + void SetThreadIndex(uint32 index) { m_threadIndex = index; } + uint32 GetThreadIndex() const { return m_threadIndex; } - Mesh* GetMesh(uint32 lodLevel, uint32 nodeIndex) const; - MeshDeformerStack* GetMeshDeformerStack(uint32 lodLevel, uint32 nodeIndex) const; + Mesh* GetMesh(size_t lodLevel, size_t nodeIndex) const; + MeshDeformerStack* GetMeshDeformerStack(size_t lodLevel, size_t nodeIndex) const; /** Finds the mesh points for which the specified node is the node with the highest influence. * This is a pretty expensive function which is only intended for use in the editor. @@ -799,69 +787,18 @@ namespace EMotionFX */ void FindMostInfluencedMeshPoints(const Node* node, AZStd::vector& outPoints) const; - MCORE_INLINE Skeleton* GetSkeleton() const { return mSkeleton; } - MCORE_INLINE uint32 GetNumNodes() const { return mSkeleton->GetNumNodes(); } + MCORE_INLINE Skeleton* GetSkeleton() const { return m_skeleton; } + MCORE_INLINE size_t GetNumNodes() const { return m_skeleton->GetNumNodes(); } - void SetMesh(uint32 lodLevel, uint32 nodeIndex, Mesh* mesh); - void SetMeshDeformerStack(uint32 lodLevel, uint32 nodeIndex, MeshDeformerStack* stack); + void SetMesh(size_t lodLevel, size_t nodeIndex, Mesh* mesh); + void SetMeshDeformerStack(size_t lodLevel, size_t nodeIndex, MeshDeformerStack* stack); - bool CheckIfHasMorphDeformer(uint32 lodLevel, uint32 nodeIndex) const; - bool CheckIfHasSkinningDeformer(uint32 lodLevel, uint32 nodeIndex) const; + bool CheckIfHasMorphDeformer(size_t lodLevel, size_t nodeIndex) const; + bool CheckIfHasSkinningDeformer(size_t lodLevel, size_t nodeIndex) const; - /** - * Calculate the object oriented box for a given LOD level. - * This will try to fit the tightest bounding box around the mesh of a node. - * If the node has no mesh and acts as bone inside skinning deformations the resulting box will contain - * all the vertices that are influenced by this given node/bone. - * Calculating this box is already done at export time. But you can use this to recalculate it if the mesh data changed. - * This method is relatively slow and not meant for per-frame calculations but only for preprocessing. - * You can use the GetOBB() method to retrieve the calculated box at any time. - * Nodes that do not have a mesh and not act as bone will have invalid OBB bounds, as they have no volume. You can check whether - * this is the case or not by using the MCore::OBB::IsValid() method. - * The box is stored in local space of the node. - * @param lodLevel The geometry LOD level to generate the OBBs from. - * @param nodeIndex The node to calculate the OBB for. - */ - void CalcOBBFromBindPose(uint32 lodLevel, uint32 nodeIndex); + void RemoveNodeMeshForLOD(size_t lodLevel, size_t nodeIndex, bool destroyMesh = true); - /** - * Get the object oriented bounding box for this node. - * The box is in local space. In order to convert it into world space you have to multiply the corner points of the box - * with the world space matrix of this node. - * Nodes that do not have a mesh and do not act as bone will have invalid bounds. You can use the MCore::OBB::CheckIfIsValid() method to check if - * the bounds are valid bounds or not. If it is not, then it means there was nothing to calculate the box from. - * Object Oriented Boxes for the nodes are calculated at export time by using the Actor::UpdateNodeBindPoseOBBs() and Node::CalcOBBFromBindPose() methods. - * @param nodeIndex The index of the node to get the OBB for. - * @result The object oriented bounding box that has been calculated before already. - */ - MCore::OBB& GetNodeOBB(uint32 nodeIndex) { return mNodeInfos[nodeIndex].mOBB; } - - /** - * Get the object oriented bounding box for this node. - * The box is in local space. In order to convert it into world space you have to multiply the corner points of the box - * with the world space matrix of this node. - * Nodes that do not have a mesh and do not act as bone will have invalid bounds. You can use the MCore::OBB::CheckIfIsValid() method to check if - * the bounds are valid bounds or not. If it is not, then it means there was nothing to calculate the box from. - * Object Oriented Boxes for the nodes are calculated at export time by using the Actor::UpdateNodeBindPoseOBBs() and Node::CalcOBBFromBindPose() methods. - * @param nodeIndex The index of the node to get the OBB for. - * @result The object oriented bounding box that has been calculated before already. - */ - const MCore::OBB& GetNodeOBB(uint32 nodeIndex) const { return mNodeInfos[nodeIndex].mOBB; } - - /** - * Set the object oriented bounding box for this node. - * The box is in local space. In order to convert it into world space you have to multiply the corner points of the box - * with the world space matrix of this node. - * Nodes that do not have a mesh and do not act as bone will have invalid bounds. You can use the MCore::OBB::CheckIfIsValid() method to check if - * the bounds are valid bounds or not. If it is not, then it means there was nothing to calculate the box from. - * @param nodeIndex The index of the node to set the OBB for. - * @param obb The object oriented bounding box that has been calculated before already. - */ - void SetNodeOBB(uint32 nodeIndex, const MCore::OBB& obb) { mNodeInfos[nodeIndex].mOBB = obb; } - - void RemoveNodeMeshForLOD(uint32 lodLevel, uint32 nodeIndex, bool destroyMesh = true); - - void SetNumNodes(uint32 numNodes); + void SetNumNodes(size_t numNodes); void SetUnitType(MCore::Distance::EUnitType unitType); MCore::Distance::EUnitType GetUnitType() const; @@ -871,9 +808,9 @@ namespace EMotionFX EAxis FindBestMatchingMotionExtractionAxis() const; - MCORE_INLINE uint32 GetRetargetRootNodeIndex() const { return mRetargetRootNode; } - MCORE_INLINE Node* GetRetargetRootNode() const { return (mRetargetRootNode != MCORE_INVALIDINDEX32) ? mSkeleton->GetNode(mRetargetRootNode) : nullptr; } - void SetRetargetRootNodeIndex(uint32 nodeIndex); + MCORE_INLINE size_t GetRetargetRootNodeIndex() const { return m_retargetRootNode; } + MCORE_INLINE Node* GetRetargetRootNode() const { return (m_retargetRootNode != InvalidIndex) ? m_skeleton->GetNode(m_retargetRootNode) : nullptr; } + void SetRetargetRootNodeIndex(size_t nodeIndex); void SetRetargetRootNode(Node* node); void AutoSetupSkeletalLODsBasedOnSkinningData(const AZStd::vector& alwaysIncludeJoints); @@ -909,7 +846,7 @@ namespace EMotionFX void Finalize(LoadRequirement loadReq = LoadRequirement::AllowAsyncLoad); private: - void InsertJointAndParents(AZ::u32 jointIndex, AZStd::unordered_set& includedJointIndices); + void InsertJointAndParents(size_t jointIndex, AZStd::unordered_set& includedJointIndices); AZStd::unordered_map ConstructSkinToSkeletonIndexMap(const AZ::Data::Asset& skinMetaAsset); void ConstructMeshes(); @@ -917,30 +854,45 @@ namespace EMotionFX Node* FindJointByMeshName(const AZStd::string_view meshName) const; - // per node info (shared between lods) - struct EMFX_API NodeInfo - { - MCore::OBB mOBB; - - NodeInfo(); - }; - // data per node, per lod struct EMFX_API NodeLODInfo { - Mesh* mMesh; - MeshDeformerStack* mStack; + Mesh* m_mesh; + MeshDeformerStack* m_stack; NodeLODInfo(); + NodeLODInfo(const NodeLODInfo&) = delete; + NodeLODInfo(NodeLODInfo&& rhs) + { + if (&rhs == this) + { + return; + } + m_mesh = rhs.m_mesh; + m_stack = rhs.m_stack; + rhs.m_mesh = nullptr; + rhs.m_stack = nullptr; + } + NodeLODInfo& operator=(const NodeLODInfo&) = delete; + NodeLODInfo& operator=(NodeLODInfo&& rhs) + { + if (&rhs == this) + { + return *this; + } + m_mesh = rhs.m_mesh; + m_stack = rhs.m_stack; + rhs.m_mesh = nullptr; + rhs.m_stack = nullptr; + return *this; + } ~NodeLODInfo(); }; // a lod level struct EMFX_API LODLevel { - MCore::Array mNodeInfos; - - LODLevel(); + AZStd::vector m_nodeInfos; }; struct MeshLODData @@ -966,32 +918,31 @@ namespace EMotionFX Node* FindMeshJoint(const AZ::Data::Asset& lodModelAsset) const; - Skeleton* mSkeleton; /**< The skeleton, containing the nodes and bind pose. */ - MCore::Array mDependencies; /**< The dependencies on other actors (shared meshes and transforms). */ - AZStd::vector mNodeInfos; /**< The per node info, shared between lods. */ - AZStd::string mName; /**< The name of the actor. */ - AZStd::string mFileName; /**< The filename of the actor. */ - MCore::Array mNodeMirrorInfos; /**< The array of node mirror info. */ - MCore::Array< MCore::Array< Material* > > mMaterials; /**< A collection of materials (for each lod). */ - MCore::Array< MorphSetup* > mMorphSetups; /**< A morph setup for each geometry LOD. */ - MCore::SmallArray mNodeGroups; /**< The set of node groups. */ + Skeleton* m_skeleton; /**< The skeleton, containing the nodes and bind pose. */ + AZStd::vector m_dependencies; /**< The dependencies on other actors (shared meshes and transforms). */ + AZStd::string m_name; /**< The name of the actor. */ + AZStd::string m_fileName; /**< The filename of the actor. */ + AZStd::vector m_nodeMirrorInfos; /**< The array of node mirror info. */ + AZStd::vector< AZStd::vector< Material* > > m_materials; /**< A collection of materials (for each lod). */ + AZStd::vector< MorphSetup* > m_morphSetups; /**< A morph setup for each geometry LOD. */ + MCore::SmallArray m_nodeGroups; /**< The set of node groups. */ AZStd::shared_ptr m_physicsSetup; /**< Hit detection, ragdoll and cloth colliders, joint limits and rigid bodies. */ AZStd::shared_ptr m_simulatedObjectSetup; /**< Setup for simulated objects */ - MCore::Distance::EUnitType mUnitType; /**< The unit type used on export. */ - MCore::Distance::EUnitType mFileUnitType; /**< The unit type used on export. */ - AZStd::vector mInvBindPoseTransforms; /**< The inverse world space bind pose transforms. */ - void* mCustomData; /**< Some custom data, for example a pointer to your own game character class which is linked to this actor. */ - uint32 mMotionExtractionNode; /**< The motion extraction node. This is the node from which to transfer a filtered part of the motion onto the actor instance. Can also be MCORE_INVALIDINDEX32 when motion extraction is disabled. */ - uint32 mRetargetRootNode; /**< The retarget root node, which controls the height displacement of the character. This is most likely the hip or pelvis node. */ - uint32 mID; /**< The unique identification number for the actor. */ - uint32 mThreadIndex; /**< The thread number we are running on, which is a value starting at 0, up to the number of threads in the job system. */ - MCore::AABB mStaticAABB; /**< The static AABB. */ - bool mDirtyFlag; /**< The dirty flag which indicates whether the user has made changes to the actor since the last file save operation. */ - bool mUsedForVisualization; /**< Indicates if the actor is used for visualization specific things and is not used as a normal in-game actor. */ + MCore::Distance::EUnitType m_unitType; /**< The unit type used on export. */ + MCore::Distance::EUnitType m_fileUnitType; /**< The unit type used on export. */ + AZStd::vector m_invBindPoseTransforms; /**< The inverse world space bind pose transforms. */ + void* m_customData; /**< Some custom data, for example a pointer to your own game character class which is linked to this actor. */ + size_t m_motionExtractionNode; /**< The motion extraction node. This is the node from which to transfer a filtered part of the motion onto the actor instance. Can also be MCORE_INVALIDINDEX32 when motion extraction is disabled. */ + size_t m_retargetRootNode; /**< The retarget root node, which controls the height displacement of the character. This is most likely the hip or pelvis node. */ + uint32 m_id; /**< The unique identification number for the actor. */ + uint32 m_threadIndex; /**< The thread number we are running on, which is a value starting at 0, up to the number of threads in the job system. */ + AZ::Aabb m_staticAabb; /**< The static AABB. */ + bool m_dirtyFlag; /**< The dirty flag which indicates whether the user has made changes to the actor since the last file save operation. */ + bool m_usedForVisualization; /**< Indicates if the actor is used for visualization specific things and is not used as a normal in-game actor. */ bool m_optimizeSkeleton; /**< Indicates if we should perform/ */ bool m_isReady = false; /**< If actor as well as its dependent files are fully loaded and initialized.*/ #if defined(EMFX_DEVELOPMENT_BUILD) - bool mIsOwnedByRuntime; /**< Set if the actor is used/owned by the engine runtime. */ + bool m_isOwnedByRuntime; /**< Set if the actor is used/owned by the engine runtime. */ #endif // EMFX_DEVELOPMENT_BUILD }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index b2091f967f..6097784e2f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -45,31 +45,27 @@ namespace EMotionFX { MCORE_ASSERT(actor); - // set the memory categories - mAttachments.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORINSTANCES); - mDependencies.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORINSTANCES); - mEnabledNodes.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORINSTANCES); - mEnabledNodes.Reserve(actor->GetNumNodes()); + m_enabledNodes.reserve(actor->GetNumNodes()); // set the actor and create the motion system - mBoolFlags = 0; - mActor = actor; - mLODLevel = 0; + m_boolFlags = 0; + m_actor = actor; + m_lodLevel = 0; m_requestedLODLevel = 0; - mNumAttachmentRefs = 0; - mThreadIndex = threadIndex; - mAttachedTo = nullptr; - mSelfAttachment = nullptr; - mCustomData = nullptr; - mID = MCore::GetIDGenerator().GenerateID(); - mVisualizeScale = 1.0f; - mMotionSamplingRate = 0.0f; - mMotionSamplingTimer = 0.0f; + m_numAttachmentRefs = 0; + m_threadIndex = threadIndex; + m_attachedTo = nullptr; + m_selfAttachment = nullptr; + m_customData = nullptr; + m_id = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); + m_visualizeScale = 1.0f; + m_motionSamplingRate = 0.0f; + m_motionSamplingTimer = 0.0f; - mTrajectoryDelta.IdentityWithZeroScale(); - mStaticAABB.Init(); + m_trajectoryDelta.IdentityWithZeroScale(); + m_staticAabb = AZ::Aabb::CreateNull(); - mAnimGraphInstance = nullptr; + m_animGraphInstance = nullptr; // set the boolean defaults SetFlag(BOOL_ISVISIBLE, true); @@ -88,18 +84,18 @@ namespace EMotionFX EnableAllNodes(); // apply actor node group default states (disable groups of nodes that are disabled on default) - const uint32 numGroups = mActor->GetNumNodeGroups(); + const uint32 numGroups = m_actor->GetNumNodeGroups(); for (uint32 i = 0; i < numGroups; ++i) { - if (mActor->GetNodeGroup(i)->GetIsEnabledOnDefault() == false) // if this group is disabled on default + if (m_actor->GetNodeGroup(i)->GetIsEnabledOnDefault() == false) // if this group is disabled on default { - mActor->GetNodeGroup(i)->DisableNodes(this); // disable all nodes inside this group + m_actor->GetNodeGroup(i)->DisableNodes(this); // disable all nodes inside this group } } // disable nodes that are disabled in LOD 0 - Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { if (skeleton->GetNode(n)->GetSkeletalLODStatus(0) == false) { @@ -108,27 +104,27 @@ namespace EMotionFX } // setup auto bounds update (it is enabled on default) - mBoundsUpdateFrequency = 0.0f; - mBoundsUpdatePassedTime = 0.0f; - mBoundsUpdateType = BOUNDS_STATIC_BASED; - mBoundsUpdateItemFreq = 1; + m_boundsUpdateFrequency = 0.0f; + m_boundsUpdatePassedTime = 0.0f; + m_boundsUpdateType = BOUNDS_STATIC_BASED; + m_boundsUpdateItemFreq = 1; // initialize the actor local and global transform - mParentWorldTransform.Identity(); - mLocalTransform.Identity(); - mWorldTransform.Identity(); - mWorldTransformInv.Identity(); + m_parentWorldTransform.Identity(); + m_localTransform.Identity(); + m_worldTransform.Identity(); + m_worldTransformInv.Identity(); // init the morph setup instance - mMorphSetup = MorphSetupInstance::Create(); - mMorphSetup->Init(actor->GetMorphSetup(0)); + m_morphSetup = MorphSetupInstance::Create(); + m_morphSetup->Init(actor->GetMorphSetup(0)); // initialize the transformation data of this instance - mTransformData = TransformData::Create(); - mTransformData->InitForActorInstance(this); + m_transformData = TransformData::Create(); + m_transformData->InitForActorInstance(this); // create the motion system - mMotionSystem = MotionLayerSystem::Create(this); + m_motionSystem = MotionLayerSystem::Create(this); // update the global and local matrices UpdateTransformations(0.0f); @@ -137,15 +133,15 @@ namespace EMotionFX UpdateDependencies(); // update the static based AABB dimensions - mStaticAABB = mActor->GetStaticAABB(); - if (mStaticAABB.CheckIfIsValid() == false) + m_staticAabb = m_actor->GetStaticAabb(); + if (!m_staticAabb.IsValid()) { UpdateMeshDeformers(0.0f, true); // TODO: not really thread safe because of shared meshes, although it probably will output correctly - UpdateStaticBasedAABBDimensions(); + UpdateStaticBasedAabbDimensions(); } // update the bounds - UpdateBounds(0, mBoundsUpdateType, 1); + UpdateBounds(/*lodLevel=*/0, m_boundsUpdateType); // register it GetActorManager().RegisterActorInstance(this); @@ -160,24 +156,24 @@ namespace EMotionFX ActorInstanceNotificationBus::Broadcast(&ActorInstanceNotificationBus::Events::OnActorInstanceDestroyed, this); // get rid of the motion system - if (mMotionSystem) + if (m_motionSystem) { - mMotionSystem->Destroy(); + m_motionSystem->Destroy(); } - if (mAnimGraphInstance) + if (m_animGraphInstance) { - mAnimGraphInstance->Destroy(); + m_animGraphInstance->Destroy(); } GetDebugDraw().UnregisterActorInstance(this); // delete all attachments // actor instances that are attached will be detached, and not deleted from memory - const uint32 numAttachments = mAttachments.GetLength(); - for (uint32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = m_attachments.size(); + for (size_t i = 0; i < numAttachments; ++i) { - ActorInstance* attachmentActorInstance = mAttachments[i]->GetAttachmentActorInstance(); + ActorInstance* attachmentActorInstance = m_attachments[i]->GetAttachmentActorInstance(); if (attachmentActorInstance) { attachmentActorInstance->SetAttachedTo(nullptr); @@ -185,24 +181,24 @@ namespace EMotionFX attachmentActorInstance->DecreaseNumAttachmentRefs(); GetActorManager().UpdateActorInstanceStatus(attachmentActorInstance); } - mAttachments[i]->Destroy(); + m_attachments[i]->Destroy(); } - mAttachments.Clear(); + m_attachments.clear(); - if (mMorphSetup) + if (m_morphSetup) { - mMorphSetup->Destroy(); + m_morphSetup->Destroy(); } - if (mTransformData) + if (m_transformData) { - mTransformData->Destroy(); + m_transformData->Destroy(); } // remove the attachment from the actor instance where it is attached to if (GetIsAttachment()) { - mAttachedTo->RemoveAttachment(this /*, false*/); + m_attachedTo->RemoveAttachment(this /*, false*/); } // automatically unregister the actor instance @@ -227,23 +223,23 @@ namespace EMotionFX if (recorder.GetIsInPlayMode() && recorder.GetHasRecorded(this)) { // output the anim graph instance, this doesn't overwrite transforms, just some things internally - if (recorder.GetRecordSettings().mRecordAnimGraphStates && mAnimGraphInstance) + if (recorder.GetRecordSettings().m_recordAnimGraphStates && m_animGraphInstance) { - mAnimGraphInstance->Update(0.0f); - mAnimGraphInstance->Output(nullptr); + m_animGraphInstance->Update(0.0f); + m_animGraphInstance->Output(nullptr); } // apply the main transformation recorder.SampleAndApplyMainTransform(recorder.GetCurrentPlayTime(), this); // apply the node transforms - if (recorder.GetRecordSettings().mRecordTransforms) + if (recorder.GetRecordSettings().m_recordTransforms) { recorder.SampleAndApplyTransforms(recorder.GetCurrentPlayTime(), this); } // sample the morph targets - if (recorder.GetRecordSettings().mRecordMorphs) + if (recorder.GetRecordSettings().m_recordMorphs) { recorder.SampleAndApplyMorphs(recorder.GetCurrentPlayTime(), this); } @@ -254,13 +250,13 @@ namespace EMotionFX UpdateAttachments(); // update the attachment parent matrices // update the bounds when needed - if (GetBoundsUpdateEnabled() && mBoundsUpdateType != BOUNDS_MESH_BASED) + if (GetBoundsUpdateEnabled()) { - mBoundsUpdatePassedTime += timePassedInSeconds; - if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) + m_boundsUpdatePassedTime += timePassedInSeconds; + if (m_boundsUpdatePassedTime >= m_boundsUpdateFrequency) { - UpdateBounds(mLODLevel, BOUNDS_NODE_BASED, mBoundsUpdateItemFreq); - mBoundsUpdatePassedTime = 0.0f; + UpdateBounds(m_lodLevel, m_boundsUpdateType, m_boundsUpdateItemFreq); + m_boundsUpdatePassedTime = 0.0f; } } @@ -274,13 +270,13 @@ namespace EMotionFX if (!attachment || !attachment->GetIsInfluencedByMultipleJoints()) { // update the motion system, which performs all blending, and updates all local transforms (excluding the local matrices) - if (mAnimGraphInstance) + if (m_animGraphInstance) { - mAnimGraphInstance->Update(timePassedInSeconds); + m_animGraphInstance->Update(timePassedInSeconds); UpdateWorldTransform(); if (updateJointTransforms && sampleMotions) { - mAnimGraphInstance->Output(mTransformData->GetCurrentPose()); + m_animGraphInstance->Output(m_transformData->GetCurrentPose()); if (m_ragdollInstance) { @@ -288,9 +284,9 @@ namespace EMotionFX } } } - else if (mMotionSystem) + else if (m_motionSystem) { - mMotionSystem->Update(timePassedInSeconds, (updateJointTransforms && sampleMotions)); + m_motionSystem->Update(timePassedInSeconds, (updateJointTransforms && sampleMotions)); } else { @@ -300,15 +296,15 @@ namespace EMotionFX // when the actor instance isn't visible, we don't want to do more things if (!updateJointTransforms) { - if (GetBoundsUpdateEnabled() && mBoundsUpdateType == BOUNDS_STATIC_BASED) + if (GetBoundsUpdateEnabled() && m_boundsUpdateType == BOUNDS_STATIC_BASED) { - UpdateBounds(mLODLevel, mBoundsUpdateType); + UpdateBounds(m_lodLevel, m_boundsUpdateType); } return; } - mTransformData->GetCurrentPose()->ApplyMorphWeightsToActorInstance(); + m_transformData->GetCurrentPose()->ApplyMorphWeightsToActorInstance(); ApplyMorphSetup(); UpdateSkinningMatrices(); @@ -316,20 +312,20 @@ namespace EMotionFX } else // we are a skin attachment { - mLocalTransform.Identity(); - if (mAnimGraphInstance) + m_localTransform.Identity(); + if (m_animGraphInstance) { - mAnimGraphInstance->Update(timePassedInSeconds); + m_animGraphInstance->Update(timePassedInSeconds); UpdateWorldTransform(); if (updateJointTransforms && sampleMotions) { - mAnimGraphInstance->Output(mTransformData->GetCurrentPose()); + m_animGraphInstance->Output(m_transformData->GetCurrentPose()); } } - else if (mMotionSystem) + else if (m_motionSystem) { - mMotionSystem->Update(timePassedInSeconds, (updateJointTransforms && sampleMotions)); + m_motionSystem->Update(timePassedInSeconds, (updateJointTransforms && sampleMotions)); } else { @@ -339,28 +335,28 @@ namespace EMotionFX // when the actor instance isn't visible, we don't want to do more things if (!updateJointTransforms) { - if (GetBoundsUpdateEnabled() && mBoundsUpdateType == BOUNDS_STATIC_BASED) + if (GetBoundsUpdateEnabled() && m_boundsUpdateType == BOUNDS_STATIC_BASED) { - UpdateBounds(mLODLevel, mBoundsUpdateType); + UpdateBounds(m_lodLevel, m_boundsUpdateType); } return; } - mSelfAttachment->UpdateJointTransforms(*mTransformData->GetCurrentPose()); - mTransformData->GetCurrentPose()->ApplyMorphWeightsToActorInstance(); + m_selfAttachment->UpdateJointTransforms(*m_transformData->GetCurrentPose()); + m_transformData->GetCurrentPose()->ApplyMorphWeightsToActorInstance(); ApplyMorphSetup(); UpdateSkinningMatrices(); UpdateAttachments(); } // update the bounds when needed - if (GetBoundsUpdateEnabled() && mBoundsUpdateType != BOUNDS_MESH_BASED) + if (GetBoundsUpdateEnabled()) { - mBoundsUpdatePassedTime += timePassedInSeconds; - if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) + m_boundsUpdatePassedTime += timePassedInSeconds; + if (m_boundsUpdatePassedTime >= m_boundsUpdateFrequency) { - UpdateBounds(mLODLevel, mBoundsUpdateType, mBoundsUpdateItemFreq); - mBoundsUpdatePassedTime = 0.0f; + UpdateBounds(m_lodLevel, m_boundsUpdateType, m_boundsUpdateItemFreq); + m_boundsUpdatePassedTime = 0.0f; } } } @@ -368,22 +364,22 @@ namespace EMotionFX // update the world transformation void ActorInstance::UpdateWorldTransform() { - mWorldTransform = mLocalTransform; - mWorldTransform.Multiply(mParentWorldTransform); - mWorldTransformInv = mWorldTransform.Inversed(); + m_worldTransform = m_localTransform; + m_worldTransform.Multiply(m_parentWorldTransform); + m_worldTransformInv = m_worldTransform.Inversed(); } // updates the skinning matrices of all nodes void ActorInstance::UpdateSkinningMatrices() { - AZ::Matrix3x4* skinningMatrices = mTransformData->GetSkinningMatrices(); - const Pose* pose = mTransformData->GetCurrentPose(); + AZ::Matrix3x4* skinningMatrices = m_transformData->GetSkinningMatrices(); + const Pose* pose = m_transformData->GetCurrentPose(); - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const uint32 nodeNumber = GetEnabledNode(i); - Transform skinningTransform = mActor->GetInverseBindPoseTransform(nodeNumber); + const size_t nodeNumber = GetEnabledNode(i); + Transform skinningTransform = m_actor->GetInverseBindPoseTransform(nodeNumber); skinningTransform.Multiply(pose->GetModelSpaceTransform(nodeNumber)); skinningMatrices[nodeNumber] = AZ::Matrix3x4::CreateFromTransform(skinningTransform.ToAZTransform()); } @@ -395,30 +391,16 @@ namespace EMotionFX timePassedInSeconds *= GetEMotionFX().GetGlobalSimulationSpeed(); // Update the mesh deformers. - const Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = mEnabledNodes.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const Skeleton* skeleton = m_actor->GetSkeleton(); + for (uint16 nodeNr : m_enabledNodes) { - const uint16 nodeNr = mEnabledNodes[i]; Node* node = skeleton->GetNode(nodeNr); - MeshDeformerStack* stack = mActor->GetMeshDeformerStack(mLODLevel, nodeNr); + MeshDeformerStack* stack = m_actor->GetMeshDeformerStack(m_lodLevel, nodeNr); if (stack) { stack->Update(this, node, timePassedInSeconds, processDisabledDeformers); } } - - // Update the bounds when we are set to use mesh based bounds. - if (GetBoundsUpdateEnabled() && - GetBoundsUpdateType() == BOUNDS_MESH_BASED) - { - mBoundsUpdatePassedTime += timePassedInSeconds; - if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) - { - UpdateBounds(mLODLevel, mBoundsUpdateType, mBoundsUpdateItemFreq); - mBoundsUpdatePassedTime = 0.0f; - } - } } // Update the mesh morph deformers, which updates the vertex positions on the CPU, so performing CPU morphing. @@ -427,30 +409,16 @@ namespace EMotionFX timePassedInSeconds *= GetEMotionFX().GetGlobalSimulationSpeed(); // Update the mesh morph deformers. - const Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = mEnabledNodes.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const Skeleton* skeleton = m_actor->GetSkeleton(); + for (uint16 nodeNr : m_enabledNodes) { - const uint16 nodeNr = mEnabledNodes[i]; Node* node = skeleton->GetNode(nodeNr); - MeshDeformerStack* stack = mActor->GetMeshDeformerStack(mLODLevel, nodeNr); + MeshDeformerStack* stack = m_actor->GetMeshDeformerStack(m_lodLevel, nodeNr); if (stack) { stack->UpdateByModifierType(this, node, timePassedInSeconds, MorphMeshDeformer::TYPE_ID, true, processDisabledDeformers); } } - - // Update the bounds when we are set to use mesh based bounds. - if (GetBoundsUpdateEnabled() && - GetBoundsUpdateType() == BOUNDS_MESH_BASED) - { - mBoundsUpdatePassedTime += timePassedInSeconds; - if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) - { - UpdateBounds(mLODLevel, mBoundsUpdateType, mBoundsUpdateItemFreq); - mBoundsUpdatePassedTime = 0.0f; - } - } } void ActorInstance::PostPhysicsUpdate(float timePassedInSeconds) @@ -472,7 +440,7 @@ namespace EMotionFX GetActorManager().GetScheduler()->RecursiveRemoveActorInstance(root); // add the attachment - mAttachments.Add(attachment); + m_attachments.emplace_back(attachment); ActorInstance* attachmentActorInstance = attachment->GetAttachmentActorInstance(); if (attachmentActorInstance) { @@ -489,27 +457,23 @@ namespace EMotionFX } // try to find the attachment number for a given actor instance - uint32 ActorInstance::FindAttachmentNr(ActorInstance* actorInstance) + size_t ActorInstance::FindAttachmentNr(ActorInstance* actorInstance) { // for all attachments - const uint32 numAttachments = mAttachments.GetLength(); - for (uint32 i = 0; i < numAttachments; ++i) + const auto foundAttachment = AZStd::find_if(m_attachments.begin(), m_attachments.end(), [actorInstance](const Attachment* attachment) { - if (mAttachments[i]->GetAttachmentActorInstance() == actorInstance) - { - return i; - } - } + return attachment->GetAttachmentActorInstance() == actorInstance; + }); - return MCORE_INVALIDINDEX32; + return foundAttachment != m_attachments.end() ? AZStd::distance(m_attachments.begin(), foundAttachment) : InvalidIndex; } // remove an attachment by actor instance pointer bool ActorInstance::RemoveAttachment(ActorInstance* actorInstance, bool delFromMem) { // try to find the attachment - const uint32 attachmentNr = FindAttachmentNr(actorInstance); - if (attachmentNr == MCORE_INVALIDINDEX32) + const size_t attachmentNr = FindAttachmentNr(actorInstance); + if (attachmentNr == InvalidIndex) { return false; } @@ -520,16 +484,16 @@ namespace EMotionFX } // remove an attachment - void ActorInstance::RemoveAttachment(uint32 nr, bool delFromMem) + void ActorInstance::RemoveAttachment(size_t nr, bool delFromMem) { - MCORE_ASSERT(nr < mAttachments.GetLength()); + MCORE_ASSERT(nr < m_attachments.size()); // first remove the current attachment tree from the scheduler ActorInstance* root = FindAttachmentRoot(); GetActorManager().GetScheduler()->RecursiveRemoveActorInstance(root); // get the attachment - Attachment* attachment = mAttachments[nr]; + Attachment* attachment = m_attachments[nr]; // its not an attachment anymore ActorInstance* attachmentInstance = attachment->GetAttachmentActorInstance(); @@ -552,7 +516,7 @@ namespace EMotionFX } // remove it from the attachment list - mAttachments.Remove(nr); + m_attachments.erase(AZStd::next(begin(m_attachments), nr)); // and re-add the root to the scheduler GetActorManager().GetScheduler()->RecursiveInsertActorInstance(root, 0); @@ -568,9 +532,9 @@ namespace EMotionFX void ActorInstance::RemoveAllAttachments(bool delFromMem) { // keep removing the last attachment until there are none left - while (mAttachments.GetLength()) + while (m_attachments.size()) { - RemoveAttachment(mAttachments.GetLength() - 1, delFromMem); + RemoveAttachment(m_attachments.size() - 1, delFromMem); } } @@ -578,30 +542,28 @@ namespace EMotionFX void ActorInstance::UpdateDependencies() { // get rid of existing dependencies - mDependencies.Clear(); + m_dependencies.clear(); // add the main dependency Actor::Dependency mainDependency; - mainDependency.mActor = mActor; - mainDependency.mAnimGraph = (mAnimGraphInstance) ? mAnimGraphInstance->GetAnimGraph() : nullptr; - mDependencies.Add(mainDependency); + mainDependency.m_actor = m_actor; + mainDependency.m_animGraph = (m_animGraphInstance) ? m_animGraphInstance->GetAnimGraph() : nullptr; + m_dependencies.emplace_back(mainDependency); // add all dependencies stored inside the actor - const uint32 numDependencies = mActor->GetNumDependencies(); - for (uint32 i = 0; i < numDependencies; ++i) + const size_t numDependencies = m_actor->GetNumDependencies(); + for (size_t i = 0; i < numDependencies; ++i) { - mDependencies.Add(*mActor->GetDependency(i)); + m_dependencies.emplace_back(*m_actor->GetDependency(i)); } } // set the attachment matrices void ActorInstance::UpdateAttachments() { - // update all attachments - const uint32 numAttachments = mAttachments.GetLength(); - for (uint32 i = 0; i < numAttachments; ++i) + for (Attachment* attachment : m_attachments) { - mAttachments[i]->Update(); + attachment->Update(); } } @@ -610,9 +572,9 @@ namespace EMotionFX // attachment root ActorInstance* ActorInstance::FindAttachmentRoot() const { - if (mAttachedTo) + if (m_attachedTo) { - return mAttachedTo->FindAttachmentRoot(); + return m_attachedTo->FindAttachmentRoot(); } return const_cast(this); @@ -632,208 +594,85 @@ namespace EMotionFX } // update the bounding volume - void ActorInstance::UpdateBounds(uint32 geomLODLevel, EBoundsType boundsType, uint32 itemFrequency) + void ActorInstance::UpdateBounds(size_t geomLODLevel, EBoundsType boundsType, uint32 itemFrequency) { // depending on the bounding volume update type switch (boundsType) { // calculate the static based AABB case BOUNDS_STATIC_BASED: - CalcStaticBasedAABB(&mAABB); + CalcStaticBasedAabb(&m_aabb); break; // based on the world space positions of the nodes (least accurate, but fastest) case BOUNDS_NODE_BASED: - CalcNodeBasedAABB(&mAABB, itemFrequency); - break; - - // based on the world space positions of the vertices of the collision meshes (faster and more accurate than mesh based) - case BOUNDS_COLLISIONMESH_BASED: - CalcCollisionMeshBasedAABB(geomLODLevel, &mAABB, itemFrequency); + CalcNodeBasedAabb(&m_aabb, itemFrequency); break; // based on the world space positions of the vertices of the meshes (most accurate) case BOUNDS_MESH_BASED: - CalcMeshBasedAABB(geomLODLevel, &mAABB, itemFrequency); - break; - - // based on the world space positions of the vertices of the meshes (most accurate) - case BOUNDS_NODEOBB_BASED: - CalcNodeOBBBasedAABB(&mAABB, itemFrequency); - break; - - case BOUNDS_NODEOBBFAST_BASED: - CalcNodeOBBBasedAABBFast(&mAABB, itemFrequency); + UpdateMeshDeformers(0.0f); + CalcMeshBasedAabb(geomLODLevel, &m_aabb, itemFrequency); break; // when we're dealing with an unspecified bounding volume update method default: MCore::LogInfo("*** EMotionFX::ActorInstance::UpdateBounds() - Unknown boundsType specified! (%d) ***", (uint32)boundsType); } - } - - // calculate the axis aligned bounding box that contains the object oriented boxes of all nodes - void ActorInstance::CalcNodeOBBBasedAABBFast(MCore::AABB* outResult, uint32 nodeFrequency) - { - // init the axis aligned bounding box - outResult->Init(); - - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); - - // for all nodes, encapsulate the world space positions - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; i += nodeFrequency) - { - nodeNr = GetEnabledNode(i); - Node* node = skeleton->GetNode(nodeNr); - if (node->GetIncludeInBoundsCalc()) - { - const MCore::OBB& obb = mActor->GetNodeOBB(nodeNr); - if (obb.CheckIfIsValid() == false) - { - continue; - } - - // calculate the corner points of the node in local space - AZ::Vector3 minPoint, maxPoint; - obb.CalcMinMaxPoints(&minPoint, &maxPoint); - - // encapsulate the results in the AABB box - const Transform worldTransform = pose->GetWorldSpaceTransform(nodeNr); - outResult->Encapsulate(worldTransform.TransformPoint(minPoint)); - outResult->Encapsulate(worldTransform.TransformPoint(maxPoint)); - } - } - } - - // more accurate node obb based method that uses the 8 corner points of the obb - void ActorInstance::CalcNodeOBBBasedAABB(MCore::AABB* outResult, uint32 nodeFrequency) - { - // init the axis aligned bounding box - outResult->Init(); - - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); - // for all nodes, encapsulate the world space positions - AZ::Vector3 cornerPoints[8]; - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; i += nodeFrequency) + // Expand the bounding volume by a tolerance area in case set. + if (!AZ::IsClose(m_boundsExpandBy, 0.0f)) { - nodeNr = GetEnabledNode(i); - Node* node = skeleton->GetNode(nodeNr); - if (node->GetIncludeInBoundsCalc()) - { - const MCore::OBB& obb = mActor->GetNodeOBB(nodeNr); - if (obb.CheckIfIsValid() == false) - { - continue; - } - - // calculate the 8 corner points - obb.CalcCornerPoints(cornerPoints); - - const Transform worldTransform = pose->GetWorldSpaceTransform(nodeNr); - - // encapsulate all OBB world space corner points inside the AABB - for (uint32 p = 0; p < 8; ++p) - { - outResult->Encapsulate(worldTransform.TransformPoint(cornerPoints[p])); - } - } + const AZ::Vector3 center = m_aabb.GetCenter(); + const AZ::Vector3 halfExtents = m_aabb.GetExtents() * 0.5f; + const AZ::Vector3 scaledHalfExtents = halfExtents * (1.0f + m_boundsExpandBy); + m_aabb.SetMin(center - scaledHalfExtents); + m_aabb.SetMax(center + scaledHalfExtents); } } // calculate the axis aligned bounding box based on the world space positions of the nodes - void ActorInstance::CalcNodeBasedAABB(MCore::AABB* outResult, uint32 nodeFrequency) + void ActorInstance::CalcNodeBasedAabb(AZ::Aabb* outResult, uint32 nodeFrequency) { - outResult->Init(); + *outResult = AZ::Aabb::CreateNull(); - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); + const Pose* pose = m_transformData->GetCurrentPose(); + const Skeleton* skeleton = m_actor->GetSkeleton(); // for all nodes, encapsulate the world space positions - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; i += nodeFrequency) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; i += nodeFrequency) { - nodeNr = GetEnabledNode(i); + const uint16 nodeNr = GetEnabledNode(i); if (skeleton->GetNode(nodeNr)->GetIncludeInBoundsCalc()) { - outResult->Encapsulate(pose->GetWorldSpaceTransform(nodeNr).mPosition); + outResult->AddPoint(pose->GetWorldSpaceTransform(nodeNr).m_position); } } } // calculate the AABB that contains all world space vertices of all meshes - void ActorInstance::CalcMeshBasedAABB(uint32 geomLODLevel, MCore::AABB* outResult, uint32 vertexFrequency) + void ActorInstance::CalcMeshBasedAabb(size_t geomLODLevel, AZ::Aabb* outResult, uint32 vertexFrequency) { - // init the axis aligned bounding box - outResult->Init(); + *outResult = AZ::Aabb::CreateNull(); - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); + const Pose* pose = m_transformData->GetCurrentPose(); + const Skeleton* skeleton = m_actor->GetSkeleton(); // for all nodes, encapsulate the world space positions - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { const uint16 nodeNr = GetEnabledNode(i); Node* node = skeleton->GetNode(nodeNr); // skip nodes without meshes - Mesh* mesh = mActor->GetMesh(geomLODLevel, nodeNr); - if (mesh == nullptr) - { - continue; - } - - // if this node should be excluded - if (node->GetIncludeInBoundsCalc() == false) - { - continue; - } - - const Transform worldTransform = pose->GetMeshNodeWorldSpaceTransform(geomLODLevel, nodeNr); - - // calculate and encapsulate the mesh bounds inside the total mesh box - MCore::AABB meshBox; - mesh->CalcAABB(&meshBox, worldTransform, vertexFrequency); - outResult->Encapsulate(meshBox); - } - } - - void ActorInstance::CalcCollisionMeshBasedAABB(uint32 geomLODLevel, MCore::AABB* outResult, uint32 vertexFrequency) - { - // init the axis aligned bounding box - outResult->Init(); - - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); - - // for all nodes, encapsulate the world space positions - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) - { - nodeNr = GetEnabledNode(i); - Node* node = skeleton->GetNode(nodeNr); - - // skip nodes without collision meshes - Mesh* mesh = mActor->GetMesh(geomLODLevel, nodeNr); + Mesh* mesh = m_actor->GetMesh(geomLODLevel, nodeNr); if (mesh == nullptr) { continue; } - if (mesh->GetIsCollisionMesh() == false) - { - continue; - } - // if this node should be excluded if (node->GetIncludeInBoundsCalc() == false) { @@ -843,9 +682,9 @@ namespace EMotionFX const Transform worldTransform = pose->GetMeshNodeWorldSpaceTransform(geomLODLevel, nodeNr); // calculate and encapsulate the mesh bounds inside the total mesh box - MCore::AABB meshBox; - mesh->CalcAABB(&meshBox, worldTransform, vertexFrequency); - outResult->Encapsulate(meshBox); + AZ::Aabb meshBox; + mesh->CalcAabb(&meshBox, worldTransform, vertexFrequency); + outResult->AddAabb(meshBox); } } @@ -853,9 +692,9 @@ namespace EMotionFX void ActorInstance::SetupAutoBoundsUpdate(float updateFrequencyInSeconds, EBoundsType boundsType, uint32 itemFrequency) { MCORE_ASSERT(itemFrequency > 0); // zero would cause an infinite loop - mBoundsUpdateFrequency = updateFrequencyInSeconds; - mBoundsUpdateType = boundsType; - mBoundsUpdateItemFreq = itemFrequency; + m_boundsUpdateFrequency = updateFrequencyInSeconds; + m_boundsUpdateType = boundsType; + m_boundsUpdateItemFreq = itemFrequency; SetBoundsUpdateEnabled(true); } @@ -870,7 +709,7 @@ namespace EMotionFX } // if there is no morph setup, we have nothing to do - MorphSetup* morphSetup = mActor->GetMorphSetup(mLODLevel); + MorphSetup* morphSetup = m_actor->GetMorphSetup(m_lodLevel); if (morphSetup == nullptr) { return; @@ -878,8 +717,8 @@ namespace EMotionFX // apply all morph targets //bool allZero = true; - const uint32 numTargets = morphSetup->GetNumMorphTargets(); - for (uint32 i = 0; i < numTargets; ++i) + const size_t numTargets = morphSetup->GetNumMorphTargets(); + for (size_t i = 0; i < numTargets; ++i) { // get the morph target MorphTarget* morphTarget = morphSetup->GetMorphTarget(i); @@ -899,37 +738,24 @@ namespace EMotionFX morphTarget->Apply(this, weight); } } - - /* - // enable or disable all morph deformers if the weights are all zero - const uint32 numNodes = mActor->GetNumNodes(); - for (uint32 n=0; nGetNode(n); - MeshDeformerStack* stack = node->GetMeshDeformerStack( mGeometryLODLevel ).GetPointer(); - if (stack == nullptr) - continue; - - stack->EnableAllDeformersByType( MorphMeshDeformer::TYPE_ID, !allZero ); - }*/ } //--------------------- // check intersection with a ray, but don't get the intersection point or closest intersecting node - Node* ActorInstance::IntersectsCollisionMesh(uint32 lodLevel, const MCore::Ray& ray) const + Node* ActorInstance::IntersectsCollisionMesh(size_t lodLevel, const MCore::Ray& ray) const { - const Skeleton* skeleton = mActor->GetSkeleton(); - const Pose* pose = mTransformData->GetCurrentPose(); + const Skeleton* skeleton = m_actor->GetSkeleton(); + const Pose* pose = m_transformData->GetCurrentPose(); // for all nodes - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { const uint16 nodeNr = GetEnabledNode(i); // check if there is a mesh for this node - Mesh* mesh = mActor->GetMesh(lodLevel, nodeNr); + Mesh* mesh = m_actor->GetMesh(lodLevel, nodeNr); if (mesh == nullptr) { continue; @@ -952,7 +778,7 @@ namespace EMotionFX return nullptr; } - Node* ActorInstance::IntersectsCollisionMesh(uint32 lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal, AZ::Vector2* outUV, float* outBaryU, float* outBaryV, uint32* outIndices) const + Node* ActorInstance::IntersectsCollisionMesh(size_t lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal, AZ::Vector2* outUV, float* outBaryU, float* outBaryV, uint32* outIndices) const { Node* closestNode = nullptr; AZ::Vector3 point; @@ -963,17 +789,16 @@ namespace EMotionFX uint32 closestIndices[3]; uint32 triIndices[3]; - const Skeleton* skeleton = mActor->GetSkeleton(); - const Pose* pose = mTransformData->GetCurrentPose(); + const Skeleton* skeleton = m_actor->GetSkeleton(); + const Pose* pose = m_transformData->GetCurrentPose(); // check all nodes - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; i++) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; i++) { - nodeNr = GetEnabledNode(i); + const uint16 nodeNr = GetEnabledNode(i); Node* curNode = skeleton->GetNode(nodeNr); - Mesh* mesh = mActor->GetMesh(lodLevel, nodeNr); + Mesh* mesh = m_actor->GetMesh(lodLevel, nodeNr); if (mesh == nullptr) { continue; @@ -1036,7 +861,7 @@ namespace EMotionFX // calculate the interpolated normal if (outNormal || outUV) { - Mesh* mesh = mActor->GetMesh(lodLevel, closestNode->GetNodeIndex()); + Mesh* mesh = m_actor->GetMesh(lodLevel, closestNode->GetNodeIndex()); // calculate the normal at the intersection point if (outNormal) @@ -1067,21 +892,20 @@ namespace EMotionFX } // check intersection with a ray, but don't get the intersection point or closest intersecting node - Node* ActorInstance::IntersectsMesh(uint32 lodLevel, const MCore::Ray& ray) const + Node* ActorInstance::IntersectsMesh(size_t lodLevel, const MCore::Ray& ray) const { - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); + const Pose* pose = m_transformData->GetCurrentPose(); + const Skeleton* skeleton = m_actor->GetSkeleton(); // for all nodes - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = GetEnabledNode(i); + const uint16 nodeNr = GetEnabledNode(i); Node* node = skeleton->GetNode(nodeNr); // check if there is a mesh for this node - Mesh* mesh = mActor->GetMesh(lodLevel, nodeNr); + Mesh* mesh = m_actor->GetMesh(lodLevel, nodeNr); if (mesh == nullptr) { continue; @@ -1118,7 +942,7 @@ namespace EMotionFX } // intersection test that returns the closest intersection - Node* ActorInstance::IntersectsMesh(uint32 lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal, AZ::Vector2* outUV, float* outBaryU, float* outBaryV, uint32* outIndices) const + Node* ActorInstance::IntersectsMesh(size_t lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal, AZ::Vector2* outUV, float* outBaryU, float* outBaryV, uint32* outIndices) const { Node* closestNode = nullptr; AZ::Vector3 point; @@ -1129,17 +953,16 @@ namespace EMotionFX uint32 closestIndices[3]; uint32 triIndices[3]; - const Pose* pose = mTransformData->GetCurrentPose(); - const Skeleton* skeleton = mActor->GetSkeleton(); + const Pose* pose = m_transformData->GetCurrentPose(); + const Skeleton* skeleton = m_actor->GetSkeleton(); // check all nodes - uint16 nodeNr; - const uint32 numNodes = GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; i++) + const size_t numNodes = GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; i++) { - nodeNr = GetEnabledNode(i); + const uint16 nodeNr = GetEnabledNode(i); Node* curNode = skeleton->GetNode(nodeNr); - Mesh* mesh = mActor->GetMesh(lodLevel, nodeNr); + Mesh* mesh = m_actor->GetMesh(lodLevel, nodeNr); if (mesh == nullptr) { continue; @@ -1197,7 +1020,7 @@ namespace EMotionFX // calculate the interpolated normal if (outNormal || outUV) { - Mesh* mesh = mActor->GetMesh(lodLevel, closestNode->GetNodeIndex()); + Mesh* mesh = m_actor->GetMesh(lodLevel, closestNode->GetNodeIndex()); // calculate the normal at the intersection point if (outNormal) @@ -1235,32 +1058,32 @@ namespace EMotionFX void ActorInstance::EnableNode(uint16 nodeIndex) { // if this node already is at an enabled state, do nothing - if (mEnabledNodes.Contains(nodeIndex)) + if (AZStd::find(begin(m_enabledNodes), end(m_enabledNodes), nodeIndex) != end(m_enabledNodes)) { return; } - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); // find the location where to insert (as the flattened hierarchy needs to be preserved in the array) bool found = false; - uint32 curNode = nodeIndex; + size_t curNode = nodeIndex; do { // get the parent of the current node - uint32 parentIndex = skeleton->GetNode(curNode)->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + size_t parentIndex = skeleton->GetNode(curNode)->GetParentIndex(); + if (parentIndex != InvalidIndex) { - const uint32 parentArrayIndex = mEnabledNodes.Find(static_cast(parentIndex)); - if (parentArrayIndex != MCORE_INVALIDINDEX32) + const auto parentArrayIter = AZStd::find(begin(m_enabledNodes), end(m_enabledNodes), static_cast(parentIndex)); + if (parentArrayIter != end(m_enabledNodes)) { - if (parentArrayIndex + 1 >= mEnabledNodes.GetLength()) + if (parentArrayIter + 1 == end(m_enabledNodes)) { - mEnabledNodes.Add(nodeIndex); + m_enabledNodes.emplace_back(nodeIndex); } else { - mEnabledNodes.Insert(parentArrayIndex + 1, nodeIndex); + m_enabledNodes.emplace(parentArrayIter + 1, nodeIndex); } found = true; } @@ -1271,7 +1094,7 @@ namespace EMotionFX } else // if we're dealing with a root node, insert it in the front of the array { - mEnabledNodes.Insert(0, nodeIndex); + m_enabledNodes.emplace(AZStd::next(begin(m_enabledNodes), 0), nodeIndex); found = true; } } while (found == false); @@ -1281,48 +1104,48 @@ namespace EMotionFX void ActorInstance::DisableNode(uint16 nodeIndex) { // try to remove the node from the array - mEnabledNodes.RemoveByValue(nodeIndex); + const auto it = AZStd::find(begin(m_enabledNodes), end(m_enabledNodes), nodeIndex); + if (it != end(m_enabledNodes)) + { + m_enabledNodes.erase(it); + } } // enable all nodes void ActorInstance::EnableAllNodes() { - const uint32 numNodes = mActor->GetNumNodes(); - mEnabledNodes.Resize(numNodes); - for (uint32 i = 0; i < numNodes; ++i) - { - mEnabledNodes[i] = static_cast(i); - } + m_enabledNodes.resize(m_actor->GetNumNodes()); + std::iota(m_enabledNodes.begin(), m_enabledNodes.end(), 0); } // disable all nodes void ActorInstance::DisableAllNodes() { - mEnabledNodes.Clear(); + m_enabledNodes.clear(); } // change the skeletal LOD level - void ActorInstance::SetSkeletalLODLevelNodeFlags(uint32 level) + void ActorInstance::SetSkeletalLODLevelNodeFlags(size_t level) { - // make sure the lod level is in range of 0..31 - const uint32 newLevel = MCore::Clamp(level, 0, 31); + // make sure the lod level is in range of 0..63 + const size_t newLevel = MCore::Clamp(level, 0, 63); // if the lod level is the same as it currently is, do nothing - if (newLevel == mLODLevel) + if (newLevel == m_lodLevel) { return; } - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); // change the state of all nodes that need state changes - const uint32 numNodes = GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Node* node = skeleton->GetNode(i); // check the curent and the new enabled state - const bool curEnabled = node->GetSkeletalLODStatus(mLODLevel); + const bool curEnabled = node->GetSkeletalLODStatus(m_lodLevel); const bool newEnabled = node->GetSkeletalLODStatus(newLevel); // if the state changed, enable or disable it @@ -1340,7 +1163,7 @@ namespace EMotionFX } } - void ActorInstance::SetLODLevel(uint32 level) + void ActorInstance::SetLODLevel(size_t level) { m_requestedLODLevel = level; } @@ -1348,20 +1171,13 @@ namespace EMotionFX void ActorInstance::UpdateLODLevel() { // Switch LOD level in case a change was requested. - if (mLODLevel != m_requestedLODLevel) + if (m_lodLevel != m_requestedLODLevel) { - // Enable and disable all nodes accordingly (do not call this after setting the new mLODLevel) + // Enable and disable all nodes accordingly (do not call this after setting the new m_lodLevel) SetSkeletalLODLevelNodeFlags(m_requestedLODLevel); // Make sure the LOD level is valid and update it. - mLODLevel = MCore::Clamp(m_requestedLODLevel, 0, mActor->GetNumLODLevels() - 1); - - /*// update the transform data - MorphSetup* morphSetup = mActor->GetMorphSetup(mLODLevel); - if (morphSetup) - mTransformData->SetNumMorphWeights( morphSetup->GetNumMorphTargets() ); - else - mTransformData->SetNumMorphWeights( 0 );*/ + m_lodLevel = MCore::Clamp(m_requestedLODLevel, 0, m_actor->GetNumLODLevels() - 1); } } @@ -1369,14 +1185,14 @@ namespace EMotionFX void ActorInstance::UpdateSkeletalLODFlags() { // change the state of all nodes that need state changes - Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Node* node = skeleton->GetNode(i); // if the new LOD says that this node should be enabled, enable it - if (node->GetSkeletalLODStatus(mLODLevel)) + if (node->GetSkeletalLODStatus(m_lodLevel)) { EnableNode(static_cast(i)); } @@ -1388,15 +1204,15 @@ namespace EMotionFX } // calculate the number of disabled nodes for a given skeletal lod level - uint32 ActorInstance::CalcNumDisabledNodes(uint32 skeletalLODLevel) const + size_t ActorInstance::CalcNumDisabledNodes(size_t skeletalLODLevel) const { uint32 numDisabledNodes = 0; - Skeleton* skeleton = mActor->GetSkeleton(); + const Skeleton* skeleton = m_actor->GetSkeleton(); // get the number of nodes and iterate through them - const uint32 numNodes = GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // get the current node Node* node = skeleton->GetNode(i); @@ -1412,14 +1228,14 @@ namespace EMotionFX } // calculate the number of skeletal LOD levels - uint32 ActorInstance::CalcNumSkeletalLODLevels() const + size_t ActorInstance::CalcNumSkeletalLODLevels() const { - uint32 numSkeletalLODLevels = 0; + size_t numSkeletalLODLevels = 0; // iterate over all skeletal LOD levels - uint32 currentNumDisabledNodes = 0; - uint32 previousNumDisabledNodes = MCORE_INVALIDINDEX32; - for (uint32 i = 0; i < 32; ++i) + size_t currentNumDisabledNodes = 0; + size_t previousNumDisabledNodes = InvalidIndex; + for (size_t i = 0; i < sizeof(size_t) * 8; ++i) { // get the number of disabled nodes in the current skeletal LOD level currentNumDisabledNodes = CalcNumDisabledNodes(i); @@ -1443,23 +1259,23 @@ namespace EMotionFX // change the current motion system void ActorInstance::SetMotionSystem(MotionSystem* newSystem, bool delCurrentFromMem) { - if (delCurrentFromMem && mMotionSystem) + if (delCurrentFromMem && m_motionSystem) { - mMotionSystem->Destroy(); + m_motionSystem->Destroy(); } - mMotionSystem = newSystem; + m_motionSystem = newSystem; } // check if this actor instance is a skin attachment bool ActorInstance::GetIsSkinAttachment() const { - if (mSelfAttachment == nullptr) + if (m_selfAttachment == nullptr) { return false; } - return mSelfAttachment->GetIsInfluencedByMultipleJoints(); + return m_selfAttachment->GetIsInfluencedByMultipleJoints(); } // draw a skeleton using lines, calling the drawline callbacks in the event handlers @@ -1478,14 +1294,14 @@ namespace EMotionFX Transform trajectoryTransform = inOutMotionExtractionNodeTransform; // Make sure the z axis is really pointing up and project it onto the ground plane. - const AZ::Vector3 forwardAxis = MCore::CalcForwardAxis(trajectoryTransform.mRotation); + const AZ::Vector3 forwardAxis = MCore::CalcForwardAxis(trajectoryTransform.m_rotation); if (forwardAxis.GetZ() > 0.0f) // Pick the closest, so if we point more upwards already, we take 1.0, otherwise take -1.0. Sometimes Y would point up, sometimes down. { - MCore::RotateFromTo(trajectoryTransform.mRotation, forwardAxis, AZ::Vector3(0.0f, 0.0f, 1.0f)); + MCore::RotateFromTo(trajectoryTransform.m_rotation, forwardAxis, AZ::Vector3(0.0f, 0.0f, 1.0f)); } else { - MCore::RotateFromTo(trajectoryTransform.mRotation, forwardAxis, AZ::Vector3(0.0f, 0.0f, -1.0f)); + MCore::RotateFromTo(trajectoryTransform.m_rotation, forwardAxis, AZ::Vector3(0.0f, 0.0f, -1.0f)); } trajectoryTransform.ApplyMotionExtractionFlags(motionExtractionFlags); @@ -1495,15 +1311,15 @@ namespace EMotionFX bindTransformProjected.ApplyMotionExtractionFlags(motionExtractionFlags); // Remove the projected rotation and translation from the transform to prevent the double transform. - inOutMotionExtractionNodeTransform.mRotation = (bindTransformProjected.mRotation.GetConjugate() * trajectoryTransform.mRotation).GetConjugate() * inOutMotionExtractionNodeTransform.mRotation; - inOutMotionExtractionNodeTransform.mPosition = inOutMotionExtractionNodeTransform.mPosition - (trajectoryTransform.mPosition - bindTransformProjected.mPosition); - inOutMotionExtractionNodeTransform.mRotation.Normalize(); + inOutMotionExtractionNodeTransform.m_rotation = (bindTransformProjected.m_rotation.GetConjugate() * trajectoryTransform.m_rotation).GetConjugate() * inOutMotionExtractionNodeTransform.m_rotation; + inOutMotionExtractionNodeTransform.m_position = inOutMotionExtractionNodeTransform.m_position - (trajectoryTransform.m_position - bindTransformProjected.m_position); + inOutMotionExtractionNodeTransform.m_rotation.Normalize(); } void ActorInstance::MotionExtractionCompensate(Transform& inOutMotionExtractionNodeTransform, EMotionExtractionFlags motionExtractionFlags) const { - MCORE_ASSERT(mActor->GetMotionExtractionNodeIndex() != MCORE_INVALIDINDEX32); - Transform bindPoseTransform = mTransformData->GetBindPose()->GetLocalSpaceTransform(mActor->GetMotionExtractionNodeIndex()); + MCORE_ASSERT(m_actor->GetMotionExtractionNodeIndex() != InvalidIndex); + Transform bindPoseTransform = m_transformData->GetBindPose()->GetLocalSpaceTransform(m_actor->GetMotionExtractionNodeIndex()); MotionExtractionCompensate(inOutMotionExtractionNodeTransform, bindPoseTransform, motionExtractionFlags); } @@ -1511,13 +1327,13 @@ namespace EMotionFX // Remove the trajectory transform from the motion extraction node to prevent double transformation. void ActorInstance::MotionExtractionCompensate(EMotionExtractionFlags motionExtractionFlags) { - const uint32 motionExtractIndex = mActor->GetMotionExtractionNodeIndex(); - if (motionExtractIndex == MCORE_INVALIDINDEX32) + const size_t motionExtractIndex = m_actor->GetMotionExtractionNodeIndex(); + if (motionExtractIndex == InvalidIndex) { return; } - Pose* currentPose = mTransformData->GetCurrentPose(); + Pose* currentPose = m_transformData->GetCurrentPose(); Transform transform = currentPose->GetLocalSpaceTransform(motionExtractIndex); MotionExtractionCompensate(transform, motionExtractionFlags); @@ -1528,13 +1344,13 @@ namespace EMotionFX { Transform curTransform = inOutTransform; #ifndef EMFX_SCALE_DISABLED - curTransform.mPosition += trajectoryDelta.mPosition * curTransform.mScale; + curTransform.m_position += trajectoryDelta.m_position * curTransform.m_scale; #else - curTransform.mPosition += trajectoryDelta.mPosition; + curTransform.m_position += trajectoryDelta.m_position; #endif - curTransform.mRotation *= trajectoryDelta.mRotation; - curTransform.mRotation.Normalize(); + curTransform.m_rotation *= trajectoryDelta.m_rotation; + curTransform.m_rotation.Normalize(); inOutTransform = curTransform; } @@ -1542,18 +1358,18 @@ namespace EMotionFX // Apply the motion extraction delta transform to the actor instance. void ActorInstance::ApplyMotionExtractionDelta(const Transform& trajectoryDelta) { - if (mActor->GetMotionExtractionNodeIndex() == MCORE_INVALIDINDEX32) + if (m_actor->GetMotionExtractionNodeIndex() == InvalidIndex) { return; } - ApplyMotionExtractionDelta(mLocalTransform, trajectoryDelta); + ApplyMotionExtractionDelta(m_localTransform, trajectoryDelta); } // apply the currently set motion extraction delta transform to the actor instance void ActorInstance::ApplyMotionExtractionDelta() { - ApplyMotionExtractionDelta(mTrajectoryDelta); + ApplyMotionExtractionDelta(m_trajectoryDelta); } void ActorInstance::SetMotionExtractionEnabled(bool enabled) @@ -1563,149 +1379,83 @@ namespace EMotionFX bool ActorInstance::GetMotionExtractionEnabled() const { - return (mBoolFlags & BOOL_MOTIONEXTRACTION) != 0; + return (m_boolFlags & BOOL_MOTIONEXTRACTION) != 0; } // update the static based aabb dimensions - void ActorInstance::UpdateStaticBasedAABBDimensions() + void ActorInstance::UpdateStaticBasedAabbDimensions() { - // backup the transform Transform orgTransform = GetLocalSpaceTransform(); - //------------------------------------- - - // reset position and scale SetLocalSpacePosition(AZ::Vector3::CreateZero()); + EMFX_SCALECODE(SetLocalSpaceScale(AZ::Vector3(1.0f, 1.0f, 1.0f));) - EMFX_SCALECODE( - SetLocalSpaceScale(AZ::Vector3(1.0f, 1.0f, 1.0f));) + UpdateTransformations(0.0f, true); + UpdateMeshDeformers(0.0f); - // rotate over x, y and z axis - AZ::Vector3 boxMin(FLT_MAX, FLT_MAX, FLT_MAX); - AZ::Vector3 boxMax(-FLT_MAX, -FLT_MAX, -FLT_MAX); - for (uint32 axis = 0; axis < 3; axis++) + // calculate the aabb of this + if (m_actor->CheckIfHasMeshes(0)) { - for (uint32 i = 0; i < 360; i += 45) // steps of 45 degrees - { - // rotate a given amount of degrees over the axis we are currently testing - AZ::Vector3 axisVector(0.0f, 0.0f, 0.0f); - axisVector.SetElement(axis, 1.0f); - const float angle = static_cast(i); - SetLocalSpaceRotation(MCore::CreateFromAxisAndAngle(axisVector, MCore::Math::DegreesToRadians(angle))); - - UpdateTransformations(0.0f, true); - UpdateMeshDeformers(0.0f); - - // calculate the aabb of this - if (mActor->CheckIfHasMeshes(0)) - { - CalcMeshBasedAABB(0, &mStaticAABB); - } - else - { - CalcNodeBasedAABB(&mStaticAABB); - } - - // find the minimum and maximum - const AZ::Vector3& curMin = mStaticAABB.GetMin(); - const AZ::Vector3& curMax = mStaticAABB.GetMax(); - if (curMin.GetX() < boxMin.GetX()) - { - boxMin.SetX(curMin.GetX()); - } - if (curMin.GetY() < boxMin.GetY()) - { - boxMin.SetY(curMin.GetY()); - } - if (curMin.GetZ() < boxMin.GetZ()) - { - boxMin.SetZ(curMin.GetZ()); - } - if (curMax.GetX() > boxMax.GetX()) - { - boxMax.SetX(curMax.GetX()); - } - if (curMax.GetY() > boxMax.GetY()) - { - boxMax.SetY(curMax.GetY()); - } - if (curMax.GetZ() > boxMax.GetZ()) - { - boxMax.SetZ(curMax.GetZ()); - } - } + CalcMeshBasedAabb(0, &m_staticAabb); + } + else + { + CalcNodeBasedAabb(&m_staticAabb); } - mStaticAABB.SetMin(boxMin); - mStaticAABB.SetMax(boxMax); - - /* - // calculate the center point of the box - const AZ::Vector3 center = mStaticAABB.CalcMiddle(); - - // find the maximum of the width, height and depth - const float maxDim = MCore::Max3( mStaticAABB.CalcWidth(), mStaticAABB.CalcHeight(), mStaticAABB.CalcDepth() ) * 0.5f; - - // make width, height and depth the same as its maximum - mStaticAABB.SetMin( center + AZ::Vector3(-maxDim, -maxDim, -maxDim) ); - mStaticAABB.SetMax( center + AZ::Vector3( maxDim, maxDim, maxDim) ); - */ - //------------------------------------- - - // restore the transform - mLocalTransform = orgTransform; + m_localTransform = orgTransform; } // calculate the moved static based aabb - void ActorInstance::CalcStaticBasedAABB(MCore::AABB* outResult) + void ActorInstance::CalcStaticBasedAabb(AZ::Aabb* outResult) { if (GetIsSkinAttachment()) { - mSelfAttachment->GetAttachToActorInstance()->CalcStaticBasedAABB(outResult); + m_selfAttachment->GetAttachToActorInstance()->CalcStaticBasedAabb(outResult); return; } - *outResult = mStaticAABB; + *outResult = m_staticAabb; EMFX_SCALECODE( - outResult->SetMin(mStaticAABB.GetMin() * mWorldTransform.mScale); - outResult->SetMax(mStaticAABB.GetMax() * mWorldTransform.mScale);) - outResult->Translate(mWorldTransform.mPosition); + outResult->SetMin(m_staticAabb.GetMin() * m_worldTransform.m_scale); + outResult->SetMax(m_staticAabb.GetMax() * m_worldTransform.m_scale);) + outResult->Translate(m_worldTransform.m_position); } - // adjust the animgraph instance + // adjust the anim graph instance void ActorInstance::SetAnimGraphInstance(AnimGraphInstance* instance) { - mAnimGraphInstance = instance; + m_animGraphInstance = instance; UpdateDependencies(); } Actor* ActorInstance::GetActor() const { - return mActor; + return m_actor; } void ActorInstance::SetID(uint32 id) { - mID = id; + m_id = id; } MotionSystem* ActorInstance::GetMotionSystem() const { - return mMotionSystem; + return m_motionSystem; } - uint32 ActorInstance::GetLODLevel() const + size_t ActorInstance::GetLODLevel() const { - return mLODLevel; + return m_lodLevel; } void ActorInstance::SetCustomData(void* customData) { - mCustomData = customData; + m_customData = customData; } void* ActorInstance::GetCustomData() const { - return mCustomData; + return m_customData; } AZ::Entity* ActorInstance::GetEntity() const @@ -1725,48 +1475,48 @@ namespace EMotionFX bool ActorInstance::GetBoundsUpdateEnabled() const { - return (mBoolFlags & BOOL_BOUNDSUPDATEENABLED); + return (m_boolFlags & BOOL_BOUNDSUPDATEENABLED); } float ActorInstance::GetBoundsUpdateFrequency() const { - return mBoundsUpdateFrequency; + return m_boundsUpdateFrequency; } float ActorInstance::GetBoundsUpdatePassedTime() const { - return mBoundsUpdatePassedTime; + return m_boundsUpdatePassedTime; } ActorInstance::EBoundsType ActorInstance::GetBoundsUpdateType() const { - return mBoundsUpdateType; + return m_boundsUpdateType; } uint32 ActorInstance::GetBoundsUpdateItemFrequency() const { - return mBoundsUpdateItemFreq; + return m_boundsUpdateItemFreq; } void ActorInstance::SetBoundsUpdateFrequency(float seconds) { - mBoundsUpdateFrequency = seconds; + m_boundsUpdateFrequency = seconds; } void ActorInstance::SetBoundsUpdatePassedTime(float seconds) { - mBoundsUpdatePassedTime = seconds; + m_boundsUpdatePassedTime = seconds; } void ActorInstance::SetBoundsUpdateType(EBoundsType bType) { - mBoundsUpdateType = bType; + m_boundsUpdateType = bType; } void ActorInstance::SetBoundsUpdateItemFrequency(uint32 freq) { MCORE_ASSERT(freq >= 1); - mBoundsUpdateItemFreq = freq; + m_boundsUpdateItemFreq = freq; } void ActorInstance::SetBoundsUpdateEnabled(bool enable) @@ -1774,79 +1524,79 @@ namespace EMotionFX SetFlag(BOOL_BOUNDSUPDATEENABLED, enable); } - void ActorInstance::SetStaticBasedAABB(const MCore::AABB& aabb) + void ActorInstance::SetStaticBasedAabb(const AZ::Aabb& aabb) { - mStaticAABB = aabb; + m_staticAabb = aabb; } - void ActorInstance::GetStaticBasedAABB(MCore::AABB* outAABB) + void ActorInstance::GetStaticBasedAabb(AZ::Aabb* outAabb) { - *outAABB = mStaticAABB; + *outAabb = m_staticAabb; } - const MCore::AABB& ActorInstance::GetStaticBasedAABB() const + const AZ::Aabb& ActorInstance::GetStaticBasedAabb() const { - return mStaticAABB; + return m_staticAabb; } - const MCore::AABB& ActorInstance::GetAABB() const + const AZ::Aabb& ActorInstance::GetAabb() const { - return mAABB; + return m_aabb; } - void ActorInstance::SetAABB(const MCore::AABB& aabb) + void ActorInstance::SetAabb(const AZ::Aabb& aabb) { - mAABB = aabb; + m_aabb = aabb; } - uint32 ActorInstance::GetNumAttachments() const + size_t ActorInstance::GetNumAttachments() const { - return mAttachments.GetLength(); + return m_attachments.size(); } - Attachment* ActorInstance::GetAttachment(uint32 nr) const + Attachment* ActorInstance::GetAttachment(size_t nr) const { - return mAttachments[nr]; + return m_attachments[nr]; } bool ActorInstance::GetIsAttachment() const { - return (mAttachedTo != nullptr); + return (m_attachedTo != nullptr); } ActorInstance* ActorInstance::GetAttachedTo() const { - return mAttachedTo; + return m_attachedTo; } Attachment* ActorInstance::GetSelfAttachment() const { - return mSelfAttachment; + return m_selfAttachment; } - uint32 ActorInstance::GetNumDependencies() const + size_t ActorInstance::GetNumDependencies() const { - return mDependencies.GetLength(); + return m_dependencies.size(); } - Actor::Dependency* ActorInstance::GetDependency(uint32 nr) + Actor::Dependency* ActorInstance::GetDependency(size_t nr) { - return &mDependencies[nr]; + return &m_dependencies[nr]; } MorphSetupInstance* ActorInstance::GetMorphSetupInstance() const { - return mMorphSetup; + return m_morphSetup; } void ActorInstance::SetParentWorldSpaceTransform(const Transform& transform) { - mParentWorldTransform = transform; + m_parentWorldTransform = transform; } const Transform& ActorInstance::GetParentWorldSpaceTransform() const { - return mParentWorldTransform; + return m_parentWorldTransform; } void ActorInstance::SetRender(bool enabled) @@ -1856,7 +1606,7 @@ namespace EMotionFX bool ActorInstance::GetRender() const { - return (mBoolFlags & BOOL_RENDER) != 0; + return (m_boolFlags & BOOL_RENDER) != 0; } void ActorInstance::SetIsUsedForVisualization(bool enabled) @@ -1866,7 +1616,7 @@ namespace EMotionFX bool ActorInstance::GetIsUsedForVisualization() const { - return (mBoolFlags & BOOL_USEDFORVISUALIZATION) != 0; + return (m_boolFlags & BOOL_USEDFORVISUALIZATION) != 0; } void ActorInstance::SetIsOwnedByRuntime(bool isOwnedByRuntime) @@ -1881,7 +1631,7 @@ namespace EMotionFX bool ActorInstance::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return (mBoolFlags & BOOL_OWNEDBYRUNTIME) != 0; + return (m_boolFlags & BOOL_OWNEDBYRUNTIME) != 0; #else return true; #endif @@ -1889,22 +1639,22 @@ namespace EMotionFX uint32 ActorInstance::GetThreadIndex() const { - return mThreadIndex; + return m_threadIndex; } void ActorInstance::SetThreadIndex(uint32 index) { - mThreadIndex = index; + m_threadIndex = index; } void ActorInstance::SetTrajectoryDeltaTransform(const Transform& transform) { - mTrajectoryDelta = transform; + m_trajectoryDelta = transform; } const Transform& ActorInstance::GetTrajectoryDeltaTransform() const { - return mTrajectoryDelta; + return m_trajectoryDelta; } AnimGraphPose* ActorInstance::RequestPose(uint32 threadIndex) @@ -1919,70 +1669,70 @@ namespace EMotionFX void ActorInstance::SetMotionSamplingTimer(float timeInSeconds) { - mMotionSamplingTimer = timeInSeconds; + m_motionSamplingTimer = timeInSeconds; } void ActorInstance::SetMotionSamplingRate(float updateRateInSeconds) { - mMotionSamplingRate = updateRateInSeconds; + m_motionSamplingRate = updateRateInSeconds; } float ActorInstance::GetMotionSamplingTimer() const { - return mMotionSamplingTimer; + return m_motionSamplingTimer; } float ActorInstance::GetMotionSamplingRate() const { - return mMotionSamplingRate; + return m_motionSamplingRate; } void ActorInstance::IncreaseNumAttachmentRefs(uint8 numToIncreaseWith) { - mNumAttachmentRefs += numToIncreaseWith; - MCORE_ASSERT(mNumAttachmentRefs == 0 || mNumAttachmentRefs == 1); + m_numAttachmentRefs += numToIncreaseWith; + MCORE_ASSERT(m_numAttachmentRefs == 0 || m_numAttachmentRefs == 1); } void ActorInstance::DecreaseNumAttachmentRefs(uint8 numToDecreaseWith) { - mNumAttachmentRefs -= numToDecreaseWith; - MCORE_ASSERT(mNumAttachmentRefs == 0 || mNumAttachmentRefs == 1); + m_numAttachmentRefs -= numToDecreaseWith; + MCORE_ASSERT(m_numAttachmentRefs == 0 || m_numAttachmentRefs == 1); } uint8 ActorInstance::GetNumAttachmentRefs() const { - return mNumAttachmentRefs; + return m_numAttachmentRefs; } void ActorInstance::SetAttachedTo(ActorInstance* actorInstance) { - mAttachedTo = actorInstance; + m_attachedTo = actorInstance; } void ActorInstance::SetSelfAttachment(Attachment* selfAttachment) { - mSelfAttachment = selfAttachment; + m_selfAttachment = selfAttachment; } void ActorInstance::EnableFlag(uint8 flag) { - mBoolFlags |= flag; + m_boolFlags |= flag; } void ActorInstance::DisableFlag(uint8 flag) { - mBoolFlags &= ~flag; + m_boolFlags &= ~flag; } void ActorInstance::SetFlag(uint8 flag, bool enabled) { if (enabled) { - mBoolFlags |= flag; + m_boolFlags |= flag; } else { - mBoolFlags &= ~flag; + m_boolFlags &= ~flag; } } @@ -1991,19 +1741,18 @@ namespace EMotionFX SetIsVisible(isVisible); // recurse to all child attachments - const uint32 numAttachments = mAttachments.GetLength(); - for (uint32 i = 0; i < numAttachments; ++i) + for (Attachment* attachment : m_attachments) { - mAttachments[i]->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); + attachment->GetAttachmentActorInstance()->RecursiveSetIsVisible(isVisible); } } void ActorInstance::RecursiveSetIsVisibleTowardsRoot(bool isVisible) { SetIsVisible(isVisible); - if (mSelfAttachment) + if (m_selfAttachment) { - mSelfAttachment->GetAttachToActorInstance()->RecursiveSetIsVisibleTowardsRoot(isVisible); + m_selfAttachment->GetAttachToActorInstance()->RecursiveSetIsVisibleTowardsRoot(isVisible); } } @@ -2015,41 +1764,38 @@ namespace EMotionFX // update the normal scale factor based on the bounds void ActorInstance::UpdateVisualizeScale() { - mVisualizeScale = 0.0f; + m_visualizeScale = 0.0f; UpdateMeshDeformers(0.0f); - MCore::AABB box; - CalcCollisionMeshBasedAABB(0, &box); - if (box.CheckIfIsValid()) - { - mVisualizeScale = MCore::Max(mVisualizeScale, box.CalcRadius()); - } + AZ::Aabb box = AZ::Aabb::CreateNull(); - CalcNodeBasedAABB(&box); - if (box.CheckIfIsValid()) + CalcNodeBasedAabb(&box); + if (box.IsValid()) { - mVisualizeScale = MCore::Max(mVisualizeScale, box.CalcRadius()); + const float boxRadius = AZ::Vector3(box.GetMax() - box.GetMin()).GetLength() * 0.5f; + m_visualizeScale = MCore::Max(m_visualizeScale, boxRadius); } - CalcMeshBasedAABB(0, &box); - if (box.CheckIfIsValid()) + CalcMeshBasedAabb(0, &box); + if (box.IsValid()) { - mVisualizeScale = MCore::Max(mVisualizeScale, box.CalcRadius()); + const float boxRadius = AZ::Vector3(box.GetMax() - box.GetMin()).GetLength() * 0.5f; + m_visualizeScale = MCore::Max(m_visualizeScale, boxRadius); } - mVisualizeScale *= 0.01f; + m_visualizeScale *= 0.01f; } // get the normal scale factor float ActorInstance::GetVisualizeScale() const { - return mVisualizeScale; + return m_visualizeScale; } // manually set the visualize scale factor void ActorInstance::SetVisualizeScale(float factor) { - mVisualizeScale = factor; + m_visualizeScale = factor; } // Recursively check if we have a given attachment in the hierarchy going downwards. @@ -2061,8 +1807,8 @@ namespace EMotionFX } // Iterate down the chain of attachments. - const AZ::u32 numAttachments = GetNumAttachments(); - for (AZ::u32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = GetNumAttachments(); + for (size_t i = 0; i < numAttachments; ++i) { if (GetAttachment(i)->GetAttachmentActorInstance()->RecursiveHasAttachment(attachmentInstance)) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h index 3567175d6d..7ca134c0db 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.h @@ -60,9 +60,6 @@ namespace EMotionFX { BOUNDS_NODE_BASED = 0, /**< Calculate the bounding volumes based on the world space node positions. */ BOUNDS_MESH_BASED = 1, /**< Calculate the bounding volumes based on the world space vertex positions. */ - BOUNDS_COLLISIONMESH_BASED = 2, /**< Calculate the bounding volumes based on the world space collision mesh vertex positions. */ - BOUNDS_NODEOBB_BASED = 3, /**< Calculate the bounding volumes based on the oriented bounding boxes of the nodes. Uses all 8 corner points of the individual node OBB boxes. */ - BOUNDS_NODEOBBFAST_BASED = 4, /**< Calculate the bounding volumes based on the oriented bounding boxes of the nodes. Uses the min and max point of the individual node OBB boxes. This is less accurate but faster. */ BOUNDS_STATIC_BASED = 5 /**< Calculate the bounding volumes based on an approximate box, based on the mesh bounds, and move this box along with the actor instance position. */ }; @@ -78,7 +75,7 @@ namespace EMotionFX * Get the unique identification number for the actor instance. * @return The unique identification number. */ - MCORE_INLINE uint32 GetID() const { return mID; } + MCORE_INLINE uint32 GetID() const { return m_id; } /** * Set the unique identification number for the actor instance. @@ -107,7 +104,7 @@ namespace EMotionFX * This can return nullptr, in which case the motion system as returned by GetMotionSystem() will be used. * @result The anim graph instance. */ - MCORE_INLINE AnimGraphInstance* GetAnimGraphInstance() const { return mAnimGraphInstance; } + MCORE_INLINE AnimGraphInstance* GetAnimGraphInstance() const { return m_animGraphInstance; } /** * Set the anim graph instance. @@ -122,7 +119,7 @@ namespace EMotionFX * So if you wish to get or set any transformations, you can do it with the object returned by this method. * @result A pointer to the transformation data object. */ - MCORE_INLINE TransformData* GetTransformData() const { return mTransformData; } + MCORE_INLINE TransformData* GetTransformData() const { return m_transformData; } /** * Enable or disable this actor instance. @@ -139,7 +136,7 @@ namespace EMotionFX * Disabled actor instances are not updated and processed. * @result Returns true when enabled, or false when disabled. */ - MCORE_INLINE bool GetIsEnabled() const { return (mBoolFlags & BOOL_ENABLED) != 0; } + MCORE_INLINE bool GetIsEnabled() const { return (m_boolFlags & BOOL_ENABLED) != 0; } /** * Check the visibility flag. @@ -147,7 +144,7 @@ namespace EMotionFX * This is used internally by the schedulers, so that heavy calculations can be skipped on invisible characters. * @result Returns true when the actor instance is marked as visible, otherwise false is returned. */ - MCORE_INLINE bool GetIsVisible() const { return (mBoolFlags & BOOL_ISVISIBLE) != 0; } + MCORE_INLINE bool GetIsVisible() const { return (m_boolFlags & BOOL_ISVISIBLE) != 0; } /** * Change the visibility state. @@ -184,7 +181,7 @@ namespace EMotionFX * @param[in] skeletalLODLevel The skeletal LOD level to calculate the number of disabled nodes for. * @return The number of disabled nodes for the given skeletal LOD level. */ - uint32 CalcNumDisabledNodes(uint32 skeletalLODLevel) const; + size_t CalcNumDisabledNodes(size_t skeletalLODLevel) const; /** * Calculate the number of used skeletal LOD levels. Each actor instance alsways has 32 skeletal LOD levels while in most cases @@ -192,7 +189,7 @@ namespace EMotionFX * relative to the previous LOD level. * @return The number of actually used skeletal LOD levels. */ - uint32 CalcNumSkeletalLODLevels() const; + size_t CalcNumSkeletalLODLevels() const; /** * Get the current used geometry and skeletal detail level. @@ -202,13 +199,13 @@ namespace EMotionFX * are needed. * @result The current LOD level. */ - uint32 GetLODLevel() const; + size_t GetLODLevel() const; /** * Set the current geometry and skeletal detail level, where 0 is the highest detail. * @param level The LOD level. Values higher than [GetNumGeometryLODLevels()-1] will be clamped to the maximum LOD. */ - void SetLODLevel(uint32 level); + void SetLODLevel(size_t level); //-------------------------------- @@ -348,6 +345,14 @@ namespace EMotionFX */ EBoundsType GetBoundsUpdateType() const; + /** + * Get the normalized percentage that the calculated bounding box is expanded with. + * This can be used to add a tolerance area to the calculated bounding box to avoid clipping the character too early. + * A static bounding box together with the expansion is the recommended way for maximum performance. + * @result A value of 1.0 means that the calculated bounding box won't be expanded at all, while 2.0 means it is twice the size. + */ + float GetExpandBoundsBy() const { return m_boundsExpandBy; } + /** * Get the bounding volume auto-update item frequency. * A value of 1 would mean every node or vertex will be taken into account in the bounds calculation. @@ -376,11 +381,19 @@ namespace EMotionFX /** * Set the bounding volume auto-update type. * This can be either based on the node's world space positions, the mesh vertex world space positions, or the - * collision mesh vertex world space postitions. + * collision mesh vertex world space positions. * @param bType The bounding volume update type. */ void SetBoundsUpdateType(EBoundsType bType); + /** + * Set the normalized percentage that the calculated bounding box should be expanded with. + * This can be used to add a tolerance area to the calculated bounding box to avoid clipping the character too early. + * A static bounding box together with the expansion is the recommended way for maximum performance. + * @param[in] expandBy A value of 1.0 means that the calculated bounding box won't be expanded at all, while 2.0 means it will be twice the size. + */ + void SetExpandBoundsBy(float expandBy) { m_boundsExpandBy = expandBy; } + /** * Set the bounding volume auto-update item frequency. * A value of 1 would mean every node or vertex will be taken into account in the bounds calculation. @@ -410,7 +423,7 @@ namespace EMotionFX * 4th vertex will be included in the bounds calculation, so only processing 25% of the total number of vertices. The same goes for * node based bounds, but then it will process every 4th node. Of course higher values produce less accurate results, but are faster to process. */ - void UpdateBounds(uint32 geomLODLevel, EBoundsType boundsType = BOUNDS_NODE_BASED, uint32 itemFrequency = 1); + void UpdateBounds(size_t geomLODLevel, EBoundsType boundsType = BOUNDS_NODE_BASED, uint32 itemFrequency = 1); /** * Update the base static axis aligned bounding box shape. @@ -420,11 +433,11 @@ namespace EMotionFX * This function is generally only executed once, when creating the actor instance. * The CalcStaticBasedAABB function then simply translates this box along with the actor instance's position. */ - void UpdateStaticBasedAABBDimensions(); + void UpdateStaticBasedAabbDimensions(); - void SetStaticBasedAABB(const MCore::AABB& aabb); - void GetStaticBasedAABB(MCore::AABB* outAABB); - const MCore::AABB& GetStaticBasedAABB() const; + void SetStaticBasedAabb(const AZ::Aabb& aabb); + void GetStaticBasedAabb(AZ::Aabb* outAabb); + const AZ::Aabb& GetStaticBasedAabb() const; /** * Calculate an axis aligned bounding box that can be used as static AABB. It is static in the way that the volume does not change. It can however be translated as it will move @@ -434,7 +447,7 @@ namespace EMotionFX * If there are no meshes present, a widened node based box will be used instead as basis. * @param outResult The resulting bounding box, moved along with the actor instance's position. */ - void CalcStaticBasedAABB(MCore::AABB* outResult); + void CalcStaticBasedAabb(AZ::Aabb* outResult); /** * Calculate the axis aligned bounding box based on the world space positions of the nodes. @@ -442,7 +455,7 @@ namespace EMotionFX * @param nodeFrequency This will include every "nodeFrequency"-th node. So a value of 1 will include all nodes. A value of 2 would * process every second node, meaning that half of the nodes will be skipped. A value of 4 would process every 4th node, etc. */ - void CalcNodeBasedAABB(MCore::AABB* outResult, uint32 nodeFrequency = 1); + void CalcNodeBasedAabb(AZ::Aabb* outResult, uint32 nodeFrequency = 1); /** * Calculate the axis aligned bounding box based on the world space vertex coordinates of the meshes. @@ -452,43 +465,7 @@ namespace EMotionFX * @param vertexFrequency This includes every "vertexFrequency"-th vertex. So for example a value of 2 would skip every second vertex and * so will process half of the vertices. A value of 4 would process only each 4th vertex, etc. */ - void CalcMeshBasedAABB(uint32 geomLODLevel, MCore::AABB* outResult, uint32 vertexFrequency = 1); - - /** - * Calculate the axis aligned bounding box based on the world space vertex coordinates of the collision meshes. - * If the actor has no collision meshes, the created box will be invalid. - * @param geomLODLevel The geometry LOD level to calculate the box for. - * @param outResult The AABB where this method should store the resulting box in. - * @param vertexFrequency This includes every "vertexFrequency"-th vertex. So for example a value of 2 would skip every second vertex and - * so will process half of the vertices. A value of 4 would process only each 4th vertex, etc. - */ - void CalcCollisionMeshBasedAABB(uint32 geomLODLevel, MCore::AABB* outResult, uint32 vertexFrequency = 1); - - /** - * Calculate the axis aligned bounding box that contains the object oriented boxes of all nodes. - * The OBB (oriented bounding box) of each node is calculated by fitting an OBB to its mesh. - * The OBB of nodes that act as bones and have no meshes themselves are fit to the set of vertices that are influenced by the given bone. - * This method will give more accurate results than the CalcNodeBasedAABB method in trade for a bit lower performance. - * Also one big advantage of this method is that you can use these bounds for hit detection, without having artists setup collision meshes. - * @param outResult The AABB where this method should store the resulting box in. - * @param nodeFrequency This will include every "nodeFrequency"-th node. So a value of 1 will include all nodes. A value of 2 would - * process every second node, meaning that half of the nodes will be skipped. A value of 4 would process every 4th node, etc. - */ - void CalcNodeOBBBasedAABB(MCore::AABB* outResult, uint32 nodeFrequency = 1); - - /** - * Calculate the axis aligned bounding box that contains the object oriented boxes of all nodes. - * The OBB (oriented bounding box) of each node is calculated by fitting an OBB to its mesh. - * The OBB of nodes that act as bones and have no meshes themselves are fit to the set of vertices that are influenced by the given bone. - * This method will give more accurate results than the CalcNodeBasedAABB method in trade for a bit lower performance. - * Also one big advantage of this method is that you can use these bounds for hit detection, without having artists setup collision meshes. - * NOTE: this is a faster variant from the CalcNodeOBBBasedAABB method. The difference is that this method only transforms the min and max point of the box in local space. - * Therefore it is less accurate, but it might still be enough. The original CalcNodeOBBBasedAABB method calculates the 8 corner points of the node obb boxes. - * @param outResult The AABB where this method should store the resulting box in. - * @param nodeFrequency This will include every "nodeFrequency"-th node. So a value of 1 will include all nodes. A value of 2 would - * process every second node, meaning that half of the nodes will be skipped. A value of 4 would process every 4th node, etc. - */ - void CalcNodeOBBBasedAABBFast(MCore::AABB* outResult, uint32 nodeFrequency = 1); + void CalcMeshBasedAabb(size_t geomLODLevel, AZ::Aabb* outResult, uint32 vertexFrequency = 1); /** * Get the axis aligned bounding box. @@ -496,14 +473,14 @@ namespace EMotionFX * That method is also called automatically when the bounds auto-update feature is enabled. * @result The axis aligned bounding box. */ - const MCore::AABB& GetAABB() const; + const AZ::Aabb& GetAabb() const; /** * Set the axis aligned bounding box. * Please beware that this box will get automatically overwritten when automatic bounds update is enabled. * @param aabb The axis aligned bounding box to store. */ - void SetAABB(const MCore::AABB& aabb); + void SetAabb(const AZ::Aabb& aabb); //------------------------------------------------------------------------------------------- @@ -512,14 +489,14 @@ namespace EMotionFX * This is relative to its parent (if it is attached ot something). Otherwise it is in world space. * @param position The position/translation to use. */ - MCORE_INLINE void SetLocalSpacePosition(const AZ::Vector3& position) { mLocalTransform.mPosition = position; } + MCORE_INLINE void SetLocalSpacePosition(const AZ::Vector3& position) { m_localTransform.m_position = position; } /** * Set the local rotation of this actor instance. * This is relative to its parent (if it is attached ot something). Otherwise it is in world space. * @param rotation The rotation to use. */ - MCORE_INLINE void SetLocalSpaceRotation(const AZ::Quaternion& rotation) { mLocalTransform.mRotation = rotation; } + MCORE_INLINE void SetLocalSpaceRotation(const AZ::Quaternion& rotation) { m_localTransform.m_rotation = rotation; } EMFX_SCALECODE ( @@ -528,14 +505,14 @@ namespace EMotionFX * This is relative to its parent (if it is attached ot something). Otherwise it is in world space. * @param scale The scale to use. */ - MCORE_INLINE void SetLocalSpaceScale(const AZ::Vector3& scale) { mLocalTransform.mScale = scale; } + MCORE_INLINE void SetLocalSpaceScale(const AZ::Vector3& scale) { m_localTransform.m_scale = scale; } /** * Get the local space scale. * This is relative to its parent (if it is attached ot something). Otherwise it is in world space. * @result The local space scale factor for each axis. */ - MCORE_INLINE const AZ::Vector3& GetLocalSpaceScale() const { return mLocalTransform.mScale; } + MCORE_INLINE const AZ::Vector3& GetLocalSpaceScale() const { return m_localTransform.m_scale; } ) /** @@ -543,20 +520,20 @@ namespace EMotionFX * This is relative to its parent (if it is attached ot something). Otherwise it is in world space. * @result The local space position. */ - MCORE_INLINE const AZ::Vector3& GetLocalSpacePosition() const { return mLocalTransform.mPosition; } + MCORE_INLINE const AZ::Vector3& GetLocalSpacePosition() const { return m_localTransform.m_position; } /** * Get the local space rotation of this actor instance. * This is relative to its parent (if it is attached ot something). Otherwise it is in world space. * @result The local space rotation. */ - MCORE_INLINE const AZ::Quaternion& GetLocalSpaceRotation() const { return mLocalTransform.mRotation; } + MCORE_INLINE const AZ::Quaternion& GetLocalSpaceRotation() const { return m_localTransform.m_rotation; } - MCORE_INLINE void SetLocalSpaceTransform(const Transform& transform) { mLocalTransform = transform; } + MCORE_INLINE void SetLocalSpaceTransform(const Transform& transform) { m_localTransform = transform; } - MCORE_INLINE const Transform& GetLocalSpaceTransform() const { return mLocalTransform; } - MCORE_INLINE const Transform& GetWorldSpaceTransform() const { return mWorldTransform; } - MCORE_INLINE const Transform& GetWorldSpaceTransformInversed() const { return mWorldTransformInv; } + MCORE_INLINE const Transform& GetLocalSpaceTransform() const { return m_localTransform; } + MCORE_INLINE const Transform& GetWorldSpaceTransform() const { return m_worldTransform; } + MCORE_INLINE const Transform& GetWorldSpaceTransformInversed() const { return m_worldTransformInv; } //------------------------------------------------------------------------------------------- @@ -591,7 +568,7 @@ namespace EMotionFX * When you set this to false, it will not be deleted from memory, but only removed from the array of attachments * that is stored locally inside this actor instance. */ - void RemoveAttachment(uint32 nr, bool delFromMem = true); + void RemoveAttachment(size_t nr, bool delFromMem = true); /** * Remove all attachments from this actor instance. @@ -616,20 +593,20 @@ namespace EMotionFX * @result Returns the attachment number, in range of [0..GetNumAttachments()-1], or MCORE_INVALIDINDEX32 when no attachment * using the specified actor instance can be found. */ - uint32 FindAttachmentNr(ActorInstance* actorInstance); + size_t FindAttachmentNr(ActorInstance* actorInstance); /** * Get the number of attachments that have been added to this actor instance. * @result The number of attachments added to this actor instance. */ - uint32 GetNumAttachments() const; + size_t GetNumAttachments() const; /** * Get a specific attachment. * @param nr The attachment number, which must be in range of [0..GetNumAttachments()-1]. * @result A pointer to the attachment. */ - Attachment* GetAttachment(uint32 nr) const; + Attachment* GetAttachment(size_t nr) const; /** * Check whether this actor instance also is an attachment or not. @@ -687,14 +664,14 @@ namespace EMotionFX * Get the number of dependencies that this actor instance has on other actors. * @result The number of dependencies. */ - uint32 GetNumDependencies() const; + size_t GetNumDependencies() const; /** * Get a given dependency. * @param nr The dependency number to get, which must be in range of [0..GetNumDependencies()]. * @result A pointer to the dependency. */ - Actor::Dependency* GetDependency(uint32 nr); + Actor::Dependency* GetDependency(size_t nr); /** * Get the morph setup instance. @@ -715,7 +692,7 @@ namespace EMotionFX * @param ray The ray to check. * @return A pointer to the node we detected the first intersection with (doesn't have to be the closest), or nullptr when no intersection found. */ - Node* IntersectsCollisionMesh(uint32 lodLevel, const MCore::Ray& ray) const; + Node* IntersectsCollisionMesh(size_t lodLevel, const MCore::Ray& ray) const; /** * Check for an intersection between the collision mesh of this actor and a given ray, and calculate the closest intersection point. @@ -734,7 +711,7 @@ namespace EMotionFX * A value of nullptr is allowed, which will skip storing the resulting triangle indices. * @return A pointer to the node we detected the closest intersection with, or nullptr when no intersection found. */ - Node* IntersectsCollisionMesh(uint32 lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal = nullptr, AZ::Vector2* outUV = nullptr, float* outBaryU = nullptr, float* outBaryV = nullptr, uint32* outIndices = nullptr) const; + Node* IntersectsCollisionMesh(size_t lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal = nullptr, AZ::Vector2* outUV = nullptr, float* outBaryU = nullptr, float* outBaryV = nullptr, uint32* outIndices = nullptr) const; /** * Check for an intersection between the real mesh (if present) of this actor and a given ray. @@ -744,7 +721,7 @@ namespace EMotionFX * @param ray The ray to test with. * @return Returns a pointer to itself when an intersection occurred, or nullptr when no intersection found. */ - Node* IntersectsMesh(uint32 lodLevel, const MCore::Ray& ray) const; + Node* IntersectsMesh(size_t lodLevel, const MCore::Ray& ray) const; /** * Checks for an intersection between the real mesh (if present) of this actor and a given ray. @@ -764,7 +741,7 @@ namespace EMotionFX * A value of nullptr is allowed, which will skip storing the resulting triangle indices. * @return A pointer to the node we detected the closest intersection with, or nullptr when no intersection found. */ - Node* IntersectsMesh(uint32 lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal = nullptr, AZ::Vector2* outUV = nullptr, float* outBaryU = nullptr, float* outBaryV = nullptr, uint32* outStartIndex = nullptr) const; + Node* IntersectsMesh(size_t lodLevel, const MCore::Ray& ray, AZ::Vector3* outIntersect, AZ::Vector3* outNormal = nullptr, AZ::Vector2* outUV = nullptr, float* outBaryU = nullptr, float* outBaryV = nullptr, uint32* outStartIndex = nullptr) const; void SetRagdoll(Physics::Ragdoll* ragdoll); RagdollInstance* GetRagdollInstance() const; @@ -811,20 +788,20 @@ namespace EMotionFX * Get direct access to the array of enabled nodes. * @result A read only reference to the array of enabled nodes. The values inside of this array are the node numbers of the enabled nodes. */ - MCORE_INLINE const MCore::Array& GetEnabledNodes() const { return mEnabledNodes; } + MCORE_INLINE const AZStd::vector& GetEnabledNodes() const { return m_enabledNodes; } /** * Get the number of enabled nodes inside this actor instance. * @result The number of nodes that have been enabled and are being updated. */ - MCORE_INLINE uint32 GetNumEnabledNodes() const { return mEnabledNodes.GetLength(); } + MCORE_INLINE size_t GetNumEnabledNodes() const { return m_enabledNodes.size(); } /** * Get the node number of a given enabled node. * @param index An index in the array of enabled nodes. This must be in range of [0..GetNumEnabledNodes()-1]. * @result The node number, which relates to Actor::GetNode( returnValue ). */ - MCORE_INLINE uint16 GetEnabledNode(uint32 index) const { return mEnabledNodes[index]; } + MCORE_INLINE uint16 GetEnabledNode(size_t index) const { return m_enabledNodes[index]; } /** * Enable all nodes inside the actor instance. @@ -879,50 +856,51 @@ namespace EMotionFX float GetMotionSamplingTimer() const; float GetMotionSamplingRate() const; - MCORE_INLINE uint32 GetNumNodes() const { return mActor->GetSkeleton()->GetNumNodes(); } + MCORE_INLINE size_t GetNumNodes() const { return m_actor->GetSkeleton()->GetNumNodes(); } void UpdateVisualizeScale(); // not automatically called on creation for performance reasons (this method relatively is slow as it updates all meshes) float GetVisualizeScale() const; void SetVisualizeScale(float factor); private: - TransformData* mTransformData; /**< The transformation data for this instance. */ - MCore::AABB mAABB; /**< The axis aligned bounding box. */ - MCore::AABB mStaticAABB; /**< A static pre-calculated bounding box, which we can move along with the position of the actor instance, and use for visibility checks. */ - - Transform mLocalTransform = Transform::CreateIdentity(); - Transform mWorldTransform = Transform::CreateIdentity(); - Transform mWorldTransformInv = Transform::CreateIdentity(); - Transform mParentWorldTransform = Transform::CreateIdentity(); - Transform mTrajectoryDelta = Transform::CreateIdentityWithZeroScale(); - - MCore::Array mAttachments; /**< The attachments linked to this actor instance. */ - MCore::Array mDependencies; /**< The actor dependencies, which specify which Actor objects this instance is dependent on. */ - MorphSetupInstance* mMorphSetup; /**< The morph setup instance. */ - MCore::Array mEnabledNodes; /**< The list of nodes that are enabled. */ - - Actor* mActor; /**< A pointer to the parent actor where this is an instance from. */ - ActorInstance* mAttachedTo; /**< Specifies the actor where this actor is attached to, or nullptr when it is no attachment. */ - Attachment* mSelfAttachment; /**< The attachment it is itself inside the mAttachedTo actor instance, or nullptr when this isn't an attachment. */ - MotionSystem* mMotionSystem; /**< The motion system, that handles all motion playback and blending etc. */ - AnimGraphInstance* mAnimGraphInstance; /**< A pointer to the anim graph instance, which can be nullptr when there is no anim graph instance. */ + TransformData* m_transformData; /**< The transformation data for this instance. */ + AZ::Aabb m_aabb; /**< The axis aligned bounding box. */ + AZ::Aabb m_staticAabb; /**< A static pre-calculated bounding box, which we can move along with the position of the actor instance, and use for visibility checks. */ + + Transform m_localTransform = Transform::CreateIdentity(); + Transform m_worldTransform = Transform::CreateIdentity(); + Transform m_worldTransformInv = Transform::CreateIdentity(); + Transform m_parentWorldTransform = Transform::CreateIdentity(); + Transform m_trajectoryDelta = Transform::CreateIdentityWithZeroScale(); + + AZStd::vector m_attachments; /**< The attachments linked to this actor instance. */ + AZStd::vector m_dependencies; /**< The actor dependencies, which specify which Actor objects this instance is dependent on. */ + MorphSetupInstance* m_morphSetup; /**< The morph setup instance. */ + AZStd::vector m_enabledNodes; /**< The list of nodes that are enabled. */ + + Actor* m_actor; /**< A pointer to the parent actor where this is an instance from. */ + ActorInstance* m_attachedTo; /**< Specifies the actor where this actor is attached to, or nullptr when it is no attachment. */ + Attachment* m_selfAttachment; /**< The attachment it is itself inside the m_attachedTo actor instance, or nullptr when this isn't an attachment. */ + MotionSystem* m_motionSystem; /**< The motion system, that handles all motion playback and blending etc. */ + AnimGraphInstance* m_animGraphInstance; /**< A pointer to the anim graph instance, which can be nullptr when there is no anim graph instance. */ AZStd::unique_ptr m_ragdollInstance; - MCore::Mutex mLock; /**< The multithread lock. */ - void* mCustomData; /**< A pointer to custom data for this actor. This could be a pointer to your engine or game object for example. */ + MCore::Mutex m_lock; /**< The multi-thread lock. */ + void* m_customData; /**< A pointer to custom data for this actor. This could be a pointer to your engine or game object for example. */ AZ::Entity* m_entity; /**< The entity to which the actor instance belongs to. */ - float mBoundsUpdateFrequency; /**< The bounds update frequency. Which is a time value in seconds. */ - float mBoundsUpdatePassedTime;/**< The time passed since the last bounds update. */ - float mMotionSamplingRate; /**< The motion sampling rate in seconds, where 0.1 would mean to update 10 times per second. A value of 0 or lower means to update every frame. */ - float mMotionSamplingTimer; /**< The time passed since the last time we sampled motions/anim graphs. */ - float mVisualizeScale; /**< Some visualization scale factor when rendering for example normals, to be at a nice size, relative to the character. */ - uint32 mLODLevel; /**< The current LOD level, where 0 is the highest detail. */ - uint32 m_requestedLODLevel; /**< Requested LOD level. The actual LOD level will be updated as soon as all transforms for the requested LOD level are ready. */ - uint32 mBoundsUpdateItemFreq; /**< The bounds update item counter step size. A value of 1 means every vertex/node, a value of 2 means every second vertex/node, etc. */ - uint32 mID; /**< The unique identification number for the actor instance. */ - uint32 mThreadIndex; /**< The thread index. This specifies the thread number this actor instance is being processed in. */ - EBoundsType mBoundsUpdateType; /**< The bounds update type (node based, mesh based or colliison mesh based). */ - uint8 mNumAttachmentRefs; /**< Specifies how many actor instances use this actor instance as attachment. */ - uint8 mBoolFlags; /**< Boolean flags. */ + float m_boundsUpdateFrequency; /**< The bounds update frequency. Which is a time value in seconds. */ + float m_boundsUpdatePassedTime;/**< The time passed since the last bounds update. */ + float m_motionSamplingRate; /**< The motion sampling rate in seconds, where 0.1 would mean to update 10 times per second. A value of 0 or lower means to update every frame. */ + float m_motionSamplingTimer; /**< The time passed since the last time we sampled motions/anim graphs. */ + float m_visualizeScale; /**< Some visualization scale factor when rendering for example normals, to be at a nice size, relative to the character. */ + size_t m_lodLevel; /**< The current LOD level, where 0 is the highest detail. */ + size_t m_requestedLODLevel; /**< Requested LOD level. The actual LOD level will be updated as soon as all transforms for the requested LOD level are ready. */ + uint32 m_boundsUpdateItemFreq; /**< The bounds update item counter step size. A value of 1 means every vertex/node, a value of 2 means every second vertex/node, etc. */ + uint32 m_id; /**< The unique identification number for the actor instance. */ + uint32 m_threadIndex; /**< The thread index. This specifies the thread number this actor instance is being processed in. */ + EBoundsType m_boundsUpdateType; /**< The bounds update type (node based, mesh based or collision mesh based). */ + float m_boundsExpandBy = 0.25f; /**< Expand bounding box by normalized percentage. (Default: 25% greater than the calculated bounding box) */ + uint8 m_numAttachmentRefs; /**< Specifies how many actor instances use this actor instance as attachment. */ + uint8 m_boolFlags; /**< Boolean flags. */ /** * Boolean masks, as replacement for having several bools as members. @@ -1024,7 +1002,7 @@ namespace EMotionFX * are needed. * @param level The skeletal detail LOD level. Values higher than 31 will be automatically clamped to 31. */ - void SetSkeletalLODLevelNodeFlags(uint32 level); + void SetSkeletalLODLevelNodeFlags(size_t level); /* * Update the LOD level in case a change was requested. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp index e40a0dde5b..681efb6039 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.cpp @@ -25,19 +25,15 @@ namespace EMotionFX ActorManager::ActorManager() : BaseObject() { - mScheduler = nullptr; - - // set memory categories - mActorInstances.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORMANAGER); - mRootActorInstances.SetMemoryCategory(EMFX_MEMCATEGORY_ACTORMANAGER); + m_scheduler = nullptr; // setup the default scheduler SetScheduler(MultiThreadScheduler::Create()); // reserve memory m_actors.reserve(512); - mActorInstances.Reserve(1024); - mRootActorInstances.Reserve(1024); + m_actorInstances.reserve(1024); + m_rootActorInstances.reserve(1024); } @@ -45,7 +41,7 @@ namespace EMotionFX ActorManager::~ActorManager() { // delete the scheduler - mScheduler->Destroy(); + m_scheduler->Destroy(); } @@ -61,8 +57,8 @@ namespace EMotionFX // destroy all actor instances while (GetNumActorInstances() > 0) { - MCORE_ASSERT(mActorInstances[0]->GetReferenceCount() == 1); - mActorInstances[0]->Destroy(); + MCORE_ASSERT(m_actorInstances[0]->GetReferenceCount() == 1); + m_actorInstances[0]->Destroy(); } UnregisterAllActorInstances(); @@ -79,11 +75,11 @@ namespace EMotionFX void ActorManager::UnregisterAllActorInstances() { LockActorInstances(); - mActorInstances.Clear(); - mRootActorInstances.Clear(); - if (mScheduler) + m_actorInstances.clear(); + m_rootActorInstances.clear(); + if (m_scheduler) { - mScheduler->Clear(); + m_scheduler->Clear(); } UnlockActorInstances(); } @@ -95,19 +91,19 @@ namespace EMotionFX LockActorInstances(); // delete the existing scheduler, if wanted - if (delExisting && mScheduler) + if (delExisting && m_scheduler) { - mScheduler->Destroy(); + m_scheduler->Destroy(); } // update the scheduler pointer - mScheduler = scheduler; + m_scheduler = scheduler; // adjust all visibility flags to false for all actor instances - const uint32 numActorInstances = mActorInstances.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = m_actorInstances.size(); + for (size_t i = 0; i < numActorInstances; ++i) { - mActorInstances[i]->SetIsVisible(false); + m_actorInstances[i]->SetIsVisible(false); } UnlockActorInstances(); @@ -120,7 +116,7 @@ namespace EMotionFX LockActors(); // check if we already registered - if (FindActorIndex(actor.get()) != MCORE_INVALIDINDEX32) + if (FindActorIndex(actor.get()) != InvalidIndex) { MCore::LogWarning("EMotionFX::ActorManager::RegisterActor() - The actor at location 0x%x has already been registered as actor, most likely already by the LoadActor of the importer.", actor.get()); UnlockActors(); @@ -139,7 +135,7 @@ namespace EMotionFX { LockActorInstances(); - mActorInstances.Add(actorInstance); + m_actorInstances.emplace_back(actorInstance); UpdateActorInstanceStatus(actorInstance, false); UnlockActorInstances(); @@ -172,38 +168,38 @@ namespace EMotionFX // find the leader actor record for a given actor - uint32 ActorManager::FindActorIndex(Actor* actor) const + size_t ActorManager::FindActorIndex(Actor* actor) const { const auto found = AZStd::find_if(m_actors.begin(), m_actors.end(), [actor](const AZStd::shared_ptr& a) { return a.get() == actor; }); - return (found != m_actors.end()) ? static_cast(AZStd::distance(m_actors.begin(), found)) : MCORE_INVALIDINDEX32; + return (found != m_actors.end()) ? AZStd::distance(m_actors.begin(), found) : InvalidIndex; } // find the actor for a given actor name - uint32 ActorManager::FindActorIndexByName(const char* actorName) const + size_t ActorManager::FindActorIndexByName(const char* actorName) const { const auto found = AZStd::find_if(m_actors.begin(), m_actors.end(), [actorName](const AZStd::shared_ptr& a) { return a->GetNameString() == actorName; }); - return (found != m_actors.end()) ? static_cast(AZStd::distance(m_actors.begin(), found)) : MCORE_INVALIDINDEX32; + return (found != m_actors.end()) ? AZStd::distance(m_actors.begin(), found) : InvalidIndex; } // find the actor for a given actor filename - uint32 ActorManager::FindActorIndexByFileName(const char* filename) const + size_t ActorManager::FindActorIndexByFileName(const char* filename) const { const auto found = AZStd::find_if(m_actors.begin(), m_actors.end(), [filename](const AZStd::shared_ptr& a) { return a->GetFileNameString() == filename; }); - return (found != m_actors.end()) ? static_cast(AZStd::distance(m_actors.begin(), found)) : MCORE_INVALIDINDEX32; + return (found != m_actors.end()) ? AZStd::distance(m_actors.begin(), found) : InvalidIndex; } @@ -213,55 +209,28 @@ namespace EMotionFX LockActorInstances(); // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) - { - if (mActorInstances[i] == actorInstance) - { - UnlockActorInstances(); - return true; - } - } - - // in case we haven't found it return failure + const bool foundActor = AZStd::find(begin(m_actorInstances), end(m_actorInstances), actorInstance) != end(m_actorInstances); UnlockActorInstances(); - return false; + return foundActor; } // find the given actor instance inside the actor manager and return its index - uint32 ActorManager::FindActorInstanceIndex(ActorInstance* actorInstance) const + size_t ActorManager::FindActorInstanceIndex(ActorInstance* actorInstance) const { - // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) - { - if (mActorInstances[i] == actorInstance) - { - return i; - } - } - - // in case we haven't found it return failure - return MCORE_INVALIDINDEX32; + const auto foundActorInstance = AZStd::find(begin(m_actorInstances), end(m_actorInstances), actorInstance); + return foundActorInstance != end(m_actorInstances) ? AZStd::distance(begin(m_actorInstances), foundActorInstance) : InvalidIndex; } // find the actor instance by the identification number ActorInstance* ActorManager::FindActorInstanceByID(uint32 id) const { - // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) + const auto foundActorInstance = AZStd::find_if(begin(m_actorInstances), end(m_actorInstances), [id](const ActorInstance* actorInstance) { - if (mActorInstances[i]->GetID() == id) - { - return mActorInstances[i]; - } - } - - // in case we haven't found it return failure - return nullptr; + return actorInstance->GetID() == id; + }); + return foundActorInstance != end(m_actorInstances) ? *foundActorInstance : nullptr; } @@ -288,9 +257,9 @@ namespace EMotionFX // unregister a given actor instance - void ActorManager::UnregisterActorInstance(uint32 nr) + void ActorManager::UnregisterActorInstance(size_t nr) { - UnregisterActorInstance(mActorInstances[nr]); + UnregisterActorInstance(m_actorInstances[nr]); } @@ -315,7 +284,7 @@ namespace EMotionFX // execute the schedule // this makes all the callback OnUpdate calls etc - mScheduler->Execute(timePassedInSeconds); + m_scheduler->Execute(timePassedInSeconds); UnlockActorInstances(); UnlockActors(); @@ -349,16 +318,19 @@ namespace EMotionFX if (actorInstance->GetAttachedTo() == nullptr) { // make sure it's in the root list - if (mRootActorInstances.Contains(actorInstance) == false) + if (AZStd::find(begin(m_rootActorInstances), end(m_rootActorInstances), actorInstance) == end(m_rootActorInstances)) { - mRootActorInstances.Add(actorInstance); + m_rootActorInstances.emplace_back(actorInstance); } } else // no root actor instance { // remove it from the root list - mRootActorInstances.RemoveByValue(actorInstance); - mScheduler->RecursiveRemoveActorInstance(actorInstance); + if (const auto it = AZStd::find(begin(m_rootActorInstances), end(m_rootActorInstances), actorInstance); it != end(m_rootActorInstances)) + { + m_rootActorInstances.erase(it); + } + m_scheduler->RecursiveRemoveActorInstance(actorInstance); } if (lock) @@ -374,13 +346,19 @@ namespace EMotionFX LockActorInstances(); // remove the actor instance from the list - mActorInstances.RemoveByValue(instance); + if (const auto it = AZStd::find(begin(m_actorInstances), end(m_actorInstances), instance); it != end(m_actorInstances)) + { + m_actorInstances.erase(it); + } // remove it from the list of roots, if it is in there - mRootActorInstances.RemoveByValue(instance); + if (const auto it = AZStd::find(begin(m_rootActorInstances), end(m_rootActorInstances), instance); it != end(m_rootActorInstances)) + { + m_rootActorInstances.erase(it); + } // remove it from the schedule - mScheduler->RemoveActorInstance(instance); + m_scheduler->RemoveActorInstance(instance); UnlockActorInstances(); } @@ -388,42 +366,42 @@ namespace EMotionFX void ActorManager::LockActorInstances() { - mActorInstanceLock.Lock(); + m_actorInstanceLock.Lock(); } void ActorManager::UnlockActorInstances() { - mActorInstanceLock.Unlock(); + m_actorInstanceLock.Unlock(); } void ActorManager::LockActors() { - mActorLock.Lock(); + m_actorLock.Lock(); } void ActorManager::UnlockActors() { - mActorLock.Unlock(); + m_actorLock.Unlock(); } - Actor* ActorManager::GetActor(uint32 nr) const + Actor* ActorManager::GetActor(size_t nr) const { return m_actors[nr].get(); } - const MCore::Array& ActorManager::GetActorInstanceArray() const + const AZStd::vector& ActorManager::GetActorInstanceArray() const { - return mActorInstances; + return m_actorInstances; } ActorUpdateScheduler* ActorManager::GetScheduler() const { - return mScheduler; + return m_scheduler; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h index 280cc33498..ff78250141 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorManager.h @@ -14,7 +14,7 @@ #include "BaseObject.h" #include "MemoryCategories.h" #include -#include +#include #include @@ -67,7 +67,7 @@ namespace EMotionFX * This does not include the clones that have been optionally created. * @result The number of registered actors. */ - MCORE_INLINE uint32 GetNumActors() const { return static_cast(m_actors.size()); } + MCORE_INLINE size_t GetNumActors() const { return m_actors.size(); } /** * Get a given actor. @@ -77,7 +77,7 @@ namespace EMotionFX * @param nr The actor number, which must be in range of [0..GetNumActors()-1]. * @result A reference to the actor object that contains the array of Actor objects. */ - Actor* GetActor(uint32 nr) const; + Actor* GetActor(size_t nr) const; /** * Find the given actor by name. @@ -99,7 +99,7 @@ namespace EMotionFX * @param actor The actor object you once passed to RegisterActor. * @result Returns the actor number, which is in range of [0..GetNumActors()-1], or returns MCORE_INVALIDINDEX32 when not found. */ - uint32 FindActorIndex(Actor* actor) const; + size_t FindActorIndex(Actor* actor) const; /** * Find the actor number for a given actor name. @@ -107,7 +107,7 @@ namespace EMotionFX * @param actorName The name of the actor. * @result Returns the actor number, which is in range of [0..GetNumActors()-1], or returns MCORE_INVALIDINDEX32 when not found. */ - uint32 FindActorIndexByName(const char* actorName) const; + size_t FindActorIndexByName(const char* actorName) const; /** * Find the actor number for a given actor filename. @@ -115,7 +115,7 @@ namespace EMotionFX * @param filename The filename of the actor. * @result Returns the actor number, which is in range of [0..GetNumActors()-1], or returns MCORE_INVALIDINDEX32 when not found. */ - uint32 FindActorIndexByFileName(const char* filename) const; + size_t FindActorIndexByFileName(const char* filename) const; // register the actor instance void RegisterActorInstance(ActorInstance* actorInstance); @@ -124,27 +124,27 @@ namespace EMotionFX * Get the number of actor instances that currently are registered. * @result The number of registered actor instances. */ - MCORE_INLINE uint32 GetNumActorInstances() const { return mActorInstances.GetLength(); } + MCORE_INLINE size_t GetNumActorInstances() const { return m_actorInstances.size(); } /** * Get a given registered actor instance. * @param nr The actor instance number, which must be in range of [0..GetNumActorInstances()-1]. * @result A pointer to the actor instance. */ - MCORE_INLINE ActorInstance* GetActorInstance(uint32 nr) const { return mActorInstances[nr]; } + MCORE_INLINE ActorInstance* GetActorInstance(size_t nr) const { return m_actorInstances[nr]; } /** * Get the array of actor instances. * @result The const reference to the actor instance array. */ - const MCore::Array& GetActorInstanceArray() const; + const AZStd::vector& GetActorInstanceArray() const; /** * Find the given actor instance inside the actor manager and return its index. * @param actorInstance A pointer to the actor instance to be searched. * @result The actor instance index for the actor manager, MCORE_INVALIDINDEX32 in case the actor instance hasn't been found. */ - uint32 FindActorInstanceIndex(ActorInstance* actorInstance) const; + size_t FindActorInstanceIndex(ActorInstance* actorInstance) const; /** * Find an actor instance inside the actor manager by its id. @@ -192,7 +192,7 @@ namespace EMotionFX * When you delete an actor instance, it automatically will unregister itself from the manager. * @param nr The actor instance number, which has to be in range of [0..GetNumActorInstances()-1]. */ - void UnregisterActorInstance(uint32 nr); + void UnregisterActorInstance(size_t nr); /** * Get the number of root actor instances. @@ -201,7 +201,7 @@ namespace EMotionFX * horse is the root attachment instance. * @result Returns the number of root actor instances. */ - MCORE_INLINE uint32 GetNumRootActorInstances() const { return mRootActorInstances.GetLength(); } + MCORE_INLINE size_t GetNumRootActorInstances() const { return m_rootActorInstances.size(); } /** * Get a given root actor instance. @@ -211,7 +211,7 @@ namespace EMotionFX * @param nr The root actor instance number, which must be in range of [0..GetNumRootActorInstances()-1]. * @result A pointer to the actor instance that is a root. */ - MCORE_INLINE ActorInstance* GetRootActorInstance(uint32 nr) const { return mRootActorInstances[nr]; } + MCORE_INLINE ActorInstance* GetRootActorInstance(size_t nr) const { return m_rootActorInstances[nr]; } /** * Get the currently used actor update scheduler. @@ -255,12 +255,12 @@ namespace EMotionFX void UnlockActors(); private: - MCore::Array mActorInstances; /**< The registered actor instances. */ + AZStd::vector m_actorInstances; /**< The registered actor instances. */ AZStd::vector> m_actors; /**< The registered actors. */ - MCore::Array mRootActorInstances; /**< Root actor instances (roots of all attachment chains). */ - ActorUpdateScheduler* mScheduler; /**< The update scheduler to use. */ - MCore::MutexRecursive mActorLock; /**< The multithread lock for touching the actors array. */ - MCore::MutexRecursive mActorInstanceLock; /**< The multithread lock for touching the actor instances array. */ + AZStd::vector m_rootActorInstances; /**< Root actor instances (roots of all attachment chains). */ + ActorUpdateScheduler* m_scheduler; /**< The update scheduler to use. */ + MCore::MutexRecursive m_actorLock; /**< The multithread lock for touching the actors array. */ + MCore::MutexRecursive m_actorInstanceLock; /**< The multithread lock for touching the actor instances array. */ /** * The constructor, which initializes using the multi processor scheduler. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h b/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h index 2ad6beeacf..9ca73e423f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorUpdateScheduler.h @@ -63,14 +63,14 @@ namespace EMotionFX * @param actorInstance The actor instance to insert. * @param startStep An offset in the schedule where to start trying to insert the actor instances. */ - virtual void RecursiveInsertActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) = 0; + virtual void RecursiveInsertActorInstance(ActorInstance* actorInstance, size_t startStep = 0) = 0; /** * Recursively remove an actor instance and its attachments from the schedule. * @param actorInstance The actor instance to remove. * @param startStep An offset in the schedule where to start trying to remove from. */ - virtual void RecursiveRemoveActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) = 0; + virtual void RecursiveRemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) = 0; /** * Remove a single actor instance from the schedule. This will not remove its attachments. @@ -78,16 +78,16 @@ namespace EMotionFX * @param startStep An offset in the schedule where to start trying to remove from. * @result Returns the offset in the schedule where the actor instance was removed. */ - virtual uint32 RemoveActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) = 0; + virtual size_t RemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) = 0; - uint32 GetNumUpdatedActorInstances() const { return mNumUpdated.GetValue(); } - uint32 GetNumVisibleActorInstances() const { return mNumVisible.GetValue(); } - uint32 GetNumSampledActorInstances() const { return mNumSampled.GetValue(); } + size_t GetNumUpdatedActorInstances() const { return m_numUpdated.GetValue(); } + size_t GetNumVisibleActorInstances() const { return m_numVisible.GetValue(); } + size_t GetNumSampledActorInstances() const { return m_numSampled.GetValue(); } protected: - MCore::AtomicUInt32 mNumUpdated; - MCore::AtomicUInt32 mNumVisible; - MCore::AtomicUInt32 mNumSampled; + MCore::AtomicSizeT m_numUpdated; + MCore::AtomicSizeT m_numVisible; + MCore::AtomicSizeT m_numSampled; /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp index 7a9001433a..a9cfbc4379 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -34,23 +35,21 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(AnimGraph, AnimGraphAllocator, 0) AnimGraph::AnimGraph() - : mGameControllerSettings(aznew AnimGraphGameControllerSettings()) + : m_gameControllerSettings(aznew AnimGraphGameControllerSettings()) { - mNodes.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH); - - mID = MCore::GetIDGenerator().GenerateID(); - mDirtyFlag = false; - mAutoUnregister = true; - mRetarget = false; - mRootStateMachine = nullptr; + m_id = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); + m_dirtyFlag = false; + m_autoUnregister = true; + m_retarget = false; + m_rootStateMachine = nullptr; #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = false; + m_isOwnedByRuntime = false; m_isOwnedByAsset = false; #endif // EMFX_DEVELOPMENT_BUILD // reserve some memory - mNodes.Reserve(1024); + m_nodes.reserve(1024); // automatically register the anim graph GetAnimGraphManager().AddAnimGraph(this); @@ -66,35 +65,35 @@ namespace EMotionFX RemoveAllNodeGroups(); - if (mRootStateMachine) + if (m_rootStateMachine) { - delete mRootStateMachine; + delete m_rootStateMachine; } // automatically unregister the anim graph - if (mAutoUnregister) + if (m_autoUnregister) { GetAnimGraphManager().RemoveAnimGraph(this, false); } - delete mGameControllerSettings; + delete m_gameControllerSettings; } void AnimGraph::RecursiveReinit() { - if (!mRootStateMachine) + if (!m_rootStateMachine) { return; } - mRootStateMachine->RecursiveReinit(); + m_rootStateMachine->RecursiveReinit(); } bool AnimGraph::InitAfterLoading() { - if (!mRootStateMachine) + if (!m_rootStateMachine) { return false; } @@ -107,7 +106,7 @@ namespace EMotionFX m_valueParameterIndexByName.emplace(m_valueParameters[i]->GetName(), i); } - return mRootStateMachine->InitAfterLoading(this); + return m_rootStateMachine->InitAfterLoading(this); } void AnimGraph::RecursiveInvalidateUniqueDatas() @@ -308,25 +307,25 @@ namespace EMotionFX // recursively find a given node AnimGraphNode* AnimGraph::RecursiveFindNodeByName(const char* nodeName) const { - return mRootStateMachine->RecursiveFindNodeByName(nodeName); + return m_rootStateMachine->RecursiveFindNodeByName(nodeName); } bool AnimGraph::IsNodeNameUnique(const AZStd::string& newNameCandidate, const AnimGraphNode* forNode) const { - return mRootStateMachine->RecursiveIsNodeNameUnique(newNameCandidate, forNode); + return m_rootStateMachine->RecursiveIsNodeNameUnique(newNameCandidate, forNode); } AnimGraphNode* AnimGraph::RecursiveFindNodeById(AnimGraphNodeId nodeId) const { - return mRootStateMachine->RecursiveFindNodeById(nodeId); + return m_rootStateMachine->RecursiveFindNodeById(nodeId); } AnimGraphStateTransition* AnimGraph::RecursiveFindTransitionById(AnimGraphConnectionId transitionId) const { - for (AnimGraphObject* object : mObjects) + for (AnimGraphObject* object : m_objects) { if (azrtti_typeid(object) == azrtti_typeid()) { @@ -346,12 +345,12 @@ namespace EMotionFX AZStd::string AnimGraph::GenerateNodeName(const AZStd::unordered_set& nameReserveList, const char* prefix) const { AZStd::string result; - uint32 number = 0; + size_t number = 0; bool found = false; while (found == false) { // build the string - result = AZStd::string::format("%s%d", prefix, number++); + result = AZStd::string::format("%s%zu", prefix, number++); // if there is no such state machine yet if (!RecursiveFindNodeByName(result.c_str()) && nameReserveList.find(result) == nameReserveList.end()) @@ -364,9 +363,9 @@ namespace EMotionFX } - uint32 AnimGraph::RecursiveCalcNumNodes() const + size_t AnimGraph::RecursiveCalcNumNodes() const { - return mRootStateMachine->RecursiveCalcNumNodes(); + return m_rootStateMachine->RecursiveCalcNumNodes(); } @@ -383,13 +382,13 @@ namespace EMotionFX void AnimGraph::RecursiveCalcStatistics(Statistics& outStatistics) const { - RecursiveCalcStatistics(outStatistics, mRootStateMachine); + RecursiveCalcStatistics(outStatistics, m_rootStateMachine); } - void AnimGraph::RecursiveCalcStatistics(Statistics& outStatistics, AnimGraphNode* animGraphNode, uint32 currentHierarchyDepth) const + void AnimGraph::RecursiveCalcStatistics(Statistics& outStatistics, AnimGraphNode* animGraphNode, size_t currentHierarchyDepth) const { - outStatistics.m_maxHierarchyDepth = MCore::Max(currentHierarchyDepth, outStatistics.m_maxHierarchyDepth); + outStatistics.m_maxHierarchyDepth = AZStd::max(currentHierarchyDepth, outStatistics.m_maxHierarchyDepth); // Are we dealing with a state machine? If yes, increase the number of transitions, states etc. in the statistics. if (azrtti_typeid(animGraphNode) == azrtti_typeid()) @@ -397,12 +396,12 @@ namespace EMotionFX AnimGraphStateMachine* stateMachine = static_cast(animGraphNode); outStatistics.m_numStateMachines++; - const AZ::u32 numTransitions = static_cast(stateMachine->GetNumTransitions()); + const size_t numTransitions = stateMachine->GetNumTransitions(); outStatistics.m_numTransitions += numTransitions; outStatistics.m_numStates += stateMachine->GetNumChildNodes(); - for (uint32 i = 0; i < numTransitions; ++i) + for (size_t i = 0; i < numTransitions; ++i) { AnimGraphStateTransition* transition = stateMachine->GetTransition(i); @@ -411,12 +410,12 @@ namespace EMotionFX outStatistics.m_numWildcardTransitions++; } - outStatistics.m_numTransitionConditions += static_cast(transition->GetNumConditions()); + outStatistics.m_numTransitionConditions += transition->GetNumConditions(); } } - const uint32 numChildNodes = animGraphNode->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = animGraphNode->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { RecursiveCalcStatistics(outStatistics, animGraphNode->GetChildNode(i), currentHierarchyDepth + 1); } @@ -424,37 +423,37 @@ namespace EMotionFX // recursively calculate the number of node connections - uint32 AnimGraph::RecursiveCalcNumNodeConnections() const + size_t AnimGraph::RecursiveCalcNumNodeConnections() const { - return mRootStateMachine->RecursiveCalcNumNodeConnections(); + return m_rootStateMachine->RecursiveCalcNumNodeConnections(); } // adjust the dirty flag void AnimGraph::SetDirtyFlag(bool dirty) { - mDirtyFlag = dirty; + m_dirtyFlag = dirty; } // adjust the auto unregistering from the anim graph manager on delete void AnimGraph::SetAutoUnregister(bool enabled) { - mAutoUnregister = enabled; + m_autoUnregister = enabled; } // do we auto unregister from the anim graph manager on delete? bool AnimGraph::GetAutoUnregister() const { - return mAutoUnregister; + return m_autoUnregister; } void AnimGraph::SetIsOwnedByRuntime(bool isOwnedByRuntime) { #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = isOwnedByRuntime; + m_isOwnedByRuntime = isOwnedByRuntime; #else AZ_UNUSED(isOwnedByRuntime); #endif @@ -464,7 +463,7 @@ namespace EMotionFX bool AnimGraph::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif @@ -493,16 +492,16 @@ namespace EMotionFX // get a pointer to the given node group - AnimGraphNodeGroup* AnimGraph::GetNodeGroup(uint32 index) const + AnimGraphNodeGroup* AnimGraph::GetNodeGroup(size_t index) const { - return mNodeGroups[index]; + return m_nodeGroups[index]; } // find the node group by name AnimGraphNodeGroup* AnimGraph::FindNodeGroupByName(const char* groupName) const { - for (AnimGraphNodeGroup* nodeGroup : mNodeGroups) + for (AnimGraphNodeGroup* nodeGroup : m_nodeGroups) { // Compare the node names and return a pointer in case they are equal. if (nodeGroup->GetNameString() == groupName) @@ -516,40 +515,34 @@ namespace EMotionFX // find the node group index by name - uint32 AnimGraph::FindNodeGroupIndexByName(const char* groupName) const + size_t AnimGraph::FindNodeGroupIndexByName(const char* groupName) const { - const size_t numNodeGroups = mNodeGroups.size(); - for (size_t i = 0; i < numNodeGroups; ++i) + const auto foundNodeGroup = AZStd::find_if(begin(m_nodeGroups), end(m_nodeGroups), [groupName](const AnimGraphNodeGroup* nodeGroup) { - // compare the node names and return the index in case they are equal - if (mNodeGroups[i]->GetNameString() == groupName) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return nodeGroup->GetNameString() == groupName; + }); + return foundNodeGroup != end(m_nodeGroups) ? AZStd::distance(begin(m_nodeGroups), foundNodeGroup) : InvalidIndex; } // add the given node group to the anim graph void AnimGraph::AddNodeGroup(AnimGraphNodeGroup* nodeGroup) { - mNodeGroups.push_back(nodeGroup); + m_nodeGroups.push_back(nodeGroup); } // remove the node group at the given index from the anim graph - void AnimGraph::RemoveNodeGroup(uint32 index, bool delFromMem) + void AnimGraph::RemoveNodeGroup(size_t index, bool delFromMem) { // destroy the object if (delFromMem) { - delete mNodeGroups[index]; + delete m_nodeGroups[index]; } // remove the node group from the array - mNodeGroups.erase(mNodeGroups.begin() + index); + m_nodeGroups.erase(m_nodeGroups.begin() + index); } @@ -559,28 +552,28 @@ namespace EMotionFX // destroy the node groups if (delFromMem) { - for (AnimGraphNodeGroup* nodeGroup : mNodeGroups) + for (AnimGraphNodeGroup* nodeGroup : m_nodeGroups) { delete nodeGroup; } } // remove all node groups - mNodeGroups.clear(); + m_nodeGroups.clear(); } // get the number of node groups - uint32 AnimGraph::GetNumNodeGroups() const + size_t AnimGraph::GetNumNodeGroups() const { - return static_cast(mNodeGroups.size()); + return m_nodeGroups.size(); } // find the node group in which the given anim graph node is in and return a pointer to it AnimGraphNodeGroup* AnimGraph::FindNodeGroupForNode(AnimGraphNode* animGraphNode) const { - for (AnimGraphNodeGroup* nodeGroup : mNodeGroups) + for (AnimGraphNodeGroup* nodeGroup : m_nodeGroups) { // check if the given node is part of the currently iterated node group if (nodeGroup->Contains(animGraphNode->GetId())) @@ -625,24 +618,24 @@ namespace EMotionFX void AnimGraph::RecursiveCollectNodesOfType(const AZ::TypeId& nodeType, AZStd::vector* outNodes) const { - mRootStateMachine->RecursiveCollectNodesOfType(nodeType, outNodes); + m_rootStateMachine->RecursiveCollectNodesOfType(nodeType, outNodes); } - void AnimGraph::RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, MCore::Array* outConditions) const + void AnimGraph::RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, AZStd::vector* outConditions) const { - mRootStateMachine->RecursiveCollectTransitionConditionsOfType(conditionType, outConditions); + m_rootStateMachine->RecursiveCollectTransitionConditionsOfType(conditionType, outConditions); } void AnimGraph::RecursiveCollectObjectsOfType(const AZ::TypeId& objectType, AZStd::vector& outObjects) { - mRootStateMachine->RecursiveCollectObjectsOfType(objectType, outObjects); + m_rootStateMachine->RecursiveCollectObjectsOfType(objectType, outObjects); } void AnimGraph::RecursiveCollectObjectsAffectedBy(AnimGraph* animGraph, AZStd::vector& outObjects) { - mRootStateMachine->RecursiveCollectObjectsAffectedBy(animGraph, outObjects); + m_rootStateMachine->RecursiveCollectObjectsAffectedBy(animGraph, outObjects); } GroupParameter* AnimGraph::FindGroupParameterByName(const AZStd::string& groupName) const @@ -691,7 +684,7 @@ namespace EMotionFX // delete all unique datas for a given object void AnimGraph::RemoveAllObjectData(AnimGraphObject* object, bool delFromMem) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); for (AnimGraphInstance* animGraphInstance : m_animGraphInstances) { @@ -703,11 +696,11 @@ namespace EMotionFX // set the root state machine void AnimGraph::SetRootStateMachine(AnimGraphStateMachine* stateMachine) { - mRootStateMachine = stateMachine; - if (mRootStateMachine) + m_rootStateMachine = stateMachine; + if (m_rootStateMachine) { // make sure the name is always the same for the root state machine - mRootStateMachine->SetName("Root"); + m_rootStateMachine->SetName("Root"); } } @@ -715,18 +708,18 @@ namespace EMotionFX // add an object void AnimGraph::AddObject(AnimGraphObject* object) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); // assign the index and add it to the objects array - object->SetObjectIndex(static_cast(mObjects.size())); - mObjects.push_back(object); + object->SetObjectIndex(m_objects.size()); + m_objects.push_back(object); // if it's a node, add it to the nodes array as well if (azrtti_istypeof(object)) { AnimGraphNode* node = static_cast(object); - node->SetNodeIndex(mNodes.GetLength()); - mNodes.Add(node); + node->SetNodeIndex(m_nodes.size()); + m_nodes.emplace_back(node); } // create a unique data for this added object in the animgraph instances as well @@ -740,7 +733,7 @@ namespace EMotionFX // remove an object void AnimGraph::RemoveObject(AnimGraphObject* object) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); const size_t objectIndex = object->GetObjectIndex(); @@ -748,64 +741,58 @@ namespace EMotionFX object->RemoveInternalAttributesForAllInstances(); // decrease the indices of all objects that have an index after this node - const size_t numObjects = mObjects.size(); + const size_t numObjects = m_objects.size(); for (size_t i = objectIndex + 1; i < numObjects; ++i) { - AnimGraphObject* curObject = mObjects[i]; + AnimGraphObject* curObject = m_objects[i]; MCORE_ASSERT(i == curObject->GetObjectIndex()); curObject->SetObjectIndex(i - 1); } // remove the object from the array - mObjects.erase(mObjects.begin() + objectIndex); + m_objects.erase(m_objects.begin() + objectIndex); // remove it from the nodes array if it is a node if (azrtti_istypeof(object)) { AnimGraphNode* node = static_cast(object); - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); - const uint32 numNodes = mNodes.GetLength(); - for (uint32 i = nodeIndex + 1; i < numNodes; ++i) + const size_t numNodes = m_nodes.size(); + for (size_t i = nodeIndex + 1; i < numNodes; ++i) { - AnimGraphNode* curNode = mNodes[i]; + AnimGraphNode* curNode = m_nodes[i]; MCORE_ASSERT(i == curNode->GetNodeIndex()); curNode->SetNodeIndex(i - 1); } // remove the object from the array - mNodes.Remove(nodeIndex); + m_nodes.erase(AZStd::next(begin(m_nodes), nodeIndex)); } } // reserve space for a given amount of objects - void AnimGraph::ReserveNumObjects(uint32 numObjects) + void AnimGraph::ReserveNumObjects(size_t numObjects) { - mObjects.reserve(numObjects); + m_objects.reserve(numObjects); } // reserve space for a given amount of nodes - void AnimGraph::ReserveNumNodes(uint32 numNodes) + void AnimGraph::ReserveNumNodes(size_t numNodes) { - mNodes.Reserve(numNodes); + m_nodes.reserve(numNodes); } // Calculate number of motion nodes in the graph - uint32 AnimGraph::CalcNumMotionNodes() const + size_t AnimGraph::CalcNumMotionNodes() const { - const uint32 numNodes = mNodes.GetLength(); - uint32 numMotionNodes = 0; - for (uint32 i = 0; i < numNodes; ++i) + return AZStd::accumulate(begin(m_nodes), end(m_nodes), size_t{0}, [](size_t total, const AnimGraphNode* node) { - if (azrtti_istypeof(mNodes[i])) - { - numMotionNodes++; - } - } - return numMotionNodes; + return total + azrtti_istypeof(node); + }); } @@ -819,7 +806,7 @@ namespace EMotionFX // register an animgraph instance void AnimGraph::AddAnimGraphInstance(AnimGraphInstance* animGraphInstance) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); m_animGraphInstances.emplace_back(animGraphInstance); } @@ -827,15 +814,15 @@ namespace EMotionFX // remove an animgraph instance void AnimGraph::RemoveAnimGraphInstance(AnimGraphInstance* animGraphInstance) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); m_animGraphInstances.erase(AZStd::remove(m_animGraphInstances.begin(), m_animGraphInstances.end(), animGraphInstance)); } // decrease internal attribute indices by one, for values higher than the given parameter - void AnimGraph::DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan) + void AnimGraph::DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) { - for (AnimGraphObject* object : mObjects) + for (AnimGraphObject* object : m_objects) { object->DecreaseInternalAttributeIndices(decreaseEverythingHigherThan); } @@ -844,72 +831,72 @@ namespace EMotionFX const char* AnimGraph::GetFileName() const { - return mFileName.c_str(); + return m_fileName.c_str(); } const AZStd::string& AnimGraph::GetFileNameString() const { - return mFileName; + return m_fileName; } void AnimGraph::SetFileName(const char* fileName) { - mFileName = fileName; + m_fileName = fileName; } AnimGraphStateMachine* AnimGraph::GetRootStateMachine() const { - return mRootStateMachine; + return m_rootStateMachine; } uint32 AnimGraph::GetID() const { - return mID; + return m_id; } void AnimGraph::SetID(uint32 id) { - mID = id; + m_id = id; } bool AnimGraph::GetDirtyFlag() const { - return mDirtyFlag; + return m_dirtyFlag; } AnimGraphGameControllerSettings& AnimGraph::GetGameControllerSettings() { - return *mGameControllerSettings; + return *m_gameControllerSettings; } bool AnimGraph::GetRetargetingEnabled() const { - return mRetarget; + return m_retarget; } void AnimGraph::SetRetargetingEnabled(bool enabled) { - mRetarget = enabled; + m_retarget = enabled; } void AnimGraph::Lock() { - mLock.Lock(); + m_lock.Lock(); } void AnimGraph::Unlock() { - mLock.Unlock(); + m_lock.Unlock(); } @@ -917,7 +904,7 @@ namespace EMotionFX { for (AnimGraphInstance* animGraphInstance : m_animGraphInstances) { - animGraphInstance->SetRetargetingEnabled(mRetarget); + animGraphInstance->SetRetargetingEnabled(m_retarget); } } @@ -933,10 +920,10 @@ namespace EMotionFX serializeContext->Class() ->Version(1) ->Field("rootGroupParameter", &AnimGraph::m_rootParameter) - ->Field("rootStateMachine", &AnimGraph::mRootStateMachine) - ->Field("nodeGroups", &AnimGraph::mNodeGroups) - ->Field("gameControllerSettings", &AnimGraph::mGameControllerSettings) - ->Field("retarget", &AnimGraph::mRetarget) + ->Field("rootStateMachine", &AnimGraph::m_rootStateMachine) + ->Field("nodeGroups", &AnimGraph::m_nodeGroups) + ->Field("gameControllerSettings", &AnimGraph::m_gameControllerSettings) + ->Field("retarget", &AnimGraph::m_retarget) ; @@ -950,7 +937,7 @@ namespace EMotionFX ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, "") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->DataElement(AZ::Edit::UIHandlers::Default, &AnimGraph::mRetarget, "Retarget", "") + ->DataElement(AZ::Edit::UIHandlers::Default, &AnimGraph::m_retarget, "Retarget", "") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &AnimGraph::OnRetargetingEnabledChanged) ; } @@ -1029,11 +1016,9 @@ namespace EMotionFX void AnimGraph::RemoveInvalidConnections(bool logWarnings) { // Iterate over all nodes - const AZ::u32 numNodes = mNodes.GetLength(); - for (AZ::u32 i = 0; i < numNodes; ++i) + for (AnimGraphNode* node : m_nodes) { - AnimGraphNode* node = mNodes[i]; - for (AZ::u32 c = 0; c < node->GetNumConnections();) + for (size_t c = 0; c < node->GetNumConnections();) { BlendTreeConnection* connection = node->GetConnection(c); if (!connection->GetSourceNode()) // Invalid source node. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h index e7c775d644..2a498f9f81 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraph.h @@ -20,7 +20,7 @@ #include #include #include -#include +#include namespace EMotionFX { @@ -65,31 +65,31 @@ namespace EMotionFX AnimGraphStateTransition* RecursiveFindTransitionById(AnimGraphConnectionId transitionId) const; void RecursiveCollectNodesOfType(const AZ::TypeId& nodeType, AZStd::vector* outNodes) const; // note: outNodes is NOT cleared internally, nodes are added to the array - void RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, MCore::Array* outConditions) const; // note: outNodes is NOT cleared internally, nodes are added to the array + void RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, AZStd::vector* outConditions) const; // note: outNodes is NOT cleared internally, nodes are added to the array // Collects all objects of type and/or derived type void RecursiveCollectObjectsOfType(const AZ::TypeId& objectType, AZStd::vector& outObjects); void RecursiveCollectObjectsAffectedBy(AnimGraph* animGraph, AZStd::vector& outObjects); - uint32 RecursiveCalcNumNodes() const; + size_t RecursiveCalcNumNodes() const; struct Statistics { - AZ::u32 m_maxHierarchyDepth; - AZ::u32 m_numStateMachines; - AZ::u32 m_numStates; - AZ::u32 m_numTransitions; - AZ::u32 m_numWildcardTransitions; - AZ::u32 m_numTransitionConditions; + size_t m_maxHierarchyDepth; + size_t m_numStateMachines; + size_t m_numStates; + size_t m_numTransitions; + size_t m_numWildcardTransitions; + size_t m_numTransitionConditions; Statistics(); }; void RecursiveCalcStatistics(Statistics& outStatistics) const; - uint32 RecursiveCalcNumNodeConnections() const; + size_t RecursiveCalcNumNodeConnections() const; - void DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan); + void DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan); AZStd::string GenerateNodeName(const AZStd::unordered_set& nameReserveList, const char* prefix = "Node") const; @@ -313,13 +313,13 @@ namespace EMotionFX * Get the number of node groups. * @result The number of node groups. */ - uint32 GetNumNodeGroups() const; + size_t GetNumNodeGroups() const; /** * Get a pointer to the given node group. * @param index The node group index, which must be in range of [0..GetNumNodeGroups()-1]. */ - AnimGraphNodeGroup* GetNodeGroup(uint32 index) const; + AnimGraphNodeGroup* GetNodeGroup(size_t index) const; /** * Find a node group based on the name and return a pointer. @@ -333,7 +333,7 @@ namespace EMotionFX * @param groupName The group name to search for. * @result The index of the node group inside this anim graph, MCORE_INVALIDINDEX32 in case the node group wasn't found. */ - uint32 FindNodeGroupIndexByName(const char* groupName) const; + size_t FindNodeGroupIndexByName(const char* groupName) const; /** * Add the given node group. @@ -346,7 +346,7 @@ namespace EMotionFX * @param index The node group index to remove. This value must be in range of [0..GetNumNodeGroups()-1]. * @param delFromMem Set to true (default) when you wish to also delete the specified group from memory. */ - void RemoveNodeGroup(uint32 index, bool delFromMem = true); + void RemoveNodeGroup(size_t index, bool delFromMem = true); /** * Remove all node groups. @@ -377,14 +377,14 @@ namespace EMotionFX void AddObject(AnimGraphObject* object); // registers the object in the array and modifies the object's object index value void RemoveObject(AnimGraphObject* object); // doesn't actually remove it from memory, just removes it from the list - uint32 GetNumObjects() const { return static_cast(mObjects.size()); } - AnimGraphObject* GetObject(uint32 index) const { return mObjects[index]; } - void ReserveNumObjects(uint32 numObjects); + size_t GetNumObjects() const { return m_objects.size(); } + AnimGraphObject* GetObject(size_t index) const { return m_objects[index]; } + void ReserveNumObjects(size_t numObjects); - uint32 GetNumNodes() const { return mNodes.GetLength(); } - AnimGraphNode* GetNode(uint32 index) const { return mNodes[index]; } - void ReserveNumNodes(uint32 numNodes); - uint32 CalcNumMotionNodes() const; + size_t GetNumNodes() const { return m_nodes.size(); } + AnimGraphNode* GetNode(size_t index) const { return m_nodes[index]; } + void ReserveNumNodes(size_t numNodes); + size_t CalcNumMotionNodes() const; size_t GetNumAnimGraphInstances() const { return m_animGraphInstances.size(); } AnimGraphInstance* GetAnimGraphInstance(size_t index) const { return m_animGraphInstances[index]; } @@ -405,7 +405,7 @@ namespace EMotionFX void RemoveInvalidConnections(bool logWarnings=false); private: - void RecursiveCalcStatistics(Statistics& outStatistics, AnimGraphNode* animGraphNode, uint32 currentHierarchyDepth = 0) const; + void RecursiveCalcStatistics(Statistics& outStatistics, AnimGraphNode* animGraphNode, size_t currentHierarchyDepth = 0) const; void OnRetargetingEnabledChanged(); @@ -415,21 +415,21 @@ namespace EMotionFX GroupParameter m_rootParameter; /**< root group parameter. */ ValueParameterVector m_valueParameters; /**< Cached version of all parameters with values. */ AZStd::unordered_map m_valueParameterIndexByName; /**< Cached version of parameter index by name to accelerate lookups. */ - AZStd::vector mNodeGroups; - AZStd::vector mObjects; - MCore::Array mNodes; + AZStd::vector m_nodeGroups; + AZStd::vector m_objects; + AZStd::vector m_nodes; AZStd::vector m_animGraphInstances; - AZStd::string mFileName; - AnimGraphStateMachine* mRootStateMachine; - AnimGraphGameControllerSettings* mGameControllerSettings; - MCore::Mutex mLock; - uint32 mID; /**< The unique identification number for this anim graph. */ - bool mAutoUnregister; /**< Specifies whether we will automatically unregister this anim graph set from this anim graph manager or not, when deleting this object. */ - bool mRetarget; /**< Is retargeting enabled on default? */ - bool mDirtyFlag; /**< The dirty flag which indicates whether the user has made changes to this anim graph since the last file save operation. */ + AZStd::string m_fileName; + AnimGraphStateMachine* m_rootStateMachine; + AnimGraphGameControllerSettings* m_gameControllerSettings; + MCore::Mutex m_lock; + uint32 m_id; /**< The unique identification number for this anim graph. */ + bool m_autoUnregister; /**< Specifies whether we will automatically unregister this anim graph set from this anim graph manager or not, when deleting this object. */ + bool m_retarget; /**< Is retargeting enabled on default? */ + bool m_dirtyFlag; /**< The dirty flag which indicates whether the user has made changes to this anim graph since the last file save operation. */ #if defined(EMFX_DEVELOPMENT_BUILD) - bool mIsOwnedByRuntime; /**< Set if the anim graph is used/owned by the engine runtime. */ + bool m_isOwnedByRuntime; /**< Set if the anim graph is used/owned by the engine runtime. */ bool m_isOwnedByAsset; /**< Set if the anim graph is used/owned by an asset. */ #endif // EMFX_DEVELOPMENT_BUILD }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.cpp index 069da49e27..497fd4c65c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.cpp @@ -53,7 +53,7 @@ namespace EMotionFX //--------------------------------------------------------------------------------------------------------------------- - void AnimGraphPropertyUtils::ReinitJointIndices(const Actor* actor, const AZStd::vector& jointNames, AZStd::vector& outJointIndices) + void AnimGraphPropertyUtils::ReinitJointIndices(const Actor* actor, const AZStd::vector& jointNames, AZStd::vector& outJointIndices) { const Skeleton* skeleton = actor->GetSkeleton(); const size_t jointCount = jointNames.size(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h index 9f7b33a66d..beb3cd7446 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphAttributeTypes.h @@ -49,12 +49,12 @@ namespace EMotionFX static AttributePose* Create(); static AttributePose* Create(AnimGraphPose* pose); - void SetValue(AnimGraphPose* value) { mValue = value; } - AnimGraphPose* GetValue() const { return mValue; } - AnimGraphPose* GetValue() { return mValue; } + void SetValue(AnimGraphPose* value) { m_value = value; } + AnimGraphPose* GetValue() const { return m_value; } + AnimGraphPose* GetValue() { return m_value; } // overloaded from the attribute base class - MCore::Attribute* Clone() const override { return Create(mValue); } + MCore::Attribute* Clone() const override { return Create(m_value); } const char* GetTypeString() const override { return "Pose"; } bool InitFrom(const MCore::Attribute* other) override { @@ -63,21 +63,21 @@ namespace EMotionFX return false; } const AttributePose* pose = static_cast(other); - mValue = pose->GetValue(); + m_value = pose->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override { MCORE_UNUSED(valueString); return false; } // unsupported bool ConvertToString(AZStd::string& outString) const override { MCORE_UNUSED(outString); return false; } // unsupported - uint32 GetClassSize() const override { return sizeof(AttributePose); } - uint32 GetDefaultInterfaceType() const override { return MCore::ATTRIBUTE_INTERFACETYPE_DEFAULT; } + size_t GetClassSize() const override { return sizeof(AttributePose); } + AZ::u32 GetDefaultInterfaceType() const override { return MCore::ATTRIBUTE_INTERFACETYPE_DEFAULT; } private: - AnimGraphPose* mValue; + AnimGraphPose* m_value; AttributePose() - : MCore::Attribute(TYPE_ID) { mValue = nullptr; } + : MCore::Attribute(TYPE_ID) { m_value = nullptr; } AttributePose(AnimGraphPose* pose) - : MCore::Attribute(TYPE_ID) { mValue = pose; } + : MCore::Attribute(TYPE_ID) { m_value = pose; } ~AttributePose() {} }; @@ -97,12 +97,12 @@ namespace EMotionFX static AttributeMotionInstance* Create(); static AttributeMotionInstance* Create(MotionInstance* motionInstance); - void SetValue(MotionInstance* value) { mValue = value; } - MotionInstance* GetValue() const { return mValue; } - MotionInstance* GetValue() { return mValue; } + void SetValue(MotionInstance* value) { m_value = value; } + MotionInstance* GetValue() const { return m_value; } + MotionInstance* GetValue() { return m_value; } // overloaded from the attribute base class - MCore::Attribute* Clone() const override { return Create(mValue); } + MCore::Attribute* Clone() const override { return Create(m_value); } const char* GetTypeString() const override { return "MotionInstance"; } bool InitFrom(const MCore::Attribute* other) override { @@ -111,28 +111,28 @@ namespace EMotionFX return false; } const AttributeMotionInstance* pose = static_cast(other); - mValue = pose->GetValue(); + m_value = pose->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override { MCORE_UNUSED(valueString); return false; } // unsupported bool ConvertToString(AZStd::string& outString) const override { MCORE_UNUSED(outString); return false; } // unsupported - uint32 GetClassSize() const override { return sizeof(AttributeMotionInstance); } - uint32 GetDefaultInterfaceType() const override { return MCore::ATTRIBUTE_INTERFACETYPE_DEFAULT; } + size_t GetClassSize() const override { return sizeof(AttributeMotionInstance); } + AZ::u32 GetDefaultInterfaceType() const override { return MCore::ATTRIBUTE_INTERFACETYPE_DEFAULT; } private: - MotionInstance* mValue; + MotionInstance* m_value; AttributeMotionInstance() - : MCore::Attribute(TYPE_ID) { mValue = nullptr; } + : MCore::Attribute(TYPE_ID) { m_value = nullptr; } AttributeMotionInstance(MotionInstance* motionInstance) - : MCore::Attribute(TYPE_ID) { mValue = motionInstance; } + : MCore::Attribute(TYPE_ID) { m_value = motionInstance; } ~AttributeMotionInstance() {} }; class AnimGraphPropertyUtils { public: - static void ReinitJointIndices(const Actor* actor, const AZStd::vector& jointNames, AZStd::vector& outJointIndices); + static void ReinitJointIndices(const Actor* actor, const AZStd::vector& jointNames, AZStd::vector& outJointIndices); }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.cpp index 1845336df9..e84ffac23a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphBindPoseNode.cpp @@ -72,7 +72,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEntryNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEntryNode.cpp index 45fc010a16..d581263e55 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEntryNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEntryNode.cpp @@ -111,7 +111,7 @@ namespace EMotionFX if (outputPose && GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp index 7a241ec18e..7bea215a71 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.cpp @@ -24,7 +24,7 @@ namespace EMotionFX { for (EventInfo& event : m_events) { - event.mEmitter = emitterNode; + event.m_emitter = emitterNode; } } @@ -32,9 +32,9 @@ namespace EMotionFX { for (EventInfo& curEvent : m_events) { - AnimGraphNodeData* emitterUniqueData = curEvent.mEmitter->FindOrCreateUniqueNodeData(animGraphInstance); - curEvent.mGlobalWeight = emitterUniqueData->GetGlobalWeight(); - curEvent.mLocalWeight = emitterUniqueData->GetLocalWeight(); + AnimGraphNodeData* emitterUniqueData = curEvent.m_emitter->FindOrCreateUniqueNodeData(animGraphInstance); + curEvent.m_globalWeight = emitterUniqueData->GetGlobalWeight(); + curEvent.m_localWeight = emitterUniqueData->GetLocalWeight(); } } @@ -45,7 +45,7 @@ namespace EMotionFX { AZStd::string eventDataString; - for (const EventDataPtr& eventData : event.mEvent->GetEventDatas()) + for (const EventDataPtr& eventData : event.m_event->GetEventDatas()) { if (eventData) { @@ -57,11 +57,11 @@ namespace EMotionFX } MCore::LogInfo("Event: (time=%f) (eventData=%s) (emitter=%s) (locWeight=%.4f globWeight=%.4f)", - event.mTimeValue, + event.m_timeValue, eventDataString.size() ? eventDataString.c_str() : "", - event.mEmitter->GetName(), - event.mLocalWeight, - event.mGlobalWeight); + event.m_emitter->GetName(), + event.m_localWeight, + event.m_globalWeight); } } @@ -76,12 +76,12 @@ namespace EMotionFX } } - void AnimGraphEventBuffer::Reserve(uint32 numEvents) + void AnimGraphEventBuffer::Reserve(size_t numEvents) { m_events.reserve(numEvents); } - void AnimGraphEventBuffer::Resize(uint32 numEvents) + void AnimGraphEventBuffer::Resize(size_t numEvents) { m_events.resize(numEvents); } @@ -93,12 +93,12 @@ namespace EMotionFX void AnimGraphEventBuffer::AddAllEventsFrom(const AnimGraphEventBuffer& eventBuffer) { - const AZ::u32 numEventsToCopy = eventBuffer.GetNumEvents(); - const uint32 numPrevEvents = GetNumEvents(); + const size_t numEventsToCopy = eventBuffer.GetNumEvents(); + const size_t numPrevEvents = GetNumEvents(); Resize(GetNumEvents() + numEventsToCopy); - for (uint32 i = 0; i < numEventsToCopy; ++i) + for (size_t i = 0; i < numEventsToCopy; ++i) { SetEvent(numPrevEvents + i, eventBuffer.GetEvent(i)); } @@ -109,7 +109,7 @@ namespace EMotionFX m_events.clear(); } - void AnimGraphEventBuffer::SetEvent(uint32 index, const EventInfo& eventInfo) + void AnimGraphEventBuffer::SetEvent(size_t index, const EventInfo& eventInfo) { m_events[index] = eventInfo; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.h index b2d049cf66..b21fa0b44a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphEventBuffer.h @@ -38,8 +38,8 @@ namespace EMotionFX AnimGraphEventBuffer& operator=(const AnimGraphEventBuffer&) = default; AnimGraphEventBuffer& operator=(AnimGraphEventBuffer&&) = default; - void Reserve(uint32 numEvents); - void Resize(uint32 numEvents); + void Reserve(size_t numEvents); + void Resize(size_t numEvents); void AddEvent(const EventInfo& newEvent); void AddAllEventsFrom(const AnimGraphEventBuffer& eventBuffer); @@ -49,11 +49,11 @@ namespace EMotionFX m_events.emplace_back(AZStd::forward(args)...); } - void SetEvent(uint32 index, const EventInfo& eventInfo); + void SetEvent(size_t index, const EventInfo& eventInfo); void Clear(); - MCORE_INLINE uint32 GetNumEvents() const { return static_cast(m_events.size()); } - MCORE_INLINE const EventInfo& GetEvent(uint32 index) const { return m_events[index]; } + MCORE_INLINE size_t GetNumEvents() const { return m_events.size(); } + MCORE_INLINE const EventInfo& GetEvent(size_t index) const { return m_events[index]; } void TriggerEvents() const; void UpdateWeights(AnimGraphInstance* animGraphInstance); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphExitNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphExitNode.cpp index 14684603c4..f4af1df28f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphExitNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphExitNode.cpp @@ -30,7 +30,7 @@ namespace EMotionFX void AnimGraphExitNode::UniqueData::Update() { - AnimGraphExitNode* exitNode = azdynamic_cast(mObject); + AnimGraphExitNode* exitNode = azdynamic_cast(m_object); AZ_Assert(exitNode, "Unique data linked to incorrect node type."); if (m_previousNode && exitNode->FindChildNodeIndex(m_previousNode) == InvalidIndex32) @@ -129,7 +129,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; @@ -157,7 +157,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -207,7 +207,7 @@ namespace EMotionFX void AnimGraphExitNode::RecursiveResetFlags(AnimGraphInstance* animGraphInstance, uint32 flagsToDisable) { UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - animGraphInstance->DisableObjectFlags(mObjectIndex, flagsToDisable); + animGraphInstance->DisableObjectFlags(m_objectIndex, flagsToDisable); // forward it to the node we came from if (uniqueData->m_previousNode && uniqueData->m_previousNode != this) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp index 83df46b74d..970e2e913c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.cpp @@ -6,6 +6,8 @@ * */ +#include +#include #include #include @@ -181,7 +183,7 @@ namespace EMotionFX ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// AnimGraphGameControllerSettings::AnimGraphGameControllerSettings() - : m_activePresetIndex(MCORE_INVALIDINDEX32) + : m_activePresetIndex(InvalidIndex) { } @@ -230,50 +232,35 @@ namespace EMotionFX size_t AnimGraphGameControllerSettings::FindPresetIndexByName(const char* presetName) const { - const size_t presetCount = m_presets.size(); - for (size_t i = 0; i < presetCount; ++i) + const auto foundPreset = AZStd::find_if(begin(m_presets), end(m_presets), [presetName](const Preset* preset) { - if (m_presets[i]->GetNameString() == presetName) - { - return i; - } - } - - // return failure - return MCORE_INVALIDINDEX32; + return preset->GetNameString() == presetName; + }); + return foundPreset != end(m_presets) ? AZStd::distance(begin(m_presets), foundPreset) : InvalidIndex; } size_t AnimGraphGameControllerSettings::FindPresetIndex(Preset* preset) const { - const size_t presetCount = m_presets.size(); - for (size_t i = 0; i < presetCount; ++i) - { - if (m_presets[i] == preset) - { - return i; - } - } - - // return failure - return MCORE_INVALIDINDEX32; + const auto foundPreset = AZStd::find(begin(m_presets), end(m_presets), preset); + return foundPreset != end(m_presets) ? AZStd::distance(begin(m_presets), foundPreset) : InvalidIndex; } void AnimGraphGameControllerSettings::SetActivePreset(Preset* preset) { - m_activePresetIndex = static_cast(FindPresetIndex(preset)); + m_activePresetIndex = FindPresetIndex(preset); } - uint32 AnimGraphGameControllerSettings::GetActivePresetIndex() const + size_t AnimGraphGameControllerSettings::GetActivePresetIndex() const { if (m_activePresetIndex < m_presets.size()) { return m_activePresetIndex; } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } @@ -384,6 +371,22 @@ namespace EMotionFX } + static bool AnimGraphGameControllerSettingsVersionConverter(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& element) + { + if (element.GetVersion() < 2) + { + constexpr AZStd::string_view activePresetIndex{"activePresetIndex"}; + if (AZ::SerializeContext::DataElementNode* presetIndexElement = element.FindSubElement(AZ::Crc32(activePresetIndex))) + { + uint32 value; + presetIndexElement->GetData(value); + presetIndexElement->Convert(context); + presetIndexElement->SetData(context, static_cast(value)); + } + } + return true; + } + void AnimGraphGameControllerSettings::Reflect(AZ::ReflectContext* context) { ParameterInfo::Reflect(context); @@ -398,7 +401,7 @@ namespace EMotionFX } serializeContext->Class() - ->Version(1) + ->Version(2, &AnimGraphGameControllerSettingsVersionConverter) ->Field("activePresetIndex", &AnimGraphGameControllerSettings::m_activePresetIndex) ->Field("presets", &AnimGraphGameControllerSettings::m_presets) ; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h index e00fef8601..c4e123c0c5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphGameControllerSettings.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include @@ -48,12 +48,11 @@ namespace EMotionFX struct EMFX_API ParameterInfo final { - AZ_RTTI(AnimGraphGameControllerSettings::ParameterInfo, "{C3220DB3-54FA-4719-80F0-CEAE5859C641}"); + AZ_TYPE_INFO(AnimGraphGameControllerSettings::ParameterInfo, "{C3220DB3-54FA-4719-80F0-CEAE5859C641}"); AZ_CLASS_ALLOCATOR_DECL ParameterInfo(); ParameterInfo(const char* parameterName); - virtual ~ParameterInfo() = default; static void Reflect(AZ::ReflectContext* context); @@ -66,12 +65,11 @@ namespace EMotionFX struct EMFX_API ButtonInfo final { - AZ_RTTI(AnimGraphGameControllerSettings::ButtonInfo, "{94027445-C44F-4310-9DF2-1A2F39518578}"); + AZ_TYPE_INFO(AnimGraphGameControllerSettings::ButtonInfo, "{94027445-C44F-4310-9DF2-1A2F39518578}"); AZ_CLASS_ALLOCATOR_DECL ButtonInfo(); ButtonInfo(AZ::u32 buttonIndex); - virtual ~ButtonInfo() = default; static void Reflect(AZ::ReflectContext* context); @@ -98,24 +96,24 @@ namespace EMotionFX /** * Check if the parameter with the given name is being controlled by the gamepad. - * This assumes that the mString member from the ButtonInfo contains the parameter name. - * @param[in] stringName The name to compare against the mString member of the button infos. + * This assumes that the m_string member from the ButtonInfo contains the parameter name. + * @param[in] stringName The name to compare against the m_string member of the button infos. * @result True in case a button info with the given string name doesn't have BUTTONMODE_NONE assigned, false in the other case. */ bool CheckIfIsParameterButtonControlled(const char* stringName); /** * Check if any of the button infos that are linked to the given string name is enabled. - * This assumes that the mString member from the ButtonInfo contains the parameter name. - * @param[in] stringName The name to compare against the mString member of the button infos. + * This assumes that the m_string member from the ButtonInfo contains the parameter name. + * @param[in] stringName The name to compare against the m_string member of the button infos. * @result True in case any of the button infos with the given string name is enabled. */ bool CheckIfIsButtonEnabled(const char* stringName); /** * Set all button infos that are linked to the given string name to the enabled flag. - * This assumes that the mString member from the ButtonInfo contains the parameter name. - * @param[in] stringName The name to compare against the mString member of the button infos. + * This assumes that the m_string member from the ButtonInfo contains the parameter name. + * @param[in] stringName The name to compare against the m_string member of the button infos. * @param[in] isEnabled True in case the button infos shall be enabled, false if they shall become disabled. */ void SetButtonEnabled(const char* stringName, bool isEnabled); @@ -155,7 +153,7 @@ namespace EMotionFX Preset* GetPreset(size_t index) const; size_t GetNumPresets() const; - uint32 GetActivePresetIndex() const; + size_t GetActivePresetIndex() const; Preset* GetActivePreset() const; void SetActivePreset(Preset* preset); @@ -166,6 +164,6 @@ namespace EMotionFX private: AZStd::vector m_presets; - AZ::u32 m_activePresetIndex; + AZ::u64 m_activePresetIndex; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphHubNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphHubNode.cpp index 7463b384f3..061593ecdc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphHubNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphHubNode.cpp @@ -119,7 +119,7 @@ namespace EMotionFX // Visualize the output pose. if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp index 46764744a8..d0c77721d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.cpp @@ -37,28 +37,26 @@ namespace EMotionFX animGraph->AddAnimGraphInstance(this); animGraph->Lock(); - mAnimGraph = animGraph; - mActorInstance = actorInstance; + m_animGraph = animGraph; + m_actorInstance = actorInstance; m_parentAnimGraphInstance = nullptr; - mMotionSet = motionSet; - mAutoUnregister = true; - mEnableVisualization = true; - mRetarget = animGraph->GetRetargetingEnabled(); - mVisualizeScale = 1.0f; + m_motionSet = motionSet; + m_autoUnregister = true; + m_enableVisualization = true; + m_retarget = animGraph->GetRetargetingEnabled(); + m_visualizeScale = 1.0f; m_autoReleaseAllPoses = true; m_autoReleaseAllRefDatas= true; #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = false; + m_isOwnedByRuntime = false; #endif // EMFX_DEVELOPMENT_BUILD if (initSettings) { - mInitSettings = *initSettings; + m_initSettings = *initSettings; } - mParamValues.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_INSTANCE); - mObjectFlags.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_INSTANCE); m_eventHandlersByEventType.resize(EVENT_TYPE_ANIM_GRAPH_INSTANCE_LAST_EVENT - EVENT_TYPE_ANIM_GRAPH_INSTANCE_FIRST_EVENT + 1); // init the internal attributes (create them) @@ -73,7 +71,7 @@ namespace EMotionFX // create the parameter value objects CreateParameterValues(); - mAnimGraph->Unlock(); + m_animGraph->Unlock(); GetEventManager().OnCreateAnimGraphInstance(this); } @@ -94,7 +92,7 @@ namespace EMotionFX GetEventManager().OnDeleteAnimGraphInstance(this); // automatically unregister the anim graph instance - if (mAutoUnregister) + if (m_autoUnregister) { GetAnimGraphManager().RemoveAnimGraphInstance(this, false); } @@ -129,7 +127,7 @@ namespace EMotionFX m_leaderGraphs.clear(); // unregister from the animgraph - mAnimGraph->RemoveAnimGraphInstance(this); + m_animGraph->RemoveAnimGraphInstance(this); } @@ -145,24 +143,23 @@ namespace EMotionFX { if (delFromMem) { - const uint32 numParams = mParamValues.GetLength(); - for (uint32 i = 0; i < numParams; ++i) + for (MCore::Attribute* paramValue : m_paramValues) { - if (mParamValues[i]) + if (paramValue) { - delete mParamValues[i]; + delete paramValue; } } } - mParamValues.Clear(); + m_paramValues.clear(); } // remove all internal attributes void AnimGraphInstance::RemoveAllInternalAttributes() { - MCore::LockGuard lock(mMutex); + MCore::LockGuard lock(m_mutex); for (MCore::Attribute* internalAttribute : m_internalAttributes) { @@ -174,12 +171,12 @@ namespace EMotionFX } - uint32 AnimGraphInstance::AddInternalAttribute(MCore::Attribute* attribute) + size_t AnimGraphInstance::AddInternalAttribute(MCore::Attribute* attribute) { - MCore::LockGuard lock(mMutex); + MCore::LockGuard lock(m_mutex); m_internalAttributes.emplace_back(attribute); - return static_cast(m_internalAttributes.size() - 1); + return m_internalAttributes.size() - 1; } @@ -197,14 +194,14 @@ namespace EMotionFX void AnimGraphInstance::ReserveInternalAttributes(size_t totalNumInternalAttributes) { - MCore::LockGuard lock(mMutex); + MCore::LockGuard lock(m_mutex); m_internalAttributes.reserve(totalNumInternalAttributes); } void AnimGraphInstance::RemoveInternalAttribute(size_t index, bool delFromMem) { - MCore::LockGuard lock(mMutex); + MCore::LockGuard lock(m_mutex); if (delFromMem) { MCore::Attribute* internalAttribute = m_internalAttributes[index]; @@ -222,7 +219,7 @@ namespace EMotionFX void AnimGraphInstance::Output(Pose* outputPose) { // reset max used - const uint32 threadIndex = mActorInstance->GetThreadIndex(); + const uint32 threadIndex = m_actorInstance->GetThreadIndex(); AnimGraphPosePool& posePool = GetEMotionFX().GetThreadData(threadIndex)->GetPosePool(); posePool.ResetMaxUsedPoses(); @@ -253,10 +250,10 @@ namespace EMotionFX } // Gather active state. Must be done in output function. - if (mSnapshot && mSnapshot->IsNetworkAuthoritative()) + if (m_snapshot && m_snapshot->IsNetworkAuthoritative()) { - mSnapshot->CollectActiveNodes(*this); - mSnapshot->CollectMotionNodePlaytimes(*this); + m_snapshot->CollectActiveNodes(*this); + m_snapshot->CollectMotionNodePlaytimes(*this); } } @@ -267,14 +264,14 @@ namespace EMotionFX { RemoveAllParameters(true); - const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - mParamValues.Resize(static_cast(valueParameters.size())); + const ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); + m_paramValues.resize(valueParameters.size()); // init the values - const uint32 numParams = mParamValues.GetLength(); - for (uint32 i = 0; i < numParams; ++i) + const size_t numParams = m_paramValues.size(); + for (size_t i = 0; i < numParams; ++i) { - mParamValues[i] = valueParameters[i]->ConstructDefaultValueAsAttribute(); + m_paramValues[i] = valueParameters[i]->ConstructDefaultValueAsAttribute(); } } @@ -283,58 +280,57 @@ namespace EMotionFX void AnimGraphInstance::AddMissingParameterValues() { // check how many parameters we need to add - const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); - const int32 numToAdd = static_cast(valueParameters.size()) - mParamValues.GetLength(); + const ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); + const ptrdiff_t numToAdd = aznumeric_cast(valueParameters.size()) - m_paramValues.size(); if (numToAdd <= 0) { return; } // make sure we have the right space pre-allocated - mParamValues.Reserve(static_cast(valueParameters.size())); + m_paramValues.reserve(valueParameters.size()); // add the remaining parameters - const uint32 startIndex = mParamValues.GetLength(); - for (int32 i = 0; i < numToAdd; ++i) + const size_t startIndex = m_paramValues.size(); + for (ptrdiff_t i = 0; i < numToAdd; ++i) { - const uint32 index = startIndex + i; - mParamValues.AddEmpty(); - mParamValues.GetLast() = valueParameters[index]->ConstructDefaultValueAsAttribute(); + const size_t index = startIndex + i; + m_paramValues.emplace_back(valueParameters[index]->ConstructDefaultValueAsAttribute()); } } // remove a parameter value - void AnimGraphInstance::RemoveParameterValue(uint32 index, bool delFromMem) + void AnimGraphInstance::RemoveParameterValue(size_t index, bool delFromMem) { if (delFromMem) { - if (mParamValues[index]) + if (m_paramValues[index]) { - delete mParamValues[index]; + delete m_paramValues[index]; } } - mParamValues.Remove(index); + m_paramValues.erase(AZStd::next(begin(m_paramValues), index)); } // reinitialize the parameter - void AnimGraphInstance::ReInitParameterValue(uint32 index) + void AnimGraphInstance::ReInitParameterValue(size_t index) { - if (mParamValues[index]) + if (m_paramValues[index]) { - delete mParamValues[index]; + delete m_paramValues[index]; } - mParamValues[index] = mAnimGraph->FindValueParameter(index)->ConstructDefaultValueAsAttribute(); + m_paramValues[index] = m_animGraph->FindValueParameter(index)->ConstructDefaultValueAsAttribute(); } void AnimGraphInstance::ReInitParameterValues() { - const AZ::u32 parameterValueCount = mParamValues.GetLength(); - for (AZ::u32 i = 0; i < parameterValueCount; ++i) + const size_t parameterValueCount = m_paramValues.size(); + for (size_t i = 0; i < parameterValueCount; ++i) { ReInitParameterValue(i); } @@ -345,7 +341,7 @@ namespace EMotionFX bool AnimGraphInstance::SwitchToState(const char* stateName) { // now try to find the state - AnimGraphNode* state = mAnimGraph->RecursiveFindNodeByName(stateName); + AnimGraphNode* state = m_animGraph->RecursiveFindNodeByName(stateName); if (state == nullptr) { return false; @@ -386,7 +382,7 @@ namespace EMotionFX bool AnimGraphInstance::TransitionToState(const char* stateName) { // now try to find the state - AnimGraphNode* state = mAnimGraph->RecursiveFindNodeByName(stateName); + AnimGraphNode* state = m_animGraph->RecursiveFindNodeByName(stateName); if (state == nullptr) { return false; @@ -442,8 +438,8 @@ namespace EMotionFX else { // get the number of child nodes, iterate through them and call the function recursively in case we are dealing with a blend tree or another node - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { RecursiveSwitchToEntryState(node->GetChildNode(i)); } @@ -472,8 +468,8 @@ namespace EMotionFX } // get the number of child nodes, iterate through them and call the function recursively - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { RecursiveResetCurrentState(node->GetChildNode(i)); } @@ -490,56 +486,56 @@ namespace EMotionFX // find the parameter value for a parameter with a given name MCore::Attribute* AnimGraphInstance::FindParameter(const AZStd::string& name) const { - const AZ::Outcome paramIndex = mAnimGraph->FindValueParameterIndexByName(name); + const AZ::Outcome paramIndex = m_animGraph->FindValueParameterIndexByName(name); if (!paramIndex.IsSuccess()) { return nullptr; } - return mParamValues[static_cast(paramIndex.GetValue())]; + return m_paramValues[paramIndex.GetValue()]; } // add the last anim graph parameter to this instance void AnimGraphInstance::AddParameterValue() { - mParamValues.Add(nullptr); - ReInitParameterValue(mParamValues.GetLength() - 1); + m_paramValues.emplace_back(nullptr); + ReInitParameterValue(m_paramValues.size() - 1); } // add the parameter of the animgraph, at a given index - void AnimGraphInstance::InsertParameterValue(uint32 index) + void AnimGraphInstance::InsertParameterValue(size_t index) { - mParamValues.Insert(index, nullptr); + m_paramValues.emplace(AZStd::next(begin(m_paramValues), index), nullptr); ReInitParameterValue(index); } // move the parameter from old index to new index - void AnimGraphInstance::MoveParameterValue(uint32 oldIndex, uint32 newIndex) + void AnimGraphInstance::MoveParameterValue(size_t oldIndex, size_t newIndex) { - MCore::Attribute* oldAttribute = mParamValues[oldIndex]; + MCore::Attribute* oldAttribute = m_paramValues[oldIndex]; // if old index is greater than new index, move elements between oldIndex and newIndex to the right of new index // otherwise, move to the left of new index if (oldIndex > newIndex) { - for (uint32 paramIndex = oldIndex; paramIndex > newIndex; paramIndex--) + for (size_t paramIndex = oldIndex; paramIndex > newIndex; paramIndex--) { - const uint32 prevIndex = paramIndex - 1; - mParamValues[paramIndex] = mParamValues[prevIndex]; + const size_t prevIndex = paramIndex - 1; + m_paramValues[paramIndex] = m_paramValues[prevIndex]; } - mParamValues[newIndex] = oldAttribute; + m_paramValues[newIndex] = oldAttribute; } else { - for (uint32 paramIndex = oldIndex; paramIndex < newIndex; paramIndex++) + for (size_t paramIndex = oldIndex; paramIndex < newIndex; paramIndex++) { - const uint32 nexIndex = paramIndex + 1; - mParamValues[paramIndex] = mParamValues[nexIndex]; + const size_t nexIndex = paramIndex + 1; + m_paramValues[paramIndex] = m_paramValues[nexIndex]; } - mParamValues[newIndex] = oldAttribute; + m_paramValues[newIndex] = oldAttribute; } } @@ -570,7 +566,7 @@ namespace EMotionFX void AnimGraphInstance::SetMotionSet(MotionSet* motionSet) { // update the local motion set pointer - mMotionSet = motionSet; + m_motionSet = motionSet; // get the number of state machines, iterate through them and recursively call the callback GetRootNode()->RecursiveOnChangeMotionSet(this, motionSet); @@ -580,20 +576,20 @@ namespace EMotionFX // adjust the auto unregistering from the anim graph manager on delete void AnimGraphInstance::SetAutoUnregisterEnabled(bool enabled) { - mAutoUnregister = enabled; + m_autoUnregister = enabled; } // do we auto unregister from the anim graph manager on delete? bool AnimGraphInstance::GetAutoUnregisterEnabled() const { - return mAutoUnregister; + return m_autoUnregister; } void AnimGraphInstance::SetIsOwnedByRuntime(bool isOwnedByRuntime) { #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = isOwnedByRuntime; + m_isOwnedByRuntime = isOwnedByRuntime; #else AZ_UNUSED(isOwnedByRuntime); #endif @@ -603,7 +599,7 @@ namespace EMotionFX bool AnimGraphInstance::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif @@ -611,17 +607,17 @@ namespace EMotionFX // find an actor instance based on a parent depth value - ActorInstance* AnimGraphInstance::FindActorInstanceFromParentDepth(uint32 parentDepth) const + ActorInstance* AnimGraphInstance::FindActorInstanceFromParentDepth(size_t parentDepth) const { // start with the actor instance this anim graph instance is working on - ActorInstance* curInstance = mActorInstance; + ActorInstance* curInstance = m_actorInstance; if (parentDepth == 0) { return curInstance; } // repeat until we are at the root - uint32 depth = 1; + size_t depth = 1; while (curInstance) { // get the attachment object @@ -658,7 +654,7 @@ namespace EMotionFX void AnimGraphInstance::AddUniqueObjectData() { m_uniqueDatas.emplace_back(nullptr); - mObjectFlags.Add(0); + m_objectFlags.emplace_back(0); } // remove the given unique data object @@ -669,14 +665,14 @@ namespace EMotionFX return; } - const uint32 index = uniqueData->GetObject()->GetObjectIndex(); + const size_t index = uniqueData->GetObject()->GetObjectIndex(); if (delFromMem && m_uniqueDatas[index]) { m_uniqueDatas[index]->Destroy(); } m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.Remove(index); + m_objectFlags.erase(AZStd::next(begin(m_objectFlags), index)); } @@ -684,7 +680,7 @@ namespace EMotionFX { AnimGraphObjectData* data = m_uniqueDatas[index]; m_uniqueDatas.erase(m_uniqueDatas.begin() + index); - mObjectFlags.Remove(static_cast(index)); + m_objectFlags.erase(AZStd::next(begin(m_objectFlags), index)); if (delFromMem && data) { data->Destroy(); @@ -707,7 +703,7 @@ namespace EMotionFX } m_uniqueDatas.clear(); - mObjectFlags.Clear(); + m_objectFlags.clear(); } @@ -811,13 +807,13 @@ namespace EMotionFX // init the hashmap void AnimGraphInstance::InitUniqueDatas() { - const uint32 numObjects = mAnimGraph->GetNumObjects(); + const size_t numObjects = m_animGraph->GetNumObjects(); m_uniqueDatas.resize(numObjects); - mObjectFlags.Resize(numObjects); - for (uint32 i = 0; i < numObjects; ++i) + m_objectFlags.resize(numObjects); + for (size_t i = 0; i < numObjects; ++i) { m_uniqueDatas[i] = nullptr; - mObjectFlags[i] = 0; + m_objectFlags[i] = 0; } } @@ -825,7 +821,7 @@ namespace EMotionFX // get the root node AnimGraphNode* AnimGraphInstance::GetRootNode() const { - return mAnimGraph->GetRootStateMachine(); + return m_animGraph->GetRootStateMachine(); } @@ -836,22 +832,22 @@ namespace EMotionFX Transform trajectoryDelta; // get the motion extraction node, and if it hasn't been set, we can already quit - Node* motionExtractNode = mActorInstance->GetActor()->GetMotionExtractionNode(); + Node* motionExtractNode = m_actorInstance->GetActor()->GetMotionExtractionNode(); if (motionExtractNode == nullptr) { trajectoryDelta.IdentityWithZeroScale(); - mActorInstance->SetTrajectoryDeltaTransform(trajectoryDelta); + m_actorInstance->SetTrajectoryDeltaTransform(trajectoryDelta); return; } // get the root node's trajectory delta - AnimGraphRefCountedData* rootData = mAnimGraph->GetRootStateMachine()->FindOrCreateUniqueNodeData(this)->GetRefCountedData(); + AnimGraphRefCountedData* rootData = m_animGraph->GetRootStateMachine()->FindOrCreateUniqueNodeData(this)->GetRefCountedData(); trajectoryDelta = rootData->GetTrajectoryDelta(); - trajectoryDelta.mRotation.Normalize(); + trajectoryDelta.m_rotation.Normalize(); // update the actor instance with the delta movement already - mActorInstance->SetTrajectoryDeltaTransform(trajectoryDelta); - mActorInstance->ApplyMotionExtractionDelta(); + m_actorInstance->SetTrajectoryDeltaTransform(trajectoryDelta); + m_actorInstance->ApplyMotionExtractionDelta(); } @@ -859,9 +855,9 @@ namespace EMotionFX void AnimGraphInstance::Update(float timePassedInSeconds) { // pass 0: (Optional, networking only) When this instance is shared between network, restore the instance using an animgraph snapshot. - if (mSnapshot) + if (m_snapshot) { - mSnapshot->Restore(*this); + m_snapshot->Restore(*this); } // pass 1: update (bottom up), update motion timers etc @@ -880,7 +876,7 @@ namespace EMotionFX } // reset all node pose ref counts - const uint32 threadIndex = mActorInstance->GetThreadIndex(); + const uint32 threadIndex = m_actorInstance->GetThreadIndex(); ResetPoseRefCountsForAllNodes(); ResetRefDataRefCountsForAllNodes(); GetEMotionFX().GetThreadData(threadIndex)->GetRefCountedDataPool().ResetMaxUsedItems(); @@ -905,7 +901,7 @@ namespace EMotionFX ApplyMotionExtraction(); // store a copy of the root's event buffer - mEventBuffer = rootNodeUniqueData->GetRefCountedData()->GetEventBuffer(); + m_eventBuffer = rootNodeUniqueData->GetRefCountedData()->GetEventBuffer(); // trigger the events inside the root node's buffer OutputEvents(); @@ -927,17 +923,16 @@ namespace EMotionFX // recursively reset flags void AnimGraphInstance::RecursiveResetFlags(uint32 flagsToDisable) { - mAnimGraph->GetRootStateMachine()->RecursiveResetFlags(this, flagsToDisable); + m_animGraph->GetRootStateMachine()->RecursiveResetFlags(this, flagsToDisable); } // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects(uint32 flagsToDisable) { - const uint32 numObjects = mObjectFlags.GetLength(); - for (uint32 i = 0; i < numObjects; ++i) + for (uint32& objectFlag : m_objectFlags) { - mObjectFlags[i] &= ~flagsToDisable; + objectFlag &= ~flagsToDisable; } } @@ -945,10 +940,10 @@ namespace EMotionFX // reset all node pose ref counts void AnimGraphInstance::ResetPoseRefCountsForAllNodes() { - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_animGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - mAnimGraph->GetNode(i)->ResetPoseRefCount(this); + m_animGraph->GetNode(i)->ResetPoseRefCount(this); } } @@ -956,10 +951,10 @@ namespace EMotionFX // reset all node pose ref counts void AnimGraphInstance::ResetRefDataRefCountsForAllNodes() { - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_animGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - mAnimGraph->GetNode(i)->ResetRefDataRefCount(this); + m_animGraph->GetNode(i)->ResetRefDataRefCount(this); } } @@ -967,7 +962,7 @@ namespace EMotionFX // reset all node flags void AnimGraphInstance::ResetFlagsForAllObjects() { - MCore::MemSet(mObjectFlags.GetPtr(), 0, sizeof(uint32) * mObjectFlags.GetLength()); + MCore::MemSet(m_objectFlags.data(), 0, sizeof(uint32) * m_objectFlags.size()); for (AnimGraphInstance* childInstance : m_childAnimGraphInstances) { @@ -979,17 +974,17 @@ namespace EMotionFX // reset flags for all nodes void AnimGraphInstance::ResetFlagsForAllNodes(uint32 flagsToDisable) { - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_animGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - AnimGraphNode* node = mAnimGraph->GetNode(i); - mObjectFlags[node->GetObjectIndex()] &= ~flagsToDisable; + AnimGraphNode* node = m_animGraph->GetNode(i); + m_objectFlags[node->GetObjectIndex()] &= ~flagsToDisable; if (GetEMotionFX().GetIsInEditorMode()) { // reset all connections - const uint32 numConnections = node->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = node->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { node->GetConnection(c)->SetIsVisited(false); } @@ -1014,19 +1009,19 @@ namespace EMotionFX void AnimGraphInstance::CollectActiveAnimGraphNodes(AZStd::vector* outNodes, const AZ::TypeId& nodeType) { outNodes->clear(); - mAnimGraph->GetRootStateMachine()->RecursiveCollectActiveNodes(this, outNodes, nodeType); + m_animGraph->GetRootStateMachine()->RecursiveCollectActiveNodes(this, outNodes, nodeType); } void AnimGraphInstance::CollectActiveNetTimeSyncNodes(AZStd::vector* outNodes) { outNodes->clear(); - mAnimGraph->GetRootStateMachine()->RecursiveCollectActiveNetTimeSyncNodes(this, outNodes); + m_animGraph->GetRootStateMachine()->RecursiveCollectActiveNetTimeSyncNodes(this, outNodes); } AnimGraphObjectData* AnimGraphInstance::FindOrCreateUniqueObjectData(const AnimGraphObject* object) { - const AZ::u32 objectIndex = object->GetObjectIndex(); + const size_t objectIndex = object->GetObjectIndex(); AnimGraphObjectData* uniqueData = m_uniqueDatas[objectIndex]; if (uniqueData) { @@ -1057,65 +1052,65 @@ namespace EMotionFX // find the parameter index AZ::Outcome AnimGraphInstance::FindParameterIndex(const AZStd::string& name) const { - return mAnimGraph->FindValueParameterIndexByName(name); + return m_animGraph->FindValueParameterIndexByName(name); } // init all internal attributes void AnimGraphInstance::InitInternalAttributes() { - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_animGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - mAnimGraph->GetNode(i)->InitInternalAttributes(this); + m_animGraph->GetNode(i)->InitInternalAttributes(this); } } void AnimGraphInstance::SetVisualizeScale(float scale) { - mVisualizeScale = scale; + m_visualizeScale = scale; } float AnimGraphInstance::GetVisualizeScale() const { - return mVisualizeScale; + return m_visualizeScale; } void AnimGraphInstance::SetVisualizationEnabled(bool enabled) { - mEnableVisualization = enabled; + m_enableVisualization = enabled; } bool AnimGraphInstance::GetVisualizationEnabled() const { - return mEnableVisualization; + return m_enableVisualization; } bool AnimGraphInstance::GetRetargetingEnabled() const { - return mRetarget; + return m_retarget; } void AnimGraphInstance::SetRetargetingEnabled(bool enabled) { - mRetarget = enabled; + m_retarget = enabled; } const AnimGraphInstance::InitSettings& AnimGraphInstance::GetInitSettings() const { - return mInitSettings; + return m_initSettings; } const AnimGraphEventBuffer& AnimGraphInstance::GetEventBuffer() const { - return mEventBuffer; + return m_eventBuffer; } @@ -1177,72 +1172,72 @@ namespace EMotionFX void AnimGraphInstance::CreateSnapshot(bool authoritative) { - if (mSnapshot) + if (m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot already created for this animgraph instance."); return; } - mSnapshot = AZStd::make_shared(*this, authoritative); + m_snapshot = AZStd::make_shared(*this, authoritative); } void AnimGraphInstance::SetSnapshotSerializer(AZStd::shared_ptr serializer) { - if (!mSnapshot) + if (!m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot should be created first."); return; } - mSnapshot->SetSnapshotSerializer(serializer); + m_snapshot->SetSnapshotSerializer(serializer); } void AnimGraphInstance::SetSnapshotChunkSerializer(AZStd::shared_ptr serializer) { - if (!mSnapshot) + if (!m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot should be created first."); return; } - mSnapshot->SetSnapshotChunkSerializer(serializer); + m_snapshot->SetSnapshotChunkSerializer(serializer); } void AnimGraphInstance::OnNetworkConnected() { - if (!mSnapshot) + if (!m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot should be created first."); return; } - mSnapshot->OnNetworkConnected(*this); + m_snapshot->OnNetworkConnected(*this); } void AnimGraphInstance::OnNetworkParamUpdate(const AttributeContainer& parameters) { - if (!mSnapshot) + if (!m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot should be created first."); return; } - mSnapshot->SetParameters(parameters); + m_snapshot->SetParameters(parameters); } void AnimGraphInstance::OnNetworkActiveNodesUpdate(const AZStd::vector& activeNodes) { - if (!mSnapshot) + if (!m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot should be created first."); return; } - mSnapshot->SetActiveNodes(activeNodes); + m_snapshot->SetActiveNodes(activeNodes); } void AnimGraphInstance::OnNetworkMotionNodePlaytimesUpdate(const MotionNodePlaytimeContainer& motionNodePlaytimes) { - if (!mSnapshot) + if (!m_snapshot) { AZ_Error("EMotionFX", false, "Snapshot should be created first."); return; } - mSnapshot->SetMotionNodePlaytimes(motionNodePlaytimes); + m_snapshot->SetMotionNodePlaytimes(motionNodePlaytimes); } void AnimGraphInstance::SetAutoReleaseRefDatas(bool automaticallyFreeRefDatas) @@ -1257,13 +1252,13 @@ namespace EMotionFX void AnimGraphInstance::ReleaseRefDatas() { - const uint32 threadIndex = mActorInstance->GetThreadIndex(); + const uint32 threadIndex = m_actorInstance->GetThreadIndex(); AnimGraphRefCountedDataPool& refDataPool = GetEMotionFX().GetThreadData(threadIndex)->GetRefCountedDataPool(); - const uint32 numNodes = mAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_animGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const AnimGraphNode* node = mAnimGraph->GetNode(i); + const AnimGraphNode* node = m_animGraph->GetNode(i); AnimGraphNodeData* nodeData = static_cast(m_uniqueDatas[node->GetObjectIndex()]); if (nodeData) { @@ -1294,7 +1289,7 @@ namespace EMotionFX } } - bool AnimGraphInstance::GetParameterValueAsFloat(uint32 paramIndex, float* outValue) + bool AnimGraphInstance::GetParameterValueAsFloat(size_t paramIndex, float* outValue) { MCore::AttributeFloat* floatAttribute = GetParameterValueChecked(paramIndex); if (floatAttribute) @@ -1320,7 +1315,7 @@ namespace EMotionFX return false; } - bool AnimGraphInstance::GetParameterValueAsBool(uint32 paramIndex, bool* outValue) + bool AnimGraphInstance::GetParameterValueAsBool(size_t paramIndex, bool* outValue) { float floatValue; if (GetParameterValueAsFloat(paramIndex, &floatValue)) @@ -1333,7 +1328,7 @@ namespace EMotionFX } - bool AnimGraphInstance::GetParameterValueAsInt(uint32 paramIndex, int32* outValue) + bool AnimGraphInstance::GetParameterValueAsInt(size_t paramIndex, int32* outValue) { float floatValue; if (GetParameterValueAsFloat(paramIndex, &floatValue)) @@ -1346,7 +1341,7 @@ namespace EMotionFX } - bool AnimGraphInstance::GetVector2ParameterValue(uint32 paramIndex, AZ::Vector2* outValue) + bool AnimGraphInstance::GetVector2ParameterValue(size_t paramIndex, AZ::Vector2* outValue) { MCore::AttributeVector2* param = GetParameterValueChecked(paramIndex); if (param) @@ -1359,7 +1354,7 @@ namespace EMotionFX } - bool AnimGraphInstance::GetVector3ParameterValue(uint32 paramIndex, AZ::Vector3* outValue) + bool AnimGraphInstance::GetVector3ParameterValue(size_t paramIndex, AZ::Vector3* outValue) { MCore::AttributeVector3* param = GetParameterValueChecked(paramIndex); if (param) @@ -1372,7 +1367,7 @@ namespace EMotionFX } - bool AnimGraphInstance::GetVector4ParameterValue(uint32 paramIndex, AZ::Vector4* outValue) + bool AnimGraphInstance::GetVector4ParameterValue(size_t paramIndex, AZ::Vector4* outValue) { MCore::AttributeVector4* param = GetParameterValueChecked(paramIndex); if (param) @@ -1385,7 +1380,7 @@ namespace EMotionFX } - bool AnimGraphInstance::GetRotationParameterValue(uint32 paramIndex, AZ::Quaternion* outRotation) + bool AnimGraphInstance::GetRotationParameterValue(size_t paramIndex, AZ::Quaternion* outRotation) { MCore::AttributeQuaternion* param = GetParameterValueChecked(paramIndex); if (param) @@ -1430,7 +1425,7 @@ namespace EMotionFX return false; } - return GetParameterValueAsFloat(static_cast(index.GetValue()), outValue); + return GetParameterValueAsFloat(index.GetValue(), outValue); } @@ -1442,7 +1437,7 @@ namespace EMotionFX return false; } - return GetParameterValueAsBool(static_cast(index.GetValue()), outValue); + return GetParameterValueAsBool(index.GetValue(), outValue); } @@ -1454,7 +1449,7 @@ namespace EMotionFX return false; } - return GetParameterValueAsInt(static_cast(index.GetValue()), outValue); + return GetParameterValueAsInt(index.GetValue(), outValue); } @@ -1466,7 +1461,7 @@ namespace EMotionFX return false; } - return GetVector2ParameterValue(static_cast(index.GetValue()), outValue); + return GetVector2ParameterValue(index.GetValue(), outValue); } @@ -1478,7 +1473,7 @@ namespace EMotionFX return false; } - return GetVector3ParameterValue(static_cast(index.GetValue()), outValue); + return GetVector3ParameterValue(index.GetValue(), outValue); } @@ -1490,7 +1485,7 @@ namespace EMotionFX return false; } - return GetVector4ParameterValue(static_cast(index.GetValue()), outValue); + return GetVector4ParameterValue(index.GetValue(), outValue); } @@ -1502,7 +1497,7 @@ namespace EMotionFX return false; } - return GetRotationParameterValue(static_cast(index.GetValue()), outRotation); + return GetRotationParameterValue(index.GetValue(), outRotation); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h index 97d076d244..81bae83515 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphInstance.h @@ -16,7 +16,7 @@ #include #include #include -#include +#include #include @@ -64,11 +64,11 @@ namespace EMotionFX struct EMFX_API InitSettings { - bool mPreInitMotionInstances; + bool m_preInitMotionInstances; InitSettings() { - mPreInitMotionInstances = false; + m_preInitMotionInstances = false; } }; @@ -79,9 +79,9 @@ namespace EMotionFX void Start(); void Stop(); - MCORE_INLINE ActorInstance* GetActorInstance() const { return mActorInstance; } - MCORE_INLINE AnimGraph* GetAnimGraph() const { return mAnimGraph; } - MCORE_INLINE MotionSet* GetMotionSet() const { return mMotionSet; } + MCORE_INLINE ActorInstance* GetActorInstance() const { return m_actorInstance; } + MCORE_INLINE AnimGraph* GetAnimGraph() const { return m_animGraph; } + MCORE_INLINE MotionSet* GetMotionSet() const { return m_motionSet; } void SetParentAnimGraphInstance(AnimGraphInstance* parentAnimGraphInstance); MCORE_INLINE AnimGraphInstance* GetParentAnimGraphInstance() const { return m_parentAnimGraphInstance; } @@ -95,30 +95,30 @@ namespace EMotionFX bool GetVector4ParameterValue(const char* paramName, AZ::Vector4* outValue); bool GetRotationParameterValue(const char* paramName, AZ::Quaternion* outRotation); - bool GetParameterValueAsFloat(uint32 paramIndex, float* outValue); - bool GetParameterValueAsBool(uint32 paramIndex, bool* outValue); - bool GetParameterValueAsInt(uint32 paramIndex, int32* outValue); - bool GetVector2ParameterValue(uint32 paramIndex, AZ::Vector2* outValue); - bool GetVector3ParameterValue(uint32 paramIndex, AZ::Vector3* outValue); - bool GetVector4ParameterValue(uint32 paramIndex, AZ::Vector4* outValue); - bool GetRotationParameterValue(uint32 paramIndex, AZ::Quaternion* outRotation); + bool GetParameterValueAsFloat(size_t paramIndex, float* outValue); + bool GetParameterValueAsBool(size_t paramIndex, bool* outValue); + bool GetParameterValueAsInt(size_t paramIndex, int32* outValue); + bool GetVector2ParameterValue(size_t paramIndex, AZ::Vector2* outValue); + bool GetVector3ParameterValue(size_t paramIndex, AZ::Vector3* outValue); + bool GetVector4ParameterValue(size_t paramIndex, AZ::Vector4* outValue); + bool GetRotationParameterValue(size_t paramIndex, AZ::Quaternion* outRotation); void SetMotionSet(MotionSet* motionSet); void CreateParameterValues(); void AddMissingParameterValues(); // add the missing parameters that the anim graph has to this anim graph instance - void ReInitParameterValue(uint32 index); + void ReInitParameterValue(size_t index); void ReInitParameterValues(); - void RemoveParameterValue(uint32 index, bool delFromMem = true); + void RemoveParameterValue(size_t index, bool delFromMem = true); void AddParameterValue(); // add the last anim graph parameter to this instance - void InsertParameterValue(uint32 index); // add the parameter of the animgraph, at a given index - void MoveParameterValue(uint32 oldIndex, uint32 newIndex); // move the parameter from old index to new index + void InsertParameterValue(size_t index); // add the parameter of the animgraph, at a given index + void MoveParameterValue(size_t oldIndex, size_t newIndex); // move the parameter from old index to new index void RemoveAllParameters(bool delFromMem); template - MCORE_INLINE T* GetParameterValueChecked(uint32 index) const + MCORE_INLINE T* GetParameterValueChecked(size_t index) const { - MCore::Attribute* baseAttrib = mParamValues[index]; + MCore::Attribute* baseAttrib = m_paramValues[index]; if (baseAttrib->GetType() == T::TYPE_ID) { return static_cast(baseAttrib); @@ -126,7 +126,7 @@ namespace EMotionFX return nullptr; } - MCORE_INLINE MCore::Attribute* GetParameterValue(uint32 index) const { return mParamValues[index]; } + MCORE_INLINE MCore::Attribute* GetParameterValue(size_t index) const { return m_paramValues[index]; } MCore::Attribute* FindParameter(const AZStd::string& name) const; AZ::Outcome FindParameterIndex(const AZStd::string& name) const; @@ -160,7 +160,7 @@ namespace EMotionFX void RemoveAllInternalAttributes(); void ReserveInternalAttributes(size_t totalNumInternalAttributes); void RemoveInternalAttribute(size_t index, bool delFromMem = true); // removes the internal attribute (does not update any indices of other attributes) - uint32 AddInternalAttribute(MCore::Attribute* attribute); // returns the index of the new added attribute + size_t AddInternalAttribute(MCore::Attribute* attribute); // returns the index of the new added attribute AnimGraphObjectData* FindOrCreateUniqueObjectData(const AnimGraphObject* object); AnimGraphNodeData* FindOrCreateUniqueNodeData(const AnimGraphNode* node); @@ -195,7 +195,7 @@ namespace EMotionFX void SetIsOwnedByRuntime(bool isOwnedByRuntime); bool GetIsOwnedByRuntime() const; - ActorInstance* FindActorInstanceFromParentDepth(uint32 parentDepth) const; + ActorInstance* FindActorInstanceFromParentDepth(size_t parentDepth) const; void SetVisualizeScale(float scale); float GetVisualizeScale() const; @@ -237,40 +237,40 @@ namespace EMotionFX void CollectActiveAnimGraphNodes(AZStd::vector* outNodes, const AZ::TypeId& nodeType = AZ::TypeId::CreateNull()); // MCORE_INVALIDINDEX32 means all node types void CollectActiveNetTimeSyncNodes(AZStd::vector* outNodes); - MCORE_INLINE uint32 GetObjectFlags(uint32 objectIndex) const { return mObjectFlags[objectIndex]; } - MCORE_INLINE void SetObjectFlags(uint32 objectIndex, uint32 flags) { mObjectFlags[objectIndex] = flags; } - MCORE_INLINE void EnableObjectFlags(uint32 objectIndex, uint32 flagsToEnable) { mObjectFlags[objectIndex] |= flagsToEnable; } - MCORE_INLINE void DisableObjectFlags(uint32 objectIndex, uint32 flagsToDisable) { mObjectFlags[objectIndex] &= ~flagsToDisable; } - MCORE_INLINE void SetObjectFlags(uint32 objectIndex, uint32 flags, bool enabled) + MCORE_INLINE uint32 GetObjectFlags(size_t objectIndex) const { return m_objectFlags[objectIndex]; } + MCORE_INLINE void SetObjectFlags(size_t objectIndex, uint32 flags) { m_objectFlags[objectIndex] = flags; } + MCORE_INLINE void EnableObjectFlags(size_t objectIndex, uint32 flagsToEnable) { m_objectFlags[objectIndex] |= flagsToEnable; } + MCORE_INLINE void DisableObjectFlags(size_t objectIndex, uint32 flagsToDisable) { m_objectFlags[objectIndex] &= ~flagsToDisable; } + MCORE_INLINE void SetObjectFlags(size_t objectIndex, uint32 flags, bool enabled) { if (enabled) { - mObjectFlags[objectIndex] |= flags; + m_objectFlags[objectIndex] |= flags; } else { - mObjectFlags[objectIndex] &= ~flags; + m_objectFlags[objectIndex] &= ~flags; } } - MCORE_INLINE bool GetIsObjectFlagEnabled(uint32 objectIndex, uint32 flag) const { return (mObjectFlags[objectIndex] & flag) != 0; } + MCORE_INLINE bool GetIsObjectFlagEnabled(size_t objectIndex, uint32 flag) const { return (m_objectFlags[objectIndex] & flag) != 0; } - MCORE_INLINE bool GetIsOutputReady(uint32 objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_OUTPUT_READY) != 0; } - MCORE_INLINE void SetIsOutputReady(uint32 objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_OUTPUT_READY, isReady); } + MCORE_INLINE bool GetIsOutputReady(size_t objectIndex) const { return (m_objectFlags[objectIndex] & OBJECTFLAGS_OUTPUT_READY) != 0; } + MCORE_INLINE void SetIsOutputReady(size_t objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_OUTPUT_READY, isReady); } - MCORE_INLINE bool GetIsSynced(uint32 objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_SYNCED) != 0; } - MCORE_INLINE void SetIsSynced(uint32 objectIndex, bool isSynced) { SetObjectFlags(objectIndex, OBJECTFLAGS_SYNCED, isSynced); } + MCORE_INLINE bool GetIsSynced(size_t objectIndex) const { return (m_objectFlags[objectIndex] & OBJECTFLAGS_SYNCED) != 0; } + MCORE_INLINE void SetIsSynced(size_t objectIndex, bool isSynced) { SetObjectFlags(objectIndex, OBJECTFLAGS_SYNCED, isSynced); } - MCORE_INLINE bool GetIsResynced(uint32 objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_RESYNC) != 0; } - MCORE_INLINE void SetIsResynced(uint32 objectIndex, bool isResynced) { SetObjectFlags(objectIndex, OBJECTFLAGS_RESYNC, isResynced); } + MCORE_INLINE bool GetIsResynced(size_t objectIndex) const { return (m_objectFlags[objectIndex] & OBJECTFLAGS_RESYNC) != 0; } + MCORE_INLINE void SetIsResynced(size_t objectIndex, bool isResynced) { SetObjectFlags(objectIndex, OBJECTFLAGS_RESYNC, isResynced); } - MCORE_INLINE bool GetIsUpdateReady(uint32 objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_UPDATE_READY) != 0; } - MCORE_INLINE void SetIsUpdateReady(uint32 objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_UPDATE_READY, isReady); } + MCORE_INLINE bool GetIsUpdateReady(size_t objectIndex) const { return (m_objectFlags[objectIndex] & OBJECTFLAGS_UPDATE_READY) != 0; } + MCORE_INLINE void SetIsUpdateReady(size_t objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_UPDATE_READY, isReady); } - MCORE_INLINE bool GetIsTopDownUpdateReady(uint32 objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_TOPDOWNUPDATE_READY) != 0; } - MCORE_INLINE void SetIsTopDownUpdateReady(uint32 objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_TOPDOWNUPDATE_READY, isReady); } + MCORE_INLINE bool GetIsTopDownUpdateReady(size_t objectIndex) const { return (m_objectFlags[objectIndex] & OBJECTFLAGS_TOPDOWNUPDATE_READY) != 0; } + MCORE_INLINE void SetIsTopDownUpdateReady(size_t objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_TOPDOWNUPDATE_READY, isReady); } - MCORE_INLINE bool GetIsPostUpdateReady(uint32 objectIndex) const { return (mObjectFlags[objectIndex] & OBJECTFLAGS_POSTUPDATE_READY) != 0; } - MCORE_INLINE void SetIsPostUpdateReady(uint32 objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_POSTUPDATE_READY, isReady); } + MCORE_INLINE bool GetIsPostUpdateReady(size_t objectIndex) const { return (m_objectFlags[objectIndex] & OBJECTFLAGS_POSTUPDATE_READY) != 0; } + MCORE_INLINE void SetIsPostUpdateReady(size_t objectIndex, bool isReady) { SetObjectFlags(objectIndex, OBJECTFLAGS_POSTUPDATE_READY, isReady); } const InitSettings& GetInitSettings() const; const AnimGraphEventBuffer& GetEventBuffer() const; @@ -283,9 +283,9 @@ namespace EMotionFX void CreateSnapshot(bool authoritative); void SetSnapshotSerializer(AZStd::shared_ptr serializer); void SetSnapshotChunkSerializer(AZStd::shared_ptr serializer); - const AZStd::shared_ptr GetSnapshot() const { return mSnapshot; } + const AZStd::shared_ptr GetSnapshot() const { return m_snapshot; } bool IsNetworkEnabled() const { return GetSnapshot(); } - MCore::LcgRandom& GetLcgRandom() { return mLcgRandom; } + MCore::LcgRandom& GetLcgRandom() { return m_lcgRandom; } void OnNetworkConnected(); void OnNetworkParamUpdate(const AttributeContainer& parameters); @@ -298,24 +298,24 @@ namespace EMotionFX void ReleasePoses(); private: - AnimGraph* mAnimGraph; - ActorInstance* mActorInstance; + AnimGraph* m_animGraph; + ActorInstance* m_actorInstance; AnimGraphInstance* m_parentAnimGraphInstance; // If this anim graph instance is in a reference node, it will have a parent anim graph instance. AZStd::vector m_childAnimGraphInstances; // If this anim graph instance contains reference nodes, the anim graph instances will be listed here. - MCore::Array mParamValues; // a value for each AnimGraph parameter (the control parameters) + AZStd::vector m_paramValues; // a value for each AnimGraph parameter (the control parameters) AZStd::vector m_uniqueDatas; // unique object data - MCore::Array mObjectFlags; // the object flags + AZStd::vector m_objectFlags; // the object flags using EventHandlerVector = AZStd::vector; AZStd::vector m_eventHandlersByEventType; /**< The event handler to use to process events organized by EventTypes. */ AZStd::vector m_internalAttributes; - MotionSet* mMotionSet; // the used motion set - MCore::Mutex mMutex; - InitSettings mInitSettings; - AnimGraphEventBuffer mEventBuffer; /**< The event buffer of the last update. */ - float mVisualizeScale; - bool mAutoUnregister; /**< Specifies whether we will automatically unregister this anim graph instance set from the anim graph manager or not, when deleting this object. */ - bool mEnableVisualization; - bool mRetarget; /**< Is retargeting enabled? */ + MotionSet* m_motionSet; // the used motion set + MCore::Mutex m_mutex; + InitSettings m_initSettings; + AnimGraphEventBuffer m_eventBuffer; /**< The event buffer of the last update. */ + float m_visualizeScale; + bool m_autoUnregister; /**< Specifies whether we will automatically unregister this anim graph instance set from the anim graph manager or not, when deleting this object. */ + bool m_enableVisualization; + bool m_retarget; /**< Is retargeting enabled? */ bool m_autoReleaseAllPoses; bool m_autoReleaseAllRefDatas; @@ -324,11 +324,11 @@ namespace EMotionFX AZStd::vector m_leaderGraphs; // Network related members - AZStd::shared_ptr mSnapshot; - MCore::LcgRandom mLcgRandom; + AZStd::shared_ptr m_snapshot; + MCore::LcgRandom m_lcgRandom; #if defined(EMFX_DEVELOPMENT_BUILD) - bool mIsOwnedByRuntime; + bool m_isOwnedByRuntime; #endif // EMFX_DEVELOPMENT_BUILD AnimGraphInstance(AnimGraph* animGraph, ActorInstance* actorInstance, MotionSet* motionSet, const InitSettings* initSettings = nullptr); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp index 8e25f6f0a8..069bb4b57a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.cpp @@ -28,16 +28,16 @@ namespace EMotionFX AnimGraphManager::AnimGraphManager() : BaseObject() - , mBlendSpaceManager(nullptr) + , m_blendSpaceManager(nullptr) { } AnimGraphManager::~AnimGraphManager() { - if (mBlendSpaceManager) + if (m_blendSpaceManager) { - mBlendSpaceManager->Destroy(); + m_blendSpaceManager->Destroy(); } // delete the anim graph instances and anim graphs //RemoveAllAnimGraphInstances(true); @@ -53,10 +53,10 @@ namespace EMotionFX void AnimGraphManager::Init() { - mAnimGraphInstances.reserve(1024); - mAnimGraphs.reserve(128); + m_animGraphInstances.reserve(1024); + m_animGraphs.reserve(128); - mBlendSpaceManager = aznew BlendSpaceManager(); + m_blendSpaceManager = aznew BlendSpaceManager(); // register custom attribute types MCore::GetAttributeFactory().RegisterAttribute(aznew AttributePose()); @@ -66,51 +66,51 @@ namespace EMotionFX void AnimGraphManager::RemoveAllAnimGraphs(bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); - while (!mAnimGraphs.empty()) + while (!m_animGraphs.empty()) { - RemoveAnimGraph(mAnimGraphs.size() - 1, delFromMemory); + RemoveAnimGraph(m_animGraphs.size() - 1, delFromMemory); } } void AnimGraphManager::RemoveAllAnimGraphInstances(bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); - while (!mAnimGraphInstances.empty()) + while (!m_animGraphInstances.empty()) { - RemoveAnimGraphInstance(mAnimGraphInstances.size() - 1, delFromMemory); + RemoveAnimGraphInstance(m_animGraphInstances.size() - 1, delFromMemory); } } void AnimGraphManager::AddAnimGraph(AnimGraph* setup) { - MCore::LockGuardRecursive lock(mAnimGraphLock); - mAnimGraphs.push_back(setup); + MCore::LockGuardRecursive lock(m_animGraphLock); + m_animGraphs.push_back(setup); } // Remove a given anim graph by index. void AnimGraphManager::RemoveAnimGraph(size_t index, bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); - AnimGraph* animGraph = mAnimGraphs[index]; - const int animGraphInstanceCount = static_cast(mAnimGraphInstances.size()); + AnimGraph* animGraph = m_animGraphs[index]; + const int animGraphInstanceCount = static_cast(m_animGraphInstances.size()); for (int i = animGraphInstanceCount - 1; i >= 0; --i) { - if (mAnimGraphInstances[i]->GetAnimGraph() == animGraph) + if (m_animGraphInstances[i]->GetAnimGraph() == animGraph) { - RemoveAnimGraphInstance(mAnimGraphInstances[i]); + RemoveAnimGraphInstance(m_animGraphInstances[i]); } } // Need to remove it from the list of anim graphs first since deleting it can cause assets to get unloaded and // this function to be called recursively (making the index to shift) - mAnimGraphs.erase(mAnimGraphs.begin() + index); + m_animGraphs.erase(m_animGraphs.begin() + index); if (delFromMemory) { @@ -125,11 +125,11 @@ namespace EMotionFX // Remove a given anim graph by pointer. bool AnimGraphManager::RemoveAnimGraph(AnimGraph* animGraph, bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); // find the index of the anim graph and return false in case the pointer is not valid - const uint32 animGraphIndex = FindAnimGraphIndex(animGraph); - if (animGraphIndex == MCORE_INVALIDINDEX32) + const size_t animGraphIndex = FindAnimGraphIndex(animGraph); + if (animGraphIndex == InvalidIndex) { return false; } @@ -141,23 +141,23 @@ namespace EMotionFX void AnimGraphManager::AddAnimGraphInstance(AnimGraphInstance* animGraphInstance) { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); - mAnimGraphInstances.push_back(animGraphInstance); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); + m_animGraphInstances.push_back(animGraphInstance); } void AnimGraphManager::RemoveAnimGraphInstance(size_t index, bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); if (delFromMemory) { - AnimGraphInstance* animGraphInstance = mAnimGraphInstances[index]; + AnimGraphInstance* animGraphInstance = m_animGraphInstances[index]; animGraphInstance->RemoveAllObjectData(true); // Remove all links to the anim graph instance that will get removed. - const uint32 numActorInstances = GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { ActorInstance* actorInstance = GetActorManager().GetActorInstance(i); if (animGraphInstance == actorInstance->GetAnimGraphInstance()) @@ -172,18 +172,18 @@ namespace EMotionFX animGraphInstance->Destroy(); } - mAnimGraphInstances.erase(mAnimGraphInstances.begin() + index); + m_animGraphInstances.erase(m_animGraphInstances.begin() + index); } // remove a given anim graph instance by pointer bool AnimGraphManager::RemoveAnimGraphInstance(AnimGraphInstance* animGraphInstance, bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); // find the index of the anim graph instance and return false in case the pointer is not valid - const uint32 instanceIndex = FindAnimGraphInstanceIndex(animGraphInstance); - if (instanceIndex == MCORE_INVALIDINDEX32) + const size_t instanceIndex = FindAnimGraphInstanceIndex(animGraphInstance); + if (instanceIndex == InvalidIndex) { return false; } @@ -196,20 +196,20 @@ namespace EMotionFX void AnimGraphManager::RemoveAnimGraphInstances(AnimGraph* animGraph, bool delFromMemory) { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); - if (mAnimGraphInstances.empty()) + if (m_animGraphInstances.empty()) { return; } // Remove anim graph instances back to front in case they are linked to the given anim graph. - const size_t numInstances = mAnimGraphInstances.size(); + const size_t numInstances = m_animGraphInstances.size(); for (size_t i = 0; i < numInstances; ++i) { const size_t reverseIndex = numInstances - 1 - i; - AnimGraphInstance* instance = mAnimGraphInstances[reverseIndex]; + AnimGraphInstance* instance = m_animGraphInstances[reverseIndex]; if (instance->GetAnimGraph() == animGraph) { RemoveAnimGraphInstance(reverseIndex, delFromMemory); @@ -218,42 +218,42 @@ namespace EMotionFX } - uint32 AnimGraphManager::FindAnimGraphIndex(AnimGraph* animGraph) const + size_t AnimGraphManager::FindAnimGraphIndex(AnimGraph* animGraph) const { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); - auto iterator = AZStd::find(mAnimGraphs.begin(), mAnimGraphs.end(), animGraph); - if (iterator == mAnimGraphs.end()) + auto iterator = AZStd::find(m_animGraphs.begin(), m_animGraphs.end(), animGraph); + if (iterator == m_animGraphs.end()) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - const size_t index = iterator - mAnimGraphs.begin(); - return static_cast(index); + const size_t index = iterator - m_animGraphs.begin(); + return index; } - uint32 AnimGraphManager::FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const + size_t AnimGraphManager::FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); - auto iterator = AZStd::find(mAnimGraphInstances.begin(), mAnimGraphInstances.end(), animGraphInstance); - if (iterator == mAnimGraphInstances.end()) + auto iterator = AZStd::find(m_animGraphInstances.begin(), m_animGraphInstances.end(), animGraphInstance); + if (iterator == m_animGraphInstances.end()) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - const size_t index = iterator - mAnimGraphInstances.begin(); - return static_cast(index); + const size_t index = iterator - m_animGraphInstances.begin(); + return index; } // find a anim graph with a given filename AnimGraph* AnimGraphManager::FindAnimGraphByFileName(const char* filename, bool isTool) const { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); - for (EMotionFX::AnimGraph* animGraph : mAnimGraphs) + for (EMotionFX::AnimGraph* animGraph : m_animGraphs) { if (animGraph->GetIsOwnedByRuntime() == isTool) { @@ -273,9 +273,9 @@ namespace EMotionFX // Find anim graph with a given id. AnimGraph* AnimGraphManager::FindAnimGraphByID(uint32 animGraphID) const { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); - for (EMotionFX::AnimGraph* animGraph : mAnimGraphs) + for (EMotionFX::AnimGraph* animGraph : m_animGraphs) { if (animGraph->GetID() == animGraphID) { @@ -290,11 +290,11 @@ namespace EMotionFX // Find the first available anim graph AnimGraph* AnimGraphManager::GetFirstAnimGraph() const { - MCore::LockGuardRecursive lock(mAnimGraphLock); + MCore::LockGuardRecursive lock(m_animGraphLock); - if (mAnimGraphs.size() > 0) + if (m_animGraphs.size() > 0) { - return mAnimGraphs[0]; + return m_animGraphs[0]; } return nullptr; } @@ -302,10 +302,10 @@ namespace EMotionFX void AnimGraphManager::SetAnimGraphVisualizationEnabled(bool enabled) { - MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); + MCore::LockGuardRecursive lock(m_animGraphInstanceLock); // Enable or disable anim graph visualization for all anim graph instances.. - for (AnimGraphInstance* animGraphInstance : mAnimGraphInstances) + for (AnimGraphInstance* animGraphInstance : m_animGraphInstances) { animGraphInstance->SetVisualizationEnabled(enabled); } @@ -314,7 +314,7 @@ namespace EMotionFX void AnimGraphManager::RecursiveCollectObjectsAffectedBy(AnimGraph* animGraph, AZStd::vector& affectedObjects) { - for (EMotionFX::AnimGraph* potentiallyAffected : mAnimGraphs) + for (EMotionFX::AnimGraph* potentiallyAffected : m_animGraphs) { if (potentiallyAffected != animGraph) // exclude the passed one since that will always be affected { @@ -326,7 +326,7 @@ namespace EMotionFX void AnimGraphManager::InvalidateInstanceUniqueDataUsingMotionSet(EMotionFX::MotionSet* motionSet) { // Update unique datas for all anim graph instances that use the given motion set. - for (EMotionFX::AnimGraphInstance* animGraphInstance : mAnimGraphInstances) + for (EMotionFX::AnimGraphInstance* animGraphInstance : m_animGraphInstances) { if (animGraphInstance->GetMotionSet() == motionSet) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h index 9f04517982..acff1779bb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphManager.h @@ -11,7 +11,7 @@ #include "EMotionFXConfig.h" #include #include "BaseObject.h" -#include +#include #include "AnimGraphObject.h" #include @@ -40,7 +40,7 @@ namespace EMotionFX void Init(); - MCORE_INLINE BlendSpaceManager* GetBlendSpaceManager() const { return mBlendSpaceManager; } + MCORE_INLINE BlendSpaceManager* GetBlendSpaceManager() const { return m_blendSpaceManager; } // anim graph helper functions void AddAnimGraph(AnimGraph* setup); @@ -48,11 +48,11 @@ namespace EMotionFX bool RemoveAnimGraph(AnimGraph* animGraph, bool delFromMemory = true); void RemoveAllAnimGraphs(bool delFromMemory = true); - MCORE_INLINE uint32 GetNumAnimGraphs() const { MCore::LockGuardRecursive lock(mAnimGraphLock); return static_cast(mAnimGraphs.size()); } - MCORE_INLINE AnimGraph* GetAnimGraph(uint32 index) const { MCore::LockGuardRecursive lock(mAnimGraphLock); return mAnimGraphs[index]; } + MCORE_INLINE size_t GetNumAnimGraphs() const { MCore::LockGuardRecursive lock(m_animGraphLock); return m_animGraphs.size(); } + MCORE_INLINE AnimGraph* GetAnimGraph(size_t index) const { MCore::LockGuardRecursive lock(m_animGraphLock); return m_animGraphs[index]; } AnimGraph* GetFirstAnimGraph() const; - uint32 FindAnimGraphIndex(AnimGraph* animGraph) const; + size_t FindAnimGraphIndex(AnimGraph* animGraph) const; AnimGraph* FindAnimGraphByFileName(const char* filename, bool isTool = true) const; AnimGraph* FindAnimGraphByID(uint32 animGraphID) const; @@ -64,21 +64,21 @@ namespace EMotionFX void RemoveAllAnimGraphInstances(bool delFromMemory = true); void InvalidateInstanceUniqueDataUsingMotionSet(EMotionFX::MotionSet* motionSet); - size_t GetNumAnimGraphInstances() const { MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); return mAnimGraphInstances.size(); } - AnimGraphInstance* GetAnimGraphInstance(size_t index) const { MCore::LockGuardRecursive lock(mAnimGraphInstanceLock); return mAnimGraphInstances[index]; } + size_t GetNumAnimGraphInstances() const { MCore::LockGuardRecursive lock(m_animGraphInstanceLock); return m_animGraphInstances.size(); } + AnimGraphInstance* GetAnimGraphInstance(size_t index) const { MCore::LockGuardRecursive lock(m_animGraphInstanceLock); return m_animGraphInstances[index]; } - uint32 FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const; + size_t FindAnimGraphInstanceIndex(AnimGraphInstance* animGraphInstance) const; void SetAnimGraphVisualizationEnabled(bool enabled); void RecursiveCollectObjectsAffectedBy(AnimGraph* animGraph, AZStd::vector& affectedObjects); private: - AZStd::vector mAnimGraphs; - AZStd::vector mAnimGraphInstances; - BlendSpaceManager* mBlendSpaceManager; - mutable MCore::MutexRecursive mAnimGraphLock; - mutable MCore::MutexRecursive mAnimGraphInstanceLock; + AZStd::vector m_animGraphs; + AZStd::vector m_animGraphInstances; + BlendSpaceManager* m_blendSpaceManager; + mutable MCore::MutexRecursive m_animGraphLock; + mutable MCore::MutexRecursive m_animGraphInstanceLock; // constructor and destructor AnimGraphManager(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp index 425b48ce2e..02865b044c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.cpp @@ -67,7 +67,7 @@ namespace EMotionFX return; } - AnimGraphNode* node = mAnimGraph->RecursiveFindNodeById(m_motionNodeId); + AnimGraphNode* node = m_animGraph->RecursiveFindNodeById(m_motionNodeId); m_motionNode = azdynamic_cast(node); } @@ -145,9 +145,9 @@ namespace EMotionFX } // Update the unique data. - if (uniqueData->mMotionInstance != motionInstance) + if (uniqueData->m_motionInstance != motionInstance) { - uniqueData->mMotionInstance = motionInstance; + uniqueData->m_motionInstance = motionInstance; } // Process the condition depending on the function used. @@ -156,13 +156,13 @@ namespace EMotionFX case FUNCTION_EVENT: { const EMotionFX::AnimGraphEventBuffer& eventBuffer = animGraphInstance->GetEventBuffer(); - const uint32 numEvents = eventBuffer.GetNumEvents(); + const size_t numEvents = eventBuffer.GetNumEvents(); // Check if the triggered motion event is of the given type and parameter from the motion condition. - for (uint32 i = 0; i < numEvents; ++i) + for (size_t i = 0; i < numEvents; ++i) { const EMotionFX::EventInfo& eventInfo = eventBuffer.GetEvent(i); - const EventDataSet& eventDatas = eventInfo.mEvent->GetEventDatas(); + const EventDataSet& eventDatas = eventInfo.m_event->GetEventDatas(); size_t matches = 0; for (const EventDataPtr& checkAgainstData : m_eventDatas) @@ -314,7 +314,7 @@ namespace EMotionFX void AnimGraphMotionCondition::SetMotionNodeId(AnimGraphNodeId motionNodeId) { m_motionNodeId = motionNodeId; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -403,7 +403,7 @@ namespace EMotionFX AnimGraphMotionCondition::UniqueData::UniqueData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance, MotionInstance* motionInstance) : AnimGraphObjectData(object, animGraphInstance) { - mMotionInstance = motionInstance; + m_motionInstance = motionInstance; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.h index 3a4e1f9bc7..14e5221aec 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionCondition.h @@ -60,7 +60,7 @@ namespace EMotionFX ~UniqueData() = default; public: - MotionInstance* mMotionInstance = nullptr; + MotionInstance* m_motionInstance = nullptr; }; AnimGraphMotionCondition(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.cpp index ea3784b11c..6bcc69360b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.cpp @@ -99,7 +99,7 @@ namespace EMotionFX bool AnimGraphMotionNode::GetIsInPlace(AnimGraphInstance* animGraphInstance) const { - EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).mConnection; + EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).m_connection; if (inPlaceConnection) { return GetInputNumberAsBool(animGraphInstance, INPUTPORT_INPLACE); @@ -110,7 +110,7 @@ namespace EMotionFX void AnimGraphMotionNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); RequestRefDatas(animGraphInstance); @@ -121,8 +121,8 @@ namespace EMotionFX } // update the input nodes - EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).mConnection; - if (playSpeedConnection && mDisabled == false) + EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).m_connection; + if (playSpeedConnection && m_disabled == false) { playSpeedConnection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); } @@ -135,8 +135,8 @@ namespace EMotionFX data->ZeroTrajectoryDelta(); // trigger the motion update - MotionInstance* motionInstance = uniqueData->mMotionInstance; - if (motionInstance && !animGraphInstance->GetIsResynced(mObjectIndex)) + MotionInstance* motionInstance = uniqueData->m_motionInstance; + if (motionInstance && !animGraphInstance->GetIsResynced(m_objectIndex)) { // update the time values and extract events into the event buffer motionInstance->SetWeight(uniqueData->GetLocalWeight()); @@ -176,9 +176,9 @@ namespace EMotionFX if (numMotions > 1) { // check if we reached the end of the motion, if so, pick a new one - if (uniqueData->mMotionInstance) + if (uniqueData->m_motionInstance) { - if (uniqueData->mMotionInstance->GetHasLooped() && m_nextMotionAfterLoop) + if (uniqueData->m_motionInstance->GetHasLooped() && m_nextMotionAfterLoop) { PickNewActiveMotion(animGraphInstance, uniqueData); } @@ -188,9 +188,9 @@ namespace EMotionFX // rewind when the weight reaches 0 when we want to if (!m_loop) { - if (uniqueData->mMotionInstance && uniqueData->GetLocalWeight() < MCore::Math::epsilon && m_rewindOnZeroWeight) + if (uniqueData->m_motionInstance && uniqueData->GetLocalWeight() < MCore::Math::epsilon && m_rewindOnZeroWeight) { - uniqueData->mMotionInstance->SetCurrentTime(0.0f); + uniqueData->m_motionInstance->SetCurrentTime(0.0f); uniqueData->SetCurrentPlayTime(0.0f); uniqueData->SetPreSyncTime(0.0f); } @@ -200,7 +200,7 @@ namespace EMotionFX HierarchicalSyncAllInputNodes(animGraphInstance, uniqueData); // top down update all incoming connections - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->GetSourceNode()->PerformTopDownUpdate(animGraphInstance, timePassedInSeconds); } @@ -211,25 +211,25 @@ namespace EMotionFX void AnimGraphMotionNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // update the input nodes - EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).mConnection; - if (playSpeedConnection && mDisabled == false) + EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).m_connection; + if (playSpeedConnection && m_disabled == false) { UpdateIncomingNode(animGraphInstance, playSpeedConnection->GetSourceNode(), timePassedInSeconds); } - if (!mDisabled) + if (!m_disabled) { UpdateIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_INPLACE), timePassedInSeconds); } // update the motion instance (current time etc) UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - MotionInstance* motionInstance = uniqueData->mMotionInstance; - if (motionInstance == nullptr || mDisabled) + MotionInstance* motionInstance = uniqueData->m_motionInstance; + if (motionInstance == nullptr || m_disabled) { if (GetEMotionFX().GetIsInEditorMode()) { - if (mDisabled == false) + if (m_disabled == false) { if (motionInstance == nullptr) { @@ -256,17 +256,17 @@ namespace EMotionFX uniqueData->SetPreSyncTime(motionInstance->GetCurrentTime()); // Make sure we use the correct play properties. - motionInstance->SetPlayMode(m_playInfo.mPlayMode); - motionInstance->SetRetargetingEnabled(m_playInfo.mRetarget && animGraphInstance->GetRetargetingEnabled()); - motionInstance->SetMotionEventsEnabled(m_playInfo.mEnableMotionEvents); - motionInstance->SetMirrorMotion(m_playInfo.mMirrorMotion); - motionInstance->SetEventWeightThreshold(m_playInfo.mEventWeightThreshold); - motionInstance->SetMaxLoops(m_playInfo.mNumLoops); - motionInstance->SetMotionExtractionEnabled(m_playInfo.mMotionExtractionEnabled); + motionInstance->SetPlayMode(m_playInfo.m_playMode); + motionInstance->SetRetargetingEnabled(m_playInfo.m_retarget && animGraphInstance->GetRetargetingEnabled()); + motionInstance->SetMotionEventsEnabled(m_playInfo.m_enableMotionEvents); + motionInstance->SetMirrorMotion(m_playInfo.m_mirrorMotion); + motionInstance->SetEventWeightThreshold(m_playInfo.m_eventWeightThreshold); + motionInstance->SetMaxLoops(m_playInfo.m_numLoops); + motionInstance->SetMotionExtractionEnabled(m_playInfo.m_motionExtractionEnabled); motionInstance->SetIsInPlace(GetIsInPlace(animGraphInstance)); - motionInstance->SetFreezeAtLastFrame(m_playInfo.mFreezeAtLastFrame); + motionInstance->SetFreezeAtLastFrame(m_playInfo.m_freezeAtLastFrame); - if (!animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) || animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_IS_SYNCLEADER)) + if (!animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) || animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_IS_SYNCLEADER)) { // See where we would end up when we would forward in time. const MotionInstance::PlayStateOut newPlayState = motionInstance->CalcPlayStateAfterUpdate(timePassedInSeconds); @@ -296,15 +296,15 @@ namespace EMotionFX void AnimGraphMotionNode::UpdatePlayBackInfo(AnimGraphInstance* animGraphInstance) { - m_playInfo.mPlayMode = (m_reverse) ? PLAYMODE_BACKWARD : PLAYMODE_FORWARD; - m_playInfo.mNumLoops = (m_loop) ? EMFX_LOOPFOREVER : 1; - m_playInfo.mFreezeAtLastFrame = true; - m_playInfo.mEnableMotionEvents = m_emitEvents; - m_playInfo.mMirrorMotion = m_mirrorMotion; - m_playInfo.mPlaySpeed = ExtractCustomPlaySpeed(animGraphInstance); - m_playInfo.mMotionExtractionEnabled = m_motionExtraction; - m_playInfo.mRetarget = m_retarget; - m_playInfo.mInPlace = GetIsInPlace(animGraphInstance); + m_playInfo.m_playMode = (m_reverse) ? PLAYMODE_BACKWARD : PLAYMODE_FORWARD; + m_playInfo.m_numLoops = (m_loop) ? EMFX_LOOPFOREVER : 1; + m_playInfo.m_freezeAtLastFrame = true; + m_playInfo.m_enableMotionEvents = m_emitEvents; + m_playInfo.m_mirrorMotion = m_mirrorMotion; + m_playInfo.m_playSpeed = ExtractCustomPlaySpeed(animGraphInstance); + m_playInfo.m_motionExtractionEnabled = m_motionExtraction; + m_playInfo.m_retarget = m_retarget; + m_playInfo.m_inPlace = GetIsInPlace(animGraphInstance); } @@ -326,12 +326,12 @@ namespace EMotionFX uniqueData->Clear(); // remove the motion instance if it already exists - if (uniqueData->mMotionInstance && uniqueData->mReload) + if (uniqueData->m_motionInstance && uniqueData->m_reload) { - GetMotionInstancePool().Free(uniqueData->mMotionInstance); - uniqueData->mMotionInstance = nullptr; - uniqueData->mMotionSetID = MCORE_INVALIDINDEX32; - uniqueData->mReload = false; + GetMotionInstancePool().Free(uniqueData->m_motionInstance); + uniqueData->m_motionInstance = nullptr; + uniqueData->m_motionSetId = MCORE_INVALIDINDEX32; + uniqueData->m_reload = false; } // get the motion set @@ -346,9 +346,9 @@ namespace EMotionFX } // get the motion from the motion set, load it on demand and make sure the motion loaded successfully - if (uniqueData->mActiveMotionIndex != MCORE_INVALIDINDEX32) + if (uniqueData->m_activeMotionIndex != MCORE_INVALIDINDEX32) { - motion = motionSet->RecursiveFindMotionById(GetMotionId(uniqueData->mActiveMotionIndex)); + motion = motionSet->RecursiveFindMotionById(GetMotionId(uniqueData->m_activeMotionIndex)); } if (!motion) @@ -360,12 +360,12 @@ namespace EMotionFX return nullptr; } - uniqueData->mMotionSetID = motionSet->GetID(); + uniqueData->m_motionSetId = motionSet->GetID(); // create the motion instance MotionInstance* motionInstance = GetMotionInstancePool().RequestNew(motion, actorInstance); motionInstance->InitFromPlayBackInfo(playInfo, true); - motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.mRetarget); + motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.m_retarget); uniqueData->SetSyncTrack(motionInstance->GetMotion()->GetEventTable()->GetSyncTrack()); uniqueData->SetIsMirrorMotion(motionInstance->GetMirrorMotion()); @@ -377,7 +377,7 @@ namespace EMotionFX motionInstance->SetWeight(1.0f, 0.0f); // update play info - uniqueData->mMotionInstance = motionInstance; + uniqueData->m_motionInstance = motionInstance; uniqueData->SetDuration(motionInstance->GetDuration()); const float curPlayTime = motionInstance->GetCurrentTime(); uniqueData->SetCurrentPlayTime(curPlayTime); @@ -395,7 +395,7 @@ namespace EMotionFX void AnimGraphMotionNode::Output(AnimGraphInstance* animGraphInstance) { // if this motion is disabled, output the bind pose - if (mDisabled) + if (m_disabled) { // request poses to use from the pool, so that all output pose ports have a valid pose to output to we reuse them using a pool system to save memory RequestPoses(animGraphInstance); @@ -406,7 +406,7 @@ namespace EMotionFX } // output the playspeed node - EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).mConnection; + EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).m_connection; if (playSpeedConnection) { OutputIncomingNode(animGraphInstance, playSpeedConnection->GetSourceNode()); @@ -416,14 +416,14 @@ namespace EMotionFX ActorInstance* actorInstance = animGraphInstance->GetActorInstance(); MotionInstance* motionInstance = nullptr; UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - if (uniqueData->mReload) + if (uniqueData->m_reload) { motionInstance = CreateMotionInstance(actorInstance, uniqueData); - uniqueData->mReload = false; + uniqueData->m_reload = false; } else { - motionInstance = uniqueData->mMotionInstance; + motionInstance = uniqueData->m_motionInstance; } // update the motion instance output port @@ -448,7 +448,7 @@ namespace EMotionFX SetHasError(uniqueData, false); } - EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).mConnection; + EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).m_connection; if (inPlaceConnection) { OutputIncomingNode(animGraphInstance, inPlaceConnection->GetSourceNode()); @@ -477,7 +477,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -486,7 +486,7 @@ namespace EMotionFX MotionInstance* AnimGraphMotionNode::FindMotionInstance(AnimGraphInstance* animGraphInstance) const { UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - return uniqueData->mMotionInstance; + return uniqueData->m_motionInstance; } @@ -495,9 +495,9 @@ namespace EMotionFX { UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); uniqueData->SetCurrentPlayTime(timeInSeconds); - if (uniqueData->mMotionInstance) + if (uniqueData->m_motionInstance) { - uniqueData->mMotionInstance->SetCurrentTime(timeInSeconds); + uniqueData->m_motionInstance->SetCurrentTime(timeInSeconds); } } @@ -510,26 +510,26 @@ namespace EMotionFX AnimGraphMotionNode::UniqueData::~UniqueData() { - GetMotionInstancePool().Free(mMotionInstance); + GetMotionInstancePool().Free(m_motionInstance); } void AnimGraphMotionNode::UniqueData::Reset() { // stop and delete the motion instance - if (mMotionInstance) + if (m_motionInstance) { - mMotionInstance->Stop(0.0f); - GetMotionInstancePool().Free(mMotionInstance); + m_motionInstance->Stop(0.0f); + GetMotionInstancePool().Free(m_motionInstance); } // reset the unique data - mMotionSetID = MCORE_INVALIDINDEX32; - mMotionInstance = nullptr; - mReload = true; - mPlaySpeed = 1.0f; - mCurrentTime = 0.0f; - mDuration = 0.0f; - mActiveMotionIndex = MCORE_INVALIDINDEX32; + m_motionSetId = MCORE_INVALIDINDEX32; + m_motionInstance = nullptr; + m_reload = true; + m_playSpeed = 1.0f; + m_currentTime = 0.0f; + m_duration = 0.0f; + m_activeMotionIndex = MCORE_INVALIDINDEX32; SetSyncTrack(nullptr); Invalidate(); @@ -537,13 +537,13 @@ namespace EMotionFX void AnimGraphMotionNode::UniqueData::Update() { - AnimGraphMotionNode* motionNode = azdynamic_cast(mObject); + AnimGraphMotionNode* motionNode = azdynamic_cast(m_object); AZ_Assert(motionNode, "Unique data linked to incorrect node type."); AnimGraphInstance* animGraphInstance = GetAnimGraphInstance(); motionNode->PickNewActiveMotion(animGraphInstance, this); - if (!mMotionInstance) + if (!m_motionInstance) { motionNode->CreateMotionInstance(animGraphInstance->GetActorInstance(), this); } @@ -560,9 +560,9 @@ namespace EMotionFX motionNode->UpdatePlayBackInfo(animGraphInstance); // update play info - if (mMotionInstance) + if (m_motionInstance) { - MotionInstance* motionInstance = mMotionInstance; + MotionInstance* motionInstance = m_motionInstance; const float currentTime = motionInstance->GetCurrentTime(); SetDuration(motionInstance->GetDuration()); SetCurrentPlayTime(currentTime); @@ -575,7 +575,7 @@ namespace EMotionFX // this function will get called to rewind motion nodes as well as states etc. to reset several settings when a state gets exited void AnimGraphMotionNode::Rewind(AnimGraphInstance* animGraphInstance) { - UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); // rewind is not necessary if unique data is not created yet if (!uniqueData) @@ -584,7 +584,7 @@ namespace EMotionFX } // find the motion instance for the given anim graph and return directly in case it is invalid - MotionInstance* motionInstance = uniqueData->mMotionInstance; + MotionInstance* motionInstance = uniqueData->m_motionInstance; if (motionInstance == nullptr) { return; @@ -605,7 +605,7 @@ namespace EMotionFX // get the speed from the connection if there is one connected, if not use the node's playspeed float AnimGraphMotionNode::ExtractCustomPlaySpeed(AnimGraphInstance* animGraphInstance) const { - EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).mConnection; + EMotionFX::BlendTreeConnection* playSpeedConnection = GetInputPort(INPUTPORT_PLAYSPEED).m_connection; // if there is a node connected to the speed input port, read that value and use it as internal speed float customSpeed; @@ -638,23 +638,23 @@ namespace EMotionFX const size_t numMotions = m_motionRandomSelectionCumulativeWeights.size(); if (numMotions == 1) { - uniqueData->mActiveMotionIndex = 0; + uniqueData->m_activeMotionIndex = 0; } else if (numMotions > 1) { - uniqueData->mReload = true; + uniqueData->m_reload = true; switch (m_indexMode) { // pick a random one, but make sure its not the same as the last one we played case INDEXMODE_RANDOMIZE_NOREPEAT: { - if (uniqueData->mActiveMotionIndex == MCORE_INVALIDINDEX32) + if (uniqueData->m_activeMotionIndex == MCORE_INVALIDINDEX32) { SelectAnyRandomMotionIndex(animGraphInstance, uniqueData); return; } - AZ::u32 curIndex = uniqueData->mActiveMotionIndex; + AZ::u32 curIndex = uniqueData->m_activeMotionIndex; // Make sure we're in a valid range. if (curIndex >= numMotions) @@ -677,17 +677,17 @@ namespace EMotionFX } const int index = FindCumulativeProbabilityIndex(remappedRandomValue); AZ_Assert(index >= 0, "Unable to find random value in motion random weights"); - uniqueData->mActiveMotionIndex = index; + uniqueData->m_activeMotionIndex = index; } break; // pick the next motion from the list case INDEXMODE_SEQUENTIAL: { - uniqueData->mActiveMotionIndex++; - if (uniqueData->mActiveMotionIndex >= numMotions) + uniqueData->m_activeMotionIndex++; + if (uniqueData->m_activeMotionIndex >= numMotions) { - uniqueData->mActiveMotionIndex = 0; + uniqueData->m_activeMotionIndex = 0; } } break; @@ -702,7 +702,7 @@ namespace EMotionFX } else { - uniqueData->mActiveMotionIndex = MCORE_INVALIDINDEX32; + uniqueData->m_activeMotionIndex = MCORE_INVALIDINDEX32; } } @@ -712,7 +712,7 @@ namespace EMotionFX const float randomValue = animGraphInstance->GetLcgRandom().GetRandomFloat() * m_motionRandomSelectionCumulativeWeights.back().second; const int index = FindCumulativeProbabilityIndex(randomValue); AZ_Assert(index >= 0, "Error: unable to find random value among motion random weights"); - uniqueData->mActiveMotionIndex = index; + uniqueData->m_activeMotionIndex = index; } int AnimGraphMotionNode::FindCumulativeProbabilityIndex(float randomValue) const @@ -777,19 +777,19 @@ namespace EMotionFX void AnimGraphMotionNode::ReloadAndInvalidateUniqueDatas() { - if (!mAnimGraph) + if (!m_animGraph) { return; } - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); - UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); + UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData) { - uniqueData->mReload = true; + uniqueData->m_reload = true; uniqueData->Invalidate(); } } @@ -803,10 +803,10 @@ namespace EMotionFX void AnimGraphMotionNode::RecursiveOnChangeMotionSet(AnimGraphInstance* animGraphInstance, MotionSet* newMotionSet) { AnimGraphNode::RecursiveOnChangeMotionSet(animGraphInstance, newMotionSet); - UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData) { - uniqueData->mReload = true; + uniqueData->m_reload = true; uniqueData->Invalidate(); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h index ab6e4bef62..a07bbc625c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphMotionNode.h @@ -72,10 +72,10 @@ namespace EMotionFX void Update() override; public: - uint32 mMotionSetID = InvalidIndex32; - uint32 mActiveMotionIndex = InvalidIndex32; - MotionInstance* mMotionInstance = nullptr; - bool mReload = false; + uint32 m_motionSetId = InvalidIndex32; + uint32 m_activeMotionIndex = InvalidIndex32; + MotionInstance* m_motionInstance = nullptr; + bool m_reload = false; }; AnimGraphMotionNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp index 44d048c03c..be5499627d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.cpp @@ -50,17 +50,17 @@ namespace EMotionFX AnimGraphNode::AnimGraphNode() : AnimGraphObject(nullptr) , m_id(AnimGraphNodeId::Create()) - , mNodeIndex(MCORE_INVALIDINDEX32) - , mDisabled(false) - , mParentNode(nullptr) - , mCustomData(nullptr) - , mVisEnabled(false) - , mIsCollapsed(false) - , mPosX(0) - , mPosY(0) + , m_nodeIndex(InvalidIndex) + , m_disabled(false) + , m_parentNode(nullptr) + , m_customData(nullptr) + , m_visEnabled(false) + , m_isCollapsed(false) + , m_posX(0) + , m_posY(0) { const AZ::u32 col = MCore::GenerateColor(); - mVisualizeColor = AZ::Color( + m_visualizeColor = AZ::Color( MCore::ExtractRed(col)/255.0f, MCore::ExtractGreen(col)/255.0f, MCore::ExtractBlue(col)/255.0f, @@ -81,21 +81,21 @@ namespace EMotionFX RemoveAllConnections(); RemoveAllChildNodes(); - if (mAnimGraph) + if (m_animGraph) { - mAnimGraph->RemoveObject(this); + m_animGraph->RemoveObject(this); } } void AnimGraphNode::RecursiveReinit() { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->Reinit(); } - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveReinit(); } @@ -113,13 +113,13 @@ namespace EMotionFX } // Initialize connections. - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->InitAfterLoading(animGraph); } // Initialize child nodes. - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { // Sync the child node's parent. childNode->SetParentNode(this); @@ -140,7 +140,7 @@ namespace EMotionFX { for (AnimGraphTriggerAction* action : m_actionSetup.GetActions()) { - action->InitAfterLoading(mAnimGraph); + action->InitAfterLoading(m_animGraph); } } @@ -148,35 +148,27 @@ namespace EMotionFX // copy base settings to the other node void AnimGraphNode::CopyBaseNodeTo(AnimGraphNode* node) const { - //CopyBaseObjectTo( node ); - - // now copy the node related things - // the parent - //if (mParentNode) - //node->mParentNode = node->GetAnimGraph()->RecursiveFindNodeByID( mParentNode->GetID() ); - - // copy the easy values node->m_name = m_name; node->m_id = m_id; - node->mNodeInfo = mNodeInfo; - node->mCustomData = mCustomData; - node->mDisabled = mDisabled; - node->mPosX = mPosX; - node->mPosY = mPosY; - node->mVisualizeColor = mVisualizeColor; - node->mVisEnabled = mVisEnabled; - node->mIsCollapsed = mIsCollapsed; + node->m_nodeInfo = m_nodeInfo; + node->m_customData = m_customData; + node->m_disabled = m_disabled; + node->m_posX = m_posX; + node->m_posY = m_posY; + node->m_visualizeColor = m_visualizeColor; + node->m_visEnabled = m_visEnabled; + node->m_isCollapsed = m_isCollapsed; } void AnimGraphNode::RemoveAllConnections() { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { delete connection; } - mConnections.clear(); + m_connections.clear(); } @@ -184,12 +176,12 @@ namespace EMotionFX BlendTreeConnection* AnimGraphNode::AddConnection(AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) { // make sure the source and target ports are in range - if (targetPort < mInputPorts.size() && sourcePort < sourceNode->mOutputPorts.size()) + if (targetPort < m_inputPorts.size() && sourcePort < sourceNode->m_outputPorts.size()) { BlendTreeConnection* connection = aznew BlendTreeConnection(sourceNode, sourcePort, targetPort); - mConnections.push_back(connection); - mInputPorts[targetPort].mConnection = connection; - sourceNode->mOutputPorts[sourcePort].mConnection = connection; + m_connections.push_back(connection); + m_inputPorts[targetPort].m_connection = connection; + sourceNode->m_outputPorts[sourcePort].m_connection = connection; return connection; } return nullptr; @@ -199,7 +191,7 @@ namespace EMotionFX BlendTreeConnection* AnimGraphNode::AddUnitializedConnection(AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) { BlendTreeConnection* connection = aznew BlendTreeConnection(sourceNode, sourcePort, targetPort); - mConnections.push_back(connection); + m_connections.push_back(connection); return connection; } @@ -207,7 +199,7 @@ namespace EMotionFX // validate the connections bool AnimGraphNode::ValidateConnections() const { - for (const BlendTreeConnection* connection : mConnections) + for (const BlendTreeConnection* connection : m_connections) { if (!connection->GetIsValid()) { @@ -222,7 +214,7 @@ namespace EMotionFX // check if the given input port is connected bool AnimGraphNode::CheckIfIsInputPortConnected(uint16 inputPort) const { - for (const BlendTreeConnection* connection : mConnections) + for (const BlendTreeConnection* connection : m_connections) { if (connection->GetTargetPort() == inputPort) { @@ -240,42 +232,42 @@ namespace EMotionFX { if (delFromMem) { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { delete childNode; } } - mChildNodes.clear(); + m_childNodes.clear(); // trigger that we removed nodes - GetEventManager().OnRemovedChildNode(mAnimGraph, this); + GetEventManager().OnRemovedChildNode(m_animGraph, this); // TODO: remove the nodes from the node groups of the anim graph as well here } // remove a given node - void AnimGraphNode::RemoveChildNode(uint32 index, bool delFromMem) + void AnimGraphNode::RemoveChildNode(size_t index, bool delFromMem) { // remove the node from its node group - AnimGraphNodeGroup* nodeGroup = mAnimGraph->FindNodeGroupForNode(mChildNodes[index]); + AnimGraphNodeGroup* nodeGroup = m_animGraph->FindNodeGroupForNode(m_childNodes[index]); if (nodeGroup) { - nodeGroup->RemoveNodeById(mChildNodes[index]->GetId()); + nodeGroup->RemoveNodeById(m_childNodes[index]->GetId()); } // delete the node from memory if (delFromMem) { - delete mChildNodes[index]; + delete m_childNodes[index]; } // delete the node from the child array - mChildNodes.erase(mChildNodes.begin() + index); + m_childNodes.erase(m_childNodes.begin() + index); // trigger callbacks - GetEventManager().OnRemovedChildNode(mAnimGraph, this); + GetEventManager().OnRemovedChildNode(m_animGraph, this); } @@ -283,11 +275,11 @@ namespace EMotionFX void AnimGraphNode::RemoveChildNodeByPointer(AnimGraphNode* node, bool delFromMem) { // find the index of the given node in the child node array and remove it in case the index is valid - const auto iterator = AZStd::find(mChildNodes.begin(), mChildNodes.end(), node); + const auto iterator = AZStd::find(m_childNodes.begin(), m_childNodes.end(), node); - if (iterator != mChildNodes.end()) + if (iterator != m_childNodes.end()) { - const uint32 index = static_cast(iterator - mChildNodes.begin()); + const size_t index = AZStd::distance(m_childNodes.begin(), iterator); RemoveChildNode(index, delFromMem); } } @@ -300,7 +292,7 @@ namespace EMotionFX return const_cast(this); } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { AnimGraphNode* result = childNode->RecursiveFindNodeByName(nodeName); if (result) @@ -320,7 +312,7 @@ namespace EMotionFX return false; } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { if (!childNode->RecursiveIsNodeNameUnique(newNameCandidate, forNode)) { @@ -339,7 +331,7 @@ namespace EMotionFX return const_cast(this); } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { AnimGraphNode* result = childNode->RecursiveFindNodeById(nodeId); if (result) @@ -355,7 +347,7 @@ namespace EMotionFX // find a child node by name AnimGraphNode* AnimGraphNode::FindChildNode(const char* name) const { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { // compare the node name with the parameter and return a pointer to the node in case they are equal if (AzFramework::StringFunc::Equal(childNode->GetName(), name, true /* case sensitive */)) @@ -371,7 +363,7 @@ namespace EMotionFX AnimGraphNode* AnimGraphNode::FindChildNodeById(AnimGraphNodeId childId) const { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { if (childNode->GetId() == childId) { @@ -384,92 +376,65 @@ namespace EMotionFX // find a child node index by name - uint32 AnimGraphNode::FindChildNodeIndex(const char* name) const + size_t AnimGraphNode::FindChildNodeIndex(const char* name) const { - const size_t numChildNodes = mChildNodes.size(); - for (size_t i = 0; i < numChildNodes; ++i) + const auto foundChildNode = AZStd::find_if(begin(m_childNodes), end(m_childNodes), [name](const AnimGraphNode* childNode) { - // compare the node name with the parameter and return the relative child node index in case they are equal - if (AzFramework::StringFunc::Equal(mChildNodes[i]->GetNameString().c_str(), name, true /* case sensitive */)) - { - return static_cast(i); - } - } - - // failure, return invalid index - return MCORE_INVALIDINDEX32; + return childNode->GetNameString() == name; + }); + return foundChildNode != end(m_childNodes) ? AZStd::distance(begin(m_childNodes), foundChildNode) : InvalidIndex; } // find a child node index - uint32 AnimGraphNode::FindChildNodeIndex(AnimGraphNode* node) const + size_t AnimGraphNode::FindChildNodeIndex(AnimGraphNode* node) const { - const auto iterator = AZStd::find(mChildNodes.begin(), mChildNodes.end(), node); - if (iterator == mChildNodes.end()) - { - return MCORE_INVALIDINDEX32; - } - - const size_t index = iterator - mChildNodes.begin(); - return static_cast(index); + const auto foundChildNode = AZStd::find(m_childNodes.begin(), m_childNodes.end(), node); + return foundChildNode != end(m_childNodes) ? AZStd::distance(begin(m_childNodes), foundChildNode) : InvalidIndex; } AnimGraphNode* AnimGraphNode::FindFirstChildNodeOfType(const AZ::TypeId& nodeType) const { - for (AnimGraphNode* childNode : mChildNodes) + const auto foundChild = AZStd::find_if(begin(m_childNodes), end(m_childNodes), [nodeType](const AnimGraphNode* childNode) { - if (azrtti_typeid(childNode) == nodeType) - { - return childNode; - } - } - - return nullptr; + return azrtti_typeid(childNode) == nodeType; + }); + return foundChild != end(m_childNodes) ? *foundChild : nullptr; } bool AnimGraphNode::HasChildNodeOfType(const AZ::TypeId& nodeType) const { - for (const AnimGraphNode* childNode : mChildNodes) + return AZStd::any_of(begin(m_childNodes), end(m_childNodes), [nodeType](const AnimGraphNode* childNode) { - if (azrtti_typeid(childNode) == nodeType) - { - return true; - } - } - - return false; + return azrtti_typeid(childNode) == nodeType; + }); } // does this node has a specific incoming connection? bool AnimGraphNode::GetHasConnection(AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) const { - for (const BlendTreeConnection* connection : mConnections) + return AZStd::any_of(begin(m_connections), end(m_connections), [sourceNode, sourcePort, targetPort](const BlendTreeConnection* connection) { - if (connection->GetSourceNode() == sourceNode && connection->GetSourcePort() == sourcePort && connection->GetTargetPort() == targetPort) - { - return true; - } - } - - return false; + return connection->GetSourceNode() == sourceNode && connection->GetSourcePort() == sourcePort && connection->GetTargetPort() == targetPort; + }); } // remove a given connection void AnimGraphNode::RemoveConnection(BlendTreeConnection* connection, bool delFromMem) { - mInputPorts[connection->GetTargetPort()].mConnection = nullptr; + m_inputPorts[connection->GetTargetPort()].m_connection = nullptr; AnimGraphNode* sourceNode = connection->GetSourceNode(); if (sourceNode) { - sourceNode->mOutputPorts[connection->GetSourcePort()].mConnection = nullptr; + sourceNode->m_outputPorts[connection->GetSourcePort()].m_connection = nullptr; } // Remove object by value. - mConnections.erase(AZStd::remove(mConnections.begin(), mConnections.end(), connection), mConnections.end()); + m_connections.erase(AZStd::remove(m_connections.begin(), m_connections.end(), connection), m_connections.end()); if (delFromMem) { delete connection; @@ -481,7 +446,7 @@ namespace EMotionFX void AnimGraphNode::RemoveConnection(AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) { // for all input connections - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetSourceNode() == sourceNode && connection->GetSourcePort() == sourcePort && connection->GetTargetPort() == targetPort) { @@ -494,25 +459,25 @@ namespace EMotionFX bool AnimGraphNode::RemoveConnectionById(AnimGraphConnectionId connectionId, bool delFromMem) { - const size_t numConnections = mConnections.size(); + const size_t numConnections = m_connections.size(); for (size_t i = 0; i < numConnections; ++i) { - if (mConnections[i]->GetId() == connectionId) + if (m_connections[i]->GetId() == connectionId) { - mInputPorts[mConnections[i]->GetTargetPort()].mConnection = nullptr; + m_inputPorts[m_connections[i]->GetTargetPort()].m_connection = nullptr; - AnimGraphNode* sourceNode = mConnections[i]->GetSourceNode(); + AnimGraphNode* sourceNode = m_connections[i]->GetSourceNode(); if (sourceNode) { - sourceNode->mOutputPorts[mConnections[i]->GetSourcePort()].mConnection = nullptr; + sourceNode->m_outputPorts[m_connections[i]->GetSourcePort()].m_connection = nullptr; } if (delFromMem) { - delete mConnections[i]; + delete m_connections[i]; } - mConnections.erase(mConnections.begin() + i); + m_connections.erase(m_connections.begin() + i); } } @@ -523,7 +488,7 @@ namespace EMotionFX // find a given connection BlendTreeConnection* AnimGraphNode::FindConnection(const AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) const { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetSourceNode() == sourceNode && connection->GetSourcePort() == sourcePort && connection->GetTargetPort() == targetPort) { @@ -537,92 +502,80 @@ namespace EMotionFX // initialize the input ports - void AnimGraphNode::InitInputPorts(uint32 numPorts) + void AnimGraphNode::InitInputPorts(size_t numPorts) { - mInputPorts.resize(numPorts); + m_inputPorts.resize(numPorts); } // initialize the output ports - void AnimGraphNode::InitOutputPorts(uint32 numPorts) + void AnimGraphNode::InitOutputPorts(size_t numPorts) { - mOutputPorts.resize(numPorts); + m_outputPorts.resize(numPorts); } // find a given output port number - uint32 AnimGraphNode::FindOutputPortIndex(const AZStd::string& name) const + size_t AnimGraphNode::FindOutputPortIndex(const AZStd::string& name) const { - const size_t numPorts = mOutputPorts.size(); - for (size_t i = 0; i < numPorts; ++i) + const auto foundPort = AZStd::find_if(begin(m_outputPorts), end(m_outputPorts), [&name](const Port& port) { - // if the port name is equal to the name we are searching for, return the index - if (mOutputPorts[i].GetNameString() == name) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return port.GetNameString() == name; + }); + return foundPort != end(m_outputPorts) ? AZStd::distance(begin(m_outputPorts), foundPort) : InvalidIndex; } // find a given input port number - uint32 AnimGraphNode::FindInputPortIndex(const AZStd::string& name) const + size_t AnimGraphNode::FindInputPortIndex(const AZStd::string& name) const { - const size_t numPorts = mInputPorts.size(); - for (size_t i = 0; i < numPorts; ++i) + const auto foundPort = AZStd::find_if(begin(m_inputPorts), end(m_inputPorts), [&name](const Port& port) { - // if the port name is equal to the name we are searching for, return the index - if (mInputPorts[i].GetNameString() == name) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return port.GetNameString() == name; + }); + return foundPort != end(m_inputPorts) ? AZStd::distance(begin(m_inputPorts), foundPort) : InvalidIndex; } // add an output port and return its index - uint32 AnimGraphNode::AddOutputPort() + size_t AnimGraphNode::AddOutputPort() { - const size_t currentSize = mOutputPorts.size(); - mOutputPorts.emplace_back(); - return static_cast(currentSize); + const size_t currentSize = m_outputPorts.size(); + m_outputPorts.emplace_back(); + return currentSize; } // add an input port, and return its index - uint32 AnimGraphNode::AddInputPort() + size_t AnimGraphNode::AddInputPort() { - const size_t currentSize = mInputPorts.size(); - mInputPorts.emplace_back(); + const size_t currentSize = m_inputPorts.size(); + m_inputPorts.emplace_back(); return static_cast(currentSize); } // setup a port name - void AnimGraphNode::SetInputPortName(uint32 portIndex, const char* name) + void AnimGraphNode::SetInputPortName(size_t portIndex, const char* name) { - MCORE_ASSERT(portIndex < mInputPorts.size()); - mInputPorts[portIndex].mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + MCORE_ASSERT(portIndex < m_inputPorts.size()); + m_inputPorts[portIndex].m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } // setup a port name - void AnimGraphNode::SetOutputPortName(uint32 portIndex, const char* name) + void AnimGraphNode::SetOutputPortName(size_t portIndex, const char* name) { - MCORE_ASSERT(portIndex < mOutputPorts.size()); - mOutputPorts[portIndex].mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + MCORE_ASSERT(portIndex < m_outputPorts.size()); + m_outputPorts[portIndex].m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } // get the total number of children - uint32 AnimGraphNode::RecursiveCalcNumNodes() const + size_t AnimGraphNode::RecursiveCalcNumNodes() const { - uint32 result = 0; - for (const AnimGraphNode* childNode : mChildNodes) + size_t result = 0; + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCountChildNodes(result); } @@ -632,12 +585,12 @@ namespace EMotionFX // recursively count the number of nodes down the hierarchy - void AnimGraphNode::RecursiveCountChildNodes(uint32& numNodes) const + void AnimGraphNode::RecursiveCountChildNodes(size_t& numNodes) const { // increase the counter numNodes++; - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCountChildNodes(numNodes); } @@ -645,21 +598,21 @@ namespace EMotionFX // recursively calculate the number of node connections - uint32 AnimGraphNode::RecursiveCalcNumNodeConnections() const + size_t AnimGraphNode::RecursiveCalcNumNodeConnections() const { - uint32 result = 0; + size_t result = 0; RecursiveCountNodeConnections(result); return result; } // recursively calculate the number of node connections - void AnimGraphNode::RecursiveCountNodeConnections(uint32& numConnections) const + void AnimGraphNode::RecursiveCountNodeConnections(size_t& numConnections) const { // add the connections to our counter numConnections += GetNumConnections(); - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCountNodeConnections(numConnections); } @@ -667,137 +620,132 @@ namespace EMotionFX // setup an output port to output a given local pose - void AnimGraphNode::SetupOutputPortAsPose(const char* name, uint32 outputPortNr, uint32 portID) + void AnimGraphNode::SetupOutputPortAsPose(const char* name, size_t outputPortNr, uint32 portID) { // check if we already registered this port ID - const uint32 duplicatePort = FindOutputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindOutputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetOutputPortAsPose() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, mOutputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetOutputPortAsPose() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, m_outputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); } SetOutputPortName(outputPortNr, name); - mOutputPorts[outputPortNr].Clear(); - mOutputPorts[outputPortNr].mCompatibleTypes[0] = AttributePose::TYPE_ID; // setup the compatible types of this port - mOutputPorts[outputPortNr].mPortID = portID; + m_outputPorts[outputPortNr].Clear(); + m_outputPorts[outputPortNr].m_compatibleTypes[0] = AttributePose::TYPE_ID; // setup the compatible types of this port + m_outputPorts[outputPortNr].m_portId = portID; } // setup an output port to output a given motion instance - void AnimGraphNode::SetupOutputPortAsMotionInstance(const char* name, uint32 outputPortNr, uint32 portID) + void AnimGraphNode::SetupOutputPortAsMotionInstance(const char* name, size_t outputPortNr, uint32 portID) { // check if we already registered this port ID - const uint32 duplicatePort = FindOutputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindOutputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetOutputPortAsMotionInstance() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, mOutputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetOutputPortAsMotionInstance() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, m_outputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); } SetOutputPortName(outputPortNr, name); - mOutputPorts[outputPortNr].Clear(); - mOutputPorts[outputPortNr].mCompatibleTypes[0] = AttributeMotionInstance::TYPE_ID; // setup the compatible types of this port - mOutputPorts[outputPortNr].mPortID = portID; + m_outputPorts[outputPortNr].Clear(); + m_outputPorts[outputPortNr].m_compatibleTypes[0] = AttributeMotionInstance::TYPE_ID; // setup the compatible types of this port + m_outputPorts[outputPortNr].m_portId = portID; } // setup an output port - void AnimGraphNode::SetupOutputPort(const char* name, uint32 outputPortNr, uint32 attributeTypeID, uint32 portID) + void AnimGraphNode::SetupOutputPort(const char* name, size_t outputPortNr, uint32 attributeTypeID, uint32 portID) { // check if we already registered this port ID - const uint32 duplicatePort = FindOutputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindOutputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetOutputPort() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' name='%s')", portID, mOutputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetOutputPort() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' name='%s')", portID, m_outputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); } SetOutputPortName(outputPortNr, name); - mOutputPorts[outputPortNr].Clear(); - mOutputPorts[outputPortNr].mCompatibleTypes[0] = attributeTypeID; - mOutputPorts[outputPortNr].mPortID = portID; + m_outputPorts[outputPortNr].Clear(); + m_outputPorts[outputPortNr].m_compatibleTypes[0] = attributeTypeID; + m_outputPorts[outputPortNr].m_portId = portID; } - void AnimGraphNode::SetupInputPortAsVector3(const char* name, uint32 inputPortNr, uint32 portID) + void AnimGraphNode::SetupInputPortAsVector3(const char* name, size_t inputPortNr, uint32 portID) { SetupInputPort(name, inputPortNr, AZStd::vector{MCore::AttributeVector3::TYPE_ID, MCore::AttributeVector2::TYPE_ID, MCore::AttributeVector4::TYPE_ID}, portID); } - void AnimGraphNode::SetupInputPortAsVector2(const char* name, uint32 inputPortNr, uint32 portID) + void AnimGraphNode::SetupInputPortAsVector2(const char* name, size_t inputPortNr, uint32 portID) { SetupInputPort(name, inputPortNr, AZStd::vector{MCore::AttributeVector2::TYPE_ID, MCore::AttributeVector3::TYPE_ID}, portID); } - void AnimGraphNode::SetupInputPortAsVector4(const char* name, uint32 inputPortNr, uint32 portID) + void AnimGraphNode::SetupInputPortAsVector4(const char* name, size_t inputPortNr, uint32 portID) { SetupInputPort(name, inputPortNr, AZStd::vector{MCore::AttributeVector4::TYPE_ID, MCore::AttributeVector3::TYPE_ID}, portID); } - void AnimGraphNode::SetupInputPort(const char* name, uint32 inputPortNr, const AZStd::vector& attributeTypeIDs, uint32 portID) + void AnimGraphNode::SetupInputPort(const char* name, size_t inputPortNr, const AZStd::vector& attributeTypeIDs, uint32 portID) { // Check if we already registered this port ID - const uint32 duplicatePort = FindInputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindInputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetInputPortAsNumber() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, MCore::GetStringIdPool().GetName(mInputPorts[duplicatePort].mNameID).c_str(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetInputPortAsNumber() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, MCore::GetStringIdPool().GetName(m_inputPorts[duplicatePort].m_nameId).c_str(), name, RTTI_GetTypeName()); } SetInputPortName(inputPortNr, name); - mInputPorts[inputPortNr].Clear(); - mInputPorts[inputPortNr].mPortID = portID; - mInputPorts[inputPortNr].SetCompatibleTypes(attributeTypeIDs); + m_inputPorts[inputPortNr].Clear(); + m_inputPorts[inputPortNr].m_portId = portID; + m_inputPorts[inputPortNr].SetCompatibleTypes(attributeTypeIDs); } // setup an input port as a number (float/int/bool) - void AnimGraphNode::SetupInputPortAsNumber(const char* name, uint32 inputPortNr, uint32 portID) + void AnimGraphNode::SetupInputPortAsNumber(const char* name, size_t inputPortNr, uint32 portID) { // check if we already registered this port ID - const uint32 duplicatePort = FindInputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindInputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetInputPortAsNumber() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, mInputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetInputPortAsNumber() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, m_inputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); } SetInputPortName(inputPortNr, name); - mInputPorts[inputPortNr].Clear(); - mInputPorts[inputPortNr].mCompatibleTypes[0] = MCore::AttributeFloat::TYPE_ID; - //mInputPorts[inputPortNr].mCompatibleTypes[1] = MCore::AttributeInt32::TYPE_ID; - //mInputPorts[inputPortNr].mCompatibleTypes[2] = MCore::AttributeBool::TYPE_ID;; - mInputPorts[inputPortNr].mPortID = portID; + m_inputPorts[inputPortNr].Clear(); + m_inputPorts[inputPortNr].m_compatibleTypes[0] = MCore::AttributeFloat::TYPE_ID; + m_inputPorts[inputPortNr].m_portId = portID; } - void AnimGraphNode::SetupInputPortAsBool(const char* name, uint32 inputPortNr, uint32 portID) + void AnimGraphNode::SetupInputPortAsBool(const char* name, size_t inputPortNr, uint32 portID) { // check if we already registered this port ID - const uint32 duplicatePort = FindInputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindInputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetInputPortAsBool() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, mInputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetInputPortAsBool() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, m_inputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); } SetInputPortName(inputPortNr, name); - mInputPorts[inputPortNr].Clear(); - mInputPorts[inputPortNr].mCompatibleTypes[0] = MCore::AttributeBool::TYPE_ID; - mInputPorts[inputPortNr].mCompatibleTypes[1] = MCore::AttributeFloat::TYPE_ID;; - mInputPorts[inputPortNr].mCompatibleTypes[2] = MCore::AttributeInt32::TYPE_ID; - mInputPorts[inputPortNr].mPortID = portID; + m_inputPorts[inputPortNr].Clear(); + m_inputPorts[inputPortNr].m_compatibleTypes[0] = MCore::AttributeBool::TYPE_ID; + m_inputPorts[inputPortNr].m_compatibleTypes[1] = MCore::AttributeFloat::TYPE_ID;; + m_inputPorts[inputPortNr].m_compatibleTypes[2] = MCore::AttributeInt32::TYPE_ID; + m_inputPorts[inputPortNr].m_portId = portID; } // setup a given input port in a generic way - void AnimGraphNode::SetupInputPort(const char* name, uint32 inputPortNr, uint32 attributeTypeID, uint32 portID) + void AnimGraphNode::SetupInputPort(const char* name, size_t inputPortNr, uint32 attributeTypeID, uint32 portID) { // check if we already registered this port ID - const uint32 duplicatePort = FindInputPortByID(portID); - if (duplicatePort != MCORE_INVALIDINDEX32) + const size_t duplicatePort = FindInputPortByID(portID); + if (duplicatePort != InvalidIndex) { - MCore::LogError("EMotionFX::AnimGraphNode::SetInputPort() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, mInputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); + MCore::LogError("EMotionFX::AnimGraphNode::SetInputPort() - There is already a port with the same ID (portID=%d existingPort='%s' newPort='%s' node='%s')", portID, m_inputPorts[duplicatePort].GetName(), name, RTTI_GetTypeName()); } SetInputPortName(inputPortNr, name); - mInputPorts[inputPortNr].Clear(); - mInputPorts[inputPortNr].mCompatibleTypes[0] = attributeTypeID; - mInputPorts[inputPortNr].mPortID = portID; - - // make sure we were able to create the attribute - //MCORE_ASSERT( mInputPorts[inputPortNr].mValue ); + m_inputPorts[inputPortNr].Clear(); + m_inputPorts[inputPortNr].m_compatibleTypes[0] = attributeTypeID; + m_inputPorts[inputPortNr].m_portId = portID; } @@ -805,7 +753,7 @@ namespace EMotionFX { ResetUniqueData(animGraphInstance); - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveResetUniqueDatas(animGraphInstance); } @@ -827,19 +775,19 @@ namespace EMotionFX { InvalidateUniqueData(animGraphInstance); - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveInvalidateUniqueDatas(animGraphInstance); } } // get the input value for a given port - const MCore::Attribute* AnimGraphNode::GetInputValue(AnimGraphInstance* animGraphInstance, uint32 inputPort) const + const MCore::Attribute* AnimGraphNode::GetInputValue(AnimGraphInstance* animGraphInstance, size_t inputPort) const { MCORE_UNUSED(animGraphInstance); // get the connection that is plugged into the port - BlendTreeConnection* connection = mInputPorts[inputPort].mConnection; + BlendTreeConnection* connection = m_inputPorts[inputPort].m_connection; MCORE_ASSERT(connection); // make sure there is a connection plugged in, otherwise we can't read the value // get the value from the output port of the source node @@ -851,17 +799,17 @@ namespace EMotionFX void AnimGraphNode::RecursiveResetFlags(AnimGraphInstance* animGraphInstance, uint32 flagsToReset) { // reset the flag in this node - animGraphInstance->DisableObjectFlags(mObjectIndex, flagsToReset); + animGraphInstance->DisableObjectFlags(m_objectIndex, flagsToReset); if (GetEMotionFX().GetIsInEditorMode()) { // reset all connections - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->SetIsVisited(false); } } - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveResetFlags(animGraphInstance, flagsToReset); } @@ -961,8 +909,8 @@ namespace EMotionFX syncMode, weight, outLeaderFactor, outFollowerFactor, outPlaySpeed); } - void AnimGraphNode::CalcSyncFactors(float leaderPlaySpeed, const AnimGraphSyncTrack* leaderSyncTrack, uint32 leaderSyncTrackIndex, float leaderDuration, - float followerPlaySpeed, const AnimGraphSyncTrack* followerSyncTrack, uint32 followerSyncTrackIndex, float followerDuration, + void AnimGraphNode::CalcSyncFactors(float leaderPlaySpeed, const AnimGraphSyncTrack* leaderSyncTrack, size_t leaderSyncTrackIndex, float leaderDuration, + float followerPlaySpeed, const AnimGraphSyncTrack* followerSyncTrack, size_t followerSyncTrackIndex, float followerDuration, ESyncMode syncMode, float weight, float* outLeaderFactor, float* outFollowerFactor, float* outPlaySpeed) { // exit if we don't want to sync or we have no leader node to sync to @@ -986,7 +934,7 @@ namespace EMotionFX if (leaderSyncTrack && followerSyncTrack && leaderSyncTrack->GetNumEvents() > 0 && followerSyncTrack->GetNumEvents() > 0) { // if the sync indices are invalid, act like no syncing - if (leaderSyncTrackIndex == MCORE_INVALIDINDEX32 || followerSyncTrackIndex == MCORE_INVALIDINDEX32) + if (leaderSyncTrackIndex == InvalidIndex || followerSyncTrackIndex == InvalidIndex) { *outLeaderFactor = 1.0f; *outFollowerFactor = 1.0f; @@ -995,13 +943,13 @@ namespace EMotionFX // get the segment lengths // TODO: handle motion clip start and end - uint32 leaderSyncIndexNext = leaderSyncTrackIndex + 1; + size_t leaderSyncIndexNext = leaderSyncTrackIndex + 1; if (leaderSyncIndexNext >= leaderSyncTrack->GetNumEvents()) { leaderSyncIndexNext = 0; } - uint32 followerSyncIndexNext = followerSyncTrackIndex + 1; + size_t followerSyncIndexNext = followerSyncTrackIndex + 1; if (followerSyncIndexNext >= followerSyncTrack->GetNumEvents()) { followerSyncIndexNext = 0; @@ -1032,10 +980,10 @@ namespace EMotionFX OnChangeMotionSet(animGraphInstance, newMotionSet); // get the number of child nodes, iterate through them and recursively call this function - const uint32 numChildNodes = GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { - mChildNodes[i]->RecursiveOnChangeMotionSet(animGraphInstance, newMotionSet); + m_childNodes[i]->RecursiveOnChangeMotionSet(animGraphInstance, newMotionSet); } } @@ -1086,7 +1034,7 @@ namespace EMotionFX startEventIndex = 0; } - if (startEventIndex == MCORE_INVALIDINDEX32) + if (startEventIndex == InvalidIndex) { startEventIndex = syncTrackB->GetNumEvents() - 1; } @@ -1118,8 +1066,8 @@ namespace EMotionFX } // update the sync indices - uniqueDataA->SetSyncIndex(static_cast(firstIndexA)); - uniqueDataB->SetSyncIndex(static_cast(secondIndexA)); + uniqueDataA->SetSyncIndex(firstIndexA); + uniqueDataB->SetSyncIndex(secondIndexA); // calculate the segment lengths const float firstSegmentLength = syncTrackA->CalcSegmentLength(firstIndexA, firstIndexB); @@ -1194,22 +1142,22 @@ namespace EMotionFX // check if the given node is the parent or the parent of the parent etc. of the node - bool AnimGraphNode::RecursiveIsParentNode(AnimGraphNode* node) const + bool AnimGraphNode::RecursiveIsParentNode(const AnimGraphNode* node) const { // if we're dealing with a root node we can directly return failure - if (!mParentNode) + if (!m_parentNode) { return false; } // check if the parent is the node and return success in that case - if (mParentNode == node) + if (m_parentNode == node) { return true; } // check if the parent's parent is the node we're searching for - return mParentNode->RecursiveIsParentNode(node); + return m_parentNode->RecursiveIsParentNode(node); } @@ -1217,22 +1165,15 @@ namespace EMotionFX bool AnimGraphNode::RecursiveIsChildNode(AnimGraphNode* node) const { // check if the given node is a child node of the current node - if (FindChildNodeIndex(node) != MCORE_INVALIDINDEX32) + if (FindChildNodeIndex(node) != InvalidIndex) { return true; } - // get the number of child nodes, iterate through them and compare if the node is a child of the child nodes of this node - for (const AnimGraphNode* childNode : mChildNodes) + return AZStd::any_of(begin(m_childNodes), end(m_childNodes), [node](const AnimGraphNode* childNode) { - if (childNode->RecursiveIsChildNode(node)) - { - return true; - } - } - - // failure, the node isn't a child or a child of a child node - return false; + return childNode->RecursiveIsChildNode(node); + }); } @@ -1250,17 +1191,17 @@ namespace EMotionFX SyncVisualObject(); // in case the parent node is valid check the error status of the parent by checking all children recursively and set that value - if (mParentNode) + if (m_parentNode) { - AnimGraphObjectData* parentUniqueData = mParentNode->FindOrCreateUniqueNodeData(uniqueData->GetAnimGraphInstance()); + AnimGraphObjectData* parentUniqueData = m_parentNode->FindOrCreateUniqueNodeData(uniqueData->GetAnimGraphInstance()); if (hasError) { - mParentNode->SetHasError(parentUniqueData, true); + m_parentNode->SetHasError(parentUniqueData, true); } - else if (!mParentNode->HierarchicalHasError(parentUniqueData, true)) + else if (!m_parentNode->HierarchicalHasError(parentUniqueData, true)) { // In case we are clearing this error, we need to check if this node siblings have errors to clear the parent. - mParentNode->SetHasError(parentUniqueData, false); + m_parentNode->SetHasError(parentUniqueData, false); } } } @@ -1272,7 +1213,7 @@ namespace EMotionFX return true; } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { AnimGraphObjectData* childUniqueData = childNode->FindOrCreateUniqueNodeData(uniqueData->GetAnimGraphInstance()); if (childUniqueData->GetHasError()) @@ -1287,21 +1228,21 @@ namespace EMotionFX // collect child nodes of the given type - void AnimGraphNode::CollectChildNodesOfType(const AZ::TypeId& nodeType, MCore::Array* outNodes) const + void AnimGraphNode::CollectChildNodesOfType(const AZ::TypeId& nodeType, AZStd::vector* outNodes) const { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { // check the current node type and add it to the output array in case they are the same if (azrtti_typeid(childNode) == nodeType) { - outNodes->Add(childNode); + outNodes->emplace_back(childNode); } } } void AnimGraphNode::CollectChildNodesOfType(const AZ::TypeId& nodeType, AZStd::vector& outNodes) const { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { if (azrtti_typeid(childNode) == nodeType) { @@ -1318,13 +1259,13 @@ namespace EMotionFX outNodes->emplace_back(const_cast(this)); } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectNodesOfType(nodeType, outNodes); } } - void AnimGraphNode::RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, MCore::Array* outConditions) const + void AnimGraphNode::RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, AZStd::vector* outConditions) const { // check if the current node is a state machine if (azrtti_typeid(this) == azrtti_typeid()) @@ -1346,13 +1287,13 @@ namespace EMotionFX AnimGraphTransitionCondition* condition = transition->GetCondition(j); if (azrtti_typeid(condition) == conditionType) { - outConditions->Add(condition); + outConditions->emplace_back(condition); } } } } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectTransitionConditionsOfType(conditionType, outConditions); } @@ -1366,7 +1307,7 @@ namespace EMotionFX outObjects.emplace_back(const_cast(this)); } - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectObjectsOfType(objectType, outObjects); } @@ -1374,7 +1315,7 @@ namespace EMotionFX void AnimGraphNode::RecursiveCollectObjectsAffectedBy(AnimGraph* animGraph, AZStd::vector& outObjects) const { - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectObjectsAffectedBy(animGraph, outObjects); } @@ -1425,60 +1366,44 @@ namespace EMotionFX // find the input port, based on the port name AnimGraphNode::Port* AnimGraphNode::FindInputPortByName(const AZStd::string& portName) { - for (Port& port : mInputPorts) + const auto foundPort = AZStd::find_if(begin(m_inputPorts), end(m_inputPorts), [&portName](const Port& port) { - if (port.GetNameString() == portName) - { - return &port; - } - } - return nullptr; + return port.GetNameString() == portName; + }); + return foundPort != end(m_inputPorts) ? foundPort : nullptr; } // find the output port, based on the port name AnimGraphNode::Port* AnimGraphNode::FindOutputPortByName(const AZStd::string& portName) { - for (Port& port : mOutputPorts) + const auto foundPort = AZStd::find_if(begin(m_outputPorts), end(m_outputPorts), [&portName](const Port& port) { - if (port.GetNameString() == portName) - { - return &port; - } - } - return nullptr; + return port.GetNameString() == portName; + }); + return foundPort != end(m_outputPorts) ? foundPort : nullptr; } // find the input port index, based on the port id - uint32 AnimGraphNode::FindInputPortByID(uint32 portID) const + size_t AnimGraphNode::FindInputPortByID(uint32 portID) const { - const size_t numPorts = mInputPorts.size(); - for (size_t i = 0; i < numPorts; ++i) + const auto foundPort = AZStd::find_if(begin(m_inputPorts), end(m_inputPorts), [portID](const Port& port) { - if (mInputPorts[i].mPortID == portID) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return port.m_portId == portID; + }); + return foundPort != end(m_inputPorts) ? AZStd::distance(begin(m_inputPorts), foundPort) : InvalidIndex; } // find the output port index, based on the port id - uint32 AnimGraphNode::FindOutputPortByID(uint32 portID) const + size_t AnimGraphNode::FindOutputPortByID(uint32 portID) const { - const size_t numPorts = mOutputPorts.size(); - for (size_t i = 0; i < numPorts; ++i) + const auto foundPort = AZStd::find_if(begin(m_outputPorts), end(m_outputPorts), [portID](const Port& port) { - if (mOutputPorts[i].mPortID == portID) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return port.m_portId == portID; + }); + return foundPort != end(m_outputPorts) ? AZStd::distance(begin(m_outputPorts), foundPort) : InvalidIndex; } @@ -1496,12 +1421,12 @@ namespace EMotionFX outConnections.clear(); // if we don't have a parent node we cannot proceed - if (!mParentNode) + if (!m_parentNode) { return; } - for (AnimGraphNode* childNode : mParentNode->GetChildNodes()) + for (AnimGraphNode* childNode : m_parentNode->GetChildNodes()) { // Skip this child if the child is this node if (childNode == this) @@ -1521,16 +1446,16 @@ namespace EMotionFX } - void AnimGraphNode::CollectOutgoingConnections(AZStd::vector >& outConnections, const uint32 portIndex) const + void AnimGraphNode::CollectOutgoingConnections(AZStd::vector >& outConnections, const size_t portIndex) const { outConnections.clear(); - if (!mParentNode) + if (!m_parentNode) { return; } - for (AnimGraphNode* childNode : mParentNode->GetChildNodes()) + for (AnimGraphNode* childNode : m_parentNode->GetChildNodes()) { // Skip this child if the child is this node if (childNode == this) @@ -1553,8 +1478,8 @@ namespace EMotionFX BlendTreeConnection* AnimGraphNode::FindConnection(uint16 port) const { // get the number of connections and iterate through them - const uint32 numConnections = GetNumConnections(); - for (uint32 i = 0; i < numConnections; ++i) + const size_t numConnections = GetNumConnections(); + for (size_t i = 0; i < numConnections; ++i) { // get the current connection and check if the connection is connected to the given port BlendTreeConnection* connection = GetConnection(i); @@ -1571,7 +1496,7 @@ namespace EMotionFX BlendTreeConnection* AnimGraphNode::FindConnectionById(AnimGraphConnectionId connectionId) const { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetId() == connectionId) { @@ -1585,15 +1510,15 @@ namespace EMotionFX bool AnimGraphNode::HasConnectionAtInputPort(AZ::u32 inputPortNr) const { - const Port& inputPort = mInputPorts[inputPortNr]; - return inputPort.mConnection != nullptr; + const Port& inputPort = m_inputPorts[inputPortNr]; + return inputPort.m_connection != nullptr; } // callback that gets called before a node gets removed void AnimGraphNode::OnRemoveNode(AnimGraph* animGraph, AnimGraphNode* nodeToRemove) { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->OnRemoveNode(animGraph, nodeToRemove); } @@ -1601,11 +1526,11 @@ namespace EMotionFX // collect internal objects - void AnimGraphNode::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphNode::RecursiveCollectObjects(AZStd::vector& outObjects) const { - outObjects.Add(const_cast(this)); + outObjects.emplace_back(const_cast(this)); - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveCollectObjects(outObjects); } @@ -1615,15 +1540,12 @@ namespace EMotionFX // topdown update void AnimGraphNode::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - //if (mDisabled) - //return; - // get the unique data AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); HierarchicalSyncAllInputNodes(animGraphInstance, uniqueData); // top down update all incoming connections - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->GetSourceNode()->PerformTopDownUpdate(animGraphInstance, timePassedInSeconds); } @@ -1644,11 +1566,11 @@ namespace EMotionFX // iterate over all incoming connections bool syncTrackFound = false; - size_t connectionIndex = MCORE_INVALIDINDEX32; - const size_t numConnections = mConnections.size(); + size_t connectionIndex = InvalidIndex; + const size_t numConnections = m_connections.size(); for (size_t i = 0; i < numConnections; ++i) { - const BlendTreeConnection* connection = mConnections[i]; + const BlendTreeConnection* connection = m_connections[i]; AnimGraphNode* sourceNode = connection->GetSourceNode(); // update the node @@ -1662,15 +1584,15 @@ namespace EMotionFX } } - if (connectionIndex != MCORE_INVALIDINDEX32) + if (connectionIndex != InvalidIndex) { - uniqueData->Init(animGraphInstance, mConnections[connectionIndex]->GetSourceNode()); + uniqueData->Init(animGraphInstance, m_connections[connectionIndex]->GetSourceNode()); } // set the current sync track to the first input connection - if (!syncTrackFound && numConnections > 0 && mConnections[0]->GetSourceNode()->GetHasOutputPose()) // just pick the first connection's sync track + if (!syncTrackFound && numConnections > 0 && m_connections[0]->GetSourceNode()->GetHasOutputPose()) // just pick the first connection's sync track { - uniqueData->Init(animGraphInstance, mConnections[0]->GetSourceNode()); + uniqueData->Init(animGraphInstance, m_connections[0]->GetSourceNode()); } } @@ -1678,7 +1600,7 @@ namespace EMotionFX // output all incoming nodes void AnimGraphNode::OutputAllIncomingNodes(AnimGraphInstance* animGraphInstance) { - for (const BlendTreeConnection* connection : mConnections) + for (const BlendTreeConnection* connection : m_connections) { OutputIncomingNode(animGraphInstance, connection->GetSourceNode()); } @@ -1699,7 +1621,7 @@ namespace EMotionFX // update all incoming nodes void AnimGraphNode::UpdateAllIncomingNodes(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - for (const BlendTreeConnection* connection : mConnections) + for (const BlendTreeConnection* connection : m_connections) { AnimGraphNode* sourceNode = connection->GetSourceNode(); sourceNode->PerformUpdate(animGraphInstance, timePassedInSeconds); @@ -1712,7 +1634,7 @@ namespace EMotionFX { if (GetEMotionFX().GetIsInEditorMode()) { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetSourceNode() == sourceNode) { @@ -1737,7 +1659,7 @@ namespace EMotionFX // mark any connection originating from this node as visited if (GetEMotionFX().GetIsInEditorMode()) { - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { if (connection->GetSourceNode() == nodeToOutput) { @@ -1752,12 +1674,12 @@ namespace EMotionFX { // Post process all incoming nodes. bool poseFound = false; - size_t connectionIndex = MCORE_INVALIDINDEX32; + size_t connectionIndex = InvalidIndex; AZ::u16 minTargetPortIndex = MCORE_INVALIDINDEX16; - const size_t numConnections = mConnections.size(); + const size_t numConnections = m_connections.size(); for (size_t i = 0; i < numConnections; ++i) { - const BlendTreeConnection* connection = mConnections[i]; + const BlendTreeConnection* connection = m_connections[i]; AnimGraphNode* sourceNode = connection->GetSourceNode(); // update the node @@ -1771,7 +1693,7 @@ namespace EMotionFX // Find the first connection that plugs into a port that can take a pose. const AZ::u16 targetPortIndex = connection->GetTargetPort(); - if (mInputPorts[targetPortIndex].mCompatibleTypes[0] == AttributePose::TYPE_ID) + if (m_inputPorts[targetPortIndex].m_compatibleTypes[0] == AttributePose::TYPE_ID) { poseFound = true; if (targetPortIndex < minTargetPortIndex) @@ -1786,9 +1708,9 @@ namespace EMotionFX RequestRefDatas(animGraphInstance); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); - if (poseFound && connectionIndex != MCORE_INVALIDINDEX32) + if (poseFound && connectionIndex != InvalidIndex) { - const BlendTreeConnection* connection = mConnections[connectionIndex]; + const BlendTreeConnection* connection = m_connections[connectionIndex]; AnimGraphNode* sourceNode = connection->GetSourceNode(); AnimGraphRefCountedData* data = uniqueData->GetRefCountedData(); @@ -1802,10 +1724,10 @@ namespace EMotionFX } } else - if (poseFound == false && numConnections > 0 && mConnections[0]->GetSourceNode()->GetHasOutputPose()) + if (poseFound == false && numConnections > 0 && m_connections[0]->GetSourceNode()->GetHasOutputPose()) { AnimGraphRefCountedData* data = uniqueData->GetRefCountedData(); - AnimGraphNode* sourceNode = mConnections[0]->GetSourceNode(); + AnimGraphNode* sourceNode = m_connections[0]->GetSourceNode(); AnimGraphRefCountedData* sourceData = sourceNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData(); data->SetEventBuffer(sourceData->GetEventBuffer()); data->SetTrajectoryDelta(sourceData->GetTrajectoryDelta()); @@ -1826,10 +1748,10 @@ namespace EMotionFX void AnimGraphNode::RecursiveSetUniqueDataFlag(AnimGraphInstance* animGraphInstance, uint32 flag, bool enabled) { // set the flag - animGraphInstance->SetObjectFlags(mObjectIndex, flag, enabled); + animGraphInstance->SetObjectFlags(m_objectIndex, flag, enabled); // recurse downwards - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->GetSourceNode()->RecursiveSetUniqueDataFlag(animGraphInstance, flag, enabled); } @@ -1894,8 +1816,8 @@ namespace EMotionFX { AnimGraphRefCountedData* refDataNodeB = nodeB ? nodeB->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData() : nullptr; - const uint32 numEventsA = refDataNodeA ? refDataNodeA->GetEventBuffer().GetNumEvents() : 0; - const uint32 numEventsB = refDataNodeB ? refDataNodeB->GetEventBuffer().GetNumEvents() : 0; + const size_t numEventsA = refDataNodeA ? refDataNodeA->GetEventBuffer().GetNumEvents() : 0; + const size_t numEventsB = refDataNodeB ? refDataNodeB->GetEventBuffer().GetNumEvents() : 0; // resize to the right number of events already AnimGraphEventBuffer& eventBuffer = refData->GetEventBuffer(); @@ -1905,7 +1827,7 @@ namespace EMotionFX if (refDataNodeA) { const AnimGraphEventBuffer& eventBufferA = refDataNodeA->GetEventBuffer(); - for (uint32 i = 0; i < numEventsA; ++i) + for (size_t i = 0; i < numEventsA; ++i) { eventBuffer.SetEvent(i, eventBufferA.GetEvent(i)); } @@ -1914,7 +1836,7 @@ namespace EMotionFX if (refDataNodeB) { const AnimGraphEventBuffer& eventBufferB = refDataNodeB->GetEventBuffer(); - for (uint32 i = 0; i < numEventsB; ++i) + for (size_t i = 0; i < numEventsB; ++i) { eventBuffer.SetEvent(numEventsA + i, eventBufferB.GetEvent(i)); } @@ -1980,7 +1902,7 @@ namespace EMotionFX void AnimGraphNode::HierarchicalSyncAllInputNodes(AnimGraphInstance* animGraphInstance, AnimGraphNodeData* uniqueDataOfThisNode) { // for all connections - for (const BlendTreeConnection* connection : mConnections) + for (const BlendTreeConnection* connection : m_connections) { AnimGraphNode* inputNode = connection->GetSourceNode(); HierarchicalSyncInputNode(animGraphInstance, inputNode, uniqueDataOfThisNode); @@ -1993,14 +1915,14 @@ namespace EMotionFX // check and add this node if (azrtti_typeid(this) == nodeType || nodeType.IsNull()) { - if (animGraphInstance->GetIsOutputReady(mObjectIndex)) // if we processed this node + if (animGraphInstance->GetIsOutputReady(m_objectIndex)) // if we processed this node { outNodes->emplace_back(const_cast(this)); } } // process all child nodes (but only active ones) - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { if (animGraphInstance->GetIsOutputReady(childNode->GetObjectIndex())) { @@ -2015,14 +1937,14 @@ namespace EMotionFX // Check and add this node if (GetNeedsNetTimeSync()) { - if (animGraphInstance->GetIsOutputReady(mObjectIndex)) // if we processed this node + if (animGraphInstance->GetIsOutputReady(m_objectIndex)) // if we processed this node { outNodes->emplace_back(const_cast(this)); } } // Process all child nodes (but only active ones) - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { if (animGraphInstance->GetIsOutputReady(childNode->GetObjectIndex())) { @@ -2034,7 +1956,7 @@ namespace EMotionFX bool AnimGraphNode::RecursiveDetectCycles(AZStd::unordered_set& nodes) const { - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { if (nodes.find(childNode) != nodes.end()) { @@ -2070,12 +1992,12 @@ namespace EMotionFX const uint32 threadIndex = animGraphInstance->GetActorInstance()->GetThreadIndex(); AnimGraphPosePool& posePool = GetEMotionFX().GetThreadData(threadIndex)->GetPosePool(); - const size_t numOutputs = mOutputPorts.size(); + const size_t numOutputs = m_outputPorts.size(); for (size_t i = 0; i < numOutputs; ++i) { - if (mOutputPorts[i].mCompatibleTypes[0] == AttributePose::TYPE_ID) + if (m_outputPorts[i].m_compatibleTypes[0] == AttributePose::TYPE_ID) { - MCore::Attribute* attribute = GetOutputAttribute(animGraphInstance, static_cast(i)); + MCore::Attribute* attribute = GetOutputAttribute(animGraphInstance, i); MCORE_ASSERT(attribute->GetType() == AttributePose::TYPE_ID); AttributePose* poseAttribute = static_cast(attribute); @@ -2098,12 +2020,12 @@ namespace EMotionFX AnimGraphPosePool& posePool = GetEMotionFX().GetThreadData(threadIndex)->GetPosePool(); - const size_t numOutputs = mOutputPorts.size(); + const size_t numOutputs = m_outputPorts.size(); for (size_t i = 0; i < numOutputs; ++i) { - if (mOutputPorts[i].mCompatibleTypes[0] == AttributePose::TYPE_ID) + if (m_outputPorts[i].m_compatibleTypes[0] == AttributePose::TYPE_ID) { - MCore::Attribute* attribute = GetOutputAttribute(animGraphInstance, static_cast(i)); + MCore::Attribute* attribute = GetOutputAttribute(animGraphInstance, i); MCORE_ASSERT(attribute->GetType() == AttributePose::TYPE_ID); AnimGraphPose* pose = posePool.RequestPose(actorInstance); @@ -2117,9 +2039,9 @@ namespace EMotionFX // free all poses from all incoming nodes void AnimGraphNode::FreeIncomingPoses(AnimGraphInstance* animGraphInstance) { - for (const Port& inputPort : mInputPorts) + for (const Port& inputPort : m_inputPorts) { - const BlendTreeConnection* connection = inputPort.mConnection; + const BlendTreeConnection* connection = inputPort.m_connection; if (connection) { AnimGraphNode* sourceNode = connection->GetSourceNode(); @@ -2132,9 +2054,9 @@ namespace EMotionFX // free all poses from all incoming nodes void AnimGraphNode::FreeIncomingRefDatas(AnimGraphInstance* animGraphInstance) { - for (const Port& port : mInputPorts) + for (const Port& port : m_inputPorts) { - const BlendTreeConnection* connection = port.mConnection; + const BlendTreeConnection* connection = port.m_connection; if (connection) { AnimGraphNode* sourceNode = connection->GetSourceNode(); @@ -2187,13 +2109,13 @@ namespace EMotionFX void AnimGraphNode::PerformTopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // check if we already did update - if (animGraphInstance->GetIsTopDownUpdateReady(mObjectIndex)) + if (animGraphInstance->GetIsTopDownUpdateReady(m_objectIndex)) { return; } // mark as done - animGraphInstance->EnableObjectFlags(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_TOPDOWNUPDATE_READY); + animGraphInstance->EnableObjectFlags(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_TOPDOWNUPDATE_READY); TopDownUpdate(animGraphInstance, timePassedInSeconds); } @@ -2203,13 +2125,13 @@ namespace EMotionFX void AnimGraphNode::PerformPostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // check if we already did update - if (animGraphInstance->GetIsPostUpdateReady(mObjectIndex)) + if (animGraphInstance->GetIsPostUpdateReady(m_objectIndex)) { return; } // mark as done - animGraphInstance->EnableObjectFlags(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_POSTUPDATE_READY); + animGraphInstance->EnableObjectFlags(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_POSTUPDATE_READY); // perform the actual post update PostUpdate(animGraphInstance, timePassedInSeconds); @@ -2223,13 +2145,13 @@ namespace EMotionFX void AnimGraphNode::PerformUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // check if we already did update - if (animGraphInstance->GetIsUpdateReady(mObjectIndex)) + if (animGraphInstance->GetIsUpdateReady(m_objectIndex)) { return; } // mark as done - animGraphInstance->EnableObjectFlags(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_UPDATE_READY); + animGraphInstance->EnableObjectFlags(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_UPDATE_READY); // increase ref count for incoming nodes IncreaseInputRefCounts(animGraphInstance); @@ -2244,13 +2166,13 @@ namespace EMotionFX void AnimGraphNode::PerformOutput(AnimGraphInstance* animGraphInstance) { // check if we already did output - if (animGraphInstance->GetIsOutputReady(mObjectIndex)) + if (animGraphInstance->GetIsOutputReady(m_objectIndex)) { return; } // mark as done - animGraphInstance->EnableObjectFlags(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_OUTPUT_READY); + animGraphInstance->EnableObjectFlags(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_OUTPUT_READY); // perform the output Output(animGraphInstance); @@ -2264,9 +2186,9 @@ namespace EMotionFX // increase input ref counts void AnimGraphNode::IncreaseInputRefDataRefCounts(AnimGraphInstance* animGraphInstance) { - for (const Port& port : mInputPorts) + for (const Port& port : m_inputPorts) { - const BlendTreeConnection* connection = port.mConnection; + const BlendTreeConnection* connection = port.m_connection; if (connection) { AnimGraphNode* sourceNode = connection->GetSourceNode(); @@ -2279,9 +2201,9 @@ namespace EMotionFX // increase input ref counts void AnimGraphNode::IncreaseInputRefCounts(AnimGraphInstance* animGraphInstance) { - for (const Port& port : mInputPorts) + for (const Port& port : m_inputPorts) { - const BlendTreeConnection* connection = port.mConnection; + const BlendTreeConnection* connection = port.m_connection; if (connection) { AnimGraphNode* sourceNode = connection->GetSourceNode(); @@ -2294,7 +2216,7 @@ namespace EMotionFX void AnimGraphNode::RelinkPortConnections() { // After deserializing, nodes hold an array of incoming connections. Each node port caches a pointer to its connection object which we need to link. - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { AnimGraphNode* sourceNode = connection->GetSourceNode(); const AZ::u16 targetPortNr = connection->GetTargetPort(); @@ -2302,9 +2224,9 @@ namespace EMotionFX if (sourceNode) { - if (sourcePortNr < sourceNode->mOutputPorts.size()) + if (sourcePortNr < sourceNode->m_outputPorts.size()) { - sourceNode->GetOutputPort(sourcePortNr).mConnection = connection; + sourceNode->GetOutputPort(sourcePortNr).m_connection = connection; } else { @@ -2312,9 +2234,9 @@ namespace EMotionFX } } - if (targetPortNr < mInputPorts.size()) + if (targetPortNr < m_inputPorts.size()) { - mInputPorts[targetPortNr].mConnection = connection; + m_inputPorts[targetPortNr].m_connection = connection; } else { @@ -2327,7 +2249,7 @@ namespace EMotionFX // do we have a child of a given type? bool AnimGraphNode::CheckIfHasChildOfType(const AZ::TypeId& nodeType) const { - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { if (azrtti_typeid(childNode) == nodeType) { @@ -2342,7 +2264,7 @@ namespace EMotionFX // check if we can visualize bool AnimGraphNode::GetCanVisualize(AnimGraphInstance* animGraphInstance) const { - return (mVisEnabled && animGraphInstance->GetVisualizationEnabled() && EMotionFX::GetRecorder().GetIsInPlayMode() == false); + return (m_visEnabled && animGraphInstance->GetVisualizationEnabled() && EMotionFX::GetRecorder().GetIsInPlayMode() == false); } @@ -2350,33 +2272,33 @@ namespace EMotionFX void AnimGraphNode::RemoveInternalAttributesForAllInstances() { // for all output ports - for (Port& port : mOutputPorts) + for (Port& port : m_outputPorts) { - const uint32 internalAttributeIndex = port.mAttributeIndex; - if (internalAttributeIndex != MCORE_INVALIDINDEX32) + const size_t internalAttributeIndex = port.m_attributeIndex; + if (internalAttributeIndex != InvalidIndex) { - const size_t numInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); animGraphInstance->RemoveInternalAttribute(internalAttributeIndex); } - mAnimGraph->DecreaseInternalAttributeIndices(internalAttributeIndex); - port.mAttributeIndex = MCORE_INVALIDINDEX32; + m_animGraph->DecreaseInternalAttributeIndices(internalAttributeIndex); + port.m_attributeIndex = InvalidIndex; } } } // decrease values higher than a given param value - void AnimGraphNode::DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan) + void AnimGraphNode::DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) { - for (Port& port : mOutputPorts) + for (Port& port : m_outputPorts) { - if (port.mAttributeIndex > decreaseEverythingHigherThan && port.mAttributeIndex != MCORE_INVALIDINDEX32) + if (port.m_attributeIndex > decreaseEverythingHigherThan && port.m_attributeIndex != InvalidIndex) { - port.mAttributeIndex--; + port.m_attributeIndex--; } } } @@ -2386,31 +2308,31 @@ namespace EMotionFX void AnimGraphNode::InitInternalAttributes(AnimGraphInstance* animGraphInstance) { // for all output ports of this node - for (Port& port : mOutputPorts) + for (Port& port : m_outputPorts) { - MCore::Attribute* newAttribute = MCore::GetAttributeFactory().CreateAttributeByType(port.mCompatibleTypes[0]); // assume compatibility type 0 to be the attribute type ID - port.mAttributeIndex = animGraphInstance->AddInternalAttribute(newAttribute); + MCore::Attribute* newAttribute = MCore::GetAttributeFactory().CreateAttributeByType(port.m_compatibleTypes[0]); // assume compatibility type 0 to be the attribute type ID + port.m_attributeIndex = animGraphInstance->AddInternalAttribute(newAttribute); } } void* AnimGraphNode::GetCustomData() const { - return mCustomData; + return m_customData; } void AnimGraphNode::SetCustomData(void* dataPointer) { - mCustomData = dataPointer; + m_customData = dataPointer; } void AnimGraphNode::SetNodeInfo(const AZStd::string& info) { - if (mNodeInfo != info) + if (m_nodeInfo != info) { - mNodeInfo = info; + m_nodeInfo = info; SyncVisualObject(); } @@ -2419,88 +2341,88 @@ namespace EMotionFX const AZStd::string& AnimGraphNode::GetNodeInfo() const { - return mNodeInfo; + return m_nodeInfo; } bool AnimGraphNode::GetIsEnabled() const { - return (mDisabled == false); + return (m_disabled == false); } void AnimGraphNode::SetIsEnabled(bool enabled) { - mDisabled = !enabled; + m_disabled = !enabled; } bool AnimGraphNode::GetIsCollapsed() const { - return mIsCollapsed; + return m_isCollapsed; } void AnimGraphNode::SetIsCollapsed(bool collapsed) { - mIsCollapsed = collapsed; + m_isCollapsed = collapsed; } void AnimGraphNode::SetVisualizeColor(const AZ::Color& color) { - mVisualizeColor = color; + m_visualizeColor = color; SyncVisualObject(); } const AZ::Color& AnimGraphNode::GetVisualizeColor() const { - return mVisualizeColor; + return m_visualizeColor; } void AnimGraphNode::SetVisualPos(int32 x, int32 y) { - mPosX = x; - mPosY = y; + m_posX = x; + m_posY = y; } int32 AnimGraphNode::GetVisualPosX() const { - return mPosX; + return m_posX; } int32 AnimGraphNode::GetVisualPosY() const { - return mPosY; + return m_posY; } bool AnimGraphNode::GetIsVisualizationEnabled() const { - return mVisEnabled; + return m_visEnabled; } void AnimGraphNode::SetVisualization(bool enabled) { - mVisEnabled = enabled; + m_visEnabled = enabled; } void AnimGraphNode::AddChildNode(AnimGraphNode* node) { - mChildNodes.push_back(node); + m_childNodes.push_back(node); node->SetParentNode(this); } - void AnimGraphNode::ReserveChildNodes(uint32 numChildNodes) + void AnimGraphNode::ReserveChildNodes(size_t numChildNodes) { - mChildNodes.reserve(numChildNodes); + m_childNodes.reserve(numChildNodes); } @@ -2523,7 +2445,7 @@ namespace EMotionFX void AnimGraphNode::ResetPoseRefCount(AnimGraphInstance* animGraphInstance) { - AnimGraphNodeData* uniqueData = reinterpret_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + AnimGraphNodeData* uniqueData = reinterpret_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData) { uniqueData->SetPoseRefCount(0); @@ -2532,7 +2454,7 @@ namespace EMotionFX void AnimGraphNode::ResetRefDataRefCount(AnimGraphInstance* animGraphInstance) { - AnimGraphNodeData* uniqueData = reinterpret_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + AnimGraphNodeData* uniqueData = reinterpret_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData) { uniqueData->SetRefDataRefCount(0); @@ -2589,14 +2511,14 @@ namespace EMotionFX ->PersistentId([](const void* instance) -> AZ::u64 { return static_cast(instance)->GetId(); }) ->Field("id", &AnimGraphNode::m_id) ->Field("name", &AnimGraphNode::m_name) - ->Field("posX", &AnimGraphNode::mPosX) - ->Field("posY", &AnimGraphNode::mPosY) - ->Field("visualizeColor", &AnimGraphNode::mVisualizeColor) - ->Field("isDisabled", &AnimGraphNode::mDisabled) - ->Field("isCollapsed", &AnimGraphNode::mIsCollapsed) - ->Field("isVisEnabled", &AnimGraphNode::mVisEnabled) - ->Field("childNodes", &AnimGraphNode::mChildNodes) - ->Field("connections", &AnimGraphNode::mConnections) + ->Field("posX", &AnimGraphNode::m_posX) + ->Field("posY", &AnimGraphNode::m_posY) + ->Field("visualizeColor", &AnimGraphNode::m_visualizeColor) + ->Field("isDisabled", &AnimGraphNode::m_disabled) + ->Field("isCollapsed", &AnimGraphNode::m_isCollapsed) + ->Field("isVisEnabled", &AnimGraphNode::m_visEnabled) + ->Field("childNodes", &AnimGraphNode::m_childNodes) + ->Field("connections", &AnimGraphNode::m_connections) ->Field("actionSetup", &AnimGraphNode::m_actionSetup); ; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h index c469631335..b515621c5b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNode.h @@ -56,63 +56,63 @@ namespace EMotionFX AZ_RTTI(AnimGraphNode::Port, "{F66CF090-468F-419A-9518-97988304FEB6}") AZ_CLASS_ALLOCATOR_DECL - BlendTreeConnection* mConnection; // the connection plugged in this port - uint32 mCompatibleTypes[4]; // four possible compatible types - uint32 mPortID; // the unique port ID (unique inside the node input or output port lists) - uint32 mNameID; // the name of the port (using the StringIdPool) - uint32 mAttributeIndex; // the index into the animgraph instance global attributes array + BlendTreeConnection* m_connection; // the connection plugged in this port + uint32 m_compatibleTypes[4]; // four possible compatible types + uint32 m_portId; // the unique port ID (unique inside the node input or output port lists) + uint32 m_nameId; // the name of the port (using the StringIdPool) + size_t m_attributeIndex; // the index into the animgraph instance global attributes array - MCORE_INLINE const char* GetName() const { return MCore::GetStringIdPool().GetName(mNameID).c_str(); } - MCORE_INLINE const AZStd::string& GetNameString() const { return MCore::GetStringIdPool().GetName(mNameID); } + MCORE_INLINE const char* GetName() const { return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } + MCORE_INLINE const AZStd::string& GetNameString() const { return MCore::GetStringIdPool().GetName(m_nameId); } - // copy settings from another port (always makes the mConnection and mValue nullptr though) + // copy settings from another port (always makes the m_connection and m_value nullptr though) void InitFrom(const Port& other) { for (uint32 i = 0; i < 4; ++i) { - mCompatibleTypes[i] = other.mCompatibleTypes[i]; + m_compatibleTypes[i] = other.m_compatibleTypes[i]; } - mPortID = other.mPortID; - mNameID = other.mNameID; - mConnection = nullptr; - mAttributeIndex = other.mAttributeIndex; + m_portId = other.m_portId; + m_nameId = other.m_nameId; + m_connection = nullptr; + m_attributeIndex = other.m_attributeIndex; } void SetCompatibleTypes(const AZStd::vector& compatibleTypes) { for (uint32 i = 0; i < 4 && i < compatibleTypes.size(); ++i) { - mCompatibleTypes[i] = compatibleTypes[i]; + m_compatibleTypes[i] = compatibleTypes[i]; } } // get the attribute value MCORE_INLINE MCore::Attribute* GetAttribute(AnimGraphInstance* animGraphInstance) const { - return animGraphInstance->GetInternalAttribute(mAttributeIndex); + return animGraphInstance->GetInternalAttribute(m_attributeIndex); } // port connection compatibility check bool CheckIfIsCompatibleWith(const Port& otherPort) const { // check the data types - for (uint32 myCompatibleTypeindex = 0; myCompatibleTypeindex < 4; ++myCompatibleTypeindex) + for (uint32 compatibleType : m_compatibleTypes) { // If there aren't any more compatibility types and we haven't found a compatible one so far, return false - if (mCompatibleTypes[myCompatibleTypeindex] == 0) + if (compatibleType == 0) { return false; } - for (uint32 otherCompatibleTypeIndex = 0; otherCompatibleTypeIndex < 4; ++otherCompatibleTypeIndex) + for (uint32 otherCompatibleTypeIndex : otherPort.m_compatibleTypes) { - if (otherPort.mCompatibleTypes[otherCompatibleTypeIndex] == mCompatibleTypes[myCompatibleTypeindex]) + if (otherCompatibleTypeIndex == compatibleType) { return true; } // If there aren't any more compatibility types and we haven't found a compatible one so far, return false - if (otherPort.mCompatibleTypes[otherCompatibleTypeIndex] == 0) + if (otherCompatibleTypeIndex == 0) { break; } @@ -126,10 +126,10 @@ namespace EMotionFX // clear compatibility types void ClearCompatibleTypes() { - mCompatibleTypes[0] = 0; - mCompatibleTypes[1] = 0; - mCompatibleTypes[2] = 0; - mCompatibleTypes[3] = 0; + m_compatibleTypes[0] = 0; + m_compatibleTypes[1] = 0; + m_compatibleTypes[2] = 0; + m_compatibleTypes[3] = 0; } void Clear() @@ -138,10 +138,10 @@ namespace EMotionFX } Port() - : mConnection(nullptr) - , mPortID(MCORE_INVALIDINDEX32) - , mNameID(MCORE_INVALIDINDEX32) - , mAttributeIndex(MCORE_INVALIDINDEX32) { ClearCompatibleTypes(); } + : m_connection(nullptr) + , m_portId(MCORE_INVALIDINDEX32) + , m_nameId(MCORE_INVALIDINDEX32) + , m_attributeIndex(InvalidIndex) { ClearCompatibleTypes(); } virtual ~Port() { } }; @@ -173,7 +173,7 @@ namespace EMotionFX void InitInternalAttributes(AnimGraphInstance* animGraphInstance) override; void RemoveInternalAttributesForAllInstances() override; - void DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan) override; + void DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) override; void OutputAllIncomingNodes(AnimGraphInstance* animGraphInstance); void UpdateAllIncomingNodes(AnimGraphInstance* animGraphInstance, float timePassedInSeconds); @@ -217,8 +217,8 @@ namespace EMotionFX virtual void SetCurrentPlayTime(AnimGraphInstance* animGraphInstance, float timeInSeconds) { FindOrCreateUniqueNodeData(animGraphInstance)->SetCurrentPlayTime(timeInSeconds); } virtual float GetCurrentPlayTime(AnimGraphInstance* animGraphInstance) const { return FindOrCreateUniqueNodeData(animGraphInstance)->GetCurrentPlayTime(); } - MCORE_INLINE uint32 GetSyncIndex(AnimGraphInstance* animGraphInstance) const { return FindOrCreateUniqueNodeData(animGraphInstance)->GetSyncIndex(); } - MCORE_INLINE void SetSyncIndex(AnimGraphInstance* animGraphInstance, uint32 syncIndex) { FindOrCreateUniqueNodeData(animGraphInstance)->SetSyncIndex(syncIndex); } + MCORE_INLINE size_t GetSyncIndex(AnimGraphInstance* animGraphInstance) const { return FindOrCreateUniqueNodeData(animGraphInstance)->GetSyncIndex(); } + MCORE_INLINE void SetSyncIndex(AnimGraphInstance* animGraphInstance, size_t syncIndex) { FindOrCreateUniqueNodeData(animGraphInstance)->SetSyncIndex(syncIndex); } virtual void SetPlaySpeed(AnimGraphInstance* animGraphInstance, float speedFactor) { FindOrCreateUniqueNodeData(animGraphInstance)->SetPlaySpeed(speedFactor); } virtual float GetPlaySpeed(AnimGraphInstance* animGraphInstance) const { return FindOrCreateUniqueNodeData(animGraphInstance)->GetPlaySpeed(); } @@ -235,8 +235,8 @@ namespace EMotionFX void HierarchicalSyncAllInputNodes(AnimGraphInstance* animGraphInstance, AnimGraphNodeData* uniqueDataOfThisNode); static void CalcSyncFactors(AnimGraphInstance* animGraphInstance, const AnimGraphNode* leaderNode, const AnimGraphNode* followerNode, ESyncMode syncMode, float weight, float* outLeaderFactor, float* outFollowerFactor, float* outPlaySpeed); - static void CalcSyncFactors(float leaderPlaySpeed, const AnimGraphSyncTrack* leaderSyncTrack, uint32 leaderSyncTrackIndex, float leaderDuration, - float followerPlaySpeed, const AnimGraphSyncTrack* followerSyncTrack, uint32 followerSyncTrackIndex, float followerDuration, + static void CalcSyncFactors(float leaderPlaySpeed, const AnimGraphSyncTrack* leaderSyncTrack, size_t leaderSyncTrackIndex, float leaderDuration, + float followerPlaySpeed, const AnimGraphSyncTrack* followerSyncTrack, size_t followerSyncTrackIndex, float followerDuration, ESyncMode syncMode, float weight, float* outLeaderFactor, float* outFollowerFactor, float* outPlaySpeed); void RequestPoses(AnimGraphInstance* animGraphInstance); @@ -270,7 +270,7 @@ namespace EMotionFX virtual bool RecursiveDetectCycles(AZStd::unordered_set& nodes) const; - void CollectChildNodesOfType(const AZ::TypeId& nodeType, MCore::Array* outNodes) const; // note: outNodes is NOT cleared internally, nodes are added to the array + void CollectChildNodesOfType(const AZ::TypeId& nodeType, AZStd::vector* outNodes) const; // note: outNodes is NOT cleared internally, nodes are added to the array /** * Collect child nodes of the given type. This will only iterate through the child nodes and isn't a recursive process. @@ -280,7 +280,7 @@ namespace EMotionFX void CollectChildNodesOfType(const AZ::TypeId& nodeType, AZStd::vector& outNodes) const; void RecursiveCollectNodesOfType(const AZ::TypeId& nodeType, AZStd::vector* outNodes) const; // note: outNodes is NOT cleared internally, nodes are added to the array - void RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, MCore::Array* outConditions) const; // note: outNodes is NOT cleared internally, nodes are added to the array + void RecursiveCollectTransitionConditionsOfType(const AZ::TypeId& conditionType, AZStd::vector* outConditions) const; // note: outNodes is NOT cleared internally, nodes are added to the array virtual void RecursiveCollectObjectsOfType(const AZ::TypeId& objectType, AZStd::vector& outObjects) const; @@ -315,10 +315,10 @@ namespace EMotionFX MCORE_INLINE AnimGraphNodeId GetId() const { return m_id; } void SetId(AnimGraphNodeId id) { m_id = id; } - const MCore::Attribute* GetInputValue(AnimGraphInstance* instance, uint32 inputPort) const; + const MCore::Attribute* GetInputValue(AnimGraphInstance* instance, size_t inputPort) const; - uint32 FindInputPortByID(uint32 portID) const; - uint32 FindOutputPortByID(uint32 portID) const; + size_t FindInputPortByID(uint32 portID) const; + size_t FindOutputPortByID(uint32 portID) const; Port* FindInputPortByName(const AZStd::string& portName); Port* FindOutputPortByName(const AZStd::string& portName); @@ -360,9 +360,9 @@ namespace EMotionFX * node of the outgoing connection. The BlendTreeConnection itself contains the pointer to the source node. The * vector will be cleared upfront. */ - void CollectOutgoingConnections(AZStd::vector>& outConnections, const uint32 portIndex) const; + void CollectOutgoingConnections(AZStd::vector>& outConnections, const size_t portIndex) const; - MCORE_INLINE bool GetInputNumberAsBool(AnimGraphInstance* animGraphInstance, uint32 inputPortNr) const + MCORE_INLINE bool GetInputNumberAsBool(AnimGraphInstance* animGraphInstance, size_t inputPortNr) const { const MCore::Attribute* attribute = GetInputAttribute(animGraphInstance, inputPortNr); if (attribute == nullptr) @@ -383,7 +383,7 @@ namespace EMotionFX return false; } - MCORE_INLINE float GetInputNumberAsFloat(AnimGraphInstance* animGraphInstance, uint32 inputPortNr) const + MCORE_INLINE float GetInputNumberAsFloat(AnimGraphInstance* animGraphInstance, size_t inputPortNr) const { const MCore::Attribute* attribute = GetInputAttribute(animGraphInstance, inputPortNr); if (attribute == nullptr) @@ -404,7 +404,7 @@ namespace EMotionFX return 0.0f; } - MCORE_INLINE int32 GetInputNumberAsInt32(AnimGraphInstance* animGraphInstance, uint32 inputPortNr) const + MCORE_INLINE int32 GetInputNumberAsInt32(AnimGraphInstance* animGraphInstance, size_t inputPortNr) const { const MCore::Attribute* attribute = GetInputAttribute(animGraphInstance, inputPortNr); if (attribute == nullptr) @@ -425,7 +425,7 @@ namespace EMotionFX return 0; } - MCORE_INLINE uint32 GetInputNumberAsUint32(AnimGraphInstance* animGraphInstance, uint32 inputPortNr) const + MCORE_INLINE uint32 GetInputNumberAsUint32(AnimGraphInstance* animGraphInstance, size_t inputPortNr) const { const MCore::Attribute* attribute = GetInputAttribute(animGraphInstance, inputPortNr); if (attribute == nullptr) @@ -446,9 +446,9 @@ namespace EMotionFX return 0; } - MCORE_INLINE AnimGraphNode* GetInputNode(uint32 portNr) + MCORE_INLINE AnimGraphNode* GetInputNode(size_t portNr) { - const BlendTreeConnection* con = mInputPorts[portNr].mConnection; + const BlendTreeConnection* con = m_inputPorts[portNr].m_connection; if (con == nullptr) { return nullptr; @@ -456,9 +456,9 @@ namespace EMotionFX return con->GetSourceNode(); } - MCORE_INLINE MCore::Attribute* GetInputAttribute(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::Attribute* GetInputAttribute(AnimGraphInstance* animGraphInstance, size_t portNr) const { - const BlendTreeConnection* con = mInputPorts[portNr].mConnection; + const BlendTreeConnection* con = m_inputPorts[portNr].m_connection; if (con == nullptr) { return nullptr; @@ -466,7 +466,7 @@ namespace EMotionFX return con->GetSourceNode()->GetOutputValue(animGraphInstance, con->GetSourcePort()); } - MCORE_INLINE MCore::AttributeFloat* GetInputFloat(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::AttributeFloat* GetInputFloat(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -477,7 +477,7 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE MCore::AttributeInt32* GetInputInt32(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::AttributeInt32* GetInputInt32(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -488,7 +488,7 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE MCore::AttributeString* GetInputString(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::AttributeString* GetInputString(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -499,7 +499,7 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE MCore::AttributeBool* GetInputBool(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::AttributeBool* GetInputBool(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -510,7 +510,7 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE bool TryGetInputVector4(AnimGraphInstance* animGraphInstance, uint32 portNr, AZ::Vector4& outResult) const + MCORE_INLINE bool TryGetInputVector4(AnimGraphInstance* animGraphInstance, size_t portNr, AZ::Vector4& outResult) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -540,7 +540,7 @@ namespace EMotionFX return false; } - MCORE_INLINE bool TryGetInputVector2(AnimGraphInstance* animGraphInstance, uint32 portNr, AZ::Vector2& outResult) const + MCORE_INLINE bool TryGetInputVector2(AnimGraphInstance* animGraphInstance, size_t portNr, AZ::Vector2& outResult) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -568,7 +568,7 @@ namespace EMotionFX return false; } - MCORE_INLINE bool TryGetInputVector3(AnimGraphInstance* animGraphInstance, uint32 portNr, AZ::Vector3& outResult) const + MCORE_INLINE bool TryGetInputVector3(AnimGraphInstance* animGraphInstance, size_t portNr, AZ::Vector3& outResult) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -606,7 +606,7 @@ namespace EMotionFX return false; } - MCORE_INLINE MCore::AttributeQuaternion* GetInputQuaternion(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::AttributeQuaternion* GetInputQuaternion(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -617,7 +617,7 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE MCore::AttributeColor* GetInputColor(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE MCore::AttributeColor* GetInputColor(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -627,7 +627,7 @@ namespace EMotionFX MCORE_ASSERT(attrib->GetType() == MCore::AttributeColor::TYPE_ID); return static_cast(attrib); } - MCORE_INLINE AttributeMotionInstance* GetInputMotionInstance(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE AttributeMotionInstance* GetInputMotionInstance(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -637,7 +637,7 @@ namespace EMotionFX MCORE_ASSERT(attrib->GetType() == AttributeMotionInstance::TYPE_ID); return static_cast(attrib); } - MCORE_INLINE AttributePose* GetInputPose(AnimGraphInstance* animGraphInstance, uint32 portNr) const + MCORE_INLINE AttributePose* GetInputPose(AnimGraphInstance* animGraphInstance, size_t portNr) const { MCore::Attribute* attrib = GetInputAttribute(animGraphInstance, portNr); if (attrib == nullptr) @@ -648,128 +648,128 @@ namespace EMotionFX return static_cast(attrib); } - MCORE_INLINE MCore::Attribute* GetOutputAttribute(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const { return mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance); } - MCORE_INLINE MCore::AttributeFloat* GetOutputNumber(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::Attribute* GetOutputAttribute(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { return m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance); } + MCORE_INLINE MCore::AttributeFloat* GetOutputNumber(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeFloat::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeFloat::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeFloat* GetOutputFloat(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeFloat* GetOutputFloat(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeFloat::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeFloat::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeInt32* GetOutputInt32(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeInt32* GetOutputInt32(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeInt32::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeInt32::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeString* GetOutputString(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeString* GetOutputString(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeString::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeString::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeBool* GetOutputBool(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeBool* GetOutputBool(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeBool::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeBool::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeVector2* GetOutputVector2(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeVector2* GetOutputVector2(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeVector2::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeVector2::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeVector3* GetOutputVector3(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeVector3* GetOutputVector3(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeVector3::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeVector3::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeVector4* GetOutputVector4(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeVector4* GetOutputVector4(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeVector4::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeVector4::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeQuaternion* GetOutputQuaternion(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeQuaternion* GetOutputQuaternion(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeQuaternion::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeQuaternion::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE MCore::AttributeColor* GetOutputColor(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE MCore::AttributeColor* GetOutputColor(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == MCore::AttributeColor::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == MCore::AttributeColor::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE AttributePose* GetOutputPose(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE AttributePose* GetOutputPose(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == AttributePose::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == AttributePose::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - MCORE_INLINE AttributeMotionInstance* GetOutputMotionInstance(AnimGraphInstance* animGraphInstance, uint32 outputPortIndex) const + MCORE_INLINE AttributeMotionInstance* GetOutputMotionInstance(AnimGraphInstance* animGraphInstance, size_t outputPortIndex) const { - if (mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) + if (m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance) == nullptr) { return nullptr; } - MCORE_ASSERT(mOutputPorts[outputPortIndex].mCompatibleTypes[0] == AttributeMotionInstance::TYPE_ID); - return static_cast(mOutputPorts[outputPortIndex].GetAttribute(animGraphInstance)); + MCORE_ASSERT(m_outputPorts[outputPortIndex].m_compatibleTypes[0] == AttributeMotionInstance::TYPE_ID); + return static_cast(m_outputPorts[outputPortIndex].GetAttribute(animGraphInstance)); } - void SetupInputPortAsNumber(const char* name, uint32 inputPortNr, uint32 portID); - void SetupInputPortAsBool(const char* name, uint32 inputPortNr, uint32 portID); - void SetupInputPort(const char* name, uint32 inputPortNr, uint32 attributeTypeID, uint32 portID); + void SetupInputPortAsNumber(const char* name, size_t inputPortNr, uint32 portID); + void SetupInputPortAsBool(const char* name, size_t inputPortNr, uint32 portID); + void SetupInputPort(const char* name, size_t inputPortNr, uint32 attributeTypeID, uint32 portID); - void SetupInputPortAsVector3(const char* name, uint32 inputPortNr, uint32 portID); - void SetupInputPortAsVector2(const char* name, uint32 inputPortNr, uint32 portID); - void SetupInputPortAsVector4(const char* name, uint32 inputPortNr, uint32 portID); - void SetupInputPort(const char* name, uint32 inputPortNr, const AZStd::vector& attributeTypeIDs, uint32 portID); + void SetupInputPortAsVector3(const char* name, size_t inputPortNr, uint32 portID); + void SetupInputPortAsVector2(const char* name, size_t inputPortNr, uint32 portID); + void SetupInputPortAsVector4(const char* name, size_t inputPortNr, uint32 portID); + void SetupInputPort(const char* name, size_t inputPortNr, const AZStd::vector& attributeTypeIDs, uint32 portID); - void SetupOutputPort(const char* name, uint32 portIndex, uint32 attributeTypeID, uint32 portID); - void SetupOutputPortAsPose(const char* name, uint32 outputPortNr, uint32 portID); - void SetupOutputPortAsMotionInstance(const char* name, uint32 outputPortNr, uint32 portID); + void SetupOutputPort(const char* name, size_t portIndex, uint32 attributeTypeID, uint32 portID); + void SetupOutputPortAsPose(const char* name, size_t outputPortNr, uint32 portID); + void SetupOutputPortAsMotionInstance(const char* name, size_t outputPortNr, uint32 portID); bool GetHasConnection(AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) const; BlendTreeConnection* FindConnection(const AnimGraphNode* sourceNode, uint16 sourcePort, uint16 targetPort) const; @@ -797,39 +797,39 @@ namespace EMotionFX virtual void RecursiveResetFlags(AnimGraphInstance* animGraphInstance, uint32 flagsToReset = 0xffffffff); - const AZStd::vector& GetInputPorts() const { return mInputPorts; } - const AZStd::vector& GetOutputPorts() const { return mOutputPorts; } - void SetInputPorts(const AZStd::vector& inputPorts) { mInputPorts = inputPorts; } - void SetOutputPorts(const AZStd::vector& outputPorts) { mOutputPorts = outputPorts; } - void InitInputPorts(uint32 numPorts); - void InitOutputPorts(uint32 numPorts); - void SetInputPortName(uint32 portIndex, const char* name); - void SetOutputPortName(uint32 portIndex, const char* name); - uint32 FindOutputPortIndex(const AZStd::string& name) const; - uint32 FindInputPortIndex(const AZStd::string& name) const; - uint32 AddOutputPort(); - uint32 AddInputPort(); + const AZStd::vector& GetInputPorts() const { return m_inputPorts; } + const AZStd::vector& GetOutputPorts() const { return m_outputPorts; } + void SetInputPorts(const AZStd::vector& inputPorts) { m_inputPorts = inputPorts; } + void SetOutputPorts(const AZStd::vector& outputPorts) { m_outputPorts = outputPorts; } + void InitInputPorts(size_t numPorts); + void InitOutputPorts(size_t numPorts); + void SetInputPortName(size_t portIndex, const char* name); + void SetOutputPortName(size_t portIndex, const char* name); + size_t FindOutputPortIndex(const AZStd::string& name) const; + size_t FindInputPortIndex(const AZStd::string& name) const; + size_t AddOutputPort(); + size_t AddInputPort(); virtual bool GetIsStateTransitionNode() const { return false; } - MCORE_INLINE MCore::Attribute* GetOutputValue(AnimGraphInstance* animGraphInstance, uint32 portIndex) const { return animGraphInstance->GetInternalAttribute(mOutputPorts[portIndex].mAttributeIndex); } - MCORE_INLINE Port& GetInputPort(uint32 index) { return mInputPorts[index]; } - MCORE_INLINE Port& GetOutputPort(uint32 index) { return mOutputPorts[index]; } - MCORE_INLINE const Port& GetInputPort(uint32 index) const { return mInputPorts[index]; } - MCORE_INLINE const Port& GetOutputPort(uint32 index) const { return mOutputPorts[index]; } + MCORE_INLINE MCore::Attribute* GetOutputValue(AnimGraphInstance* animGraphInstance, size_t portIndex) const { return animGraphInstance->GetInternalAttribute(m_outputPorts[portIndex].m_attributeIndex); } + MCORE_INLINE Port& GetInputPort(size_t index) { return m_inputPorts[index]; } + MCORE_INLINE Port& GetOutputPort(size_t index) { return m_outputPorts[index]; } + MCORE_INLINE const Port& GetInputPort(size_t index) const { return m_inputPorts[index]; } + MCORE_INLINE const Port& GetOutputPort(size_t index) const { return m_outputPorts[index]; } void RelinkPortConnections(); - MCORE_INLINE uint32 GetNumConnections() const { return static_cast(mConnections.size()); } - MCORE_INLINE BlendTreeConnection* GetConnection(uint32 index) const { return mConnections[index]; } - const AZStd::vector& GetConnections() const { return mConnections; } + MCORE_INLINE size_t GetNumConnections() const { return m_connections.size(); } + MCORE_INLINE BlendTreeConnection* GetConnection(size_t index) const { return m_connections[index]; } + const AZStd::vector& GetConnections() const { return m_connections; } - AZ_FORCE_INLINE AnimGraphNode* GetParentNode() const { return mParentNode; } - AZ_FORCE_INLINE void SetParentNode(AnimGraphNode* node) { mParentNode = node; } + AZ_FORCE_INLINE AnimGraphNode* GetParentNode() const { return m_parentNode; } + AZ_FORCE_INLINE void SetParentNode(AnimGraphNode* node) { m_parentNode = node; } /** * Check if the given node is the parent or the parent of the parent etc. of the node. * @param[in] node The parent node we try to search. * @result True in case the given node is the parent or the parent of the parent etc. of the node, false in case the given node wasn't found in any of the parents. */ - virtual bool RecursiveIsParentNode(AnimGraphNode* node) const; + virtual bool RecursiveIsParentNode(const AnimGraphNode* node) const; /** * Check if the given node is a child or a child of a child etc. of the node. @@ -857,14 +857,14 @@ namespace EMotionFX * @param[in] name The name of the node to search. * @return The index of the child node with the given name in case of success, in the other case MCORE_INVALIDINDEX32 will be returned. */ - uint32 FindChildNodeIndex(const char* name) const; + size_t FindChildNodeIndex(const char* name) const; /** * Find child node index. This will only iterate through the child nodes and isn't a recursive process. * @param[in] node A pointer to the node for which we want to find the child node index. * @return The index of the child node in case of success, in the other case MCORE_INVALIDINDEX32 will be returned. */ - uint32 FindChildNodeIndex(AnimGraphNode* node) const; + size_t FindChildNodeIndex(AnimGraphNode* node) const; AnimGraphNode* FindFirstChildNodeOfType(const AZ::TypeId& nodeType) const; @@ -875,22 +875,22 @@ namespace EMotionFX */ bool HasChildNodeOfType(const AZ::TypeId& nodeType) const; - uint32 RecursiveCalcNumNodes() const; - uint32 RecursiveCalcNumNodeConnections() const; + size_t RecursiveCalcNumNodes() const; + size_t RecursiveCalcNumNodeConnections() const; void CopyBaseNodeTo(AnimGraphNode* node) const; - MCORE_INLINE uint32 GetNumChildNodes() const { return static_cast(mChildNodes.size()); } - MCORE_INLINE AnimGraphNode* GetChildNode(uint32 index) const { return mChildNodes[index]; } - const AZStd::vector& GetChildNodes() const { return mChildNodes; } + MCORE_INLINE size_t GetNumChildNodes() const { return m_childNodes.size(); } + MCORE_INLINE AnimGraphNode* GetChildNode(size_t index) const { return m_childNodes[index]; } + const AZStd::vector& GetChildNodes() const { return m_childNodes; } void SetNodeInfo(const AZStd::string& info); const AZStd::string& GetNodeInfo() const; void AddChildNode(AnimGraphNode* node); - void ReserveChildNodes(uint32 numChildNodes); + void ReserveChildNodes(size_t numChildNodes); - void RemoveChildNode(uint32 index, bool delFromMem = true); + void RemoveChildNode(size_t index, bool delFromMem = true); void RemoveChildNodeByPointer(AnimGraphNode* node, bool delFromMem = true); void RemoveAllChildNodes(bool delFromMem = true); bool CheckIfHasChildOfType(const AZ::TypeId& nodeType) const; // non-recursive @@ -916,7 +916,7 @@ namespace EMotionFX void SetHasError(AnimGraphObjectData* uniqueData, bool hasError); // collect internal objects - void RecursiveCollectObjects(MCore::Array& outObjects) const override; + void RecursiveCollectObjects(AZStd::vector& outObjects) const override; virtual void RecursiveSetUniqueDataFlag(AnimGraphInstance* animGraphInstance, uint32 flag, bool enabled); void FilterEvents(AnimGraphInstance* animGraphInstance, EEventMode eventMode, AnimGraphNode* nodeA, AnimGraphNode* nodeB, float localWeight, AnimGraphRefCountedData* refData); @@ -924,8 +924,8 @@ namespace EMotionFX bool GetCanVisualize(AnimGraphInstance* animGraphInstance) const; - MCORE_INLINE uint32 GetNodeIndex() const { return mNodeIndex; } - MCORE_INLINE void SetNodeIndex(uint32 index) { mNodeIndex = index; } + MCORE_INLINE size_t GetNodeIndex() const { return m_nodeIndex; } + MCORE_INLINE void SetNodeIndex(size_t index) { m_nodeIndex = index; } void ResetPoseRefCount(AnimGraphInstance* animGraphInstance); MCORE_INLINE void IncreasePoseRefCount(AnimGraphInstance* animGraphInstance) { FindOrCreateUniqueNodeData(animGraphInstance)->IncreasePoseRefCount(); } @@ -944,30 +944,30 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - uint32 mNodeIndex; + size_t m_nodeIndex; AZ::u64 m_id; - AZStd::vector mConnections; - AZStd::vector mInputPorts; - AZStd::vector mOutputPorts; - AZStd::vector mChildNodes; + AZStd::vector m_connections; + AZStd::vector m_inputPorts; + AZStd::vector m_outputPorts; + AZStd::vector m_childNodes; TriggerActionSetup m_actionSetup; - AnimGraphNode* mParentNode; - void* mCustomData; - AZ::Color mVisualizeColor; + AnimGraphNode* m_parentNode; + void* m_customData; + AZ::Color m_visualizeColor; AZStd::string m_name; - AZStd::string mNodeInfo; - int32 mPosX; - int32 mPosY; - bool mDisabled; - bool mVisEnabled; - bool mIsCollapsed; + AZStd::string m_nodeInfo; + int32 m_posX; + int32 m_posY; + bool m_disabled; + bool m_visEnabled; + bool m_isCollapsed; virtual void Output(AnimGraphInstance* animGraphInstance); virtual void TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds); virtual void PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds); void Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) override; - void RecursiveCountChildNodes(uint32& numNodes) const; - void RecursiveCountNodeConnections(uint32& numConnections) const; + void RecursiveCountChildNodes(size_t& numNodes) const; + void RecursiveCountNodeConnections(size_t& numConnections) const; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp index f8f2b0a98c..b329928c39 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.cpp @@ -20,19 +20,19 @@ namespace EMotionFX // constructor AnimGraphNodeData::AnimGraphNodeData(AnimGraphNode* node, AnimGraphInstance* animGraphInstance) : AnimGraphObjectData(reinterpret_cast(node), animGraphInstance) - , mDuration(0.0f) - , mCurrentTime(0.0f) - , mPlaySpeed(1.0f) - , mPreSyncTime(0.0f) - , mGlobalWeight(1.0f) - , mLocalWeight(1.0f) - , mSyncIndex(MCORE_INVALIDINDEX32) - , mPoseRefCount(0) - , mRefDataRefCount(0) - , mInheritFlags(0) + , m_duration(0.0f) + , m_currentTime(0.0f) + , m_playSpeed(1.0f) + , m_preSyncTime(0.0f) + , m_globalWeight(1.0f) + , m_localWeight(1.0f) + , m_syncIndex(InvalidIndex) + , m_poseRefCount(0) + , m_refDataRefCount(0) + , m_inheritFlags(0) , m_isMirrorMotion(false) - , mRefCountedData(nullptr) - , mSyncTrack(nullptr) + , m_refCountedData(nullptr) + , m_syncTrack(nullptr) { } @@ -47,16 +47,16 @@ namespace EMotionFX // reset the sync related data void AnimGraphNodeData::Clear() { - mDuration = 0.0f; - mCurrentTime = 0.0f; - mPreSyncTime = 0.0f; - mPlaySpeed = 1.0f; - mGlobalWeight = 1.0f; - mLocalWeight = 1.0f; - mInheritFlags = 0; + m_duration = 0.0f; + m_currentTime = 0.0f; + m_preSyncTime = 0.0f; + m_playSpeed = 1.0f; + m_globalWeight = 1.0f; + m_localWeight = 1.0f; + m_inheritFlags = 0; m_isMirrorMotion = false; - mSyncIndex = MCORE_INVALIDINDEX32; - mSyncTrack = nullptr; + m_syncIndex = InvalidIndex; + m_syncTrack = nullptr; } @@ -70,15 +70,15 @@ namespace EMotionFX // init from existing node data void AnimGraphNodeData::Init(AnimGraphNodeData* nodeData) { - mDuration = nodeData->mDuration; - mCurrentTime = nodeData->mCurrentTime; - mPreSyncTime = nodeData->mPreSyncTime; - mPlaySpeed = nodeData->mPlaySpeed; - mSyncIndex = nodeData->mSyncIndex; - mGlobalWeight = nodeData->mGlobalWeight; - mInheritFlags = nodeData->mInheritFlags; + m_duration = nodeData->m_duration; + m_currentTime = nodeData->m_currentTime; + m_preSyncTime = nodeData->m_preSyncTime; + m_playSpeed = nodeData->m_playSpeed; + m_syncIndex = nodeData->m_syncIndex; + m_globalWeight = nodeData->m_globalWeight; + m_inheritFlags = nodeData->m_inheritFlags; m_isMirrorMotion = nodeData->m_isMirrorMotion; - mSyncTrack = nodeData->mSyncTrack; + m_syncTrack = nodeData->m_syncTrack; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h index a3bfc34606..1ad82b1d55 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeData.h @@ -51,70 +51,70 @@ namespace EMotionFX void Init(AnimGraphInstance* animGraphInstance, AnimGraphNode* node); void Init(AnimGraphNodeData* nodeData); - MCORE_INLINE AnimGraphNode* GetNode() const { return reinterpret_cast(mObject); } - MCORE_INLINE void SetNode(AnimGraphNode* node) { mObject = reinterpret_cast(node); } + MCORE_INLINE AnimGraphNode* GetNode() const { return reinterpret_cast(m_object); } + MCORE_INLINE void SetNode(AnimGraphNode* node) { m_object = reinterpret_cast(node); } - MCORE_INLINE void SetSyncIndex(uint32 syncIndex) { mSyncIndex = syncIndex; } - MCORE_INLINE uint32 GetSyncIndex() const { return mSyncIndex; } + MCORE_INLINE void SetSyncIndex(size_t syncIndex) { m_syncIndex = syncIndex; } + MCORE_INLINE size_t GetSyncIndex() const { return m_syncIndex; } - MCORE_INLINE void SetCurrentPlayTime(float absoluteTime) { mCurrentTime = absoluteTime; } - MCORE_INLINE float GetCurrentPlayTime() const { return mCurrentTime; } + MCORE_INLINE void SetCurrentPlayTime(float absoluteTime) { m_currentTime = absoluteTime; } + MCORE_INLINE float GetCurrentPlayTime() const { return m_currentTime; } - MCORE_INLINE void SetPlaySpeed(float speed) { mPlaySpeed = speed; } - MCORE_INLINE float GetPlaySpeed() const { return mPlaySpeed; } + MCORE_INLINE void SetPlaySpeed(float speed) { m_playSpeed = speed; } + MCORE_INLINE float GetPlaySpeed() const { return m_playSpeed; } - MCORE_INLINE void SetDuration(float durationInSeconds) { mDuration = durationInSeconds; } - MCORE_INLINE float GetDuration() const { return mDuration; } + MCORE_INLINE void SetDuration(float durationInSeconds) { m_duration = durationInSeconds; } + MCORE_INLINE float GetDuration() const { return m_duration; } - MCORE_INLINE void SetPreSyncTime(float timeInSeconds) { mPreSyncTime = timeInSeconds; } - MCORE_INLINE float GetPreSyncTime() const { return mPreSyncTime; } + MCORE_INLINE void SetPreSyncTime(float timeInSeconds) { m_preSyncTime = timeInSeconds; } + MCORE_INLINE float GetPreSyncTime() const { return m_preSyncTime; } - MCORE_INLINE void SetGlobalWeight(float weight) { mGlobalWeight = weight; } - MCORE_INLINE float GetGlobalWeight() const { return mGlobalWeight; } + MCORE_INLINE void SetGlobalWeight(float weight) { m_globalWeight = weight; } + MCORE_INLINE float GetGlobalWeight() const { return m_globalWeight; } - MCORE_INLINE void SetLocalWeight(float weight) { mLocalWeight = weight; } - MCORE_INLINE float GetLocalWeight() const { return mLocalWeight; } + MCORE_INLINE void SetLocalWeight(float weight) { m_localWeight = weight; } + MCORE_INLINE float GetLocalWeight() const { return m_localWeight; } - MCORE_INLINE uint8 GetInheritFlags() const { return mInheritFlags; } + MCORE_INLINE uint8 GetInheritFlags() const { return m_inheritFlags; } - MCORE_INLINE bool GetIsBackwardPlaying() const { return (mInheritFlags & INHERITFLAGS_BACKWARD) != 0; } - MCORE_INLINE void SetBackwardFlag() { mInheritFlags |= INHERITFLAGS_BACKWARD; } - MCORE_INLINE void ClearInheritFlags() { mInheritFlags = 0; } + MCORE_INLINE bool GetIsBackwardPlaying() const { return (m_inheritFlags & INHERITFLAGS_BACKWARD) != 0; } + MCORE_INLINE void SetBackwardFlag() { m_inheritFlags |= INHERITFLAGS_BACKWARD; } + MCORE_INLINE void ClearInheritFlags() { m_inheritFlags = 0; } - MCORE_INLINE uint8 GetPoseRefCount() const { return mPoseRefCount; } - MCORE_INLINE void IncreasePoseRefCount() { mPoseRefCount++; } - MCORE_INLINE void DecreasePoseRefCount() { mPoseRefCount--; } - MCORE_INLINE void SetPoseRefCount(uint8 refCount) { mPoseRefCount = refCount; } + MCORE_INLINE uint8 GetPoseRefCount() const { return m_poseRefCount; } + MCORE_INLINE void IncreasePoseRefCount() { m_poseRefCount++; } + MCORE_INLINE void DecreasePoseRefCount() { m_poseRefCount--; } + MCORE_INLINE void SetPoseRefCount(uint8 refCount) { m_poseRefCount = refCount; } - MCORE_INLINE uint8 GetRefDataRefCount() const { return mRefDataRefCount; } - MCORE_INLINE void IncreaseRefDataRefCount() { mRefDataRefCount++; } - MCORE_INLINE void DecreaseRefDataRefCount() { mRefDataRefCount--; } - MCORE_INLINE void SetRefDataRefCount(uint8 refCount) { mRefDataRefCount = refCount; } + MCORE_INLINE uint8 GetRefDataRefCount() const { return m_refDataRefCount; } + MCORE_INLINE void IncreaseRefDataRefCount() { m_refDataRefCount++; } + MCORE_INLINE void DecreaseRefDataRefCount() { m_refDataRefCount--; } + MCORE_INLINE void SetRefDataRefCount(uint8 refCount) { m_refDataRefCount = refCount; } - MCORE_INLINE void SetRefCountedData(AnimGraphRefCountedData* data) { mRefCountedData = data; } - MCORE_INLINE AnimGraphRefCountedData* GetRefCountedData() const { return mRefCountedData; } + MCORE_INLINE void SetRefCountedData(AnimGraphRefCountedData* data) { m_refCountedData = data; } + MCORE_INLINE AnimGraphRefCountedData* GetRefCountedData() const { return m_refCountedData; } - MCORE_INLINE const AnimGraphSyncTrack* GetSyncTrack() const { return mSyncTrack; } - MCORE_INLINE AnimGraphSyncTrack* GetSyncTrack() { return mSyncTrack; } - MCORE_INLINE void SetSyncTrack(AnimGraphSyncTrack* syncTrack) { mSyncTrack = syncTrack; } + MCORE_INLINE const AnimGraphSyncTrack* GetSyncTrack() const { return m_syncTrack; } + MCORE_INLINE AnimGraphSyncTrack* GetSyncTrack() { return m_syncTrack; } + MCORE_INLINE void SetSyncTrack(AnimGraphSyncTrack* syncTrack) { m_syncTrack = syncTrack; } bool GetIsMirrorMotion() const { return m_isMirrorMotion; } void SetIsMirrorMotion(bool newValue) { m_isMirrorMotion = newValue; } protected: - float mDuration; - float mCurrentTime; - float mPlaySpeed; - float mPreSyncTime; - float mGlobalWeight; - float mLocalWeight; - uint32 mSyncIndex; /**< The last used sync track index. */ - uint8 mPoseRefCount; - uint8 mRefDataRefCount; - uint8 mInheritFlags; + float m_duration; + float m_currentTime; + float m_playSpeed; + float m_preSyncTime; + float m_globalWeight; + float m_localWeight; + size_t m_syncIndex; /**< The last used sync track index. */ + uint8 m_poseRefCount; + uint8 m_refDataRefCount; + uint8 m_inheritFlags; bool m_isMirrorMotion; - AnimGraphRefCountedData* mRefCountedData; - AnimGraphSyncTrack* mSyncTrack; + AnimGraphRefCountedData* m_refCountedData; + AnimGraphSyncTrack* m_syncTrack; void Delete() override; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp index 3d93476c6a..f2958cdde4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.cpp @@ -17,8 +17,8 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(AnimGraphNodeGroup, AnimGraphAllocator, 0) AnimGraphNodeGroup::AnimGraphNodeGroup() - : mColor(AZ::Color::CreateU32(255, 255, 255, 255)) - , mIsVisible(true) + : m_color(AZ::Color::CreateU32(255, 255, 255, 255)) + , m_isVisible(true) { } @@ -26,15 +26,15 @@ namespace EMotionFX AnimGraphNodeGroup::AnimGraphNodeGroup(const char* groupName) { SetName(groupName); - mIsVisible = true; + m_isVisible = true; } - AnimGraphNodeGroup::AnimGraphNodeGroup(const char* groupName, uint32 numNodes) + AnimGraphNodeGroup::AnimGraphNodeGroup(const char* groupName, size_t numNodes) { SetName(groupName); SetNumNodes(numNodes); - mIsVisible = true; + m_isVisible = true; } @@ -46,7 +46,7 @@ namespace EMotionFX void AnimGraphNodeGroup::RemoveAllNodes() { - mNodeIds.clear(); + m_nodeIds.clear(); } @@ -55,11 +55,11 @@ namespace EMotionFX { if (groupName) { - mName = groupName; + m_name = groupName; } else { - mName.clear(); + m_name.clear(); } } @@ -67,63 +67,63 @@ namespace EMotionFX // get the name of the group as character buffer const char* AnimGraphNodeGroup::GetName() const { - return mName.c_str(); + return m_name.c_str(); } // get the name of the string as mcore string object const AZStd::string& AnimGraphNodeGroup::GetNameString() const { - return mName; + return m_name; } // set the color of the group void AnimGraphNodeGroup::SetColor(const AZ::u32& color) { - mColor = color; + m_color = color; } // get the color of the group AZ::u32 AnimGraphNodeGroup::GetColor() const { - return mColor; + return m_color; } // set the visibility flag void AnimGraphNodeGroup::SetIsVisible(bool isVisible) { - mIsVisible = isVisible; + m_isVisible = isVisible; } // set the number of nodes - void AnimGraphNodeGroup::SetNumNodes(uint32 numNodes) + void AnimGraphNodeGroup::SetNumNodes(size_t numNodes) { - mNodeIds.resize(numNodes); + m_nodeIds.resize(numNodes); } // get the number of nodes - uint32 AnimGraphNodeGroup::GetNumNodes() const + size_t AnimGraphNodeGroup::GetNumNodes() const { - return static_cast(mNodeIds.size()); + return m_nodeIds.size(); } // set a given node to a given node number - void AnimGraphNodeGroup::SetNode(uint32 index, AnimGraphNodeId nodeId) + void AnimGraphNodeGroup::SetNode(size_t index, AnimGraphNodeId nodeId) { - mNodeIds[index] = nodeId; + m_nodeIds[index] = nodeId; } // get the node number of a given index - AnimGraphNodeId AnimGraphNodeGroup::GetNode(uint32 index) const + AnimGraphNodeId AnimGraphNodeGroup::GetNode(size_t index) const { - return mNodeIds[index]; + return m_nodeIds[index]; } @@ -133,7 +133,7 @@ namespace EMotionFX // add the node in case it is not in yet if (Contains(nodeId) == false) { - mNodeIds.push_back(nodeId); + m_nodeIds.push_back(nodeId); } } @@ -142,14 +142,14 @@ namespace EMotionFX void AnimGraphNodeGroup::RemoveNodeById(AnimGraphNodeId nodeId) { const AZ::u64 convertedId = nodeId; - mNodeIds.erase(AZStd::remove(mNodeIds.begin(), mNodeIds.end(), convertedId), mNodeIds.end()); + m_nodeIds.erase(AZStd::remove(m_nodeIds.begin(), m_nodeIds.end(), convertedId), m_nodeIds.end()); } // remove a given array element from the list of nodes - void AnimGraphNodeGroup::RemoveNodeByGroupIndex(uint32 index) + void AnimGraphNodeGroup::RemoveNodeByGroupIndex(size_t index) { - mNodeIds.erase(mNodeIds.begin() + index); + m_nodeIds.erase(m_nodeIds.begin() + index); } @@ -157,23 +157,23 @@ namespace EMotionFX bool AnimGraphNodeGroup::Contains(AnimGraphNodeId nodeId) const { const AZ::u64 convertedId = nodeId; - return AZStd::find(mNodeIds.begin(), mNodeIds.end(), convertedId) != mNodeIds.end(); + return AZStd::find(m_nodeIds.begin(), m_nodeIds.end(), convertedId) != m_nodeIds.end(); } // init from another group void AnimGraphNodeGroup::InitFrom(const AnimGraphNodeGroup& other) { - mNodeIds = other.mNodeIds; - mColor = other.mColor; - mName = other.mName; - mIsVisible = other.mIsVisible; + m_nodeIds = other.m_nodeIds; + m_color = other.m_color; + m_name = other.m_name; + m_isVisible = other.m_isVisible; } bool AnimGraphNodeGroup::GetIsVisible() const { - return mIsVisible; + return m_isVisible; } @@ -187,9 +187,9 @@ namespace EMotionFX serializeContext->Class() ->Version(1) - ->Field("nodes", &AnimGraphNodeGroup::mNodeIds) - ->Field("name", &AnimGraphNodeGroup::mName) - ->Field("color", &AnimGraphNodeGroup::mColor) - ->Field("isVisible", &AnimGraphNodeGroup::mIsVisible); + ->Field("nodes", &AnimGraphNodeGroup::m_nodeIds) + ->Field("name", &AnimGraphNodeGroup::m_name) + ->Field("color", &AnimGraphNodeGroup::m_color) + ->Field("isVisible", &AnimGraphNodeGroup::m_isVisible); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h index a3aa0ec9a6..7e1fc909e5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphNodeGroup.h @@ -41,7 +41,7 @@ namespace EMotionFX * @param numNodes The number of nodes to create inside the group. This will have all uninitialized values for the node ids in the group, so be sure that you * set them all to some valid node index using the AnimGraphNodeGroup::SetNode(...) method. This constructor automatically calls the SetNumNodes(...) method. */ - AnimGraphNodeGroup(const char* groupName, uint32 numNodes); + AnimGraphNodeGroup(const char* groupName, size_t numNodes); /** * The destructor. @@ -96,13 +96,13 @@ namespace EMotionFX * This will resize the array of node ids. Don't forget to initialize the node values after increasing the number of nodes. * @param numNodes The number of nodes that are inside this group. */ - void SetNumNodes(uint32 numNodes); + void SetNumNodes(size_t numNodes); /** * Get the number of nodes that remain inside this group. * @result The number of nodes inside this group. */ - uint32 GetNumNodes() const; + size_t GetNumNodes() const; /** * Set the value of a given node. @@ -110,14 +110,14 @@ namespace EMotionFX * @param nodeID The value for the given node. This is the node id where this group will belong to. * To get access to the actual node object use AnimGraph::RecursiveFindNodeByID( nodeID ). */ - void SetNode(uint32 index, AnimGraphNodeId nodeId); + void SetNode(size_t index, AnimGraphNodeId nodeId); /** * Get the node id for a given node inside the group. * @param index The node number inside this group, which must be in range of [0..GetNumNodes()-1]. * @result The node id, which points inside the Actor object. Use AnimGraph::RecursiveFindNodeByID( nodeID ) to get access to the node information. */ - AnimGraphNodeId GetNode(uint32 index) const; + AnimGraphNodeId GetNode(size_t index) const; /** * Check if the node with the given id is inside the node group. @@ -149,7 +149,7 @@ namespace EMotionFX * @param index The node index in the group. So for example an index value of 5 will remove the sixth node from the group. * The index value must be in range of [0..GetNumNodes() - 1]. */ - void RemoveNodeByGroupIndex(uint32 index); + void RemoveNodeByGroupIndex(size_t index); /** * Clear the node group. This removes all nodes. @@ -165,9 +165,9 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - AZStd::vector mNodeIds; /**< The node ids that are inside this group. */ - AZStd::string mName; /**< The unique identification number for the node group name. */ - AZ::u32 mColor; /**< The color the nodes of the group will be filled with. */ - bool mIsVisible; + AZStd::vector m_nodeIds; /**< The node ids that are inside this group. */ + AZStd::string m_name; /**< The unique identification number for the node group name. */ + AZ::u32 m_color; /**< The color the nodes of the group will be filled with. */ + bool m_isVisible; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp index a56e8d246e..6bee03f0ae 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.cpp @@ -27,8 +27,8 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(AnimGraphObject, AnimGraphAllocator, 0) AnimGraphObject::AnimGraphObject() - : mAnimGraph(nullptr) - , mObjectIndex(MCORE_INVALIDINDEX32) + : m_animGraph(nullptr) + , m_objectIndex(MCORE_INVALIDINDEX32) { } @@ -36,7 +36,7 @@ namespace EMotionFX AnimGraphObject::AnimGraphObject(AnimGraph* animGraph) : AnimGraphObject() { - mAnimGraph = animGraph; + m_animGraph = animGraph; } @@ -89,7 +89,7 @@ namespace EMotionFX // save and return number of bytes written, when outputBuffer is nullptr only return num bytes it would write - uint32 AnimGraphObject::SaveUniqueData(AnimGraphInstance* animGraphInstance, uint8* outputBuffer) const + size_t AnimGraphObject::SaveUniqueData(AnimGraphInstance* animGraphInstance, uint8* outputBuffer) const { AnimGraphObjectData* data = animGraphInstance->FindOrCreateUniqueObjectData(this); if (data) @@ -103,7 +103,7 @@ namespace EMotionFX // load and return number of bytes read, when dataBuffer is nullptr, 0 should be returned - uint32 AnimGraphObject::LoadUniqueData(AnimGraphInstance* animGraphInstance, const uint8* dataBuffer) + size_t AnimGraphObject::LoadUniqueData(AnimGraphInstance* animGraphInstance, const uint8* dataBuffer) { AnimGraphObjectData* data = animGraphInstance->FindOrCreateUniqueObjectData(this); if (data) @@ -116,25 +116,25 @@ namespace EMotionFX // collect internal objects - void AnimGraphObject::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphObject::RecursiveCollectObjects(AZStd::vector& outObjects) const { - outObjects.Add(const_cast(this)); + outObjects.emplace_back(const_cast(this)); } void AnimGraphObject::InvalidateUniqueDatas() { AnimGraphObject* object = this; - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); object->InvalidateUniqueData(animGraphInstance); } } void AnimGraphObject::InvalidateUniqueData(AnimGraphInstance* animGraphInstance) { - AnimGraphObjectData* uniqueData = animGraphInstance->GetUniqueObjectData(mObjectIndex); + AnimGraphObjectData* uniqueData = animGraphInstance->GetUniqueObjectData(m_objectIndex); if (uniqueData) { uniqueData->Invalidate(); @@ -143,7 +143,7 @@ namespace EMotionFX void AnimGraphObject::ResetUniqueData(AnimGraphInstance* animGraphInstance) { - AnimGraphObjectData* uniqueData = animGraphInstance->GetUniqueObjectData(mObjectIndex); + AnimGraphObjectData* uniqueData = animGraphInstance->GetUniqueObjectData(m_objectIndex); if (uniqueData) { uniqueData->Reset(); @@ -153,10 +153,10 @@ namespace EMotionFX void AnimGraphObject::ResetUniqueDatas() { AnimGraphObject* object = this; - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); object->ResetUniqueData(animGraphInstance); } } @@ -165,7 +165,7 @@ namespace EMotionFX void AnimGraphObject::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { MCORE_UNUSED(timePassedInSeconds); - animGraphInstance->EnableObjectFlags(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_UPDATE_READY); + animGraphInstance->EnableObjectFlags(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_UPDATE_READY); } void AnimGraphObject::Reinit() @@ -220,7 +220,7 @@ namespace EMotionFX // decrease internal attribute indices for index values higher than the specified parameter - void AnimGraphObject::DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan) + void AnimGraphObject::DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan) { MCORE_UNUSED(decreaseEverythingHigherThan); // currently no implementation for the base object type, but this will come later @@ -230,15 +230,15 @@ namespace EMotionFX // does the init for all anim graph instances in the parent animgraph void AnimGraphObject::InitInternalAttributesForAllInstances() { - if (mAnimGraph == nullptr) + if (m_animGraph == nullptr) { return; } - const size_t numInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numInstances; ++i) { - InitInternalAttributes(mAnimGraph->GetAnimGraphInstance(i)); + InitInternalAttributes(m_animGraph->GetAnimGraphInstance(i)); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h index c3d6968a2d..ebc92964b0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObject.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -134,7 +134,7 @@ namespace EMotionFX void InitInternalAttributesForAllInstances(); // does the init for all anim graph instances in the parent animgraph virtual void InitInternalAttributes(AnimGraphInstance* animGraphInstance); virtual void RemoveInternalAttributesForAllInstances(); - virtual void DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan); + virtual void DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan); virtual void Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds); @@ -144,16 +144,16 @@ namespace EMotionFX virtual void RecursiveOnChangeMotionSet(AnimGraphInstance* animGraphInstance, MotionSet* newMotionSet) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(newMotionSet); } virtual void OnActorMotionExtractionNodeChanged() {} - MCORE_INLINE uint32 GetObjectIndex() const { return mObjectIndex; } - MCORE_INLINE void SetObjectIndex(size_t index) { mObjectIndex = static_cast(index); } + MCORE_INLINE size_t GetObjectIndex() const { return m_objectIndex; } + MCORE_INLINE void SetObjectIndex(size_t index) { m_objectIndex = index; } - MCORE_INLINE AnimGraph* GetAnimGraph() const { return mAnimGraph; } - MCORE_INLINE void SetAnimGraph(AnimGraph* animGraph) { mAnimGraph = animGraph; } + MCORE_INLINE AnimGraph* GetAnimGraph() const { return m_animGraph; } + MCORE_INLINE void SetAnimGraph(AnimGraph* animGraph) { m_animGraph = animGraph; } - uint32 SaveUniqueData(AnimGraphInstance* animGraphInstance, uint8* outputBuffer) const; // save and return number of bytes written, when outputBuffer is nullptr only return num bytes it would write - uint32 LoadUniqueData(AnimGraphInstance* animGraphInstance, const uint8* dataBuffer); // load and return number of bytes read, when dataBuffer is nullptr, 0 should be returned + size_t SaveUniqueData(AnimGraphInstance* animGraphInstance, uint8* outputBuffer) const; // save and return number of bytes written, when outputBuffer is nullptr only return num bytes it would write + size_t LoadUniqueData(AnimGraphInstance* animGraphInstance, const uint8* dataBuffer); // load and return number of bytes read, when dataBuffer is nullptr, 0 should be returned - virtual void RecursiveCollectObjects(MCore::Array& outObjects) const; + virtual void RecursiveCollectObjects(AZStd::vector& outObjects) const; bool GetHasErrorFlag(AnimGraphInstance* animGraphInstance) const; void SetHasErrorFlag(AnimGraphInstance* animGraphInstance, bool hasError); @@ -166,8 +166,8 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - AnimGraph* mAnimGraph; - uint32 mObjectIndex; + AnimGraph* m_animGraph; + size_t m_objectIndex; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.cpp index 3434294747..9c3a7022d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.cpp @@ -20,9 +20,9 @@ namespace EMotionFX AnimGraphObjectData::AnimGraphObjectData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance) : BaseObject() { - mObject = object; - mAnimGraphInstance = animGraphInstance; - mObjectFlags = 0; + m_object = object; + m_animGraphInstance = animGraphInstance; + m_objectFlags = 0; } AnimGraphObjectData::~AnimGraphObjectData() diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.h index e9cb1ea809..25f28282bd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphObjectData.h @@ -70,8 +70,8 @@ public: \ AnimGraphObjectData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance); virtual ~AnimGraphObjectData(); - MCORE_INLINE AnimGraphObject* GetObject() const { return mObject; } - void SetObject(AnimGraphObject* object) { mObject = object; } + MCORE_INLINE AnimGraphObject* GetObject() const { return m_object; } + void SetObject(AnimGraphObject* object) { m_object = object; } // save and return number of bytes written, when outputBuffer is nullptr only return num bytes it would write virtual uint32 Save(uint8* outputBuffer) const; @@ -91,33 +91,33 @@ public: \ bool IsInvalidated() const { return m_invalidated; } void Validate() { m_invalidated = false; } - MCORE_INLINE uint8 GetObjectFlags() const { return mObjectFlags; } - MCORE_INLINE void SetObjectFlags(uint8 flags) { mObjectFlags = flags; } - MCORE_INLINE void EnableObjectFlags(uint8 flagsToEnable) { mObjectFlags |= flagsToEnable; } - MCORE_INLINE void DisableObjectFlags(uint8 flagsToDisable) { mObjectFlags &= ~flagsToDisable; } + MCORE_INLINE uint8 GetObjectFlags() const { return m_objectFlags; } + MCORE_INLINE void SetObjectFlags(uint8 flags) { m_objectFlags = flags; } + MCORE_INLINE void EnableObjectFlags(uint8 flagsToEnable) { m_objectFlags |= flagsToEnable; } + MCORE_INLINE void DisableObjectFlags(uint8 flagsToDisable) { m_objectFlags &= ~flagsToDisable; } MCORE_INLINE void SetObjectFlags(uint8 flags, bool enabled) { if (enabled) { - mObjectFlags |= flags; + m_objectFlags |= flags; } else { - mObjectFlags &= ~flags; + m_objectFlags &= ~flags; } } - MCORE_INLINE bool GetIsObjectFlagEnabled(uint8 flag) const { return (mObjectFlags & flag) != 0; } + MCORE_INLINE bool GetIsObjectFlagEnabled(uint8 flag) const { return (m_objectFlags & flag) != 0; } - MCORE_INLINE bool GetHasError() const { return (mObjectFlags & FLAGS_HAS_ERROR); } + MCORE_INLINE bool GetHasError() const { return (m_objectFlags & FLAGS_HAS_ERROR); } MCORE_INLINE void SetHasError(bool hasError) { SetObjectFlags(FLAGS_HAS_ERROR, hasError); } - AnimGraphInstance* GetAnimGraphInstance() { return mAnimGraphInstance; } - const AnimGraphInstance* GetAnimGraphInstance() const { return mAnimGraphInstance; } + AnimGraphInstance* GetAnimGraphInstance() { return m_animGraphInstance; } + const AnimGraphInstance* GetAnimGraphInstance() const { return m_animGraphInstance; } protected: - AnimGraphObject* mObject; /**< Pointer to the object where this data belongs to. */ - AnimGraphInstance* mAnimGraphInstance; /**< The animgraph instance where this unique data belongs to. */ - uint8 mObjectFlags; + AnimGraphObject* m_object; /**< Pointer to the object where this data belongs to. */ + AnimGraphInstance* m_animGraphInstance; /**< The animgraph instance where this unique data belongs to. */ + uint8 m_objectFlags; bool m_invalidated = true; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterAction.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterAction.cpp index c1a35b9399..ec3eb91056 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterAction.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterAction.cpp @@ -46,10 +46,10 @@ namespace EMotionFX void AnimGraphParameterAction::Reinit() { // Find the parameter index for the given parameter name, to prevent string based lookups every frame - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); if (m_parameterIndex.IsSuccess()) { - m_valueParameter = mAnimGraph->FindValueParameter(m_parameterIndex.GetValue()); + m_valueParameter = m_animGraph->FindValueParameter(m_parameterIndex.GetValue()); } else { @@ -123,7 +123,7 @@ namespace EMotionFX void AnimGraphParameterAction::SetParameterName(const AZStd::string& parameterName) { m_parameterName = parameterName; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -142,7 +142,7 @@ namespace EMotionFX if (m_parameterIndex.IsSuccess()) { // get access to the parameter info and return the type of its default value - const ValueParameter* valueParameter = mAnimGraph->FindValueParameter(m_parameterIndex.GetValue()); + const ValueParameter* valueParameter = m_animGraph->FindValueParameter(m_parameterIndex.GetValue()); return azrtti_typeid(valueParameter); } else @@ -186,7 +186,7 @@ namespace EMotionFX { AZ_UNUSED(beforeChange); AZ_UNUSED(afterChange); - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } void AnimGraphParameterAction::ParameterRemoved(const AZStd::string& oldParameterName) @@ -198,7 +198,7 @@ namespace EMotionFX } else { - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterCondition.cpp index 052175eb92..c79a24690c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphParameterCondition.cpp @@ -78,7 +78,7 @@ namespace EMotionFX void AnimGraphParameterCondition::Reinit() { // Find the parameter index for the given parameter name, to prevent string based lookups every frame - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); SetFunction(m_function); } @@ -114,7 +114,7 @@ namespace EMotionFX void AnimGraphParameterCondition::SetParameterName(const AZStd::string& parameterName) { m_parameterName = parameterName; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -131,7 +131,7 @@ namespace EMotionFX if (m_parameterIndex.IsSuccess()) { // get access to the parameter info and return the type of its default value - const ValueParameter* valueParameter = mAnimGraph->FindValueParameter(m_parameterIndex.GetValue()); + const ValueParameter* valueParameter = m_animGraph->FindValueParameter(m_parameterIndex.GetValue()); return azrtti_typeid(valueParameter); } return AZ::TypeId::CreateNull(); @@ -144,7 +144,7 @@ namespace EMotionFX return false; } - const ValueParameter* valueParameter = mAnimGraph->FindValueParameter(m_parameterIndex.GetValue()); + const ValueParameter* valueParameter = m_animGraph->FindValueParameter(m_parameterIndex.GetValue()); if (!valueParameter) { return false; @@ -500,7 +500,7 @@ namespace EMotionFX if (!newParameterMask.empty()) { m_parameterName = *newParameterMask.begin(); - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } } @@ -514,7 +514,7 @@ namespace EMotionFX { AZ_UNUSED(newParameterName); // Just recompute the index in the case the new parameter was inserted before ours - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } void AnimGraphParameterCondition::ParameterRenamed(const AZStd::string& oldParameterName, const AZStd::string& newParameterName) @@ -530,7 +530,7 @@ namespace EMotionFX AZ_UNUSED(beforeChange); AZ_UNUSED(afterChange); // Just recompute the index - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } void AnimGraphParameterCondition::ParameterRemoved(const AZStd::string& oldParameterName) @@ -542,7 +542,7 @@ namespace EMotionFX } else { - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPlayTimeCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPlayTimeCondition.cpp index 1a80a5a09b..125491dc21 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPlayTimeCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPlayTimeCondition.cpp @@ -56,7 +56,7 @@ namespace EMotionFX return; } - m_node = mAnimGraph->RecursiveFindNodeById(m_nodeId); + m_node = m_animGraph->RecursiveFindNodeById(m_nodeId); } @@ -181,7 +181,7 @@ namespace EMotionFX void AnimGraphPlayTimeCondition::SetNodeId(AnimGraphNodeId nodeId) { m_nodeId = nodeId; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.cpp index 7918d73c3c..595f434c1c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.cpp @@ -18,16 +18,15 @@ namespace EMotionFX // constructor AnimGraphPose::AnimGraphPose() { - mFlags = 0; + m_flags = 0; } // copy constructor AnimGraphPose::AnimGraphPose(const AnimGraphPose& other) { - mFlags = 0; - mPose.InitFromPose(&other.mPose); - //mFlags = other.mFlags; + m_flags = 0; + m_pose.InitFromPose(&other.m_pose); } @@ -40,8 +39,7 @@ namespace EMotionFX // = operator AnimGraphPose& AnimGraphPose::operator=(const AnimGraphPose& other) { - mPose.InitFromPose(&other.mPose); - //mFlags = other.mFlags; + m_pose.InitFromPose(&other.m_pose); return *this; } @@ -50,7 +48,7 @@ namespace EMotionFX void AnimGraphPose::LinkToActorInstance(const ActorInstance* actorInstance) { // resize the transformation buffer, which contains the local space transformations - mPose.LinkToActorInstance(actorInstance); + m_pose.LinkToActorInstance(actorInstance); } @@ -61,7 +59,7 @@ namespace EMotionFX LinkToActorInstance(actorInstance); // fill the local pose with the bind pose - mPose.InitFromBindPose(actorInstance); + m_pose.InitFromBindPose(actorInstance); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h index 122749e714..b46faddf7f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPose.h @@ -39,29 +39,29 @@ namespace EMotionFX void LinkToActorInstance(const ActorInstance* actorInstance); void InitFromBindPose(const ActorInstance* actorInstance); - MCORE_INLINE uint32 GetNumNodes() const { return mPose.GetNumTransforms(); } - MCORE_INLINE const Pose& GetPose() const { return mPose; } - MCORE_INLINE Pose& GetPose() { return mPose; } - MCORE_INLINE void SetPose(const Pose& pose) { mPose = pose; } - MCORE_INLINE const ActorInstance* GetActorInstance() const { return mPose.GetActorInstance(); } + MCORE_INLINE size_t GetNumNodes() const { return m_pose.GetNumTransforms(); } + MCORE_INLINE const Pose& GetPose() const { return m_pose; } + MCORE_INLINE Pose& GetPose() { return m_pose; } + MCORE_INLINE void SetPose(const Pose& pose) { m_pose = pose; } + MCORE_INLINE const ActorInstance* GetActorInstance() const { return m_pose.GetActorInstance(); } - MCORE_INLINE bool GetIsInUse() const { return (mFlags & FLAG_INUSE); } + MCORE_INLINE bool GetIsInUse() const { return (m_flags & FLAG_INUSE); } MCORE_INLINE void SetIsInUse(bool inUse) { if (inUse) { - mFlags |= FLAG_INUSE; + m_flags |= FLAG_INUSE; } else { - mFlags &= ~FLAG_INUSE; + m_flags &= ~FLAG_INUSE; } } AnimGraphPose& operator=(const AnimGraphPose& other); private: - Pose mPose; /**< The pose, containing the node transformation. */ - uint8 mFlags; /**< The flags. */ + Pose m_pose; /**< The pose, containing the node transformation. */ + uint8 m_flags; /**< The flags. */ }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp index f30d742a24..4d9d2ca999 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.cpp @@ -16,12 +16,10 @@ namespace EMotionFX // constructor AnimGraphPosePool::AnimGraphPosePool() { - mPoses.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSEPOOL); - mFreePoses.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSEPOOL); - mPoses.Reserve(12); - mFreePoses.Reserve(12); + m_poses.reserve(12); + m_freePoses.reserve(12); Resize(8); - mMaxUsed = 0; + m_maxUsed = 0; } @@ -29,44 +27,43 @@ namespace EMotionFX AnimGraphPosePool::~AnimGraphPosePool() { // delete all poses - const uint32 numPoses = mPoses.GetLength(); - for (uint32 i = 0; i < numPoses; ++i) + for (AnimGraphPose* pose : m_poses) { - delete mPoses[i]; + delete pose; } - mPoses.Clear(); + m_poses.clear(); // clear the free array - mFreePoses.Clear(); + m_freePoses.clear(); } // resize the number of poses in the pool - void AnimGraphPosePool::Resize(uint32 numPoses) + void AnimGraphPosePool::Resize(size_t numPoses) { - const uint32 numOldPoses = mPoses.GetLength(); + const size_t numOldPoses = m_poses.size(); // if we will remove poses - int32 difference = numPoses - numOldPoses; - if (difference < 0) + if (numPoses < numOldPoses) { // remove the last poses - difference = abs(difference); - for (int32 i = 0; i < difference; ++i) + const size_t numToRemove = numOldPoses - numPoses; + for (size_t i = 0; i < numToRemove; ++i) { - AnimGraphPose* pose = mPoses[mFreePoses.GetLength() - 1]; - MCORE_ASSERT(mFreePoses.Contains(pose)); // make sure the pose is not already in use + AnimGraphPose* pose = m_poses.back(); + MCORE_ASSERT(AZStd::find(begin(m_freePoses), end(m_freePoses), pose) == end(m_freePoses)); // make sure the pose is not already in use delete pose; - mPoses.Remove(mFreePoses.GetLength() - 1); + m_poses.erase(m_freePoses.end() - 1); } } else // we want to add new poses { - for (int32 i = 0; i < difference; ++i) + const size_t numToAdd = numPoses - numOldPoses; + for (size_t i = 0; i < numToAdd; ++i) { AnimGraphPose* newPose = new AnimGraphPose(); - mPoses.Add(newPose); - mFreePoses.Add(newPose); + m_poses.emplace_back(newPose); + m_freePoses.emplace_back(newPose); } } } @@ -76,22 +73,22 @@ namespace EMotionFX AnimGraphPose* AnimGraphPosePool::RequestPose(const ActorInstance* actorInstance) { // if we have no free poses left, allocate a new one - if (mFreePoses.GetLength() == 0) + if (m_freePoses.empty()) { AnimGraphPose* newPose = new AnimGraphPose(); newPose->LinkToActorInstance(actorInstance); - mPoses.Add(newPose); - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedPoses()); + m_poses.emplace_back(newPose); + m_maxUsed = AZStd::max(m_maxUsed, GetNumUsedPoses()); newPose->SetIsInUse(true); return newPose; } // request the last free pose - AnimGraphPose* pose = mFreePoses[mFreePoses.GetLength() - 1]; + AnimGraphPose* pose = m_freePoses[m_freePoses.size() - 1]; //if (pose->GetActorInstance() != actorInstance) pose->LinkToActorInstance(actorInstance); - mFreePoses.RemoveLast(); // remove it from the list of free poses - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedPoses()); + m_freePoses.pop_back(); // remove it from the list of free poses + m_maxUsed = AZStd::max(m_maxUsed, GetNumUsedPoses()); pose->SetIsInUse(true); return pose; } @@ -100,8 +97,7 @@ namespace EMotionFX // free the pose again void AnimGraphPosePool::FreePose(AnimGraphPose* pose) { - //MCORE_ASSERT( mPoses.Contains(pose) ); - mFreePoses.Add(pose); + m_freePoses.emplace_back(pose); pose->SetIsInUse(false); } @@ -109,10 +105,8 @@ namespace EMotionFX // free all poses void AnimGraphPosePool::FreeAllPoses() { - const uint32 numPoses = mPoses.GetLength(); - for (uint32 i = 0; i < numPoses; ++i) + for (AnimGraphPose* curPose : m_poses) { - AnimGraphPose* curPose = mPoses[i]; if (curPose->GetIsInUse()) { FreePose(curPose); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h index 2c792e2005..a7244e2dc2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphPosePool.h @@ -10,7 +10,7 @@ // include required headers #include "EMotionFXConfig.h" -#include +#include @@ -34,22 +34,22 @@ namespace EMotionFX AnimGraphPosePool(); ~AnimGraphPosePool(); - void Resize(uint32 numPoses); + void Resize(size_t numPoses); AnimGraphPose* RequestPose(const ActorInstance* actorInstance); void FreePose(AnimGraphPose* pose); void FreeAllPoses(); - MCORE_INLINE uint32 GetNumFreePoses() const { return mFreePoses.GetLength(); } - MCORE_INLINE uint32 GetNumPoses() const { return mPoses.GetLength(); } - MCORE_INLINE uint32 GetNumUsedPoses() const { return (mPoses.GetLength() - mFreePoses.GetLength()); } - MCORE_INLINE uint32 GetNumMaxUsedPoses() const { return mMaxUsed; } - MCORE_INLINE void ResetMaxUsedPoses() { mMaxUsed = 0; } + MCORE_INLINE size_t GetNumFreePoses() const { return m_freePoses.size(); } + MCORE_INLINE size_t GetNumPoses() const { return m_poses.size(); } + MCORE_INLINE size_t GetNumUsedPoses() const { return m_poses.size() - m_freePoses.size(); } + MCORE_INLINE size_t GetNumMaxUsedPoses() const { return m_maxUsed; } + MCORE_INLINE void ResetMaxUsedPoses() { m_maxUsed = 0; } private: - MCore::Array mPoses; - MCore::Array mFreePoses; - uint32 mMaxUsed; + AZStd::vector m_poses; + AZStd::vector m_freePoses; + size_t m_maxUsed; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedData.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedData.h index f3d04eeacb..2d4c1624ba 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedData.h @@ -29,24 +29,24 @@ namespace EMotionFX MCORE_INLINE AnimGraphRefCountedData() = default; MCORE_INLINE ~AnimGraphRefCountedData() = default; - MCORE_INLINE AnimGraphEventBuffer& GetEventBuffer() { return mEventBuffer; } - MCORE_INLINE const AnimGraphEventBuffer& GetEventBuffer() const { return mEventBuffer; } - MCORE_INLINE void SetEventBuffer(const AnimGraphEventBuffer& buf) { mEventBuffer = buf; } - MCORE_INLINE void ClearEventBuffer() { mEventBuffer.Clear(); } + MCORE_INLINE AnimGraphEventBuffer& GetEventBuffer() { return m_eventBuffer; } + MCORE_INLINE const AnimGraphEventBuffer& GetEventBuffer() const { return m_eventBuffer; } + MCORE_INLINE void SetEventBuffer(const AnimGraphEventBuffer& buf) { m_eventBuffer = buf; } + MCORE_INLINE void ClearEventBuffer() { m_eventBuffer.Clear(); } - MCORE_INLINE Transform& GetTrajectoryDelta() { return mTrajectoryDelta; } - MCORE_INLINE const Transform& GetTrajectoryDelta() const { return mTrajectoryDelta; } - MCORE_INLINE void SetTrajectoryDelta(const Transform& transform) { mTrajectoryDelta = transform; } + MCORE_INLINE Transform& GetTrajectoryDelta() { return m_trajectoryDelta; } + MCORE_INLINE const Transform& GetTrajectoryDelta() const { return m_trajectoryDelta; } + MCORE_INLINE void SetTrajectoryDelta(const Transform& transform) { m_trajectoryDelta = transform; } - MCORE_INLINE Transform& GetTrajectoryDeltaMirrored() { return mTrajectoryDeltaMirrored; } - MCORE_INLINE const Transform& GetTrajectoryDeltaMirrored() const { return mTrajectoryDeltaMirrored; } - MCORE_INLINE void SetTrajectoryDeltaMirrored(const Transform& tform) { mTrajectoryDeltaMirrored = tform; } + MCORE_INLINE Transform& GetTrajectoryDeltaMirrored() { return m_trajectoryDeltaMirrored; } + MCORE_INLINE const Transform& GetTrajectoryDeltaMirrored() const { return m_trajectoryDeltaMirrored; } + MCORE_INLINE void SetTrajectoryDeltaMirrored(const Transform& tform) { m_trajectoryDeltaMirrored = tform; } - MCORE_INLINE void ZeroTrajectoryDelta() { mTrajectoryDelta.IdentityWithZeroScale(); mTrajectoryDeltaMirrored.IdentityWithZeroScale(); } + MCORE_INLINE void ZeroTrajectoryDelta() { m_trajectoryDelta.IdentityWithZeroScale(); m_trajectoryDeltaMirrored.IdentityWithZeroScale(); } private: - AnimGraphEventBuffer mEventBuffer; - Transform mTrajectoryDelta = Transform::CreateIdentityWithZeroScale(); - Transform mTrajectoryDeltaMirrored = Transform::CreateIdentityWithZeroScale(); + AnimGraphEventBuffer m_eventBuffer; + Transform m_trajectoryDelta = Transform::CreateIdentityWithZeroScale(); + Transform m_trajectoryDeltaMirrored = Transform::CreateIdentityWithZeroScale(); }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp index 6f77868ad7..4fdcaea7f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.cpp @@ -8,6 +8,8 @@ // include required headers #include "AnimGraphRefCountedDataPool.h" +#include +#include namespace EMotionFX @@ -15,12 +17,10 @@ namespace EMotionFX // constructor AnimGraphRefCountedDataPool::AnimGraphRefCountedDataPool() { - mItems.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_REFCOUNTEDDATA); - mFreeItems.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_REFCOUNTEDDATA); - mItems.Reserve(32); - mFreeItems.Reserve(32); + m_items.reserve(32); + m_freeItems.reserve(32); Resize(16); - mMaxUsed = 0; + m_maxUsed = 0; } @@ -28,44 +28,43 @@ namespace EMotionFX AnimGraphRefCountedDataPool::~AnimGraphRefCountedDataPool() { // delete all items - const uint32 numItems = mItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (AnimGraphRefCountedData*& item : m_items) { - delete mItems[i]; + delete item; } - mItems.Clear(); + m_items.clear(); // clear the free array - mFreeItems.Clear(); + m_freeItems.clear(); } // resize the number of items in the pool - void AnimGraphRefCountedDataPool::Resize(uint32 numItems) + void AnimGraphRefCountedDataPool::Resize(size_t numItems) { - const uint32 numOldItems = mItems.GetLength(); + const size_t numOldItems = m_items.size(); // if we will remove Items - int32 difference = numItems - numOldItems; - if (difference < 0) + if (numItems < numOldItems) { // remove the last Items - difference = abs(difference); - for (int32 i = 0; i < difference; ++i) + const size_t numToRemove = numOldItems - numItems; + for (size_t i = 0; i < numToRemove; ++i) { - AnimGraphRefCountedData* item = mItems[mFreeItems.GetLength() - 1]; - MCORE_ASSERT(mFreeItems.Contains(item)); // make sure the Item is not already in use + AnimGraphRefCountedData* item = m_items.back(); + MCORE_ASSERT(AZStd::find(begin(m_freeItems), end(m_freeItems), item) != end(m_freeItems)); // make sure the Item is not already in use delete item; - mItems.Remove(mFreeItems.GetLength() - 1); + m_items.erase(m_items.end() - 1); } } else // we want to add new Items { - for (int32 i = 0; i < difference; ++i) + const size_t numToAdd = numItems - numOldItems; + for (size_t i = 0; i < numToAdd; ++i) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); - mItems.Add(newItem); - mFreeItems.Add(newItem); + m_items.emplace_back(newItem); + m_freeItems.emplace_back(newItem); } } } @@ -75,18 +74,18 @@ namespace EMotionFX AnimGraphRefCountedData* AnimGraphRefCountedDataPool::RequestNew() { // if we have no free items left, allocate a new one - if (mFreeItems.GetLength() == 0) + if (m_freeItems.empty()) { AnimGraphRefCountedData* newItem = new AnimGraphRefCountedData(); - mItems.Add(newItem); - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedItems()); + m_items.emplace_back(newItem); + m_maxUsed = AZStd::max(m_maxUsed, GetNumUsedItems()); return newItem; } // request the last free item - AnimGraphRefCountedData* item = mFreeItems[mFreeItems.GetLength() - 1]; - mFreeItems.RemoveLast(); // remove it from the list of free Items - mMaxUsed = MCore::Max(mMaxUsed, GetNumUsedItems()); + AnimGraphRefCountedData* item = m_freeItems[m_freeItems.size() - 1]; + m_freeItems.pop_back(); // remove it from the list of free Items + m_maxUsed = AZStd::max(m_maxUsed, GetNumUsedItems()); return item; } @@ -94,7 +93,7 @@ namespace EMotionFX // free the item again void AnimGraphRefCountedDataPool::Free(AnimGraphRefCountedData* item) { - MCORE_ASSERT(mItems.Contains(item)); - mFreeItems.Add(item); + MCORE_ASSERT(AZStd::find(begin(m_items), end(m_items), item) != end(m_items)); + m_freeItems.emplace_back(item); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h index b3b287fb37..3a7c38ed00 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphRefCountedDataPool.h @@ -11,7 +11,7 @@ // include required headers #include "EMotionFXConfig.h" #include "AnimGraphRefCountedData.h" -#include +#include namespace EMotionFX @@ -29,20 +29,20 @@ namespace EMotionFX AnimGraphRefCountedDataPool(); ~AnimGraphRefCountedDataPool(); - void Resize(uint32 numItems); + void Resize(size_t numItems); AnimGraphRefCountedData* RequestNew(); void Free(AnimGraphRefCountedData* item); - MCORE_INLINE uint32 GetNumFreeItems() const { return mFreeItems.GetLength(); } - MCORE_INLINE uint32 GetNumItems() const { return mItems.GetLength(); } - MCORE_INLINE uint32 GetNumUsedItems() const { return (mItems.GetLength() - mFreeItems.GetLength()); } - MCORE_INLINE uint32 GetNumMaxUsedItems() const { return mMaxUsed; } - MCORE_INLINE void ResetMaxUsedItems() { mMaxUsed = 0; } + MCORE_INLINE size_t GetNumFreeItems() const { return m_freeItems.size(); } + MCORE_INLINE size_t GetNumItems() const { return m_items.size(); } + MCORE_INLINE size_t GetNumUsedItems() const { return m_items.size() - m_freeItems.size(); } + MCORE_INLINE size_t GetNumMaxUsedItems() const { return m_maxUsed; } + MCORE_INLINE void ResetMaxUsedItems() { m_maxUsed = 0; } private: - MCore::Array mItems; - MCore::Array mFreeItems; - uint32 mMaxUsed; + AZStd::vector m_items; + AZStd::vector m_freeItems; + size_t m_maxUsed; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp index 57500b01d9..605810c5cc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.cpp @@ -56,7 +56,7 @@ namespace EMotionFX // to the non-existing old anim graph, while the new one is about to be loaded asynchronously. // In case the asset already got destroyed (AnimGraphAssetHandler::DestroyAsset()), it removed all anim graph instances already. - if (GetAnimGraphManager().FindAnimGraphInstanceIndex(m_referencedAnimGraphInstance) != InvalidIndex32) + if (GetAnimGraphManager().FindAnimGraphInstanceIndex(m_referencedAnimGraphInstance) != InvalidIndex) { m_referencedAnimGraphInstance->Destroy(); } @@ -68,7 +68,7 @@ namespace EMotionFX void AnimGraphReferenceNode::UniqueData::Update() { - AnimGraphReferenceNode* referenceNode = azdynamic_cast(mObject); + AnimGraphReferenceNode* referenceNode = azdynamic_cast(m_object); AZ_Assert(referenceNode, "Unique data linked to incorrect node type."); MotionSet* motionSet = referenceNode->GetMotionSet(); @@ -116,10 +116,10 @@ namespace EMotionFX { // This node listens to changes in AnimGraph and MotionSet assets. We need to remove this node before disconnecting the asset bus to avoid the disconnect // removing the MotionSet which can in turn access this node that is being deleted. - if (mAnimGraph) + if (m_animGraph) { - mAnimGraph->RemoveObject(this); - mAnimGraph = nullptr; + m_animGraph->RemoveObject(this); + m_animGraph = nullptr; } AZ::Data::AssetBus::MultiHandler::BusDisconnect(); } @@ -296,9 +296,9 @@ namespace EMotionFX } // Update the values for attributes that are fed through a connection - AZ_Assert(mInputPorts.size() == m_parameterIndexByPortIndex.size(), "Expected m_parameterIndexByPortIndex and numInputPorts to be in sync"); + AZ_Assert(m_inputPorts.size() == m_parameterIndexByPortIndex.size(), "Expected m_parameterIndexByPortIndex and numInputPorts to be in sync"); - const uint32 numInputPorts = static_cast(mInputPorts.size()); + const uint32 numInputPorts = static_cast(m_inputPorts.size()); for (uint32 i = 0; i < numInputPorts; ++i) { MCore::Attribute* attribute = GetInputAttribute(animGraphInstance, i); // returns the attribute of the upstream side of the connection @@ -375,8 +375,8 @@ namespace EMotionFX // Release any left over ref data for the referenced anim graph instance. const uint32 threadIndex = referencedAnimGraphInstance->GetActorInstance()->GetThreadIndex(); AnimGraphRefCountedDataPool& refDataPool = GetEMotionFX().GetThreadData(threadIndex)->GetRefCountedDataPool(); - const uint32 numReferencedNodes = referencedAnimGraph->GetNumNodes(); - for (uint32 i = 0; i < numReferencedNodes; ++i) + const size_t numReferencedNodes = referencedAnimGraph->GetNumNodes(); + for (size_t i = 0; i < numReferencedNodes; ++i) { const AnimGraphNode* node = referencedAnimGraph->GetNode(i); AnimGraphNodeData* nodeData = static_cast(referencedAnimGraphInstance->GetUniqueObjectData(node->GetObjectIndex())); @@ -437,7 +437,7 @@ namespace EMotionFX AnimGraph* referencedAnimGraph = GetReferencedAnimGraph(); if (referencedAnimGraph) { - UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData && uniqueData->m_referencedAnimGraphInstance) { uniqueData->m_referencedAnimGraphInstance->RecursiveInvalidateUniqueDatas(); @@ -499,7 +499,7 @@ namespace EMotionFX } - void AnimGraphReferenceNode::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphReferenceNode::RecursiveCollectObjects(AZStd::vector& outObjects) const { AnimGraphNode::RecursiveCollectObjects(outObjects); @@ -531,10 +531,10 @@ namespace EMotionFX // Use an anim graph instance to recursively go through the parents. If we hit a parent that is referenceAnimGraph, // that means that the child we are about to add is a parent, therefore a cycle - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); if (numAnimGraphInstances > 0) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(0); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(0); do { if (animGraphInstance->GetAnimGraph() == referenceAnimGraph) @@ -627,11 +627,11 @@ namespace EMotionFX { // Inform the unique datas as well as other systems about the changed anim graph asset, destroy and nullptr the reference // anim graph instances so that we don't try to update an anim graph instance or while the asset already got destructed. - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); - UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); + UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData) { uniqueData->OnReferenceAnimGraphAssetChanged(); @@ -667,11 +667,11 @@ namespace EMotionFX void AnimGraphReferenceNode::OnMaskedParametersChanged() { - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); - UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(mObjectIndex)); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); + UniqueData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(m_objectIndex)); if (uniqueData) { uniqueData->m_parameterMappingCacheDirty = true; @@ -834,10 +834,10 @@ namespace EMotionFX { MotionSet* motionSet = GetMotionSet(); - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); if (uniqueData->m_referencedAnimGraphInstance) @@ -886,7 +886,7 @@ namespace EMotionFX // exclude those parameters for (const AnimGraphNode::Port& port : GetInputPorts()) { - if (port.mConnection) + if (port.m_connection) { parameterNames.emplace_back(port.GetNameString()); } @@ -979,7 +979,7 @@ namespace EMotionFX AZ_Assert(!GetNumConnections(), "Unexpected connections"); - const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); + const ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); const ValueParameterVector& referencedValueParameters = referencedAnimGraph->RecursivelyGetValueParameters(); // For each parameter in referencedValueParameters, if it is not in valueParameters or is not compatible, add it @@ -1014,10 +1014,10 @@ namespace EMotionFX m_reinitMaskedParameters = false; } - bool portChanged = !mInputPorts.empty(); + bool portChanged = !m_inputPorts.empty(); // Remove all input ports - mInputPorts.clear(); + m_inputPorts.clear(); m_parameterIndexByPortIndex.clear(); // Get the ValueParameters from the AnimGraph @@ -1054,16 +1054,16 @@ namespace EMotionFX }), m_maskedParameterNames.end() ); - mConnections.erase( - AZStd::remove_if(mConnections.begin(), mConnections.end(), [&removedPortIndexes](const BlendTreeConnection* connection) + m_connections.erase( + AZStd::remove_if(m_connections.begin(), m_connections.end(), [&removedPortIndexes](const BlendTreeConnection* connection) { return removedPortIndexes.find(connection->GetTargetPort()) != removedPortIndexes.end(); }), - mConnections.end() + m_connections.end() ); // Shift the port indexes of the remaining connections - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { AZ::u16 originalTargetPort = connection->GetTargetPort(); AZ::u16 targetPort = originalTargetPort; @@ -1115,17 +1115,17 @@ namespace EMotionFX // Update the input ports. Don't call RelinkPortConnections, // because ReinitInputPorts cannot guarantee that the connected // nodes have been initialized - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { const AZ::u16 targetPortNr = connection->GetTargetPort(); - if (targetPortNr < mInputPorts.size()) + if (targetPortNr < m_inputPorts.size()) { - mInputPorts[targetPortNr].mConnection = connection; + m_inputPorts[targetPortNr].m_connection = connection; } else { - AZ_Error("EMotionFX", false, "Can't make connection to input port %i of '%s', max port count is %i.", targetPortNr, GetName(), mInputPorts.size()); + AZ_Error("EMotionFX", false, "Can't make connection to input port %i of '%s', max port count is %i.", targetPortNr, GetName(), m_inputPorts.size()); } } AnimGraphNotificationBus::Broadcast(&AnimGraphNotificationBus::Events::OnSyncVisualObject, this); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.h index 23bb6ac138..db4dc0ea3e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphReferenceNode.h @@ -98,7 +98,7 @@ namespace EMotionFX void RecursiveCollectActiveNodes(AnimGraphInstance* animGraphInstance, AZStd::vector* outNodes, const AZ::TypeId& nodeType) const override; AnimGraphPose* GetMainOutputPose(AnimGraphInstance* animGraphInstance) const override; - void RecursiveCollectObjects(MCore::Array& outObjects) const override; + void RecursiveCollectObjects(AZStd::vector& outObjects) const override; void RecursiveCollectObjectsAffectedBy(AnimGraph* animGraph, AZStd::vector& outObjects) const override; bool RecursiveDetectCycles(AZStd::unordered_set& nodes) const override; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp index 110a35781e..b0a7134043 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSnapshot.cpp @@ -41,7 +41,7 @@ namespace EMotionFX const size_t numValueParameters = instance.GetAnimGraph()->GetNumValueParameters(); for (size_t i = 0; i < numValueParameters; ++i) { - m_parameters.emplace_back(instance.GetParameterValue(static_cast(i))->Clone()); + m_parameters.emplace_back(instance.GetParameterValue(i)->Clone()); } } @@ -62,7 +62,7 @@ namespace EMotionFX return m_parameters; } - void AnimGraphSnapshot::SetActiveNodes(const AZStd::vector& activeNodes) + void AnimGraphSnapshot::SetActiveNodes(const NodeIndexContainer& activeNodes) { if (m_activeStateNodes != activeNodes) { @@ -71,7 +71,7 @@ namespace EMotionFX } } - const AZStd::vector& AnimGraphSnapshot::GetActiveNodes() const + const NodeIndexContainer& AnimGraphSnapshot::GetActiveNodes() const { return m_activeStateNodes; } @@ -94,7 +94,7 @@ namespace EMotionFX for (size_t i = 0; i < numParams; ++i) { - m_parameters[i]->InitFrom(instance.GetParameterValue(static_cast(i))); + m_parameters[i]->InitFrom(instance.GetParameterValue(i)); } } @@ -111,7 +111,7 @@ namespace EMotionFX AnimGraphNode* currentState = stateMachine->GetCurrentState(&instance); AZ_Assert(currentState, "There should always be a valid current state."); - m_activeStateNodes.emplace_back(currentState->GetNodeIndex()); + m_activeStateNodes.emplace_back(aznumeric_caster(currentState->GetNodeIndex())); } } @@ -123,9 +123,9 @@ namespace EMotionFX for (const AnimGraphNode* animGraphNode : tempGraphNodes) { - const AZ::u32 nodeIndex = animGraphNode->GetNodeIndex(); + const size_t nodeIndex = animGraphNode->GetNodeIndex(); float normalizedPlaytime = animGraphNode->GetCurrentPlayTime(&instance) / animGraphNode->GetDuration(&instance); - m_motionNodePlaytimes.emplace_back(nodeIndex, normalizedPlaytime); + m_motionNodePlaytimes.emplace_back(aznumeric_caster(nodeIndex), normalizedPlaytime); } } @@ -135,14 +135,14 @@ namespace EMotionFX for (size_t i = 0; i < numParams; ++i) { - MCore::Attribute* attribute = instance.GetParameterValue(static_cast(i)); + MCore::Attribute* attribute = instance.GetParameterValue(i); attribute->InitFrom(m_parameters[i]); } } void AnimGraphSnapshot::RestoreActiveNodes(AnimGraphInstance& instance) { - for (const AZ::u32 nodeIndex : m_activeStateNodes) + for (const size_t nodeIndex : m_activeStateNodes) { AnimGraphNode* node = instance.GetAnimGraph()->GetNode(nodeIndex); AnimGraphNode* parent = node->GetParentNode(); @@ -159,7 +159,7 @@ namespace EMotionFX if (AZStd::find(activeStates.begin(), activeStates.end(), node) == activeStates.end()) { stateMachine->EndAllActiveTransitions(&instance); - uniqueData->mCurrentState = node; + uniqueData->m_currentState = node; } } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp index 341f045918..4a81cf585b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.cpp @@ -63,7 +63,7 @@ namespace EMotionFX return; } - m_state = mAnimGraph->RecursiveFindNodeById(m_stateId); + m_state = m_animGraph->RecursiveFindNodeById(m_stateId); } @@ -100,7 +100,7 @@ namespace EMotionFX { // in case a event got triggered constantly fire true until the condition gets reset const UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - if (uniqueData->mTriggered) + if (uniqueData->m_triggered) { return true; } @@ -149,7 +149,7 @@ namespace EMotionFX // reached the specified play time if (m_state) { - const float currentLocalTime = m_state->GetCurrentPlayTime(uniqueData->mAnimGraphInstance); + const float currentLocalTime = m_state->GetCurrentPlayTime(uniqueData->m_animGraphInstance); // the has reached play time condition is not part of the event handler, so we have to manually handle it here if (AZ::IsClose(currentLocalTime, m_playTime, AZ::Constants::FloatEpsilon) || currentLocalTime >= m_playTime) { @@ -170,7 +170,7 @@ namespace EMotionFX { // find the unique data and reset it UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - uniqueData->mTriggered = false; + uniqueData->m_triggered = false; } // construct and output the information summary string for this object @@ -221,10 +221,10 @@ namespace EMotionFX // constructor AnimGraphStateCondition::UniqueData::UniqueData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance) : AnimGraphObjectData(object, animGraphInstance) - , mAnimGraphInstance(animGraphInstance) + , m_animGraphInstance(animGraphInstance) { - mEventHandler = nullptr; - mTriggered = false; + m_eventHandler = nullptr; + m_triggered = false; CreateEventHandler(); } @@ -240,22 +240,22 @@ namespace EMotionFX { DeleteEventHandler(); - if (mAnimGraphInstance) + if (m_animGraphInstance) { - mEventHandler = aznew AnimGraphStateCondition::EventHandler(static_cast(mObject), this); - mAnimGraphInstance->AddEventHandler(mEventHandler); + m_eventHandler = aznew AnimGraphStateCondition::EventHandler(static_cast(m_object), this); + m_animGraphInstance->AddEventHandler(m_eventHandler); } } void AnimGraphStateCondition::UniqueData::DeleteEventHandler() { - if (mEventHandler) + if (m_eventHandler) { - mAnimGraphInstance->RemoveEventHandler(mEventHandler); + m_animGraphInstance->RemoveEventHandler(m_eventHandler); - delete mEventHandler; - mEventHandler = nullptr; + delete m_eventHandler; + m_eventHandler = nullptr; } } @@ -279,8 +279,8 @@ namespace EMotionFX AnimGraphStateCondition::EventHandler::EventHandler(AnimGraphStateCondition* condition, UniqueData* uniqueData) : EMotionFX::AnimGraphInstanceEventHandler() { - mCondition = condition; - mUniqueData = uniqueData; + m_condition = condition; + m_uniqueData = uniqueData; } @@ -292,7 +292,7 @@ namespace EMotionFX bool AnimGraphStateCondition::EventHandler::IsTargetState(const AnimGraphNode* state) const { - const AnimGraphNode* conditionState = mCondition->GetState(); + const AnimGraphNode* conditionState = m_condition->GetState(); if (conditionState) { const AZStd::string& stateName = conditionState->GetNameString(); @@ -311,10 +311,10 @@ namespace EMotionFX return; } - const TestFunction testFunction = mCondition->GetTestFunction(); + const TestFunction testFunction = m_condition->GetTestFunction(); if (testFunction == targetFunction && IsTargetState(state)) { - mUniqueData->mTriggered = true; + m_uniqueData->m_triggered = true; } } @@ -355,7 +355,7 @@ namespace EMotionFX void AnimGraphStateCondition::SetStateId(AnimGraphNodeId stateId) { m_stateId = stateId; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.h index bc4ca4bf75..1c772e8fbe 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateCondition.h @@ -63,9 +63,9 @@ namespace EMotionFX // The anim graph instance pointer shouldn't change. If it were to // change, we'd need to remove an existing event handler and create // a new one in the new anim graph instance. - AnimGraphInstance* const mAnimGraphInstance; - AnimGraphStateCondition::EventHandler* mEventHandler; - bool mTriggered; + AnimGraphInstance* const m_animGraphInstance; + AnimGraphStateCondition::EventHandler* m_eventHandler; + bool m_triggered; }; AnimGraphStateCondition(); @@ -125,8 +125,8 @@ namespace EMotionFX bool IsTargetState(const AnimGraphNode* state) const; void OnStateChange(AnimGraphInstance* animGraphInstance, AnimGraphNode* state, TestFunction targetFunction); - AnimGraphStateCondition* mCondition; - UniqueData* mUniqueData; + AnimGraphStateCondition* m_condition; + UniqueData* m_uniqueData; }; AZ::Crc32 GetTestFunctionVisibility() const; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp index 2db1d920ef..9b4c2d07ac 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.cpp @@ -35,8 +35,8 @@ namespace EMotionFX AnimGraphStateMachine::AnimGraphStateMachine() : AnimGraphNode() - , mEntryState(nullptr) - , mEntryStateNodeNr(MCORE_INVALIDINDEX32) + , m_entryState(nullptr) + , m_entryStateNodeNr(InvalidIndex) , m_entryStateId(AnimGraphNodeId::InvalidId) , m_alwaysStartInEntryState(true) { @@ -55,7 +55,7 @@ namespace EMotionFX // Re-initialize all child nodes and connections AnimGraphNode::RecursiveReinit(); - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { transition->RecursiveReinit(); } @@ -68,7 +68,7 @@ namespace EMotionFX return false; } - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { transition->InitAfterLoading(animGraph); } @@ -82,12 +82,12 @@ namespace EMotionFX void AnimGraphStateMachine::RemoveAllTransitions() { - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { delete transition; } - mTransitions.clear(); + m_transitions.clear(); } void AnimGraphStateMachine::Output(AnimGraphInstance* animGraphInstance) @@ -95,7 +95,7 @@ namespace EMotionFX ActorInstance* actorInstance = animGraphInstance->GetActorInstance(); AnimGraphPose* outputPose = nullptr; - if (mDisabled) + if (m_disabled) { // Output bind pose in case state machine is disabled. RequestPoses(animGraphInstance); @@ -114,13 +114,13 @@ namespace EMotionFX const AZStd::vector& activeStates = uniqueData->GetActiveStates(); // Single active state, no active transition. - if (!isTransitioning && uniqueData->mCurrentState) + if (!isTransitioning && uniqueData->m_currentState) { - uniqueData->mCurrentState->PerformOutput(animGraphInstance); + uniqueData->m_currentState->PerformOutput(animGraphInstance); RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); - *outputPose = *uniqueData->mCurrentState->GetMainOutputPose(animGraphInstance); + *outputPose = *uniqueData->m_currentState->GetMainOutputPose(animGraphInstance); } // One or more transitions active. else if (isTransitioning) @@ -184,7 +184,7 @@ namespace EMotionFX if (outputPose && GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -204,9 +204,8 @@ namespace EMotionFX bool requestInterruption = false; const bool isTransitioning = IsTransitioning(animGraphInstance); AnimGraphStateTransition* latestActiveTransition = GetLatestActiveTransition(uniqueData); - const AnimGraphNodeId sourceNodeId = sourceNode->GetId(); - for (AnimGraphStateTransition* curTransition : mTransitions) + for (AnimGraphStateTransition* curTransition : m_transitions) { if (curTransition->GetIsDisabled()) { @@ -322,7 +321,7 @@ namespace EMotionFX } const bool isTransitioning = IsTransitioning(animGraphInstance); - for (const AnimGraphStateTransition* transition : mTransitions) + for (const AnimGraphStateTransition* transition : m_transitions) { // get the current transition and skip it directly if in case it is disabled if (transition->GetIsDisabled()) @@ -370,7 +369,7 @@ namespace EMotionFX // Update the source node for the transition instance in case we're dealing with a wildcard transition. if (transition->GetIsWildcardTransition()) { - sourceNode = uniqueData->mCurrentState; + sourceNode = uniqueData->m_currentState; transition->SetSourceNode(animGraphInstance, sourceNode); } @@ -423,7 +422,6 @@ namespace EMotionFX AnimGraphNode* targetState = transition->GetTargetNode(); AnimGraphStateTransition* latestActiveTransition = GetLatestActiveTransition(uniqueData); const bool isLatestTransition = (latestActiveTransition == transition); - const bool isDone = transition->GetIsDone(animGraphInstance); EventManager& eventManager = GetEventManager(); // End transition and emit transition events. @@ -433,7 +431,7 @@ namespace EMotionFX // Reset the conditions of the transition that has just ended. transition->ResetConditions(animGraphInstance); - targetState->OnStateEnter(animGraphInstance, uniqueData->mCurrentState, transition); + targetState->OnStateEnter(animGraphInstance, uniqueData->m_currentState, transition); eventManager.OnStateEnter(animGraphInstance, targetState); // Ending latest active transition. @@ -441,11 +439,11 @@ namespace EMotionFX { // Emit end state events and adjust the previous and the active states in case the latest active transition is ending. // In other cases we're not leaving the current state yet as it is still active as a source state from another active transition. - uniqueData->mCurrentState->OnStateEnd(animGraphInstance, targetState, transition); - eventManager.OnStateEnd(animGraphInstance, uniqueData->mCurrentState); + uniqueData->m_currentState->OnStateEnd(animGraphInstance, targetState, transition); + eventManager.OnStateEnd(animGraphInstance, uniqueData->m_currentState); - uniqueData->mPreviousState = uniqueData->mCurrentState; - uniqueData->mCurrentState = targetState; + uniqueData->m_previousState = uniqueData->m_currentState; + uniqueData->m_currentState = targetState; } // Ending any interrupted transition on the transition stack that ended transitioning. else if (transition->GetIsDone(animGraphInstance)) @@ -481,14 +479,14 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); // Defer switch to entry state. - if (uniqueData->mSwitchToEntryState) + if (uniqueData->m_switchToEntryState) { AnimGraphNode* entryState = GetEntryState(); if (entryState) { SwitchToState(animGraphInstance, entryState); } - uniqueData->mSwitchToEntryState = false; + uniqueData->m_switchToEntryState = false; } // Update all currently active transitions. @@ -509,8 +507,8 @@ namespace EMotionFX } // Update the conditions and trigger the right transition based on the conditions and priority levels etc. - UpdateConditions(animGraphInstance, uniqueData->mCurrentState, timePassedInSeconds); - CheckConditions(uniqueData->mCurrentState, animGraphInstance, uniqueData, /*calledFromWithinUpdate*/ true); + UpdateConditions(animGraphInstance, uniqueData->m_currentState, timePassedInSeconds); + CheckConditions(uniqueData->m_currentState, animGraphInstance, uniqueData, /*calledFromWithinUpdate*/ true); #ifdef ENABLE_SINGLEFRAME_MULTISTATETRANSITIONING // Check if our latest active transition is already done, end it and check for further transition candidates. @@ -521,8 +519,8 @@ namespace EMotionFX // End all transitions on the stack back to front EndAllActiveTransitions(animGraphInstance, uniqueData); - UpdateConditions(animGraphInstance, uniqueData->mCurrentState, 0.0f); - CheckConditions(uniqueData->mCurrentState, animGraphInstance, uniqueData, /*calledFromWithinUpdate=*/true); + UpdateConditions(animGraphInstance, uniqueData->m_currentState, 0.0f); + CheckConditions(uniqueData->m_currentState, animGraphInstance, uniqueData, /*calledFromWithinUpdate=*/true); if (numPasses >= s_maxNumPasses) { @@ -547,9 +545,9 @@ namespace EMotionFX UpdateExitStateReachedFlag(animGraphInstance, uniqueData); // Perform play speed synchronization when transitioning. - if (uniqueData->mCurrentState) + if (uniqueData->m_currentState) { - uniqueData->Init(animGraphInstance, uniqueData->mCurrentState); + uniqueData->Init(animGraphInstance, uniqueData->m_currentState); if (IsTransitioning(uniqueData)) { @@ -614,12 +612,12 @@ namespace EMotionFX { if (azrtti_typeid(activeState) == azrtti_typeid()) { - uniqueData->mReachedExitState = true; + uniqueData->m_reachedExitState = true; return; } } - uniqueData->mReachedExitState = false; + uniqueData->m_reachedExitState = false; } void AnimGraphStateMachine::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) @@ -646,7 +644,7 @@ namespace EMotionFX if (!IsTransitioning(uniqueData)) { - AnimGraphNode* activeState = uniqueData->mCurrentState; + AnimGraphNode* activeState = uniqueData->m_currentState; if (activeState) { // Single active state, no active transition. @@ -730,28 +728,28 @@ namespace EMotionFX } // tell the current node to which node we're exiting - if (uniqueData->mCurrentState) + if (uniqueData->m_currentState) { - uniqueData->mCurrentState->OnStateExit(animGraphInstance, targetState, nullptr); - uniqueData->mCurrentState->OnStateEnd(animGraphInstance, targetState, nullptr); + uniqueData->m_currentState->OnStateExit(animGraphInstance, targetState, nullptr); + uniqueData->m_currentState->OnStateEnd(animGraphInstance, targetState, nullptr); } // tell the new current node from which node we're coming if (targetState) { - targetState->OnStateEntering(animGraphInstance, uniqueData->mCurrentState, nullptr); - targetState->OnStateEnter(animGraphInstance, uniqueData->mCurrentState, nullptr); + targetState->OnStateEntering(animGraphInstance, uniqueData->m_currentState, nullptr); + targetState->OnStateEnter(animGraphInstance, uniqueData->m_currentState, nullptr); } // Inform the event manager. EventManager& eventManager = GetEventManager(); - eventManager.OnStateExit(animGraphInstance, uniqueData->mCurrentState); + eventManager.OnStateExit(animGraphInstance, uniqueData->m_currentState); eventManager.OnStateEntering(animGraphInstance, targetState); - eventManager.OnStateEnd(animGraphInstance, uniqueData->mCurrentState); + eventManager.OnStateEnd(animGraphInstance, uniqueData->m_currentState); eventManager.OnStateEnter(animGraphInstance, targetState); - uniqueData->mPreviousState = uniqueData->mCurrentState; - uniqueData->mCurrentState = targetState; + uniqueData->m_previousState = uniqueData->m_currentState; + uniqueData->m_currentState = targetState; uniqueData->m_activeTransitions.clear(); } @@ -816,7 +814,7 @@ namespace EMotionFX void AnimGraphStateMachine::AddTransition(AnimGraphStateTransition* transition) { - mTransitions.push_back(transition); + m_transitions.push_back(transition); } AnimGraphStateTransition* AnimGraphStateMachine::FindTransition(AnimGraphInstance* animGraphInstance, AnimGraphNode* currentState, AnimGraphNode* targetState) const @@ -845,7 +843,7 @@ namespace EMotionFX AnimGraphStateTransition* prioritizedTransition = nullptr; // first check if there is a ready transition that points directly to the target state - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { // get the current transition and skip it directly if in case it is disabled if (transition->GetIsDisabled()) @@ -877,7 +875,7 @@ namespace EMotionFX /////////////////////////////////////////////////////////////////////// // in case there is no direct and no indirect transition ready, check for wildcard transitions // there is a maximum number of one for wild card transitions, so we don't need to check the priority values here - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { // get the current transition and skip it directly if in case it is disabled if (transition->GetIsDisabled()) @@ -898,10 +896,10 @@ namespace EMotionFX AZ::Outcome AnimGraphStateMachine::FindTransitionIndexById(AnimGraphConnectionId transitionId) const { - const size_t numTransitions = mTransitions.size(); + const size_t numTransitions = m_transitions.size(); for (size_t i = 0; i < numTransitions; ++i) { - if (mTransitions[i]->GetId() == transitionId) + if (m_transitions[i]->GetId() == transitionId) { return AZ::Success(i); } @@ -912,10 +910,10 @@ namespace EMotionFX AZ::Outcome AnimGraphStateMachine::FindTransitionIndex(const AnimGraphStateTransition* transition) const { - const auto& iterator = AZStd::find(mTransitions.begin(), mTransitions.end(), transition); - if (iterator != mTransitions.end()) + const auto& iterator = AZStd::find(m_transitions.begin(), m_transitions.end(), transition); + if (iterator != m_transitions.end()) { - const size_t index = iterator - mTransitions.begin(); + const size_t index = iterator - m_transitions.begin(); return AZ::Success(index); } @@ -927,7 +925,7 @@ namespace EMotionFX const AZ::Outcome transitionIndex = FindTransitionIndexById(transitionId); if (transitionIndex.IsSuccess()) { - return mTransitions[transitionIndex.GetValue()]; + return m_transitions[transitionIndex.GetValue()]; } return nullptr; @@ -935,7 +933,7 @@ namespace EMotionFX bool AnimGraphStateMachine::CheckIfHasWildcardTransition(AnimGraphNode* state) const { - for (const AnimGraphStateTransition* transition : mTransitions) + for (const AnimGraphStateTransition* transition : m_transitions) { // check if the given transition is a wildcard transition and if the target node is the given one if (transition->GetTargetNode() == state && transition->GetIsWildcardTransition()) @@ -951,10 +949,10 @@ namespace EMotionFX { if (delFromMem) { - delete mTransitions[transitionIndex]; + delete m_transitions[transitionIndex]; } - mTransitions.erase(mTransitions.begin() + transitionIndex); + m_transitions.erase(m_transitions.begin() + transitionIndex); } AnimGraphNode* AnimGraphStateMachine::GetEntryState() @@ -962,38 +960,38 @@ namespace EMotionFX const AnimGraphNodeId entryStateId = GetEntryStateId(); if (entryStateId.IsValid()) { - if (!mEntryState || (mEntryState && mEntryState->GetId() != entryStateId)) + if (!m_entryState || (m_entryState && m_entryState->GetId() != entryStateId)) { // Sync the entry state based on the id. - mEntryState = FindChildNodeById(entryStateId); + m_entryState = FindChildNodeById(entryStateId); } } else { // Legacy file format way. - if (!mEntryState) + if (!m_entryState) { - if (mEntryStateNodeNr != MCORE_INVALIDINDEX32 && mEntryStateNodeNr < GetNumChildNodes()) + if (m_entryStateNodeNr != InvalidIndex && m_entryStateNodeNr < GetNumChildNodes()) { - mEntryState = GetChildNode(mEntryStateNodeNr); + m_entryState = GetChildNode(m_entryStateNodeNr); } } // End: Legacy file format way. // TODO: Enable this line when deprecating the leagacy file format. - //mEntryState = nullptr; + // m_entryState = nullptr; } - return mEntryState; + return m_entryState; } void AnimGraphStateMachine::SetEntryState(AnimGraphNode* entryState) { - mEntryState = entryState; + m_entryState = entryState; - if (mEntryState) + if (m_entryState) { - m_entryStateId = mEntryState->GetId(); + m_entryStateId = m_entryState->GetId(); } else { @@ -1001,25 +999,25 @@ namespace EMotionFX } // Used for the legacy file format. Get rid of this along with the old file format. - mEntryStateNodeNr = FindChildNodeIndex(mEntryState); + m_entryStateNodeNr = FindChildNodeIndex(m_entryState); } AnimGraphNode* AnimGraphStateMachine::GetCurrentState(AnimGraphInstance* animGraphInstance) { UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueNodeData(this)); - return uniqueData->mCurrentState; + return uniqueData->m_currentState; } bool AnimGraphStateMachine::GetExitStateReached(AnimGraphInstance* animGraphInstance) const { // get the unique data for this state machine in a given anim graph instance UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueNodeData(this)); - return uniqueData->mReachedExitState; + return uniqueData->m_reachedExitState; } void AnimGraphStateMachine::RecursiveOnChangeMotionSet(AnimGraphInstance* animGraphInstance, MotionSet* newMotionSet) { - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { transition->OnChangeMotionSet(animGraphInstance, newMotionSet); } @@ -1031,18 +1029,18 @@ namespace EMotionFX void AnimGraphStateMachine::OnRemoveNode(AnimGraph* animGraph, AnimGraphNode* nodeToRemove) { // is the node to remove the entry state? - if (mEntryState == nodeToRemove) + if (m_entryState == nodeToRemove) { SetEntryState(nullptr); } - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { transition->OnRemoveNode(animGraph, nodeToRemove); } bool childNodeRemoved = false; - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { if (childNode == nodeToRemove) { @@ -1062,7 +1060,7 @@ namespace EMotionFX { ResetUniqueData(animGraphInstance); - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RecursiveResetUniqueDatas(animGraphInstance); } @@ -1072,7 +1070,7 @@ namespace EMotionFX { AnimGraphNode::RecursiveInvalidateUniqueDatas(animGraphInstance); - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { transition->RecursiveInvalidateUniqueDatas(animGraphInstance); } @@ -1083,25 +1081,25 @@ namespace EMotionFX void AnimGraphStateMachine::UniqueData::Reset() { m_activeTransitions.clear(); - mCurrentState = nullptr; - mPreviousState = nullptr; - mReachedExitState = false; - mSwitchToEntryState = true; + m_currentState = nullptr; + m_previousState = nullptr; + m_reachedExitState = false; + m_switchToEntryState = true; } void AnimGraphStateMachine::UniqueData::Update() { - AnimGraphStateMachine* stateMachine = azdynamic_cast(mObject); + AnimGraphStateMachine* stateMachine = azdynamic_cast(m_object); AZ_Assert(stateMachine, "Unique data linked to incorrect node type."); // check if any of the active states are invalid and reset them if they are - if (mCurrentState && stateMachine->FindChildNodeIndex(mCurrentState) == MCORE_INVALIDINDEX32) + if (m_currentState && stateMachine->FindChildNodeIndex(m_currentState) == InvalidIndex) { - mCurrentState = nullptr; + m_currentState = nullptr; } - if (mPreviousState && stateMachine->FindChildNodeIndex(mPreviousState) == MCORE_INVALIDINDEX32) + if (m_previousState && stateMachine->FindChildNodeIndex(m_previousState) == InvalidIndex) { - mPreviousState = nullptr; + m_previousState = nullptr; } // Check if the currently active transitions are valid and remove them from the transition stack if not. @@ -1113,8 +1111,8 @@ namespace EMotionFX const bool isTransitionValid = transition && stateMachine->FindTransitionIndex(transition).IsSuccess() && - stateMachine->FindChildNodeIndex(transition->GetSourceNode(GetAnimGraphInstance())) != MCORE_INVALIDINDEX32 && - stateMachine->FindChildNodeIndex(transition->GetTargetNode()) != MCORE_INVALIDINDEX32; + stateMachine->FindChildNodeIndex(transition->GetSourceNode(GetAnimGraphInstance())) != InvalidIndex && + stateMachine->FindChildNodeIndex(transition->GetTargetNode()) != InvalidIndex; if (!isTransitionValid) { @@ -1127,9 +1125,9 @@ namespace EMotionFX { m_activeStates.clear(); - if (mCurrentState) + if (m_currentState) { - m_activeStates.emplace_back(mCurrentState); + m_activeStates.emplace_back(m_currentState); } // Add target state for all active transitions to the active states. @@ -1160,40 +1158,40 @@ namespace EMotionFX // rewind the state machine if (m_alwaysStartInEntryState && entryState) { - if (uniqueData->mCurrentState) + if (uniqueData->m_currentState) { - uniqueData->mCurrentState->OnStateExit(animGraphInstance, entryState, nullptr); - uniqueData->mCurrentState->OnStateEnd(animGraphInstance, entryState, nullptr); + uniqueData->m_currentState->OnStateExit(animGraphInstance, entryState, nullptr); + uniqueData->m_currentState->OnStateEnd(animGraphInstance, entryState, nullptr); - GetEventManager().OnStateExit(animGraphInstance, uniqueData->mCurrentState); - GetEventManager().OnStateEnd(animGraphInstance, uniqueData->mCurrentState); + GetEventManager().OnStateExit(animGraphInstance, uniqueData->m_currentState); + GetEventManager().OnStateEnd(animGraphInstance, uniqueData->m_currentState); } // rewind the entry state and reset conditions of all outgoing transitions entryState->Rewind(animGraphInstance); ResetOutgoingTransitionConditions(animGraphInstance, entryState); - mEntryState->OnStateEntering(animGraphInstance, uniqueData->mCurrentState, nullptr); - mEntryState->OnStateEnter(animGraphInstance, uniqueData->mCurrentState, nullptr); + m_entryState->OnStateEntering(animGraphInstance, uniqueData->m_currentState, nullptr); + m_entryState->OnStateEnter(animGraphInstance, uniqueData->m_currentState, nullptr); GetEventManager().OnStateEntering(animGraphInstance, entryState); GetEventManager().OnStateEnter(animGraphInstance, entryState); // reset the the unique data of the state machine and overwrite the current state as that is not nullptr but the entry state uniqueData->Reset(); - uniqueData->mCurrentState = entryState; + uniqueData->m_currentState = entryState; } } void AnimGraphStateMachine::RecursiveResetFlags(AnimGraphInstance* animGraphInstance, uint32 flagsToDisable) { // clear the output for all child nodes, just to make sure - for (const AnimGraphNode* childNode : mChildNodes) + for (const AnimGraphNode* childNode : m_childNodes) { animGraphInstance->DisableObjectFlags(childNode->GetObjectIndex(), flagsToDisable); } // Reset flags for this state machine. - animGraphInstance->DisableObjectFlags(mObjectIndex, flagsToDisable); + animGraphInstance->DisableObjectFlags(m_objectIndex, flagsToDisable); // Reset flags recursively for all active states within this state machine. const AZStd::vector& activeStates = GetActiveStates(animGraphInstance); @@ -1211,7 +1209,7 @@ namespace EMotionFX void AnimGraphStateMachine::ResetOutgoingTransitionConditions(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { - for (AnimGraphStateTransition* transition : mTransitions) + for (AnimGraphStateTransition* transition : m_transitions) { // get the transition, check if it is a possible outgoing connection for our given state and reset it in this case if (transition->GetIsWildcardTransition() || @@ -1225,7 +1223,7 @@ namespace EMotionFX uint32 AnimGraphStateMachine::CalcNumIncomingTransitions(AnimGraphNode* state) const { uint32 result = 0; - for (const AnimGraphStateTransition* transition : mTransitions) + for (const AnimGraphStateTransition* transition : m_transitions) { if (transition->GetTargetNode() == state) { @@ -1238,7 +1236,7 @@ namespace EMotionFX uint32 AnimGraphStateMachine::CalcNumWildcardTransitions(AnimGraphNode* state) const { uint32 result = 0; - for (const AnimGraphStateTransition* transition : mTransitions) + for (const AnimGraphStateTransition* transition : m_transitions) { if (transition->GetIsWildcardTransition() && transition->GetTargetNode() == state) { @@ -1267,7 +1265,7 @@ namespace EMotionFX uint32 AnimGraphStateMachine::CalcNumOutgoingTransitions(AnimGraphNode* state) const { uint32 result = 0; - for (const AnimGraphStateTransition* transition : mTransitions) + for (const AnimGraphStateTransition* transition : m_transitions) { if (!transition->GetIsWildcardTransition() && transition->GetSourceNode() == state) { @@ -1277,9 +1275,9 @@ namespace EMotionFX return result; } - void AnimGraphStateMachine::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphStateMachine::RecursiveCollectObjects(AZStd::vector& outObjects) const { - for (const AnimGraphStateTransition* transition : mTransitions) + for (const AnimGraphStateTransition* transition : m_transitions) { transition->RecursiveCollectObjects(outObjects); // this will automatically add all transition conditions as well } @@ -1350,7 +1348,7 @@ namespace EMotionFX if (!IsTransitioning(uniqueData)) { - AnimGraphNode* activeState = uniqueData->mCurrentState; + AnimGraphNode* activeState = uniqueData->m_currentState; if (activeState) { // Single active state, no active transition. @@ -1376,7 +1374,7 @@ namespace EMotionFX if (syncMode != SYNCMODE_DISABLED) { - if (animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) + if (animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) { sourceNode->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_SYNCED, true); animGraphInstance->SetObjectFlags(sourceNode->GetObjectIndex(), AnimGraphInstance::OBJECTFLAGS_IS_SYNCLEADER, true); @@ -1422,9 +1420,9 @@ namespace EMotionFX { Reset(); - AnimGraphStateMachine* stateMachine = azdynamic_cast(mObject); + AnimGraphStateMachine* stateMachine = azdynamic_cast(m_object); AZ_Assert(stateMachine, "Unique data linked to incorrect node type."); - mCurrentState = stateMachine->GetEntryState(); + m_currentState = stateMachine->GetEntryState(); } uint32 AnimGraphStateMachine::UniqueData::Save(uint8* outputBuffer) const @@ -1440,8 +1438,8 @@ namespace EMotionFX resultSize += chunkSize; SaveVectorOfObjects(m_activeTransitions, &destBuffer, resultSize); - SaveChunk((uint8*)&mCurrentState, sizeof(AnimGraphNode*), &destBuffer, resultSize); - SaveChunk((uint8*)&mPreviousState, sizeof(AnimGraphNode*), &destBuffer, resultSize); + SaveChunk((uint8*)&m_currentState, sizeof(AnimGraphNode*), &destBuffer, resultSize); + SaveChunk((uint8*)&m_previousState, sizeof(AnimGraphNode*), &destBuffer, resultSize); return resultSize; } @@ -1456,8 +1454,8 @@ namespace EMotionFX resultSize += chunkSize; LoadVectorOfObjects(m_activeTransitions, &sourceBuffer, resultSize); - LoadChunk((uint8*)&mCurrentState, sizeof(AnimGraphNode*), &sourceBuffer, resultSize); - LoadChunk((uint8*)&mPreviousState, sizeof(AnimGraphNode*), &sourceBuffer, resultSize); + LoadChunk((uint8*)&m_currentState, sizeof(AnimGraphNode*), &sourceBuffer, resultSize); + LoadChunk((uint8*)&m_previousState, sizeof(AnimGraphNode*), &sourceBuffer, resultSize); return resultSize; } @@ -1465,7 +1463,7 @@ namespace EMotionFX void AnimGraphStateMachine::RecursiveSetUniqueDataFlag(AnimGraphInstance* animGraphInstance, uint32 flag, bool enabled) { // Set flag for this state machine. - animGraphInstance->SetObjectFlags(mObjectIndex, flag, enabled); + animGraphInstance->SetObjectFlags(m_objectIndex, flag, enabled); // Set flag recursively for all active states within this state machine. const AZStd::vector& activeStates = GetActiveStates(animGraphInstance); @@ -1480,7 +1478,7 @@ namespace EMotionFX // check and add this node if (azrtti_typeid(this) == nodeType || nodeType.IsNull()) { - if (animGraphInstance->GetIsOutputReady(mObjectIndex)) // if we processed this node + if (animGraphInstance->GetIsOutputReady(m_objectIndex)) // if we processed this node { outNodes->emplace_back(const_cast(this)); } @@ -1505,7 +1503,7 @@ namespace EMotionFX void AnimGraphStateMachine::ReserveTransitions(size_t numTransitions) { - mTransitions.reserve(numTransitions); + m_transitions.reserve(numTransitions); } void AnimGraphStateMachine::SetEntryStateId(AnimGraphNodeId entryStateId) @@ -1557,7 +1555,7 @@ namespace EMotionFX serializeContext->Class() ->Version(1) ->Field("entryStateId", &AnimGraphStateMachine::m_entryStateId) - ->Field("transitions", &AnimGraphStateMachine::mTransitions) + ->Field("transitions", &AnimGraphStateMachine::m_transitions) ->Field("alwaysStartInEntryState", &AnimGraphStateMachine::m_alwaysStartInEntryState); AZ::EditContext* editContext = serializeContext->GetEditContext(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h index 7c0a5a14f9..1a00a82744 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateMachine.h @@ -56,11 +56,11 @@ namespace EMotionFX public: AZStd::vector m_activeTransitions; /**< Stack of active transitions. */ - AnimGraphNode* mCurrentState; /**< The current state. */ - AnimGraphNode* mPreviousState; /**< The previously used state, so the one used before the current one, the one from which we transitioned into the current one. */ - bool mReachedExitState; /**< True in case the state machine's current state is an exit state, false it not. */ + AnimGraphNode* m_currentState; /**< The current state. */ + AnimGraphNode* m_previousState; /**< The previously used state, so the one used before the current one, the one from which we transitioned into the current one. */ + bool m_reachedExitState; /**< True in case the state machine's current state is an exit state, false it not. */ AnimGraphRefCountedData m_prevData; - bool mSwitchToEntryState; + bool m_switchToEntryState; private: AZStd::vector m_activeStates; // TODO: See function comment. @@ -95,7 +95,7 @@ namespace EMotionFX AnimGraphPose* GetMainOutputPose(AnimGraphInstance* animGraphInstance) const override { return GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); } - void RecursiveCollectObjects(MCore::Array& outObjects) const override; + void RecursiveCollectObjects(AZStd::vector& outObjects) const override; void RecursiveCollectObjectsOfType(const AZ::TypeId& objectType, AZStd::vector& outObjects) const override; @@ -112,14 +112,14 @@ namespace EMotionFX * Get the number of transitions inside this state machine. This includes all kinds of transitions, so also wildcard transitions. * @result The number of transitions inside the state machine. */ - size_t GetNumTransitions() const { return mTransitions.size(); } + size_t GetNumTransitions() const { return m_transitions.size(); } /** * Get a pointer to the state machine transition of the given index. * @param[in] index The index of the transition to return. * @result A pointer to the state machine transition at the given index. */ - AnimGraphStateTransition* GetTransition(size_t index) const { return mTransitions[index]; } + AnimGraphStateTransition* GetTransition(size_t index) const { return m_transitions[index]; } /** * Remove the state machine transition at the given index. @@ -265,9 +265,9 @@ namespace EMotionFX void EndAllActiveTransitions(AnimGraphInstance* animGraphInstance); private: - AZStd::vector mTransitions; /**< The higher the index, the older the active transtion, the more time passed since it got started. Index = 0 is the most recent transition and the one with the highest global influence.*/ - AnimGraphNode* mEntryState; /**< A pointer to the initial state, so the state where the machine starts. */ - uint32 mEntryStateNodeNr; /**< Used only in the legacy file format. Remove after the legacy file format will be removed. */ + AZStd::vector m_transitions; /**< The higher the index, the older the active transtion, the more time passed since it got started. Index = 0 is the most recent transition and the one with the highest global influence.*/ + AnimGraphNode* m_entryState; /**< A pointer to the initial state, so the state where the machine starts. */ + size_t m_entryStateNodeNr; /**< Used only in the legacy file format. Remove after the legacy file format will be removed. */ AZ::u64 m_entryStateId; /**< The node id of the entry state. */ bool m_alwaysStartInEntryState; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp index 15d6f6bd3a..e90491b696 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.cpp @@ -117,8 +117,8 @@ namespace EMotionFX continue; } - const AZ::u32 numNodes = nodeGroup->GetNumNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = nodeGroup->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { AnimGraphNodeId nodeId = nodeGroup->GetNode(i); AnimGraphNode* node = stateMachine->FindChildNodeById(nodeId); @@ -180,9 +180,9 @@ namespace EMotionFX float duration ) : AnimGraphObject() - , mConditions(AZStd::move(conditions)) - , mSourceNode(source) - , mTargetNode(target) + , m_conditions(AZStd::move(conditions)) + , m_sourceNode(source) + , m_targetNode(target) , m_sourceNodeId(source ? source->GetId() : ObjectId::InvalidId) , m_targetNodeId(target ? target->GetId() : ObjectId::InvalidId) , m_transitionTime(duration) @@ -192,31 +192,31 @@ namespace EMotionFX AnimGraphStateTransition::~AnimGraphStateTransition() { RemoveAllConditions(true); - if (mAnimGraph) + if (m_animGraph) { - mAnimGraph->RemoveObject(this); + m_animGraph->RemoveObject(this); } } void AnimGraphStateTransition::Reinit() { - if (!mAnimGraph) + if (!m_animGraph) { - mSourceNode = nullptr; - mTargetNode = nullptr; + m_sourceNode = nullptr; + m_targetNode = nullptr; return; } // Re-link the source node. if (GetSourceNodeId().IsValid()) { - mSourceNode = mAnimGraph->RecursiveFindNodeById(GetSourceNodeId()); + m_sourceNode = m_animGraph->RecursiveFindNodeById(GetSourceNodeId()); } // Re-link the target node. if (GetTargetNodeId().IsValid()) { - mTargetNode = mAnimGraph->RecursiveFindNodeById(GetTargetNodeId()); + m_targetNode = m_animGraph->RecursiveFindNodeById(GetTargetNodeId()); } AnimGraphObject::Reinit(); @@ -226,7 +226,7 @@ namespace EMotionFX { Reinit(); - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { condition->Reinit(); } @@ -243,7 +243,7 @@ namespace EMotionFX InitInternalAttributesForAllInstances(); - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { condition->SetTransition(this); condition->InitAfterLoading(animGraph); @@ -265,7 +265,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); // calculate the blend weight, based on the type of smoothing - const float weight = uniqueData->mBlendWeight; + const float weight = uniqueData->m_blendWeight; // blend the two poses *outputPose = from; @@ -282,37 +282,37 @@ namespace EMotionFX { const float blendTime = GetBlendTime(animGraphInstance); - uniqueData->mTotalSeconds += timePassedInSeconds; - if (uniqueData->mTotalSeconds >= blendTime) + uniqueData->m_totalSeconds += timePassedInSeconds; + if (uniqueData->m_totalSeconds >= blendTime) { - uniqueData->mTotalSeconds = blendTime; - uniqueData->mIsDone = true; + uniqueData->m_totalSeconds = blendTime; + uniqueData->m_isDone = true; } else { - uniqueData->mIsDone = false; + uniqueData->m_isDone = false; } // calculate the blend weight if (blendTime > MCore::Math::epsilon) { - uniqueData->mBlendProgress = uniqueData->mTotalSeconds / blendTime; + uniqueData->m_blendProgress = uniqueData->m_totalSeconds / blendTime; } else { - uniqueData->mBlendProgress = 1.0f; + uniqueData->m_blendProgress = 1.0f; } - uniqueData->mBlendWeight = CalculateWeight(uniqueData->mBlendProgress); + uniqueData->m_blendWeight = CalculateWeight(uniqueData->m_blendProgress); } } void AnimGraphStateTransition::ExtractMotion(AnimGraphInstance* animGraphInstance, AnimGraphRefCountedData* sourceData, Transform* outTransform, Transform* outTransformMirrored) const { UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - const float weight = uniqueData->mBlendWeight; + const float weight = uniqueData->m_blendWeight; - AnimGraphRefCountedData* targetData = mTargetNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData(); + AnimGraphRefCountedData* targetData = m_targetNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData(); CalculateMotionExtractionDelta(m_extractionMode, sourceData, targetData, weight, true, *outTransform, *outTransformMirrored); } @@ -321,12 +321,12 @@ namespace EMotionFX // get the unique data UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - uniqueData->mBlendWeight = 0.0f; - uniqueData->mIsDone = false; - uniqueData->mTotalSeconds = 0.0f; - uniqueData->mBlendProgress = 0.0f; + uniqueData->m_blendWeight = 0.0f; + uniqueData->m_isDone = false; + uniqueData->m_totalSeconds = 0.0f; + uniqueData->m_blendProgress = 0.0f; - mTargetNode->SetSyncIndex(animGraphInstance, MCORE_INVALIDINDEX32); + m_targetNode->SetSyncIndex(animGraphInstance, MCORE_INVALIDINDEX32); // Trigger action for (AnimGraphTriggerAction* action : m_actionSetup.GetActions()) @@ -343,23 +343,23 @@ namespace EMotionFX { // get the unique data and return the is done flag UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - return uniqueData->mIsDone; + return uniqueData->m_isDone; } float AnimGraphStateTransition::GetBlendWeight(AnimGraphInstance* animGraphInstance) const { // get the unique data and return the is done flag UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - return uniqueData->mBlendWeight; + return uniqueData->m_blendWeight; } void AnimGraphStateTransition::OnEndTransition(AnimGraphInstance* animGraphInstance) { // get the unique data UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - uniqueData->mBlendWeight = 1.0f; - uniqueData->mBlendProgress = 1.0f; - uniqueData->mIsDone = true; + uniqueData->m_blendWeight = 1.0f; + uniqueData->m_blendProgress = 1.0f; + uniqueData->m_isDone = true; // Trigger action for (AnimGraphTriggerAction* action : m_actionSetup.GetActions()) @@ -374,28 +374,28 @@ namespace EMotionFX void AnimGraphStateTransition::AddCondition(AnimGraphTransitionCondition* condition) { condition->SetTransition(this); - mConditions.push_back(condition); + m_conditions.push_back(condition); } void AnimGraphStateTransition::InsertCondition(AnimGraphTransitionCondition* condition, size_t index) { condition->SetTransition(this); - mConditions.insert(mConditions.begin() + index, condition); + m_conditions.insert(m_conditions.begin() + index, condition); } void AnimGraphStateTransition::ReserveConditions(size_t numConditions) { - mConditions.reserve(numConditions); + m_conditions.reserve(numConditions); } void AnimGraphStateTransition::RemoveCondition(size_t index, bool delFromMem) { if (delFromMem) { - delete mConditions[index]; + delete m_conditions[index]; } - mConditions.erase(mConditions.begin() + index); + m_conditions.erase(m_conditions.begin() + index); } void AnimGraphStateTransition::RemoveAllConditions(bool delFromMem) @@ -403,19 +403,19 @@ namespace EMotionFX // delete them all from memory if (delFromMem) { - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { delete condition; } } - mConditions.clear(); + m_conditions.clear(); } // check if all conditions are tested positive bool AnimGraphStateTransition::CheckIfIsReady(AnimGraphInstance* animGraphInstance) const { - if (mConditions.empty()) + if (m_conditions.empty()) { return false; } @@ -423,7 +423,7 @@ namespace EMotionFX if (!GetEMotionFX().GetIsInEditorMode()) { // If we are not in editor mode, we can early out for the first failed condition - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { const bool testResult = condition->TestCondition(animGraphInstance); @@ -440,7 +440,7 @@ namespace EMotionFX // If we are in editor mode, we need to execute all the conditions so the UI can reflect properly which ones // passed and which ones didn't bool isReady = true; - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { const bool testResult = condition->TestCondition(animGraphInstance); @@ -455,27 +455,27 @@ namespace EMotionFX void AnimGraphStateTransition::SetIsWildcardTransition(bool isWildcardTransition) { - mIsWildcardTransition = isWildcardTransition; + m_isWildcardTransition = isWildcardTransition; } void AnimGraphStateTransition::SetSourceNode(AnimGraphInstance* animGraphInstance, AnimGraphNode* sourceNode) { UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - uniqueData->mSourceNode = sourceNode; + uniqueData->m_sourceNode = sourceNode; } // get the source node of the transition AnimGraphNode* AnimGraphStateTransition::GetSourceNode(AnimGraphInstance* animGraphInstance) const { // return the normal source node in case we are not dealing with a wildcard transition - if (mIsWildcardTransition == false) + if (m_isWildcardTransition == false) { - return mSourceNode; + return m_sourceNode; } // wildcard transition special case handling UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - return uniqueData->mSourceNode; + return uniqueData->m_sourceNode; } void AnimGraphStateTransition::SetBlendTime(float blendTime) @@ -488,8 +488,8 @@ namespace EMotionFX MCORE_UNUSED(animGraphInstance); // Use a blend time of zero in case this transition is connected to aan entry or exit state. - if ((mSourceNode && (azrtti_typeid(mSourceNode) == azrtti_typeid() || azrtti_typeid(mSourceNode) == azrtti_typeid())) || - (mTargetNode && (azrtti_typeid(mTargetNode) == azrtti_typeid() || azrtti_typeid(mTargetNode) == azrtti_typeid()))) + if ((m_sourceNode && (azrtti_typeid(m_sourceNode) == azrtti_typeid() || azrtti_typeid(m_sourceNode) == azrtti_typeid())) || + (m_targetNode && (azrtti_typeid(m_targetNode) == azrtti_typeid() || azrtti_typeid(m_targetNode) == azrtti_typeid()))) { return 0.0f; } @@ -500,7 +500,7 @@ namespace EMotionFX // callback that gets called before a node gets removed void AnimGraphStateTransition::OnRemoveNode(AnimGraph* animGraph, AnimGraphNode* nodeToRemove) { - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { condition->OnRemoveNode(animGraph, nodeToRemove); } @@ -508,7 +508,7 @@ namespace EMotionFX void AnimGraphStateTransition::ResetConditions(AnimGraphInstance* animGraphInstance) { - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { condition->Reset(animGraphInstance); } @@ -596,7 +596,7 @@ namespace EMotionFX { if (m_canBeInterruptedByOthers && transition != this && - (GetIsWildcardTransition() || transition->GetIsWildcardTransition() || transition->GetSourceNode() == mSourceNode)) + (GetIsWildcardTransition() || transition->GetIsWildcardTransition() || transition->GetSourceNode() == m_sourceNode)) { // Allow all in case the transition candidate list is empty, otherwise only allow transitions from the possible interruption candidate list. if (m_canBeInterruptedByTransitionIds.empty() || @@ -663,14 +663,14 @@ namespace EMotionFX } // add all sub objects - void AnimGraphStateTransition::RecursiveCollectObjects(MCore::Array& outObjects) const + void AnimGraphStateTransition::RecursiveCollectObjects(AZStd::vector& outObjects) const { - for (const AnimGraphTransitionCondition* condition : mConditions) + for (const AnimGraphTransitionCondition* condition : m_conditions) { condition->RecursiveCollectObjects(outObjects); } - outObjects.Add(const_cast(this)); + outObjects.emplace_back(const_cast(this)); } // calculate the blend weight, based on the type of smoothing @@ -706,7 +706,7 @@ namespace EMotionFX { AnimGraphObject::InvalidateUniqueData(animGraphInstance); - for (AnimGraphTransitionCondition* condition : mConditions) + for (AnimGraphTransitionCondition* condition : m_conditions) { condition->InvalidateUniqueData(animGraphInstance); } @@ -761,11 +761,11 @@ namespace EMotionFX void AnimGraphStateTransition::SetSourceNode(AnimGraphNode* node) { - mSourceNode = node; + m_sourceNode = node; - if (mSourceNode) + if (m_sourceNode) { - m_sourceNodeId = mSourceNode->GetId(); + m_sourceNodeId = m_sourceNode->GetId(); } else { @@ -775,17 +775,17 @@ namespace EMotionFX AnimGraphNode* AnimGraphStateTransition::GetSourceNode() const { - AZ_Assert(!mSourceNode || (mSourceNode && mSourceNode->GetId() == GetSourceNodeId()), "Source node not in sync with node id."); - return mSourceNode; + AZ_Assert(!m_sourceNode || (m_sourceNode && m_sourceNode->GetId() == GetSourceNodeId()), "Source node not in sync with node id."); + return m_sourceNode; } void AnimGraphStateTransition::SetTargetNode(AnimGraphNode* node) { - mTargetNode = node; + m_targetNode = node; - if (mTargetNode) + if (m_targetNode) { - m_targetNodeId = mTargetNode->GetId(); + m_targetNodeId = m_targetNode->GetId(); } else { @@ -795,36 +795,36 @@ namespace EMotionFX AnimGraphNode* AnimGraphStateTransition::GetTargetNode() const { - AZ_Assert(mTargetNode && mTargetNode->GetId() == GetTargetNodeId(), "Target node not in sync with node id."); - return mTargetNode; + AZ_Assert(m_targetNode && m_targetNode->GetId() == GetTargetNodeId(), "Target node not in sync with node id."); + return m_targetNode; } void AnimGraphStateTransition::SetVisualOffsets(int32 startX, int32 startY, int32 endX, int32 endY) { - mStartOffsetX = startX; - mStartOffsetY = startY; - mEndOffsetX = endX; - mEndOffsetY = endY; + m_startOffsetX = startX; + m_startOffsetY = startY; + m_endOffsetX = endX; + m_endOffsetY = endY; } int32 AnimGraphStateTransition::GetVisualStartOffsetX() const { - return mStartOffsetX; + return m_startOffsetX; } int32 AnimGraphStateTransition::GetVisualStartOffsetY() const { - return mStartOffsetY; + return m_startOffsetY; } int32 AnimGraphStateTransition::GetVisualEndOffsetX() const { - return mEndOffsetX; + return m_endOffsetX; } int32 AnimGraphStateTransition::GetVisualEndOffsetY() const { - return mEndOffsetY; + return m_endOffsetY; } bool AnimGraphStateTransition::CanWildcardTransitionFrom(AnimGraphNode* sourceNode) const @@ -837,7 +837,7 @@ namespace EMotionFX if (sourceNode) { - if (m_allowTransitionsFrom.Contains(mAnimGraph, sourceNode->GetId())) + if (m_allowTransitionsFrom.Contains(m_animGraph, sourceNode->GetId())) { // In case the given source node is part of the filter (either as individual state or part of a node group), return success. return true; @@ -849,23 +849,23 @@ namespace EMotionFX AZ::Outcome AnimGraphStateTransition::FindConditionIndex(AnimGraphTransitionCondition* condition) const { - const auto iterator = AZStd::find(mConditions.begin(), mConditions.end(), condition); - if (iterator == mConditions.end()) + const auto iterator = AZStd::find(m_conditions.begin(), m_conditions.end(), condition); + if (iterator == m_conditions.end()) { return AZ::Failure(); } - return AZ::Success(static_cast(AZStd::distance(mConditions.begin(), iterator))); + return AZ::Success(static_cast(AZStd::distance(m_conditions.begin(), iterator))); } AnimGraphStateMachine* AnimGraphStateTransition::GetStateMachine() const { - if (!mTargetNode) + if (!m_targetNode) { return nullptr; } - return azdynamic_cast(mTargetNode->GetParentNode()); + return azdynamic_cast(m_targetNode->GetParentNode()); } AZ::Crc32 AnimGraphStateTransition::GetEaseInOutSmoothnessVisibility() const @@ -881,8 +881,8 @@ namespace EMotionFX AZ::Crc32 AnimGraphStateTransition::GetVisibilityHideWhenExitOrEntry() const { // Hide when the transition is connected to an entry or an exit state. - if ((mSourceNode && (azrtti_typeid(mSourceNode) == azrtti_typeid() || azrtti_typeid(mSourceNode) == azrtti_typeid())) || - (mTargetNode && (azrtti_typeid(mTargetNode) == azrtti_typeid() || azrtti_typeid(mTargetNode) == azrtti_typeid()))) + if ((m_sourceNode && (azrtti_typeid(m_sourceNode) == azrtti_typeid() || azrtti_typeid(m_sourceNode) == azrtti_typeid())) || + (m_targetNode && (azrtti_typeid(m_targetNode) == azrtti_typeid() || azrtti_typeid(m_targetNode) == azrtti_typeid()))) { return AZ::Edit::PropertyVisibility::Hide; } @@ -1008,7 +1008,7 @@ namespace EMotionFX ->Field("id", &AnimGraphStateTransition::m_id) ->Field("sourceNodeId", &AnimGraphStateTransition::m_sourceNodeId) ->Field("targetNodeId", &AnimGraphStateTransition::m_targetNodeId) - ->Field("isWildcard", &AnimGraphStateTransition::mIsWildcardTransition) + ->Field("isWildcard", &AnimGraphStateTransition::m_isWildcardTransition) ->Field("isDisabled", &AnimGraphStateTransition::m_isDisabled) ->Field("priority", &AnimGraphStateTransition::m_priority) ->Field("canBeInterruptedByOthers", &AnimGraphStateTransition::m_canBeInterruptedByOthers) @@ -1025,11 +1025,11 @@ namespace EMotionFX ->Field("interpolationType", &AnimGraphStateTransition::m_interpolationType) ->Field("easeInSmoothness", &AnimGraphStateTransition::m_easeInSmoothness) ->Field("easeOutSmoothness", &AnimGraphStateTransition::m_easeOutSmoothness) - ->Field("startOffsetX", &AnimGraphStateTransition::mStartOffsetX) - ->Field("startOffsetY", &AnimGraphStateTransition::mStartOffsetY) - ->Field("endOffsetX", &AnimGraphStateTransition::mEndOffsetX) - ->Field("endOffsetY", &AnimGraphStateTransition::mEndOffsetY) - ->Field("conditions", &AnimGraphStateTransition::mConditions) + ->Field("startOffsetX", &AnimGraphStateTransition::m_startOffsetX) + ->Field("startOffsetY", &AnimGraphStateTransition::m_startOffsetY) + ->Field("endOffsetX", &AnimGraphStateTransition::m_endOffsetX) + ->Field("endOffsetY", &AnimGraphStateTransition::m_endOffsetY) + ->Field("conditions", &AnimGraphStateTransition::m_conditions) ->Field("actionSetup", &AnimGraphStateTransition::m_actionSetup) ->Field("extractionMode", &AnimGraphStateTransition::m_extractionMode) ; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h index 5e8d5446ef..9da239b13b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphStateTransition.h @@ -63,11 +63,11 @@ namespace EMotionFX ~UniqueData() = default; public: - AnimGraphNode* mSourceNode = nullptr; - float mBlendWeight = 0.0f; - float mBlendProgress = 0.0f; - float mTotalSeconds = 0.0f; - bool mIsDone = false; + AnimGraphNode* m_sourceNode = nullptr; + float m_blendWeight = 0.0f; + float m_blendProgress = 0.0f; + float m_totalSeconds = 0.0f; + bool m_isDone = false; }; class StateFilterLocal final @@ -120,7 +120,7 @@ namespace EMotionFX AnimGraphObjectData* CreateUniqueData(AnimGraphInstance* animGraphInstance) override { return aznew UniqueData(this, animGraphInstance); } void InvalidateUniqueData(AnimGraphInstance* animGraphInstance) override; - void RecursiveCollectObjects(MCore::Array& outObjects) const override; + void RecursiveCollectObjects(AZStd::vector& outObjects) const override; void ExtractMotion(AnimGraphInstance* animGraphInstance, AnimGraphRefCountedData* sourceData, Transform* outTransform, Transform* outTransformMirrored) const; void OnStartTransition(AnimGraphInstance* animGraphInstance); @@ -218,14 +218,14 @@ namespace EMotionFX * to the destination state. It is basically a transition from all nodes to the destination node of the wildcard transition. A wildcard transition does not have a fixed source node. * @result True in case the transition is a wildcard transition, false if not. */ - bool GetIsWildcardTransition() const { return mIsWildcardTransition; } + bool GetIsWildcardTransition() const { return m_isWildcardTransition; } bool CanWildcardTransitionFrom(AnimGraphNode* sourceNode) const; AnimGraphStateMachine* GetStateMachine() const; - MCORE_INLINE size_t GetNumConditions() const { return mConditions.size(); } - MCORE_INLINE AnimGraphTransitionCondition* GetCondition(size_t index) const { return mConditions[index]; } + MCORE_INLINE size_t GetNumConditions() const { return m_conditions.size(); } + MCORE_INLINE AnimGraphTransitionCondition* GetCondition(size_t index) const { return m_conditions[index]; } AZ::Outcome FindConditionIndex(AnimGraphTransitionCondition* condition) const; void AddCondition(AnimGraphTransitionCondition* condition); @@ -262,12 +262,12 @@ namespace EMotionFX AZ::Crc32 GetVisibilityCanBeInterruptedBy() const; AZ::Crc32 GetVisibilityMaxInterruptionBlendWeight() const; - AZStd::vector mConditions{}; + AZStd::vector m_conditions{}; StateFilterLocal m_allowTransitionsFrom; TriggerActionSetup m_actionSetup; - AnimGraphNode* mSourceNode = nullptr; - AnimGraphNode* mTargetNode = nullptr; + AnimGraphNode* m_sourceNode = nullptr; + AnimGraphNode* m_targetNode = nullptr; AZ::u64 m_sourceNodeId = AnimGraphNodeId::InvalidId; AZ::u64 m_targetNodeId = AnimGraphNodeId::InvalidId; AZ::u64 m_id = AnimGraphConnectionId::Create(); /**< The unique identification number. */ @@ -275,16 +275,16 @@ namespace EMotionFX float m_transitionTime = 0.3f; float m_easeInSmoothness = 0.0f; float m_easeOutSmoothness = 1.0f; - AZ::s32 mStartOffsetX = 0; - AZ::s32 mStartOffsetY = 0; - AZ::s32 mEndOffsetX = 0; - AZ::s32 mEndOffsetY = 0; + AZ::s32 m_startOffsetX = 0; + AZ::s32 m_startOffsetY = 0; + AZ::s32 m_endOffsetX = 0; + AZ::s32 m_endOffsetY = 0; AZ::u32 m_priority = 0; AnimGraphObject::ESyncMode m_syncMode = AnimGraphObject::SYNCMODE_DISABLED; AnimGraphObject::EEventMode m_eventMode = AnimGraphObject::EVENTMODE_BOTHNODES; AnimGraphObject::EExtractionMode m_extractionMode = AnimGraphObject::EXTRACTIONMODE_BLEND; EInterpolationType m_interpolationType = INTERPOLATIONFUNCTION_LINEAR; - bool mIsWildcardTransition = false; /**< Flag which indicates if the state transition is a wildcard transition or not. */ + bool m_isWildcardTransition = false; /**< Flag which indicates if the state transition is a wildcard transition or not. */ bool m_isDisabled = false; bool m_canBeInterruptedByOthers = false; AZStd::vector m_canBeInterruptedByTransitionIds{}; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp index 6c0bd18548..3c77beaa60 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphSyncTrack.cpp @@ -114,8 +114,8 @@ namespace EMotionFX const size_t numEvents = m_events.size(); if (numEvents == 0 || timeInSeconds > GetDuration() || timeInSeconds < 0.0f) { - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; } @@ -189,7 +189,7 @@ namespace EMotionFX } // actually we didn't find this combination - return MCORE_INVALIDINDEX32; + return InvalidIndex; } @@ -200,8 +200,8 @@ namespace EMotionFX const size_t numEvents = m_events.size(); if (numEvents == 0) { - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; } @@ -217,8 +217,8 @@ namespace EMotionFX } else { - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; } } @@ -271,15 +271,15 @@ namespace EMotionFX // if we didn't find a single hit we won't find any other if (found == false) { - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; } } // we didn't find it - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; } @@ -307,8 +307,8 @@ namespace EMotionFX current = AdvanceAndWrapIterator(current, forward, m_events.cbegin(), m_events.cend()); } while (current != start); - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; }; @@ -319,13 +319,13 @@ namespace EMotionFX const size_t numEvents = m_events.size(); if (numEvents == 0) { - *outIndexA = MCORE_INVALIDINDEX32; - *outIndexB = MCORE_INVALIDINDEX32; + *outIndexA = InvalidIndex; + *outIndexB = InvalidIndex; return false; } // if the sync index is not set, start at the first pair (which starts from the last sync key) - if (syncIndex == MCORE_INVALIDINDEX32) + if (syncIndex == InvalidIndex) { if (forward) { @@ -364,7 +364,7 @@ namespace EMotionFX float AnimGraphSyncTrack::GetDuration() const { - return mMotion->GetMotionData()->GetDuration(); + return m_motion->GetMotionData()->GetDuration(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTagCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTagCondition.cpp index 6b2d0084d7..e6f6e9b9bd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTagCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTagCondition.cpp @@ -54,7 +54,7 @@ namespace EMotionFX for (size_t i = 0; i < numTags; ++i) { // Search for the parameter with the name of the tag and save the index. - const AZ::Outcome parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_tags[i]); + const AZ::Outcome parameterIndex = m_animGraph->FindValueParameterIndexByName(m_tags[i]); if (parameterIndex.IsSuccess()) { // Cache the parameter index to avoid string lookups at runtime. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.cpp index a339d5752b..3da55ced3e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.cpp @@ -73,7 +73,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); // increase the elapsed time of the condition - uniqueData->mElapsedTime += timePassedInSeconds; + uniqueData->m_elapsedTime += timePassedInSeconds; } @@ -84,7 +84,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); // reset the elapsed time - uniqueData->mElapsedTime = 0.0f; + uniqueData->m_elapsedTime = 0.0f; // use randomized count downs? if (m_useRandomization) @@ -93,17 +93,17 @@ namespace EMotionFX if (animGraphInstance->IsNetworkEnabled()) { // using a seeded random in order to generate predictable result in network. - uniqueData->mCountDownTime = MCore::Random::RandF(m_minRandomTime, m_maxRandomTime, animGraphInstance->GetLcgRandom()); + uniqueData->m_countDownTime = MCore::Random::RandF(m_minRandomTime, m_maxRandomTime, animGraphInstance->GetLcgRandom()); } else { - uniqueData->mCountDownTime = MCore::Random::RandF(m_minRandomTime, m_maxRandomTime); + uniqueData->m_countDownTime = MCore::Random::RandF(m_minRandomTime, m_maxRandomTime); } } else { // get the fixed count down value from the attribute - uniqueData->mCountDownTime = m_countDownTime; + uniqueData->m_countDownTime = m_countDownTime; } } @@ -115,7 +115,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); // in case the elapsed time is bigger than the count down time, we can trigger the condition - if (uniqueData->mElapsedTime + 0.0001f >= uniqueData->mCountDownTime) // The 0.0001f is to counter floating point inaccuracies. The AZ float epsilon is too small. + if (uniqueData->m_elapsedTime + 0.0001f >= uniqueData->m_countDownTime) // The 0.0001f is to counter floating point inaccuracies. The AZ float epsilon is too small. { return true; } @@ -162,8 +162,8 @@ namespace EMotionFX AnimGraphTimeCondition::UniqueData::UniqueData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance) : AnimGraphObjectData(object, animGraphInstance) { - mElapsedTime = 0.0f; - mCountDownTime = 0.0f; + m_elapsedTime = 0.0f; + m_countDownTime = 0.0f; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.h b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.h index 96de4f2d36..47d17a4d10 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTimeCondition.h @@ -42,8 +42,8 @@ namespace EMotionFX ~UniqueData() override; public: - float mElapsedTime; /**< The elapsed time in seconds for the given anim graph instance. */ - float mCountDownTime; /**< The count down time in seconds for the given anim graph instance. */ + float m_elapsedTime; /**< The elapsed time in seconds for the given anim graph instance. */ + float m_countDownTime; /**< The count down time in seconds for the given anim graph instance. */ }; AnimGraphTimeCondition(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTransitionCondition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTransitionCondition.cpp index dd297177f3..d7b626f4cf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTransitionCondition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTransitionCondition.cpp @@ -24,9 +24,9 @@ namespace EMotionFX AnimGraphTransitionCondition::~AnimGraphTransitionCondition() { - if (mAnimGraph) + if (m_animGraph) { - mAnimGraph->RemoveObject(this); + m_animGraph->RemoveObject(this); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTriggerAction.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTriggerAction.cpp index 05b4c6c5b5..ffb8898ce0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTriggerAction.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphTriggerAction.cpp @@ -30,9 +30,9 @@ namespace EMotionFX AnimGraphTriggerAction::~AnimGraphTriggerAction() { - if (mAnimGraph) + if (m_animGraph) { - mAnimGraph->RemoveObject(this); + m_animGraph->RemoveObject(this); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphVector2Condition.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphVector2Condition.cpp index ac1e283c19..987f74417e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphVector2Condition.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AnimGraphVector2Condition.cpp @@ -57,7 +57,7 @@ namespace EMotionFX SetOperation(m_operation); // Find the parameter index for the given parameter name, to prevent string based lookups every frame - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } @@ -89,7 +89,7 @@ namespace EMotionFX if (m_parameterIndex.IsSuccess()) { // get access to the parameter info and return the type of its default value - const ValueParameter* valueParameter = mAnimGraph->FindValueParameter(m_parameterIndex.GetValue()); + const ValueParameter* valueParameter = m_animGraph->FindValueParameter(m_parameterIndex.GetValue()); return azrtti_typeid(valueParameter); } else @@ -348,7 +348,7 @@ namespace EMotionFX { AZ_UNUSED(beforeChange); AZ_UNUSED(afterChange); - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } void AnimGraphVector2Condition::ParameterRemoved(const AZStd::string& oldParameterName) @@ -360,7 +360,7 @@ namespace EMotionFX } else { - m_parameterIndex = mAnimGraph->FindValueParameterIndexByName(m_parameterName); + m_parameterIndex = m_animGraph->FindValueParameterIndexByName(m_parameterName); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.cpp index 2afc50278c..d35314860f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.cpp @@ -19,7 +19,7 @@ namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(AttachmentNode, AttachmentAllocator, 0) - AttachmentNode::AttachmentNode(ActorInstance* attachToActorInstance, AZ::u32 attachToNodeIndex, ActorInstance* attachment, bool managedExternally) + AttachmentNode::AttachmentNode(ActorInstance* attachToActorInstance, size_t attachToNodeIndex, ActorInstance* attachment, bool managedExternally) : Attachment(attachToActorInstance, attachment) , m_attachedToNode(attachToNodeIndex) , m_isManagedExternally(managedExternally) @@ -33,7 +33,7 @@ namespace EMotionFX } - AttachmentNode* AttachmentNode::Create(ActorInstance* attachToActorInstance, AZ::u32 attachToNodeIndex, ActorInstance* attachment, bool managedExternally) + AttachmentNode* AttachmentNode::Create(ActorInstance* attachToActorInstance, size_t attachToNodeIndex, ActorInstance* attachment, bool managedExternally) { return aznew AttachmentNode(attachToActorInstance, attachToNodeIndex, attachment, managedExternally); } @@ -55,7 +55,7 @@ namespace EMotionFX } - uint32 AttachmentNode::GetAttachToNodeIndex() const + size_t AttachmentNode::GetAttachToNodeIndex() const { return m_attachedToNode; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.h index 5bef33a90b..f88bcea648 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentNode.h @@ -44,7 +44,7 @@ namespace EMotionFX * @param attachment The actor instance that you want to attach to this node (for example a gun). * @param managedExternally Specify whether the parent transform (where we are attached to) propagates into the attachment actor instance. */ - static AttachmentNode* Create(ActorInstance* attachToActorInstance, AZ::u32 attachToNodeIndex, ActorInstance* attachment, bool managedExternally = false); + static AttachmentNode* Create(ActorInstance* attachToActorInstance, size_t attachToNodeIndex, ActorInstance* attachment, bool managedExternally = false); /** * Get the attachment type ID. @@ -72,7 +72,7 @@ namespace EMotionFX * This node is part of the actor from which the actor instance returned by GetAttachToActorInstance() is created. * @result The node index where we will attach this attachment to. */ - AZ::u32 GetAttachToNodeIndex() const; + size_t GetAttachToNodeIndex() const; /** * Check whether the transformations of the attachment are modified by using a parent-child relationship in forward kinematics. @@ -97,7 +97,7 @@ namespace EMotionFX protected: - AZ::u32 m_attachedToNode; /**< The node where the attachment is linked to. */ + size_t m_attachedToNode; /**< The node where the attachment is linked to. */ bool m_isManagedExternally; /**< Is this attachment basically managed (transformation wise) by something else? (like an Attachment component). The default is false. */ /** @@ -107,7 +107,7 @@ namespace EMotionFX * @param attachment The actor instance that you want to attach to this node (for example a gun). * @param managedExternally Specify whether the parent transform (where we are attached to) propagates into the attachment actor instance. */ - AttachmentNode(ActorInstance* attachToActorInstance, AZ::u32 attachToNodeIndex, ActorInstance* attachment, bool managedExternally = false); + AttachmentNode(ActorInstance* attachToActorInstance, size_t attachToNodeIndex, ActorInstance* attachment, bool managedExternally = false); /** * The destructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.cpp index f2f761e849..db66e1c50a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.cpp @@ -53,12 +53,12 @@ namespace EMotionFX } // Iterate over the morph targets inside the attachment, and try to locate them inside the actor instance we are attaching to. - const AZ::u32 numTargetMorphs = targetMorphSetup->GetNumMorphTargets(); - m_morphMap.reserve(static_cast(numTargetMorphs)); - for (AZ::u32 i = 0; i < numTargetMorphs; ++i) + const size_t numTargetMorphs = targetMorphSetup->GetNumMorphTargets(); + m_morphMap.reserve(numTargetMorphs); + for (size_t i = 0; i < numTargetMorphs; ++i) { - const AZ::u32 sourceMorphIndex = sourceMorphSetup->FindMorphTargetNumberByID(targetMorphSetup->GetMorphTarget(i)->GetID()); - if (sourceMorphIndex == MCORE_INVALIDINDEX32) + const size_t sourceMorphIndex = sourceMorphSetup->FindMorphTargetNumberByID(targetMorphSetup->GetMorphTarget(i)->GetID()); + if (sourceMorphIndex == InvalidIndex) { continue; } @@ -82,9 +82,9 @@ namespace EMotionFX Skeleton* attachmentSkeleton = m_attachment->GetActor()->GetSkeleton(); Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton(); - const uint32 numNodes = attachmentSkeleton->GetNumNodes(); + const size_t numNodes = attachmentSkeleton->GetNumNodes(); m_jointMap.reserve(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { Node* attachmentNode = attachmentSkeleton->GetNode(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.h b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.h index acbf975054..26302c50c1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/AttachmentSkin.h @@ -37,14 +37,14 @@ namespace EMotionFX */ struct EMFX_API JointMapping { - AZ::u32 m_sourceJoint; /**< The source joint in the actor where this is attached to. */ - AZ::u32 m_targetJoint; /**< The target joint in the attachment actor instance. */ + size_t m_sourceJoint; /**< The source joint in the actor where this is attached to. */ + size_t m_targetJoint; /**< The target joint in the attachment actor instance. */ }; struct EMFX_API MorphMapping { - AZ::u32 m_sourceMorphIndex; /**< The source morph target index. The source is the actor instance we are attaching to. */ - AZ::u32 m_targetMorphIndex; /**< The target morph target index. The target is the attachment actor instance. */ + size_t m_sourceMorphIndex; /**< The source morph target index. The source is the actor instance we are attaching to. */ + size_t m_targetMorphIndex; /**< The target morph target index. The target is the attachment actor instance. */ }; /** @@ -92,14 +92,14 @@ namespace EMotionFX * @param nodeIndex The joint index inside the actor instance that represents the attachment. * @result A reference to the mapping information for this joint. */ - MCORE_INLINE JointMapping& GetJointMapping(uint32 nodeIndex) { return m_jointMap[nodeIndex]; } + MCORE_INLINE JointMapping& GetJointMapping(size_t nodeIndex) { return m_jointMap[nodeIndex]; } /** * Get the mapping for a given joint. * @param nodeIndex The joint index inside the actor instance that represents the attachment. * @result A reference to the mapping information for this joint. */ - MCORE_INLINE const JointMapping& GetJointMapping(uint32 nodeIndex) const { return m_jointMap[nodeIndex]; } + MCORE_INLINE const JointMapping& GetJointMapping(size_t nodeIndex) const { return m_jointMap[nodeIndex]; } protected: AZStd::vector m_jointMap; /**< Specifies which joints we need to copy transforms from and to. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp index ee4b6d0dab..0e823075a4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp @@ -81,7 +81,7 @@ namespace EMotionFX void BlendSpace1DNode::UniqueData::Update() { - BlendSpace1DNode* blendSpaceNode = azdynamic_cast(mObject); + BlendSpace1DNode* blendSpaceNode = azdynamic_cast(m_object); AZ_Assert(blendSpaceNode, "Unique data linked to incorrect node type."); blendSpaceNode->UpdateMotionInfos(this); @@ -172,7 +172,7 @@ namespace EMotionFX } // If the node is disabled, simply output a bind pose. - if (mDisabled) + if (m_disabled) { SetBindPoseAtOutput(animGraphInstance); return; @@ -246,7 +246,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -262,7 +262,7 @@ namespace EMotionFX DoTopDownUpdate(animGraphInstance, m_syncMode, uniqueData->m_leaderMotionIdx, uniqueData->m_motionInfos, uniqueData->m_allMotionsHaveSyncTracks); - EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection; + EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).m_connection; if (paramConnection) { AnimGraphNode* paramSrcNode = paramConnection->GetSourceNode(); @@ -276,9 +276,9 @@ namespace EMotionFX void BlendSpace1DNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (!mDisabled) + if (!m_disabled) { - EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection; + EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).m_connection; if (paramConnection) { UpdateIncomingNode(animGraphInstance, paramConnection->GetSourceNode(), timePassedInSeconds); @@ -291,7 +291,7 @@ namespace EMotionFX AZ_Assert(uniqueData, "UniqueData not found for BlendSpace1DNode"); uniqueData->Clear(); - if (mDisabled) + if (m_disabled) { return; } @@ -331,7 +331,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); AnimGraphRefCountedData* data = uniqueData->GetRefCountedData(); @@ -340,7 +340,7 @@ namespace EMotionFX return; } - EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection; + EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).m_connection; if (paramConnection) { paramConnection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -410,7 +410,7 @@ namespace EMotionFX MotionInstance* motionInstance = motionInstancePool.RequestNew(motion, actorInstance); motionInstance->InitFromPlayBackInfo(playInfo, true); - motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.mRetarget); + motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.m_retarget); motionInstance->UnPause(); motionInstance->SetIsActive(true); motionInstance->SetWeight(1.0f, 0.0f); @@ -434,7 +434,7 @@ namespace EMotionFX bool BlendSpace1DNode::GetIsInPlace(AnimGraphInstance* animGraphInstance) const { - EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).mConnection; + EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).m_connection; if (inPlaceConnection) { return GetInputNumberAsBool(animGraphInstance, INPUTPORT_INPLACE); @@ -584,7 +584,7 @@ namespace EMotionFX void BlendSpace1DNode::SetMotions(const AZStd::vector& motions) { m_motions = motions; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -638,7 +638,7 @@ namespace EMotionFX } else { - EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection; + EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).m_connection; if (GetEMotionFX().GetIsInEditorMode()) { @@ -754,7 +754,7 @@ namespace EMotionFX void BlendSpace1DNode::SetCalculationMethod(ECalculationMethod calculationMethod) { m_calculationMethod = calculationMethod; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -770,7 +770,7 @@ namespace EMotionFX void BlendSpace1DNode::SetSyncLeaderMotionId(const AZStd::string& syncLeaderMotionId) { m_syncLeaderMotionId = syncLeaderMotionId; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -786,7 +786,7 @@ namespace EMotionFX void BlendSpace1DNode::SetEvaluatorType(const AZ::TypeId& evaluatorType) { m_evaluatorType = evaluatorType; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace2DNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace2DNode.cpp index c1f1035f00..b34a860b71 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace2DNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace2DNode.cpp @@ -160,7 +160,7 @@ namespace EMotionFX void BlendSpace2DNode::UniqueData::Update() { - BlendSpace2DNode* blendSpaceNode = azdynamic_cast(mObject); + BlendSpace2DNode* blendSpaceNode = azdynamic_cast(m_object); AZ_Assert(blendSpaceNode, "Unique data linked to incorrect node type."); blendSpaceNode->UpdateMotionInfos(this); @@ -273,7 +273,7 @@ namespace EMotionFX bool BlendSpace2DNode::GetIsInPlace(AnimGraphInstance* animGraphInstance) const { - EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).mConnection; + EMotionFX::BlendTreeConnection* inPlaceConnection = GetInputPort(INPUTPORT_INPLACE).m_connection; if (inPlaceConnection) { return GetInputNumberAsBool(animGraphInstance, INPUTPORT_INPLACE); @@ -301,7 +301,7 @@ namespace EMotionFX } // If the node is disabled, simply output a bind pose. - if (mDisabled) + if (m_disabled) { SetBindPoseAtOutput(animGraphInstance); return; @@ -378,7 +378,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -389,7 +389,7 @@ namespace EMotionFX return; } - if (mDisabled) + if (m_disabled) { return; } @@ -401,7 +401,7 @@ namespace EMotionFX for (int i = 0; i < 2; ++i) { const uint32 portIdx = (i == 0) ? INPUTPORT_XVALUE : INPUTPORT_YVALUE; - EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(portIdx).mConnection; + EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(portIdx).m_connection; if (paramConnection) { AnimGraphNode* paramSrcNode = paramConnection->GetSourceNode(); @@ -420,15 +420,15 @@ namespace EMotionFX return; } - if (!mDisabled) + if (!m_disabled) { - EMotionFX::BlendTreeConnection* param1Connection = GetInputPort(INPUTPORT_XVALUE).mConnection; + EMotionFX::BlendTreeConnection* param1Connection = GetInputPort(INPUTPORT_XVALUE).m_connection; if (param1Connection) { UpdateIncomingNode(animGraphInstance, param1Connection->GetSourceNode(), timePassedInSeconds); } - EMotionFX::BlendTreeConnection* param2Connection = GetInputPort(INPUTPORT_YVALUE).mConnection; + EMotionFX::BlendTreeConnection* param2Connection = GetInputPort(INPUTPORT_YVALUE).m_connection; if (param2Connection) { UpdateIncomingNode(animGraphInstance, param2Connection->GetSourceNode(), timePassedInSeconds); @@ -441,7 +441,7 @@ namespace EMotionFX AZ_Assert(uniqueData, "Unique data not found for blend space 2D node '%s'.", GetName()); uniqueData->Clear(); - if (mDisabled) + if (m_disabled) { return; } @@ -481,7 +481,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); AnimGraphRefCountedData* data = uniqueData->GetRefCountedData(); @@ -490,12 +490,12 @@ namespace EMotionFX return; } - EMotionFX::BlendTreeConnection* param1Connection = GetInputPort(INPUTPORT_XVALUE).mConnection; + EMotionFX::BlendTreeConnection* param1Connection = GetInputPort(INPUTPORT_XVALUE).m_connection; if (param1Connection) { param1Connection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); } - EMotionFX::BlendTreeConnection* param2Connection = GetInputPort(INPUTPORT_YVALUE).mConnection; + EMotionFX::BlendTreeConnection* param2Connection = GetInputPort(INPUTPORT_YVALUE).m_connection; if (param2Connection) { param2Connection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -565,7 +565,7 @@ namespace EMotionFX MotionInstance* motionInstance = motionInstancePool.RequestNew(motion, actorInstance); motionInstance->InitFromPlayBackInfo(playInfo, true); - motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.mRetarget); + motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.m_retarget); motionInstance->UnPause(); motionInstance->SetIsActive(true); motionInstance->SetWeight(1.0f, 0.0f); @@ -693,7 +693,7 @@ namespace EMotionFX void BlendSpace2DNode::SetMotions(const AZStd::vector& motions) { m_motions = motions; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -709,7 +709,7 @@ namespace EMotionFX void BlendSpace2DNode::SetSyncLeaderMotionId(const AZStd::string& syncLeaderMotionId) { m_syncLeaderMotionId = syncLeaderMotionId; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -725,7 +725,7 @@ namespace EMotionFX void BlendSpace2DNode::SetEvaluatorTypeX(const AZ::TypeId& evaluatorType) { m_evaluatorTypeX = evaluatorType; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -747,7 +747,7 @@ namespace EMotionFX void BlendSpace2DNode::SetCalculationMethodX(ECalculationMethod calculationMethod) { m_calculationMethodX = calculationMethod; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -763,7 +763,7 @@ namespace EMotionFX void BlendSpace2DNode::SetEvaluatorTypeY(const AZ::TypeId& evaluatorType) { m_evaluatorTypeY = evaluatorType; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -785,7 +785,7 @@ namespace EMotionFX void BlendSpace2DNode::SetCalculationMethodY(ECalculationMethod calculationMethod) { m_calculationMethodY = calculationMethod; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -1041,8 +1041,8 @@ namespace EMotionFX { AZ::Vector2 samplePoint; - EMotionFX::BlendTreeConnection* inputConnectionX = GetInputPort(INPUTPORT_XVALUE).mConnection; - EMotionFX::BlendTreeConnection* inputConnectionY = GetInputPort(INPUTPORT_YVALUE).mConnection; + EMotionFX::BlendTreeConnection* inputConnectionX = GetInputPort(INPUTPORT_XVALUE).m_connection; + EMotionFX::BlendTreeConnection* inputConnectionY = GetInputPort(INPUTPORT_YVALUE).m_connection; if (GetEMotionFX().GetIsInEditorMode()) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.cpp index 953bb530e7..2c3960ca5e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.cpp @@ -233,7 +233,7 @@ namespace EMotionFX MotionInstance* motionInstance = motionInfo.m_motionInstance; motionInstance->SetFreezeAtLastFrame(!motionInstance->GetIsPlayingForever()); motionInstance->SetPlaySpeed(motionInfo.m_playSpeed); - motionInstance->SetRetargetingEnabled(m_retarget && mAnimGraph->GetRetargetingEnabled()); + motionInstance->SetRetargetingEnabled(m_retarget && m_animGraph->GetRetargetingEnabled()); motionInfo.m_preSyncTime = motionInstance->GetCurrentTime(); // If syncing is enabled, we are going to update the current play time (m_currentTime) of all motions later based @@ -361,8 +361,8 @@ namespace EMotionFX trajectoryDeltaAMirrored.Add(instanceDelta, blendInfo.m_weight); motionInstance->SetMirrorMotion(isMirrored); // restore current mirrored flag } - trajectoryDelta.mRotation.Normalize(); - trajectoryDeltaAMirrored.mRotation.Normalize(); + trajectoryDelta.m_rotation.Normalize(); + trajectoryDeltaAMirrored.m_rotation.Normalize(); } data->SetTrajectoryDelta(trajectoryDelta); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.h index 893962d65d..b2acd240ee 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceNode.h @@ -102,8 +102,8 @@ namespace EMotionFX virtual const AZStd::vector& GetMotions() const = 0; //! The node is in interactive mode when the user is interactively changing the current point. - void SetInteractiveMode(bool enable) { mInteractiveMode = enable; } - bool IsInInteractiveMode() const { return mInteractiveMode; } + void SetInteractiveMode(bool enable) { m_interactiveMode = enable; } + bool IsInInteractiveMode() const { return m_interactiveMode; } static void Reflect(AZ::ReflectContext* context); @@ -166,7 +166,7 @@ namespace EMotionFX static const char* s_eventModeNone; protected: - bool mInteractiveMode = false;// true when the user is changing the current point by dragging in GUI + bool m_interactiveMode = false;// true when the user is changing the current point by dragging in GUI bool m_retarget = true; bool m_inPlace = false; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceParamEvaluator.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceParamEvaluator.cpp index 48f343cfc3..fb3f9e398a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceParamEvaluator.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpaceParamEvaluator.cpp @@ -100,14 +100,14 @@ namespace EMotionFX Transform transform; motion->CalcNodeTransform(&motionInstance, &transform, actor, node, 0, retargeting); - AZ::Vector3 position(transform.mPosition); + AZ::Vector3 position(transform.m_position); float distance = 0.0f; float time = sampleTimeStep; for (uint32 i = 1; i < numSamples; ++i, time += sampleTimeStep) { motion->CalcNodeTransform(&motionInstance, &transform, actor, node, time, retargeting); - distance += (transform.mPosition - position).GetLength(); - position = transform.mPosition; + distance += (transform.m_position - position).GetLength(); + position = transform.m_position; } return distance / duration; @@ -142,16 +142,16 @@ namespace EMotionFX Transform transform; motion->CalcNodeTransform(&motionInstance, &transform, actor, node, 0, retargeting); - AZ::Quaternion rotation(transform.mRotation); + AZ::Quaternion rotation(transform.m_rotation); float totalAngle = 0.0f; float time = sampleTimeStep; for (uint32 i = 1; i < numSamples; ++i, time += sampleTimeStep) { motion->CalcNodeTransform(&motionInstance, &transform, actor, node, time, retargeting); - AZ::Quaternion deltaRotation = transform.mRotation * rotation.GetConjugate(); + AZ::Quaternion deltaRotation = transform.m_rotation * rotation.GetConjugate(); const float angle = -MCore::GetEulerZ(deltaRotation);// negating because we prefer the convention of clockwise being +ve totalAngle += angle; - rotation = transform.mRotation; + rotation = transform.m_rotation; } return totalAngle / duration; @@ -185,7 +185,7 @@ namespace EMotionFX Transform endTransform; motion->CalcNodeTransform(&motionInstance, &endTransform, actor, node, duration, retargeting); - AZ::Vector3 diffVec(endTransform.mPosition - startTransform.mPosition); + AZ::Vector3 diffVec(endTransform.m_position - startTransform.m_position); return ::atan2f(diffVec.GetX(), diffVec.GetY()); } @@ -218,19 +218,19 @@ namespace EMotionFX Transform transform; motion->CalcNodeTransform(&motionInstance, &transform, actor, node, 0, retargeting); - AZ::Vector3 position(transform.mPosition); + AZ::Vector3 position(transform.m_position); float slopeSum = 0.0f; float time = sampleTimeStep; uint32 count = 0; // number of samples added to slopeSum for (uint32 i = 1; i < numSamples; ++i, time += sampleTimeStep) { motion->CalcNodeTransform(&motionInstance, &transform, actor, node, time, retargeting); - AZ::Vector3 diffVec(transform.mPosition - position); + AZ::Vector3 diffVec(transform.m_position - position); float horizontalDistance = AZ::Vector2(diffVec.GetX(), diffVec.GetY()).GetLength(); if (horizontalDistance > 0) { slopeSum += atan2f(diffVec.GetZ(), horizontalDistance); - position = transform.mPosition; + position = transform.m_position; count++; } } @@ -268,16 +268,16 @@ namespace EMotionFX Transform transform; motion->CalcNodeTransform(&motionInstance, &transform, actor, node, 0, retargeting); - AZ::Quaternion rotation(transform.mRotation); + AZ::Quaternion rotation(transform.m_rotation); float totalTurnAngle = 0.0f; float time = sampleTimeStep; for (uint32 i = 1; i < numSamples; ++i, time += sampleTimeStep) { motion->CalcNodeTransform(&motionInstance, &transform, actor, node, time, retargeting); - AZ::Quaternion deltaRotation = transform.mRotation * rotation.GetConjugate(); + AZ::Quaternion deltaRotation = transform.m_rotation * rotation.GetConjugate(); const float angle = -MCore::GetEulerZ(deltaRotation);// negating because we prefer the convention of clockwise being +ve totalTurnAngle += angle; - rotation = transform.mRotation; + rotation = transform.m_rotation; } return totalTurnAngle; @@ -311,7 +311,7 @@ namespace EMotionFX Transform endTransform; motion->CalcNodeTransform(&motionInstance, &endTransform, actor, node, duration, retargeting); - return (endTransform.mPosition - startTransform.mPosition).GetLength(); + return (endTransform.m_position - startTransform.m_position).GetLength(); } const char* BlendSpaceTravelDistanceParamEvaluator::GetName() const @@ -345,15 +345,15 @@ namespace EMotionFX Transform transform; motion->CalcNodeTransform(&motionInstance, &transform, actor, node, 0, retargeting); - AZ::Vector3 position(transform.mPosition); + AZ::Vector3 position(transform.m_position); float distance = 0.0f; float time = sampleTimeStep; for (uint32 i = 1; i < numSamples; ++i, time += sampleTimeStep) { motion->CalcNodeTransform(&motionInstance, &transform, actor, node, time, retargeting); - AZ::Vector3 moveVec(transform.mPosition - position); + AZ::Vector3 moveVec(transform.m_position - position); distance += moveVec.Dot(xAxis); - position = transform.mPosition; + position = transform.m_position; } return distance / duration; @@ -390,15 +390,15 @@ namespace EMotionFX Transform transform; motion->CalcNodeTransform(&motionInstance, &transform, actor, node, 0, retargeting); - AZ::Vector3 position(transform.mPosition); + AZ::Vector3 position(transform.m_position); float distance = 0.0f; float time = sampleTimeStep; for (uint32 i = 1; i < numSamples; ++i, time += sampleTimeStep) { motion->CalcNodeTransform(&motionInstance, &transform, actor, node, time, retargeting); - AZ::Vector3 moveVec(transform.mPosition - position); + AZ::Vector3 moveVec(transform.m_position - position); distance += moveVec.Dot(yAxis); - position = transform.mPosition; + position = transform.m_position; } return distance / duration; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp index 1952ba9b2a..f742696275 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.cpp @@ -30,7 +30,7 @@ namespace EMotionFX : AnimGraphNode() , m_finalNodeId(AnimGraphNodeId::InvalidId) , m_finalNode(nullptr) - , mVirtualFinalNode(nullptr) + , m_virtualFinalNode(nullptr) { // setup output ports InitOutputPorts(1); @@ -88,7 +88,7 @@ namespace EMotionFX // Relink input and output ports for all nodes in the blend tree with their corresponding connections. // This has to be done after all child nodes called InitAfterLoading() and RegisterPorts(). We're depending on the node load order here // and a given node might be connected to one that has not been loaded yet and thus the ports have not been created yet. - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->RelinkPortConnections(); } @@ -102,9 +102,9 @@ namespace EMotionFX AnimGraphNode* BlendTree::GetRealFinalNode() const { // if there is a virtual final node, use that one - if (mVirtualFinalNode) + if (m_virtualFinalNode) { - return mVirtualFinalNode; + return m_virtualFinalNode; } // otherwise get the real final node @@ -126,7 +126,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // if this node is disabled, output the bind pose - if (mDisabled) + if (m_disabled) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -156,7 +156,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -165,7 +165,7 @@ namespace EMotionFX void BlendTree::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if this node is disabled, exit - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); @@ -213,7 +213,7 @@ namespace EMotionFX void BlendTree::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if this node is disabled, output the bind pose - if (mDisabled) + if (m_disabled) { AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Clear(); @@ -243,7 +243,7 @@ namespace EMotionFX // rewind the nodes in the tree void BlendTree::Rewind(AnimGraphInstance* animGraphInstance) { - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { childNode->Rewind(animGraphInstance); } @@ -276,7 +276,7 @@ namespace EMotionFX void BlendTree::RecursiveSetUniqueDataFlag(AnimGraphInstance* animGraphInstance, uint32 flag, bool enabled) { // set flag for this node - animGraphInstance->SetObjectFlags(mObjectIndex, flag, enabled); + animGraphInstance->SetObjectFlags(m_objectIndex, flag, enabled); // get the final node AnimGraphNode* finalNode = GetRealFinalNode(); @@ -310,7 +310,7 @@ namespace EMotionFX void BlendTree::SetVirtualFinalNode(AnimGraphNode* node) { - mVirtualFinalNode = node; + m_virtualFinalNode = node; AnimGraphNotificationBus::Broadcast(&AnimGraphNotificationBus::Events::OnVirtualFinalNodeSet, this); } @@ -319,7 +319,7 @@ namespace EMotionFX void BlendTree::SetFinalNodeId(const AnimGraphNodeId finalNodeId) { m_finalNodeId = finalNodeId; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -342,7 +342,7 @@ namespace EMotionFX AZStd::unordered_set visitedNodes; AZStd::unordered_set > cycleConnections; - for (AnimGraphNode* childNode : mChildNodes) + for (AnimGraphNode* childNode : m_childNodes) { visitedNodes.clear(); visitedNodes.emplace(childNode); @@ -356,8 +356,8 @@ namespace EMotionFX void BlendTree::RecursiveFindCycles(AnimGraphNode* nextNode, AZStd::unordered_set& visitedNodes, AZStd::unordered_set >& cycleConnections) const { AZStd::unordered_map > sourceNodesAndConnections; - const uint32 numConnections = nextNode->GetNumConnections(); - for (uint32 j = 0; j < numConnections; ++j) + const size_t numConnections = nextNode->GetNumConnections(); + for (size_t j = 0; j < numConnections; ++j) { AnimGraphNode* sourceNode = nextNode->GetConnection(j)->GetSourceNode(); sourceNodesAndConnections[sourceNode].emplace_back(nextNode->GetConnection(j)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.h index cfe844fdb9..4ba4ba1f00 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTree.h @@ -64,7 +64,7 @@ namespace EMotionFX bool GetHasOutputPose() const override { return true; } void SetVirtualFinalNode(AnimGraphNode* node); - MCORE_INLINE AnimGraphNode* GetVirtualFinalNode() const { return mVirtualFinalNode; } + MCORE_INLINE AnimGraphNode* GetVirtualFinalNode() const { return m_virtualFinalNode; } void SetFinalNodeId(const AnimGraphNodeId finalNodeId); AZ_FORCE_INLINE AnimGraphNodeId GetFinalNodeId() const { return m_finalNodeId; } @@ -100,7 +100,7 @@ namespace EMotionFX private: AZ::u64 m_finalNodeId; /**< Id of the final node that gets serialized. The final node represents the output of the blend tree. */ BlendTreeFinalNode* m_finalNode; /**< The cached final node pointer based on the final node id. */ - AnimGraphNode* mVirtualFinalNode; /**< The virtual final node, which is the node who's output is used as final output. A value of nullptr means it will use the real mFinalNode. */ + AnimGraphNode* m_virtualFinalNode; /**< The virtual final node, which is the node who's output is used as final output. A value of nullptr means it will use the real m_finalNode. */ /** * Helper function that recursively (through incoming connections) detect cycles. The function performs a DFS to find back edges (connections to itself or to one of its ancestors). diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp index 60e5f837b0..c8f53a4b6f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.cpp @@ -28,28 +28,28 @@ namespace EMotionFX BlendTreeAccumTransformNode::UniqueData::UniqueData(AnimGraphNode* node, AnimGraphInstance* animGraphInstance) : AnimGraphNodeData(node, animGraphInstance) { - mAdditiveTransform.Identity(); - EMFX_SCALECODE(mAdditiveTransform.mScale.CreateZero();) + m_additiveTransform.Identity(); + EMFX_SCALECODE(m_additiveTransform.m_scale.CreateZero();) SetHasError(true); } void BlendTreeAccumTransformNode::UniqueData::Update() { - BlendTreeAccumTransformNode* accumTransformNode = azdynamic_cast(mObject); + BlendTreeAccumTransformNode* accumTransformNode = azdynamic_cast(m_object); AZ_Assert(accumTransformNode, "Unique data linked to incorrect node type."); - const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + const ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); const Actor* actor = actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); const Node* node = skeleton->FindNodeByName(accumTransformNode->GetTargetNodeName().c_str()); if (node) { - mNodeIndex = node->GetNodeIndex(); + m_nodeIndex = node->GetNodeIndex(); SetHasError(false); } else { - mNodeIndex = InvalidIndex32; + m_nodeIndex = InvalidIndex; SetHasError(true); } } @@ -137,7 +137,7 @@ namespace EMotionFX // make sure we have at least an input pose, otherwise output the bind pose - if (GetInputPort(INPUTPORT_POSE).mConnection == nullptr) + if (GetInputPort(INPUTPORT_POSE).m_connection == nullptr) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_RESULT)->GetValue(); @@ -154,12 +154,12 @@ namespace EMotionFX // get the local transform from our node Transform inputTransform; - outputPose->GetPose().GetLocalSpaceTransform(uniqueData->mNodeIndex, &inputTransform); + outputPose->GetPose().GetLocalSpaceTransform(uniqueData->m_nodeIndex, &inputTransform); Transform outputTransform = inputTransform; // process the rotation - if (GetInputPort(INPUTPORT_ROTATE_AMOUNT).mConnection) + if (GetInputPort(INPUTPORT_ROTATE_AMOUNT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_ROTATE_AMOUNT)); @@ -188,15 +188,15 @@ namespace EMotionFX } const AZ::Quaternion targetRot = MCore::CreateFromAxisAndAngle(axis, MCore::Math::DegreesToRadians(360.0f * (inputAmount - 0.5f) * invertFactor)); - AZ::Quaternion deltaRot = MCore::LinearInterpolate(AZ::Quaternion::CreateIdentity(), targetRot, uniqueData->mDeltaTime * factor); + AZ::Quaternion deltaRot = MCore::LinearInterpolate(AZ::Quaternion::CreateIdentity(), targetRot, uniqueData->m_deltaTime * factor); deltaRot.Normalize(); - uniqueData->mAdditiveTransform.mRotation = uniqueData->mAdditiveTransform.mRotation * deltaRot; - outputTransform.mRotation = (inputTransform.mRotation * uniqueData->mAdditiveTransform.mRotation); - outputTransform.mRotation.Normalize(); + uniqueData->m_additiveTransform.m_rotation = uniqueData->m_additiveTransform.m_rotation * deltaRot; + outputTransform.m_rotation = (inputTransform.m_rotation * uniqueData->m_additiveTransform.m_rotation); + outputTransform.m_rotation.Normalize(); } // process the translation - if (GetInputPort(INPUTPORT_TRANSLATE_AMOUNT).mConnection) + if (GetInputPort(INPUTPORT_TRANSLATE_AMOUNT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_TRANSLATE_AMOUNT)); @@ -225,15 +225,15 @@ namespace EMotionFX } axis *= (inputAmount - 0.5f) * invertFactor; - uniqueData->mAdditiveTransform.mPosition += MCore::LinearInterpolate(AZ::Vector3::CreateZero(), axis, uniqueData->mDeltaTime * factor); - outputTransform.mPosition = inputTransform.mPosition + uniqueData->mAdditiveTransform.mPosition; + uniqueData->m_additiveTransform.m_position += MCore::LinearInterpolate(AZ::Vector3::CreateZero(), axis, uniqueData->m_deltaTime * factor); + outputTransform.m_position = inputTransform.m_position + uniqueData->m_additiveTransform.m_position; } // process the scale EMFX_SCALECODE ( - if (GetInputPort(INPUTPORT_SCALE_AMOUNT).mConnection) + if (GetInputPort(INPUTPORT_SCALE_AMOUNT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_SCALE_AMOUNT)); @@ -265,18 +265,18 @@ namespace EMotionFX } axis *= (inputAmount - 0.5f) * invertFactor; - uniqueData->mAdditiveTransform.mScale += MCore::LinearInterpolate(AZ::Vector3::CreateZero(), axis, uniqueData->mDeltaTime * factor); - outputTransform.mScale = inputTransform.mScale + uniqueData->mAdditiveTransform.mScale; + uniqueData->m_additiveTransform.m_scale += MCore::LinearInterpolate(AZ::Vector3::CreateZero(), axis, uniqueData->m_deltaTime * factor); + outputTransform.m_scale = inputTransform.m_scale + uniqueData->m_additiveTransform.m_scale; } ) // update the transformation of the node - outputPose->GetPose().SetLocalSpaceTransform(uniqueData->mNodeIndex, outputTransform); + outputPose->GetPose().SetLocalSpaceTransform(uniqueData->m_nodeIndex, outputTransform); // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -288,21 +288,21 @@ namespace EMotionFX // store the passed time UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - uniqueData->mDeltaTime = timePassedInSeconds; + uniqueData->m_deltaTime = timePassedInSeconds; } void BlendTreeAccumTransformNode::OnAxisChanged() { - if (!mAnimGraph) + if (!m_animGraph) { return; } - const size_t numInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueNodeData(this)); if (!uniqueData) @@ -310,8 +310,8 @@ namespace EMotionFX continue; } - uniqueData->mAdditiveTransform.Identity(); - EMFX_SCALECODE(uniqueData->mAdditiveTransform.mScale.CreateZero();) + uniqueData->m_additiveTransform.Identity(); + EMFX_SCALECODE(uniqueData->m_additiveTransform.m_scale.CreateZero();) InvalidateUniqueData(animGraphInstance); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h index 86ad69ec69..8f8fc21a6e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeAccumTransformNode.h @@ -83,9 +83,9 @@ namespace EMotionFX void Update() override; public: - Transform mAdditiveTransform = Transform::CreateIdentity(); - uint32 mNodeIndex = InvalidIndex32; - float mDeltaTime = 0.0f; + Transform m_additiveTransform = Transform::CreateIdentity(); + size_t m_nodeIndex = InvalidIndex; + float m_deltaTime = 0.0f; }; BlendTreeAccumTransformNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp index 703838f22b..1f3f41bb15 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2AdditiveNode.cpp @@ -45,7 +45,7 @@ namespace EMotionFX void BlendTreeBlend2AdditiveNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Clear(); @@ -91,7 +91,7 @@ namespace EMotionFX void BlendTreeBlend2AdditiveNode::Output(AnimGraphInstance* animGraphInstance) { // If we disabled this blend node, simply output a bind pose. - if (mDisabled) + if (m_disabled) { RequestPoses(animGraphInstance); AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -109,7 +109,7 @@ namespace EMotionFX OutputIncomingNode(animGraphInstance, weightNode); } - const size_t numNodes = uniqueData->mMask.size(); + const size_t numNodes = uniqueData->m_mask.size(); if (numNodes == 0) { OutputNoFeathering(animGraphInstance); @@ -122,7 +122,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { AnimGraphPose* outPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); - animGraphInstance->GetActorInstance()->DrawSkeleton(outPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outPose->GetPose(), m_visualizeColor); } } @@ -207,14 +207,14 @@ namespace EMotionFX Pose& outputLocalPose = outputPose->GetPose(); // If we use a mask, overwrite those nodes. - const size_t numNodes = uniqueData->mMask.size(); + const size_t numNodes = uniqueData->m_mask.size(); if (numNodes > 0) { Transform transform; for (size_t n = 0; n < numNodes; ++n) { - const float finalWeight = blendWeight;// * uniqueData->mWeights[n]; - const uint32 nodeIndex = uniqueData->mMask[n]; + const float finalWeight = blendWeight;// * uniqueData->m_weights[n]; + const size_t nodeIndex = uniqueData->m_mask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.ApplyAdditive(additivePose.GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); @@ -241,7 +241,7 @@ namespace EMotionFX Transform delta = Transform::CreateIdentityWithZeroScale(); Transform deltaMirrored = Transform::CreateIdentityWithZeroScale(); - const bool hasMotionExtractionNodeInMask = (uniqueData->mMask.size() == 0) || (uniqueData->mMask.size() > 0 && AZStd::find(uniqueData->mMask.begin(), uniqueData->mMask.end(), actor->GetMotionExtractionNodeIndex()) != uniqueData->mMask.end()); + const bool hasMotionExtractionNodeInMask = (uniqueData->m_mask.size() == 0) || (uniqueData->m_mask.size() > 0 && AZStd::find(uniqueData->m_mask.begin(), uniqueData->m_mask.end(), actor->GetMotionExtractionNodeIndex()) != uniqueData->m_mask.end()); if (!hasMotionExtractionNodeInMask || !nodeBData || m_extractionMode == EXTRACTIONMODE_SOURCEONLY) { delta = nodeAData->GetTrajectoryDelta(); @@ -278,13 +278,13 @@ namespace EMotionFX void BlendTreeBlend2AdditiveNode::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { return; } UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { AnimGraphNodeData* sourceNodeUniqueData = con->GetSourceNode()->FindOrCreateUniqueNodeData(animGraphInstance); @@ -318,7 +318,7 @@ namespace EMotionFX // If we want to sync the motions. if (m_syncMode != SYNCMODE_DISABLED) { - const bool resync = (uniqueData->mSyncTrackNode != nodeA); + const bool resync = (uniqueData->m_syncTrackNode != nodeA); if (resync) { nodeA->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); @@ -327,7 +327,7 @@ namespace EMotionFX nodeB->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); } - uniqueData->mSyncTrackNode = nodeA; + uniqueData->m_syncTrackNode = nodeA; } // Sync the leader to this node. @@ -336,13 +336,13 @@ namespace EMotionFX // Sync the motion's to the leader. for (uint32 i = 0; i < 2; ++i) { - BlendTreeConnection* connection = mInputPorts[INPUTPORT_POSE_A + i].mConnection; + BlendTreeConnection* connection = m_inputPorts[INPUTPORT_POSE_A + i].m_connection; if (!connection) { continue; } - if (animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) + if (animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) { connection->GetSourceNode()->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_SYNCED, true); } @@ -389,7 +389,7 @@ namespace EMotionFX // post sync update void BlendTreeBlend2AdditiveNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); @@ -399,7 +399,7 @@ namespace EMotionFX return; } - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { con->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -443,7 +443,7 @@ namespace EMotionFX FilterEvents(animGraphInstance, eventMode, nodeA, nodeB, weight, data); // Output motion extraction deltas. - if (animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex() != MCORE_INVALIDINDEX32) + if (animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex() != InvalidIndex) { UpdateMotionExtraction(animGraphInstance, nodeA, nodeB, weight, uniqueData); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp index c94bf09eb5..8e52ea6bef 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2LegacyNode.cpp @@ -46,7 +46,7 @@ namespace EMotionFX void BlendTreeBlend2LegacyNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Clear(); @@ -95,7 +95,7 @@ namespace EMotionFX void BlendTreeBlend2LegacyNode::Output(AnimGraphInstance* animGraphInstance) { - if (mDisabled) + if (m_disabled) { RequestPoses(animGraphInstance); AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -112,7 +112,7 @@ namespace EMotionFX OutputIncomingNode(animGraphInstance, weightNode); } - const size_t numNodes = uniqueData->mMask.size(); + const size_t numNodes = uniqueData->m_mask.size(); if (numNodes == 0) { OutputNoFeathering(animGraphInstance); @@ -125,7 +125,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -227,7 +227,7 @@ namespace EMotionFX *outputPose = *nodeA->GetMainOutputPose(animGraphInstance); Pose& outputLocalPose = outputPose->GetPose(); - const size_t numNodes = uniqueData->mMask.size(); + const size_t numNodes = uniqueData->m_mask.size(); if (numNodes > 0) { Transform transform = Transform::CreateIdentity(); @@ -236,8 +236,8 @@ namespace EMotionFX { for (size_t n = 0; n < numNodes; ++n) { - const float finalWeight = blendWeight /* * uniqueData->mWeights[n]*/; - const uint32 nodeIndex = uniqueData->mMask[n]; + const float finalWeight = blendWeight /* * uniqueData->m_weights[n]*/; + const size_t nodeIndex = uniqueData->m_mask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.Blend(localMaskPose.GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); @@ -249,8 +249,8 @@ namespace EMotionFX const Pose* bindPose = actorInstance->GetTransformData()->GetBindPose(); for (size_t n = 0; n < numNodes; ++n) { - const float finalWeight = blendWeight /* * uniqueData->mWeights[n]*/; - const uint32 nodeIndex = uniqueData->mMask[n]; + const float finalWeight = blendWeight /* * uniqueData->m_weights[n]*/; + const size_t nodeIndex = uniqueData->m_mask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.BlendAdditive(localMaskPose.GetLocalSpaceTransform(nodeIndex), bindPose->GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); @@ -272,7 +272,7 @@ namespace EMotionFX Transform delta = Transform::CreateIdentityWithZeroScale(); Transform deltaMirrored = Transform::CreateIdentityWithZeroScale(); - const bool hasMotionExtractionNodeInMask = (uniqueData->mMask.size() == 0) || (uniqueData->mMask.size() > 0 && AZStd::find(uniqueData->mMask.begin(), uniqueData->mMask.end(), actor->GetMotionExtractionNodeIndex()) != uniqueData->mMask.end()); + const bool hasMotionExtractionNodeInMask = (uniqueData->m_mask.size() == 0) || (uniqueData->m_mask.size() > 0 && AZStd::find(uniqueData->m_mask.begin(), uniqueData->m_mask.end(), actor->GetMotionExtractionNodeIndex()) != uniqueData->m_mask.end()); if (!m_additiveBlending) { CalculateMotionExtractionDelta(m_extractionMode, nodeAData, nodeBData, weight, hasMotionExtractionNodeInMask, delta, deltaMirrored); @@ -291,13 +291,13 @@ namespace EMotionFX void BlendTreeBlend2LegacyNode::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { return; } UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { AnimGraphNodeData* sourceNodeUniqueData = con->GetSourceNode()->FindOrCreateUniqueNodeData(animGraphInstance); @@ -322,7 +322,7 @@ namespace EMotionFX if (m_syncMode != SYNCMODE_DISABLED) { - const bool resync = (uniqueData->mSyncTrackNode != nodeA); + const bool resync = (uniqueData->m_syncTrackNode != nodeA); if (resync) { nodeA->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); @@ -331,20 +331,20 @@ namespace EMotionFX nodeB->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); } - uniqueData->mSyncTrackNode = nodeA; + uniqueData->m_syncTrackNode = nodeA; } nodeA->AutoSync(animGraphInstance, this, 0.0f, SYNCMODE_TRACKBASED, false); for (uint32 i = 0; i < 2; ++i) { - BlendTreeConnection* connection = mInputPorts[INPUTPORT_POSE_A + i].mConnection; + BlendTreeConnection* connection = m_inputPorts[INPUTPORT_POSE_A + i].m_connection; if (!connection) { continue; } - if (animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) + if (animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) { connection->GetSourceNode()->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_SYNCED, true); } @@ -412,7 +412,7 @@ namespace EMotionFX void BlendTreeBlend2LegacyNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); @@ -422,7 +422,7 @@ namespace EMotionFX return; } - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { con->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -461,7 +461,7 @@ namespace EMotionFX eventMode = EVENTMODE_BOTHNODES; } FilterEvents(animGraphInstance, eventMode, nodeA, nodeB, weight, data); - if (animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex() != MCORE_INVALIDINDEX32) + if (animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex() != InvalidIndex) { UpdateMotionExtraction(animGraphInstance, nodeA, nodeB, weight, uniqueData); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp index 3cfff94f72..06223d4b14 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2Node.cpp @@ -45,7 +45,7 @@ namespace EMotionFX void BlendTreeBlend2Node::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Clear(); @@ -91,7 +91,7 @@ namespace EMotionFX void BlendTreeBlend2Node::Output(AnimGraphInstance* animGraphInstance) { - if (mDisabled) + if (m_disabled) { RequestPoses(animGraphInstance); AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -108,7 +108,7 @@ namespace EMotionFX OutputIncomingNode(animGraphInstance, weightNode); } - const size_t numNodes = uniqueData->mMask.size(); + const size_t numNodes = uniqueData->m_mask.size(); if (numNodes == 0) { OutputNoFeathering(animGraphInstance); @@ -121,7 +121,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -210,14 +210,14 @@ namespace EMotionFX *outputPose = *nodeA->GetMainOutputPose(animGraphInstance); Pose& outputLocalPose = outputPose->GetPose(); - const size_t numNodes = uniqueData->mMask.size(); + const size_t numNodes = uniqueData->m_mask.size(); if (numNodes > 0) { Transform transform; for (size_t n = 0; n < numNodes; ++n) { - const float finalWeight = blendWeight /* * uniqueData->mWeights[n]*/; - const uint32 nodeIndex = uniqueData->mMask[n]; + const float finalWeight = blendWeight /* * uniqueData->m_weights[n]*/; + const size_t nodeIndex = uniqueData->m_mask[n]; transform = outputLocalPose.GetLocalSpaceTransform(nodeIndex); transform.Blend(localMaskPose.GetLocalSpaceTransform(nodeIndex), finalWeight); outputLocalPose.SetLocalSpaceTransform(nodeIndex, transform); @@ -244,7 +244,7 @@ namespace EMotionFX Transform delta = Transform::CreateIdentityWithZeroScale(); Transform deltaMirrored = Transform::CreateIdentityWithZeroScale(); - const bool hasMotionExtractionNodeInMask = (uniqueData->mMask.size() == 0) || (uniqueData->mMask.size() > 0 && AZStd::find(uniqueData->mMask.begin(), uniqueData->mMask.end(), actor->GetMotionExtractionNodeIndex()) != uniqueData->mMask.end()); + const bool hasMotionExtractionNodeInMask = (uniqueData->m_mask.size() == 0) || (uniqueData->m_mask.size() > 0 && AZStd::find(uniqueData->m_mask.begin(), uniqueData->m_mask.end(), actor->GetMotionExtractionNodeIndex()) != uniqueData->m_mask.end()); CalculateMotionExtractionDelta(m_extractionMode, nodeAData, nodeBData, weight, hasMotionExtractionNodeInMask, delta, deltaMirrored); data->SetTrajectoryDelta(delta); @@ -254,13 +254,13 @@ namespace EMotionFX void BlendTreeBlend2Node::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { return; } UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { AnimGraphNodeData* sourceNodeUniqueData = con->GetSourceNode()->FindOrCreateUniqueNodeData(animGraphInstance); @@ -287,7 +287,7 @@ namespace EMotionFX if (m_syncMode != SYNCMODE_DISABLED) { - const bool resync = (uniqueData->mSyncTrackNode != nodeA); + const bool resync = (uniqueData->m_syncTrackNode != nodeA); if (resync) { nodeA->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); @@ -296,20 +296,20 @@ namespace EMotionFX nodeB->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); } - uniqueData->mSyncTrackNode = nodeA; + uniqueData->m_syncTrackNode = nodeA; } nodeA->AutoSync(animGraphInstance, this, 0.0f, SYNCMODE_TRACKBASED, false); for (uint32 i = 0; i < 2; ++i) { - BlendTreeConnection* connection = mInputPorts[INPUTPORT_POSE_A + i].mConnection; + BlendTreeConnection* connection = m_inputPorts[INPUTPORT_POSE_A + i].m_connection; if (!connection) { continue; } - if (animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) + if (animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) { connection->GetSourceNode()->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_SYNCED, true); } @@ -360,7 +360,7 @@ namespace EMotionFX void BlendTreeBlend2Node::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); @@ -370,7 +370,7 @@ namespace EMotionFX return; } - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { con->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -405,7 +405,7 @@ namespace EMotionFX FilterEvents(animGraphInstance, m_eventMode, nodeA, nodeB, weight, data); - if (animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex() != MCORE_INVALIDINDEX32) + if (animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex() != InvalidIndex) { UpdateMotionExtraction(animGraphInstance, nodeA, nodeB, weight, uniqueData); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp index 1a33ee1d85..fd399085a0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.cpp @@ -21,23 +21,23 @@ namespace EMotionFX BlendTreeBlend2NodeBase::UniqueData::UniqueData(AnimGraphNode* node, AnimGraphInstance* animGraphInstance) : AnimGraphNodeData(node, animGraphInstance) - , mSyncTrackNode(nullptr) + , m_syncTrackNode(nullptr) { } void BlendTreeBlend2NodeBase::UniqueData::Update() { - BlendTreeBlend2NodeBase* blend2Node = azdynamic_cast(mObject); + BlendTreeBlend2NodeBase* blend2Node = azdynamic_cast(m_object); AZ_Assert(blend2Node, "Unique data linked to incorrect node type."); - mMask.clear(); + m_mask.clear(); - Actor* actor = mAnimGraphInstance->GetActorInstance()->GetActor(); + Actor* actor = m_animGraphInstance->GetActorInstance()->GetActor(); const AZStd::vector& weightedNodeMask = blend2Node->GetWeightedNodeMask(); if (!weightedNodeMask.empty()) { const size_t numNodes = weightedNodeMask.size(); - mMask.reserve(numNodes); + m_mask.reserve(numNodes); // Try to find the node indices by name for all masked nodes. const Skeleton* skeleton = actor->GetSkeleton(); @@ -46,7 +46,7 @@ namespace EMotionFX Node* node = skeleton->FindNodeByName(weightedNode.first.c_str()); if (node) { - mMask.emplace_back(node->GetNodeIndex()); + m_mask.emplace_back(node->GetNodeIndex()); } } } @@ -100,8 +100,8 @@ namespace EMotionFX void BlendTreeBlend2NodeBase::FindBlendNodes(AnimGraphInstance* animGraphInstance, AnimGraphNode** outBlendNodeA, AnimGraphNode** outBlendNodeB, float* outWeight, bool isAdditive, bool optimizeByWeight) { - BlendTreeConnection* connectionA = mInputPorts[INPUTPORT_POSE_A].mConnection; - BlendTreeConnection* connectionB = mInputPorts[INPUTPORT_POSE_B].mConnection; + BlendTreeConnection* connectionA = m_inputPorts[INPUTPORT_POSE_A].m_connection; + BlendTreeConnection* connectionB = m_inputPorts[INPUTPORT_POSE_B].m_connection; if (!connectionA && !connectionB) { *outBlendNodeA = nullptr; @@ -112,11 +112,11 @@ namespace EMotionFX if (connectionA && connectionB) { - *outWeight = (mInputPorts[INPUTPORT_WEIGHT].mConnection) ? GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT) : 0.0f; + *outWeight = (m_inputPorts[INPUTPORT_WEIGHT].m_connection) ? GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT) : 0.0f; *outWeight = MCore::Clamp(*outWeight, 0.0f, 1.0f); UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueObjectData(this)); - if (uniqueData->mMask.size() > 0) + if (!uniqueData->m_mask.empty()) { *outBlendNodeA = connectionA->GetSourceNode(); *outBlendNodeB = connectionB->GetSourceNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h index d67238705d..9a9b51b5d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlend2NodeBase.h @@ -54,8 +54,8 @@ namespace EMotionFX void Update() override; public: - AZStd::vector mMask; - AnimGraphNode* mSyncTrackNode; + AZStd::vector m_mask; + AnimGraphNode* m_syncTrackNode; }; BlendTreeBlend2NodeBase(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.cpp index 147e5c0aa9..7720822655 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.cpp @@ -31,7 +31,7 @@ namespace EMotionFX void BlendTreeBlendNNode::UniqueData::Update() { - BlendTreeBlendNNode* blendNNode = azdynamic_cast(mObject); + BlendTreeBlendNNode* blendNNode = azdynamic_cast(m_object); AZ_Assert(blendNNode, "Unique data linked to incorrect node type."); blendNNode->UpdateParamWeightRanges(); @@ -136,11 +136,11 @@ namespace EMotionFX { float weightRange = 0.0f; const float defaultWeightStep = 1.0f; - for (const AnimGraphNode::Port& port : mInputPorts) + for (const AnimGraphNode::Port& port : m_inputPorts) { - if (port.mConnection && port.mPortID != PORTID_INPUT_WEIGHT) + if (port.m_connection && port.m_portId != PORTID_INPUT_WEIGHT) { - m_paramWeights.emplace_back(port.mPortID, weightRange); + m_paramWeights.emplace_back(port.m_portId, weightRange); weightRange += defaultWeightStep; } } @@ -172,9 +172,9 @@ namespace EMotionFX } float weight = m_paramWeights.front().m_weightRange; - if (!mDisabled) + if (!m_disabled) { - if (mInputPorts[INPUTPORT_WEIGHT].mConnection) + if (m_inputPorts[INPUTPORT_WEIGHT].m_connection) { weight = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT); } @@ -191,8 +191,8 @@ namespace EMotionFX *outWeight = 0.0f; // Calculate the blend weight and get the nodes - *outNodeA = GetInputPort(INPUTPORT_POSE_0 + poseIndexA).mConnection->GetSourceNode(); - *outNodeB = GetInputPort(INPUTPORT_POSE_0 + poseIndexB).mConnection->GetSourceNode(); + *outNodeA = GetInputPort(INPUTPORT_POSE_0 + poseIndexA).m_connection->GetSourceNode(); + *outNodeB = GetInputPort(INPUTPORT_POSE_0 + poseIndexB).m_connection->GetSourceNode(); *outIndexA = poseIndexA; *outIndexB = poseIndexB; @@ -227,8 +227,8 @@ namespace EMotionFX // Search complete: the input weight is between m_paramWeights[i] and m_paramWeights[i - 1] // Calculate the blend weight and get the nodes and then return - *outNodeA = GetInputPort(INPUTPORT_POSE_0 + poseIndexA).mConnection->GetSourceNode(); - *outNodeB = GetInputPort(INPUTPORT_POSE_0 + poseIndexB).mConnection->GetSourceNode(); + *outNodeA = GetInputPort(INPUTPORT_POSE_0 + poseIndexA).m_connection->GetSourceNode(); + *outNodeB = GetInputPort(INPUTPORT_POSE_0 + poseIndexB).m_connection->GetSourceNode(); *outIndexA = poseIndexA; *outIndexB = poseIndexB; @@ -242,8 +242,8 @@ namespace EMotionFX *outWeight = 0.0f; // Calculate the blend weight and get the nodes - *outNodeA = GetInputPort(INPUTPORT_POSE_0 + poseIndexA).mConnection->GetSourceNode(); - *outNodeB = GetInputPort(INPUTPORT_POSE_0 + poseIndexB).mConnection->GetSourceNode(); + *outNodeA = GetInputPort(INPUTPORT_POSE_0 + poseIndexA).m_connection->GetSourceNode(); + *outNodeB = GetInputPort(INPUTPORT_POSE_0 + poseIndexB).m_connection->GetSourceNode(); *outIndexA = poseIndexA; *outIndexB = poseIndexB; } @@ -259,7 +259,7 @@ namespace EMotionFX // check if we need to resync, this indicates the two motions we blend between changed bool resync = false; - if (uniqueData->mIndexA != poseIndexA || uniqueData->mIndexB != poseIndexB) + if (uniqueData->m_indexA != poseIndexA || uniqueData->m_indexB != poseIndexB) { resync = true; nodeA->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_RESYNC, true); @@ -272,14 +272,14 @@ namespace EMotionFX for (uint32 i = 0; i < 10; ++i) { // check if this port is used - BlendTreeConnection* connection = mInputPorts[i].mConnection; + BlendTreeConnection* connection = m_inputPorts[i].m_connection; if (connection == nullptr) { continue; } // mark this node recursively as synced - if (animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) + if (animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) { connection->GetSourceNode()->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_SYNCED, true); } @@ -307,8 +307,8 @@ namespace EMotionFX } } - uniqueData->mIndexA = poseIndexA; - uniqueData->mIndexB = poseIndexB; + uniqueData->m_indexA = poseIndexA; + uniqueData->m_indexB = poseIndexB; } // perform the calculations / actions @@ -320,7 +320,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // if there are no connections, there is nothing to do - if (mDisabled || !HasRequiredInputs()) + if (m_disabled || !HasRequiredInputs()) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -331,13 +331,13 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } // output the input weight node - BlendTreeConnection* connection = mInputPorts[INPUTPORT_WEIGHT].mConnection; + BlendTreeConnection* connection = m_inputPorts[INPUTPORT_WEIGHT].m_connection; if (connection) { OutputIncomingNode(animGraphInstance, connection->GetSourceNode()); @@ -361,7 +361,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } @@ -377,7 +377,7 @@ namespace EMotionFX *outputPose = *poseA; if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } @@ -394,7 +394,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } @@ -408,31 +408,31 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } bool BlendTreeBlendNNode::HasRequiredInputs() const { - if (mConnections.empty()) + if (m_connections.empty()) { return false; } // If we have only one input connection and it is our weight input, that means we have no input poses. - return !(mConnections.size() == 1 && mInputPorts[INPUTPORT_WEIGHT].mConnection); + return !(m_connections.size() == 1 && m_inputPorts[INPUTPORT_WEIGHT].m_connection); } void BlendTreeBlendNNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { - if (mDisabled || !HasRequiredInputs()) + if (m_disabled || !HasRequiredInputs()) { UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); uniqueData->Clear(); return; } - const BlendTreeConnection* weightConnection = mInputPorts[INPUTPORT_WEIGHT].mConnection; + const BlendTreeConnection* weightConnection = m_inputPorts[INPUTPORT_WEIGHT].m_connection; if (weightConnection) { UpdateIncomingNode(animGraphInstance, weightConnection->GetSourceNode(), timePassedInSeconds); @@ -475,14 +475,14 @@ namespace EMotionFX void BlendTreeBlendNNode::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if the node is disabled - if (mDisabled || !HasRequiredInputs()) + if (m_disabled || !HasRequiredInputs()) { return; } // top down update the weight input UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).mConnection; + const BlendTreeConnection* con = GetInputPort(INPUTPORT_WEIGHT).m_connection; if (con) { con->GetSourceNode()->FindOrCreateUniqueNodeData(animGraphInstance)->SetGlobalWeight(uniqueData->GetGlobalWeight()); @@ -565,7 +565,7 @@ namespace EMotionFX void BlendTreeBlendNNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if we don't have enough inputs or are disabled, we don't need to update anything - if (mDisabled || !HasRequiredInputs()) + if (m_disabled || !HasRequiredInputs()) { // request the reference counted data inside the unique data RequestRefDatas(animGraphInstance); @@ -577,7 +577,7 @@ namespace EMotionFX } // get the input weight - BlendTreeConnection* connection = mInputPorts[INPUTPORT_WEIGHT].mConnection; + BlendTreeConnection* connection = m_inputPorts[INPUTPORT_WEIGHT].m_connection; if (connection) { connection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -732,21 +732,21 @@ namespace EMotionFX float* lastNonDefaultValue = nullptr; for (const AnimGraphNode::Port& port : inputPorts) { - if (port.mConnection && port.mPortID != PORTID_INPUT_WEIGHT) + if (port.m_connection && port.m_portId != PORTID_INPUT_WEIGHT) { const float defaultRangeValue = m_paramWeights.empty() ? 0.0f : m_paramWeights.back().GetWeightRange(); - auto portToWeightRangeIterator = portToWeightRangeTable.find(port.mPortID); + auto portToWeightRangeIterator = portToWeightRangeTable.find(port.m_portId); if (portToWeightRangeIterator == portToWeightRangeTable.end()) { // New connection just plugged - m_paramWeights.emplace_back(port.mPortID, defaultRangeValue); + m_paramWeights.emplace_back(port.m_portId, defaultRangeValue); defaultElementsCount++; } else { // Existing connection, using existing weight range - m_paramWeights.emplace_back(port.mPortID, portToWeightRangeIterator->second); + m_paramWeights.emplace_back(port.m_portId, portToWeightRangeIterator->second); // We want to fill the previous default values with uniformly distributed // Weight ranges, if possible: diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h index 22b78db313..72d6ad120c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBlendNNode.h @@ -94,8 +94,8 @@ namespace EMotionFX void Update() override; public: - uint32 mIndexA = InvalidIndex32; - uint32 mIndexB = InvalidIndex32; + uint32 m_indexA = InvalidIndex32; + uint32 m_indexB = InvalidIndex32; }; BlendTreeBlendNNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBoolLogicNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBoolLogicNode.cpp index 70cd7092f8..fc85790518 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBoolLogicNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeBoolLogicNode.cpp @@ -33,7 +33,7 @@ namespace EMotionFX SetupOutputPort("Float", OUTPUTPORT_VALUE, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_VALUE); SetupOutputPort("Bool", OUTPUTPORT_BOOL, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_BOOL); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -121,7 +121,7 @@ namespace EMotionFX void BlendTreeBoolLogicNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if there are no incoming connections, there is nothing to do - if (mConnections.empty()) + if (m_connections.empty()) { return; } @@ -131,7 +131,7 @@ namespace EMotionFX // if both x and y inputs have connections bool x, y; - if (mConnections.size() == 2) + if (m_connections.size() == 2) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_X)); OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_Y)); @@ -142,7 +142,7 @@ namespace EMotionFX else // only x or y is connected { // if only x has something plugged in - if (mConnections[0]->GetTargetPort() == INPUTPORT_X) + if (m_connections[0]->GetTargetPort() == INPUTPORT_X) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_X)); x = GetInputNumberAsBool(animGraphInstance, INPUTPORT_X); @@ -150,7 +150,7 @@ namespace EMotionFX } else // only y has an input { - MCORE_ASSERT(mConnections[0]->GetTargetPort() == INPUTPORT_Y); + MCORE_ASSERT(m_connections[0]->GetTargetPort() == INPUTPORT_Y); OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_Y)); x = m_defaultValue; y = GetInputNumberAsBool(animGraphInstance, INPUTPORT_Y); @@ -174,7 +174,7 @@ namespace EMotionFX void BlendTreeBoolLogicNode::SetFunction(EFunction func) { m_functionEnum = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp index 7bbbd5ade8..084396f201 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.cpp @@ -20,9 +20,9 @@ namespace EMotionFX : m_animGraph(nullptr) , m_sourceNode(nullptr) , m_id(AnimGraphConnectionId::Create()) - , mSourcePort(MCORE_INVALIDINDEX16) - , mTargetPort(MCORE_INVALIDINDEX16) - , mVisited(false) + , m_sourcePort(MCORE_INVALIDINDEX16) + , m_targetPort(MCORE_INVALIDINDEX16) + , m_visited(false) { } @@ -34,8 +34,8 @@ namespace EMotionFX m_animGraph = sourceNode->GetAnimGraph(); } - mSourcePort = sourcePort; - mTargetPort = targetPort; + m_sourcePort = sourcePort; + m_targetPort = targetPort; SetSourceNode(sourceNode); } @@ -80,7 +80,7 @@ namespace EMotionFX bool BlendTreeConnection::GetIsValid() const { // make sure the node and input numbers are valid - if (!m_sourceNode || mSourcePort == MCORE_INVALIDINDEX16 || mTargetPort == MCORE_INVALIDINDEX16) + if (!m_sourceNode || m_sourcePort == MCORE_INVALIDINDEX16 || m_targetPort == MCORE_INVALIDINDEX16) { return false; } @@ -101,7 +101,7 @@ namespace EMotionFX ->Version(2) ->Field("id", &BlendTreeConnection::m_id) ->Field("sourceNodeId", &BlendTreeConnection::m_sourceNodeId) - ->Field("sourcePortNr", &BlendTreeConnection::mSourcePort) - ->Field("targetPortNr", &BlendTreeConnection::mTargetPort); + ->Field("sourcePortNr", &BlendTreeConnection::m_sourcePort) + ->Field("targetPortNr", &BlendTreeConnection::m_targetPort); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.h index 437cf6de51..7750b7b998 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeConnection.h @@ -41,17 +41,17 @@ namespace EMotionFX AZ_FORCE_INLINE AnimGraphNode* GetSourceNode() const { return m_sourceNode; } AZ_FORCE_INLINE AnimGraphNodeId GetSourceNodeId() const { return m_sourceNodeId; } - MCORE_INLINE AZ::u16 GetSourcePort() const { return mSourcePort; } - MCORE_INLINE AZ::u16 GetTargetPort() const { return mTargetPort; } + MCORE_INLINE AZ::u16 GetSourcePort() const { return m_sourcePort; } + MCORE_INLINE AZ::u16 GetTargetPort() const { return m_targetPort; } - MCORE_INLINE void SetSourcePort(AZ::u16 sourcePort) { mSourcePort = sourcePort; } - MCORE_INLINE void SetTargetPort(AZ::u16 targetPort) { mTargetPort = targetPort; } + MCORE_INLINE void SetSourcePort(AZ::u16 sourcePort) { m_sourcePort = sourcePort; } + MCORE_INLINE void SetTargetPort(AZ::u16 targetPort) { m_targetPort = targetPort; } AnimGraphConnectionId GetId() const { return m_id; } void SetId(AnimGraphConnectionId id) { m_id = id; } - MCORE_INLINE void SetIsVisited(bool visited) { mVisited = visited; } - MCORE_INLINE bool GetIsVisited() const { return mVisited; } + MCORE_INLINE void SetIsVisited(bool visited) { m_visited = visited; } + MCORE_INLINE bool GetIsVisited() const { return m_visited; } AnimGraph* GetAnimGraph() const { return m_animGraph; } @@ -62,8 +62,8 @@ namespace EMotionFX AnimGraphNode* m_sourceNode; /**< The source node from which the incoming connection comes. */ AZ::u64 m_sourceNodeId; AZ::u64 m_id; - AZ::u16 mSourcePort; /**< The source port number, so the output port number of the node where the connection comes from. */ - AZ::u16 mTargetPort; /**< The target port number, which is the input port number of the target node. */ - bool mVisited; /**< True when during updates this connection was used. */ + AZ::u16 m_sourcePort; /**< The source port number, so the output port number of the node where the connection comes from. */ + AZ::u16 m_targetPort; /**< The target port number, which is the input port number of the target node. */ + bool m_visited; /**< True when during updates this connection was used. */ }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeDirectionToWeightNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeDirectionToWeightNode.cpp index c87cc32e67..8167addf44 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeDirectionToWeightNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeDirectionToWeightNode.cpp @@ -73,8 +73,8 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // if there are less than two incoming connections, there is nothing to do - const size_t numConnections = mConnections.size(); - if (numConnections < 2 || mDisabled) + const size_t numConnections = m_connections.size(); + if (numConnections < 2 || m_disabled) { GetOutputFloat(animGraphInstance, OUTPUTPORT_WEIGHT)->SetValue(0.0f); return; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFinalNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFinalNode.cpp index c69a778f7e..85418a81b8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFinalNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFinalNode.cpp @@ -71,7 +71,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // if there is no input, just output a bind pose - if (mConnections.empty()) + if (m_connections.empty()) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_RESULT)->GetValue(); @@ -80,7 +80,7 @@ namespace EMotionFX } // output the source node - AnimGraphNode* sourceNode = mConnections[0]->GetSourceNode(); + AnimGraphNode* sourceNode = m_connections[0]->GetSourceNode(); OutputIncomingNode(animGraphInstance, sourceNode); RequestPoses(animGraphInstance); @@ -93,7 +93,7 @@ namespace EMotionFX void BlendTreeFinalNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if there are no connections, output nothing - if (mConnections.empty()) + if (m_connections.empty()) { AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Clear(); @@ -101,7 +101,7 @@ namespace EMotionFX } // update the source node - AnimGraphNode* sourceNode = mConnections[0]->GetSourceNode(); + AnimGraphNode* sourceNode = m_connections[0]->GetSourceNode(); UpdateIncomingNode(animGraphInstance, sourceNode, timePassedInSeconds); // update the sync track diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.cpp index 41c688f36a..b93659661d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatConditionNode.cpp @@ -36,7 +36,7 @@ namespace EMotionFX SetupOutputPort("Bool", OUTPUTPORT_BOOL, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_BOOL); // false on default - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -119,7 +119,7 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // if there are no incoming connections, there is nothing to do - const size_t numConnections = mConnections.size(); + const size_t numConnections = m_connections.size(); if (numConnections == 0) { return; @@ -138,7 +138,7 @@ namespace EMotionFX else // only x or y is connected { // if only x has something plugged in - if (mConnections[0]->GetTargetPort() == INPUTPORT_X) + if (m_connections[0]->GetTargetPort() == INPUTPORT_X) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_X)); x = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_X); @@ -146,7 +146,7 @@ namespace EMotionFX } else // only y has an input { - MCORE_ASSERT(mConnections[0]->GetTargetPort() == INPUTPORT_Y); + MCORE_ASSERT(m_connections[0]->GetTargetPort() == INPUTPORT_Y); x = m_defaultValue; OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_Y)); y = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_Y); @@ -198,7 +198,7 @@ namespace EMotionFX void BlendTreeFloatConditionNode::SetFunction(EFunction func) { m_functionEnum = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath1Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath1Node.cpp index 55924d8fd0..c70a1b69a6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath1Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath1Node.cpp @@ -29,7 +29,7 @@ namespace EMotionFX InitOutputPorts(1); SetupOutputPort("Result", OUTPUTPORT_RESULT, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_RESULT); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -192,12 +192,12 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // If there are no incoming connections, there is nothing to do. - if (mConnections.empty()) + if (m_connections.empty()) { return; } // Pass the input value as output in case we are disabled and have connected inputs. - else if (mDisabled) + else if (m_disabled) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_X)); GetOutputFloat(animGraphInstance, OUTPUTPORT_RESULT)->SetValue(GetInputNumberAsFloat(animGraphInstance, INPUTPORT_X)); @@ -219,7 +219,7 @@ namespace EMotionFX void BlendTreeFloatMath1Node::SetMathFunction(EMathFunction func) { m_mathFunction = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath2Node.cpp index 30a056ee34..de63373bd0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath2Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatMath2Node.cpp @@ -32,7 +32,7 @@ namespace EMotionFX InitOutputPorts(1); SetupOutputPort("Result", OUTPUTPORT_RESULT, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_RESULT); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -131,14 +131,14 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // if there are no incoming connections, there is nothing to do - if (mConnections.empty()) + if (m_connections.empty()) { return; } // if both x and y inputs have connections float x, y; - if (mConnections.size() == 2) + if (m_connections.size() == 2) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_X)); OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_Y)); @@ -149,7 +149,7 @@ namespace EMotionFX else // only x or y is connected { // if only x has something plugged in - if (mConnections[0]->GetTargetPort() == INPUTPORT_X) + if (m_connections[0]->GetTargetPort() == INPUTPORT_X) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_X)); x = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_X); @@ -157,7 +157,7 @@ namespace EMotionFX } else // only y has an input { - MCORE_ASSERT(mConnections[0]->GetTargetPort() == INPUTPORT_Y); + MCORE_ASSERT(m_connections[0]->GetTargetPort() == INPUTPORT_Y); x = m_defaultValue; OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_Y)); y = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_Y); @@ -178,7 +178,7 @@ namespace EMotionFX void BlendTreeFloatMath2Node::SetMathFunction(EMathFunction func) { m_mathFunction = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatSwitchNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatSwitchNode.cpp index 048cc48478..46fced6883 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatSwitchNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFloatSwitchNode.cpp @@ -81,7 +81,7 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // if the decision port has no incomming connection, there is nothing we can do - if (mInputPorts[INPUTPORT_DECISION].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_DECISION].m_connection == nullptr) { return; } @@ -91,7 +91,7 @@ namespace EMotionFX const int32 decisionValue = MCore::Clamp(GetInputNumberAsInt32(animGraphInstance, INPUTPORT_DECISION), 0, 4); // max 5 cases // return the value for that port - if (mInputPorts[INPUTPORT_0 + decisionValue].mConnection) + if (m_inputPorts[INPUTPORT_0 + decisionValue].m_connection) { //OutputIncomingNode( animGraphInstance, GetInputNode(INPUTPORT_0 + decisionValue) ); GetOutputFloat(animGraphInstance, OUTPUTPORT_RESULT)->SetValue(GetInputNumberAsFloat(animGraphInstance, INPUTPORT_0 + decisionValue)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp index 4e4f0ed4e4..d81b090300 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.cpp @@ -31,16 +31,16 @@ namespace EMotionFX void BlendTreeFootIKNode::UniqueData::Update() { - BlendTreeFootIKNode* footIKNode = azdynamic_cast(mObject); + BlendTreeFootIKNode* footIKNode = azdynamic_cast(m_object); AZ_Assert(footIKNode, "Unique data linked to incorrect node type."); - const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + const ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); const Actor* actor = actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); SetHasError(false); // Initialize the legs. - if (!footIKNode->InitLegs(mAnimGraphInstance, this)) + if (!footIKNode->InitLegs(m_animGraphInstance, this)) { SetHasError(true); } @@ -49,7 +49,7 @@ namespace EMotionFX const AZStd::string& hipJointName = footIKNode->GetHipJointName(); if ((hipJointName.empty() || !skeleton->FindNodeAndIndexByName(hipJointName, m_hipJointIndex)) && !GetEMotionFX().GetEnableServerOptimization()) { - footIKNode = azdynamic_cast(mObject); + footIKNode = azdynamic_cast(m_object); AZ_Error("EMotionFX", false, "Anim graph footplant IK node '%s' cannot find hip joint named '%s'", footIKNode->GetName(), hipJointName.c_str()); SetHasError(true); } @@ -102,7 +102,7 @@ namespace EMotionFX float BlendTreeFootIKNode::GetActorInstanceScale(const ActorInstance* actorInstance) const { #ifndef EMFX_SCALE_DISABLED - return actorInstance->GetWorldSpaceTransform().mScale.GetZ(); + return actorInstance->GetWorldSpaceTransform().m_scale.GetZ(); #else return 1.0f; #endif @@ -185,7 +185,7 @@ namespace EMotionFX AZ_Error("EMotionFX", false, "Anim graph footplant IK node '%s' cannot find foot joint named '%s'.", GetName(), footJointName.c_str()); return false; } - leg.m_footHeight = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).mPosition.GetZ(); + leg.m_footHeight = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).m_position.GetZ(); // Now grab the parent, assuming this is the knee. Node* knee = footJoint->GetParentNode(); @@ -214,7 +214,7 @@ namespace EMotionFX } leg.m_jointIndices[LegJointId::Toe] = toeJoint->GetNodeIndex(); - leg.m_toeHeight = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Toe]).mPosition.GetZ(); + leg.m_toeHeight = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Toe]).m_position.GetZ(); leg.m_weight = 0.0f; leg.m_targetWeight = 0.0f; leg.DisableFlag(LegFlags::FootDown); @@ -270,16 +270,16 @@ namespace EMotionFX // Generate the ray start and end position. void BlendTreeFootIKNode::GenerateRayStartEnd(LegId legId, LegJointId jointId, AnimGraphInstance* animGraphInstance, UniqueData* uniqueData, const Pose& inputPose, AZ::Vector3& outRayStart, AZ::Vector3& outRayEnd) const { - const AZ::u32 jointIndex = uniqueData->m_legs[legId].m_jointIndices[jointId]; - AZ_Assert(jointIndex != MCORE_INVALIDINDEX32, "Expecting the joint index to be valid."); + const size_t jointIndex = uniqueData->m_legs[legId].m_jointIndices[jointId]; + AZ_Assert(jointIndex != InvalidIndex, "Expecting the joint index to be valid."); const float rayLength = GetRaycastLength(animGraphInstance); - const AZ::Vector3 upVector = animGraphInstance->GetActorInstance()->GetWorldSpaceTransform().mRotation + const AZ::Vector3 upVector = animGraphInstance->GetActorInstance()->GetWorldSpaceTransform().m_rotation .TransformVector(AZ::Vector3(0.0f, 0.0f, 1.0f)); - const AZ::Vector3 jointPositionModelSpace = inputPose.GetModelSpaceTransform(jointIndex).mPosition; - const AZ::Vector3 hipPositionModelSpace = inputPose.GetModelSpaceTransform(uniqueData->m_hipJointIndex).mPosition; - const AZ::Vector3 jointPositionWorldSpace = inputPose.GetWorldSpaceTransform(jointIndex).mPosition; - const AZ::Vector3 hipPositionWorldSpace = inputPose.GetWorldSpaceTransform(uniqueData->m_hipJointIndex).mPosition; + const AZ::Vector3 jointPositionModelSpace = inputPose.GetModelSpaceTransform(jointIndex).m_position; + const AZ::Vector3 hipPositionModelSpace = inputPose.GetModelSpaceTransform(uniqueData->m_hipJointIndex).m_position; + const AZ::Vector3 jointPositionWorldSpace = inputPose.GetWorldSpaceTransform(jointIndex).m_position; + const AZ::Vector3 hipPositionWorldSpace = inputPose.GetWorldSpaceTransform(uniqueData->m_hipJointIndex).m_position; const float hipHeightDiff = hipPositionModelSpace.GetZ() - jointPositionModelSpace.GetZ(); outRayStart = jointPositionWorldSpace + upVector * hipHeightDiff; outRayEnd = jointPositionWorldSpace - upVector * rayLength; @@ -327,7 +327,7 @@ namespace EMotionFX if (rayResult.m_intersected) { ActorInstance* actorInstance = animGraphInstance->GetActorInstance(); - raycastResult.m_position = rayResult.m_position + actorInstance->GetWorldSpaceTransform().mRotation + raycastResult.m_position = rayResult.m_position + actorInstance->GetWorldSpaceTransform().m_rotation .TransformVector(AZ::Vector3(0.0f, 0.0f, heightOffset)); raycastResult.m_normal = rayResult.m_normal; raycastResult.m_intersected = true; @@ -406,20 +406,20 @@ namespace EMotionFX { const Leg& leg = solveParams.m_uniqueData->m_legs[legId]; - AZ::Quaternion result = solveParams.m_outputPose->GetWorldSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).mRotation; + AZ::Quaternion result = solveParams.m_outputPose->GetWorldSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).m_rotation; const bool footDown = leg.IsFlagEnabled(LegFlags::FootDown); const bool toeDown = leg.IsFlagEnabled(LegFlags::ToeDown); const float weight = leg.m_weight * solveParams.m_weight; if (!solveParams.m_forceIKDisabled && leg.IsFlagEnabled(LegFlags::IkEnabled) && weight > AZ::Constants::FloatEpsilon) { - const AZ::u32 footIndex = leg.m_jointIndices[LegJointId::Foot]; - const AZ::u32 toeIndex = leg.m_jointIndices[LegJointId::Toe]; + const size_t footIndex = leg.m_jointIndices[LegJointId::Foot]; + const size_t toeIndex = leg.m_jointIndices[LegJointId::Toe]; // When both foot and toe are on the floor float distToToeTarget = 0.01f; if (solveParams.m_intersections[legId].m_toeResult.m_intersected) { - distToToeTarget = (solveParams.m_outputPose->GetWorldSpaceTransform(footIndex).mPosition - solveParams.m_intersections[legId].m_toeResult.m_position).GetLength(); + distToToeTarget = (solveParams.m_outputPose->GetWorldSpaceTransform(footIndex).m_position - solveParams.m_intersections[legId].m_toeResult.m_position).GetLength(); } bool bothPlanted = false; @@ -428,8 +428,8 @@ namespace EMotionFX bothPlanted = true; // Get the current vector from the foot to the toe. - const AZ::Vector3 footPos = solveParams.m_outputPose->GetWorldSpaceTransform(footIndex).mPosition; - const AZ::Vector3 oldToePos = solveParams.m_outputPose->GetWorldSpaceTransform(toeIndex).mPosition; + const AZ::Vector3 footPos = solveParams.m_outputPose->GetWorldSpaceTransform(footIndex).m_position; + const AZ::Vector3 oldToePos = solveParams.m_outputPose->GetWorldSpaceTransform(toeIndex).m_position; const AZ::Vector3 oldToToe = (oldToePos - footPos).GetNormalizedSafe(); // Get the new vector from the foot to the toe. @@ -439,20 +439,20 @@ namespace EMotionFX // Apply a delta rotation to the foot. Transform newTransform = solveParams.m_outputPose->GetWorldSpaceTransform(footIndex); const AZ::Quaternion deltaRot = AZ::Quaternion::CreateShortestArc(oldToToe, newToToe); - result = deltaRot * newTransform.mRotation; + result = deltaRot * newTransform.m_rotation; } else if (footDown) { // Get the current vector from the foot to the toe. - const AZ::Vector3 footPos = solveParams.m_outputPose->GetWorldSpaceTransform(footIndex).mPosition; - const AZ::Vector3 oldToePos = solveParams.m_outputPose->GetWorldSpaceTransform(toeIndex).mPosition; + const AZ::Vector3 footPos = solveParams.m_outputPose->GetWorldSpaceTransform(footIndex).m_position; + const AZ::Vector3 oldToePos = solveParams.m_outputPose->GetWorldSpaceTransform(toeIndex).m_position; const AZ::Vector3 oldToToe = (oldToePos - footPos).GetNormalizedSafe(); // Get the new vector from the foot to the toe. const IntersectionResults& intersections = solveParams.m_intersections[legId]; const float footToeHeightDiff = leg.m_footHeight - leg.m_toeHeight; const AZ::Plane plane = AZ::Plane::CreateFromNormalAndPoint(intersections.m_footResult.m_normal, intersections.m_footResult.m_position); - const AZ::Vector3 offset = solveParams.m_actorInstance->GetWorldSpaceTransform().mRotation + const AZ::Vector3 offset = solveParams.m_actorInstance->GetWorldSpaceTransform().m_rotation .TransformVector((footToeHeightDiff * intersections.m_footResult.m_normal)); AZ::Vector3 newToePos = plane.GetProjected(oldToToe); newToePos = intersections.m_footResult.m_position + newToePos.GetNormalizedSafe() * leg.m_footLength; @@ -462,7 +462,7 @@ namespace EMotionFX // Apply a delta rotation to the foot. Transform newTransform = solveParams.m_outputPose->GetWorldSpaceTransform(footIndex); const AZ::Quaternion deltaRot = AZ::Quaternion::CreateShortestArc(oldToToe, newToToe); - result = deltaRot * newTransform.mRotation; + result = deltaRot * newTransform.m_rotation; } // Visualize some debug things in the viewport. @@ -523,9 +523,9 @@ namespace EMotionFX void BlendTreeFootIKNode::SolveLegIK(LegId legId, const IKSolveParameters& solveParams) { Leg& leg = solveParams.m_uniqueData->m_legs[legId]; - const AZ::u32 upperLegIndex = leg.m_jointIndices[LegJointId::UpperLeg]; - const AZ::u32 kneeIndex = leg.m_jointIndices[LegJointId::Knee]; - const AZ::u32 footIndex = leg.m_jointIndices[LegJointId::Foot]; + const size_t upperLegIndex = leg.m_jointIndices[LegJointId::UpperLeg]; + const size_t kneeIndex = leg.m_jointIndices[LegJointId::Knee]; + const size_t footIndex = leg.m_jointIndices[LegJointId::Foot]; // Calculate the world space transforms of the joints inside the leg. Transform inputGlobalTransforms[4]; @@ -548,8 +548,8 @@ namespace EMotionFX { const float actorInstanceScale = GetActorInstanceScale(solveParams.m_actorInstance); const float surfaceOffset = s_surfaceThreshold * actorInstanceScale; - footDown = solveParams.m_intersections[legId].m_footResult.m_intersected ? IsBelowSurface(inputGlobalTransforms[LegJointId::Foot].mPosition, footTargetPosition, solveParams.m_intersections[legId].m_footResult.m_normal, surfaceOffset) : false; - toeDown = solveParams.m_intersections[legId].m_toeResult.m_intersected ? IsBelowSurface(inputGlobalTransforms[LegJointId::Toe].mPosition, toeTargetPosition, solveParams.m_intersections[legId].m_toeResult.m_normal, surfaceOffset) : false; + footDown = solveParams.m_intersections[legId].m_footResult.m_intersected ? IsBelowSurface(inputGlobalTransforms[LegJointId::Foot].m_position, footTargetPosition, solveParams.m_intersections[legId].m_footResult.m_normal, surfaceOffset) : false; + toeDown = solveParams.m_intersections[legId].m_toeResult.m_intersected ? IsBelowSurface(inputGlobalTransforms[LegJointId::Toe].m_position, toeTargetPosition, solveParams.m_intersections[legId].m_toeResult.m_normal, surfaceOffset) : false; } else { @@ -607,8 +607,8 @@ namespace EMotionFX } // Limit the target position in height. - const AZ::Vector3 vecToTarget = solveParams.m_actorInstance->GetWorldSpaceTransformInversed().mRotation - .TransformVector(footTargetPosition - inputGlobalTransforms[LegJointId::Foot].mPosition); + const AZ::Vector3 vecToTarget = solveParams.m_actorInstance->GetWorldSpaceTransformInversed().m_rotation + .TransformVector(footTargetPosition - inputGlobalTransforms[LegJointId::Foot].m_position); const float feetDifference = vecToTarget.GetZ(); const float maxFootAdjustment = GetMaxFootAdjustment(solveParams.m_animGraphInstance); if (feetDifference > maxFootAdjustment) @@ -617,11 +617,11 @@ namespace EMotionFX } // Calculate the pole vector. - const AZ::Vector3 toFoot = (inputGlobalTransforms[LegJointId::Foot].mPosition - inputGlobalTransforms[LegJointId::UpperLeg].mPosition).GetNormalizedSafe(); - AZ::Vector3 toKnee = (inputGlobalTransforms[LegJointId::Knee].mPosition - inputGlobalTransforms[LegJointId::UpperLeg].mPosition).GetNormalizedSafe(); + const AZ::Vector3 toFoot = (inputGlobalTransforms[LegJointId::Foot].m_position - inputGlobalTransforms[LegJointId::UpperLeg].m_position).GetNormalizedSafe(); + AZ::Vector3 toKnee = (inputGlobalTransforms[LegJointId::Knee].m_position - inputGlobalTransforms[LegJointId::UpperLeg].m_position).GetNormalizedSafe(); if (AZ::IsClose(toFoot.Dot(toKnee), 1.0f, 0.001f)) { - toKnee += solveParams.m_actorInstance->GetWorldSpaceTransform().mRotation.TransformVector(AZ::Vector3(0.0f, 0.01f, 0.0f)); + toKnee += solveParams.m_actorInstance->GetWorldSpaceTransform().m_rotation.TransformVector(AZ::Vector3(0.0f, 0.01f, 0.0f)); toKnee.NormalizeSafe(); } const AZ::Vector3 planeNormal = toFoot.Cross(toKnee); @@ -629,27 +629,27 @@ namespace EMotionFX // Solve the two joint IK problem by calculating the new position of the knee. AZ::Vector3 kneePos; - Solve2LinkIK(inputGlobalTransforms[LegJointId::UpperLeg].mPosition, inputGlobalTransforms[LegJointId::Knee].mPosition, inputGlobalTransforms[LegJointId::Foot].mPosition, footTargetPosition, finalPoleVector, &kneePos); + Solve2LinkIK(inputGlobalTransforms[LegJointId::UpperLeg].m_position, inputGlobalTransforms[LegJointId::Knee].m_position, inputGlobalTransforms[LegJointId::Foot].m_position, footTargetPosition, finalPoleVector, &kneePos); // Update the upper leg. - AZ::Vector3 oldForward = (inputGlobalTransforms[LegJointId::Knee].mPosition - inputGlobalTransforms[LegJointId::UpperLeg].mPosition).GetNormalizedSafe(); - AZ::Vector3 newForward = (kneePos - inputGlobalTransforms[LegJointId::UpperLeg].mPosition).GetNormalizedSafe(); + AZ::Vector3 oldForward = (inputGlobalTransforms[LegJointId::Knee].m_position - inputGlobalTransforms[LegJointId::UpperLeg].m_position).GetNormalizedSafe(); + AZ::Vector3 newForward = (kneePos - inputGlobalTransforms[LegJointId::UpperLeg].m_position).GetNormalizedSafe(); Transform newTransform = inputGlobalTransforms[LegJointId::UpperLeg]; - MCore::RotateFromTo(newTransform.mRotation, oldForward, newForward); + MCore::RotateFromTo(newTransform.m_rotation, oldForward, newForward); solveParams.m_outputPose->SetWorldSpaceTransform(upperLegIndex, newTransform); // Update the knee. - const AZ::Vector3 footPos = solveParams.m_outputPose->GetWorldSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).mPosition; + const AZ::Vector3 footPos = solveParams.m_outputPose->GetWorldSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).m_position; oldForward = (footPos - kneePos).GetNormalized(); newForward = (footTargetPosition - kneePos).GetNormalizedSafe(); newTransform = solveParams.m_outputPose->GetWorldSpaceTransform(leg.m_jointIndices[LegJointId::Knee]); - MCore::RotateFromTo(newTransform.mRotation, oldForward, newForward); - newTransform.mPosition = kneePos; + MCore::RotateFromTo(newTransform.m_rotation, oldForward, newForward); + newTransform.m_position = kneePos; solveParams.m_outputPose->SetWorldSpaceTransform(kneeIndex, newTransform); if (leg.IsFlagEnabled(LegFlags::FirstUpdate)) { - leg.m_currentFootRot = inputGlobalTransforms[LegJointId::Foot].mRotation; + leg.m_currentFootRot = inputGlobalTransforms[LegJointId::Foot].m_rotation; leg.DisableFlag(LegFlags::FirstUpdate); } @@ -679,7 +679,7 @@ namespace EMotionFX blendT = 1.0f; } leg.m_currentFootRot = leg.m_currentFootRot.NLerp(footRotation, blendT); - footTransform.mRotation = leg.m_currentFootRot; + footTransform.m_rotation = leg.m_currentFootRot; solveParams.m_outputPose->SetWorldSpaceTransform(footIndex, footTransform); // Draw debug lines. @@ -689,8 +689,8 @@ namespace EMotionFX drawData->Lock(); if (!solveParams.m_forceIKDisabled && leg.IsFlagEnabled(LegFlags::IkEnabled) && solveParams.m_intersections[legId].m_footResult.m_intersected) { - drawData->DrawLine(inputGlobalTransforms[LegJointId::UpperLeg].mPosition, kneePos, mVisualizeColor); - drawData->DrawLine(kneePos, footTargetPosition, mVisualizeColor); + drawData->DrawLine(inputGlobalTransforms[LegJointId::UpperLeg].m_position, kneePos, m_visualizeColor); + drawData->DrawLine(kneePos, footTargetPosition, m_visualizeColor); } drawData->Unlock(); } @@ -701,7 +701,7 @@ namespace EMotionFX { for (size_t i = 1; i < 4; ++i) { - const AZ::u32 nodeIndex = leg.m_jointIndices[Toe - i]; + const size_t nodeIndex = leg.m_jointIndices[Toe - i]; solveParams.m_outputPose->UpdateLocalSpaceTransform(nodeIndex); Transform finalTransform = solveParams.m_inputPose->GetLocalSpaceTransform(nodeIndex); finalTransform.Blend(solveParams.m_outputPose->GetLocalSpaceTransform(nodeIndex), weight); @@ -719,11 +719,11 @@ namespace EMotionFX leg.m_legLength = 0.0f; for (size_t legNodeIndex = 1; legNodeIndex < 3; ++legNodeIndex) { - leg.m_legLength += (inputPose.GetModelSpaceTransform(leg.m_jointIndices[legNodeIndex]).mPosition - inputPose.GetModelSpaceTransform(leg.m_jointIndices[legNodeIndex - 1]).mPosition).GetLength(); + leg.m_legLength += (inputPose.GetModelSpaceTransform(leg.m_jointIndices[legNodeIndex]).m_position - inputPose.GetModelSpaceTransform(leg.m_jointIndices[legNodeIndex - 1]).m_position).GetLength(); } // Calculate the foot length. - leg.m_footLength = (inputPose.GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Toe]).mPosition - inputPose.GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).mPosition).GetLength(); + leg.m_footLength = (inputPose.GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Toe]).m_position - inputPose.GetModelSpaceTransform(leg.m_jointIndices[LegJointId::Foot]).m_position).GetLength(); } // Adjust the hip by moving it downwards when we can't reach a given target. @@ -739,8 +739,8 @@ namespace EMotionFX // If the target foot position is below the ground plane in model space, so if we actually have to lower the hips. ActorInstance* actorInstance = animGraphInstance->GetActorInstance(); - const AZ::Vector3 upVector = actorInstance->GetWorldSpaceTransform().mRotation.TransformVector(AZ::Vector3(0.0f, 0.0f, 1.0f)); - const AZ::Vector3 leftFootBindPoseModelSpace = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(leftLeg.m_jointIndices[LegJointId::Foot]).mPosition; + const AZ::Vector3 upVector = actorInstance->GetWorldSpaceTransform().m_rotation.TransformVector(AZ::Vector3(0.0f, 0.0f, 1.0f)); + const AZ::Vector3 leftFootBindPoseModelSpace = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(leftLeg.m_jointIndices[LegJointId::Foot]).m_position; const AZ::Vector3 leftFootBindWorldPos = actorInstance->GetWorldSpaceTransform().TransformPoint(leftFootBindPoseModelSpace); const AZ::Plane leftSurfacePlane = AZ::Plane::CreateFromNormalAndPoint(upVector, leftFootBindWorldPos); float leftCorrection = leftSurfacePlane.GetPointDist(intersectionResults[LegId::Left].m_footResult.m_position); @@ -750,7 +750,7 @@ namespace EMotionFX } // Do the same for the right leg. - const AZ::Vector3 rightFootBindPoseModelSpace = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(rightLeg.m_jointIndices[LegJointId::Foot]).mPosition; + const AZ::Vector3 rightFootBindPoseModelSpace = actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(rightLeg.m_jointIndices[LegJointId::Foot]).m_position; const AZ::Vector3 rightFootBindWorldPos = actorInstance->GetWorldSpaceTransform().TransformPoint(rightFootBindPoseModelSpace); const AZ::Plane rightSurfacePlane = AZ::Plane::CreateFromNormalAndPoint(upVector, rightFootBindWorldPos); float rightCorrection = rightSurfacePlane.GetPointDist(intersectionResults[LegId::Right].m_footResult.m_position); @@ -768,7 +768,7 @@ namespace EMotionFX // Debug render some line to show the displacement. if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - const AZ::Vector3 hipPos = inputPose.GetWorldSpaceTransform(uniqueData->m_hipJointIndex).mPosition; + const AZ::Vector3 hipPos = inputPose.GetWorldSpaceTransform(uniqueData->m_hipJointIndex).m_position; DebugDraw::ActorInstanceData* drawData = GetDebugDraw().GetActorInstanceData(animGraphInstance->GetActorInstance()); drawData->Lock(); drawData->DrawLine(hipPos, hipPos + AZ::Vector3(0.0f, 0.0f, correction), AZ::Color(1.0f, 0.0f, 1.0f, 1.0f)); @@ -786,7 +786,7 @@ namespace EMotionFX } const float interpolatedCorrection = AZ::Lerp(uniqueData->m_curHipCorrection, correction, t); uniqueData->m_curHipCorrection = interpolatedCorrection; - hipTransform.mPosition += animGraphInstance->GetActorInstance()->GetWorldSpaceTransform().mRotation + hipTransform.m_position += animGraphInstance->GetActorInstance()->GetWorldSpaceTransform().m_rotation .TransformVector(AZ::Vector3(0.0f, 0.0f, interpolatedCorrection)); outputPose.SetWorldSpaceTransform(uniqueData->m_hipJointIndex, hipTransform); inputPose = outputPose; // As we adjusted our hip, the input pose to the IK leg solve has been modified, so update it. @@ -829,7 +829,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // If nothing is connected to the input pose, output a bind pose. - if (!GetInputPort(INPUTPORT_POSE).mConnection) + if (!GetInputPort(INPUTPORT_POSE).m_connection) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -840,7 +840,7 @@ namespace EMotionFX // Get the weight from the input port. float weight = 1.0f; - if (GetInputPort(INPUTPORT_WEIGHT).mConnection) + if (GetInputPort(INPUTPORT_WEIGHT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_WEIGHT)); weight = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT); @@ -848,7 +848,7 @@ namespace EMotionFX } // If the weight is near zero or if this node is disabled or if the node is enable for server optimization, we can skip all calculations and just output the input pose. - if (weight < MCore::Math::epsilon || mDisabled || GetEMotionFX().GetEnableServerOptimization()) + if (weight < MCore::Math::epsilon || m_disabled || GetEMotionFX().GetEnableServerOptimization()) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_POSE)); const AnimGraphPose* inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); @@ -924,11 +924,11 @@ namespace EMotionFX } const AnimGraphEventBuffer& eventBuffer = uniqueData->m_eventBuffer; - const AZ::u32 numEvents = eventBuffer.GetNumEvents(); - for (AZ::u32 i = 0; i < numEvents; ++i) + const size_t numEvents = eventBuffer.GetNumEvents(); + for (size_t i = 0; i < numEvents; ++i) { const EventInfo& eventInfo = eventBuffer.GetEvent(i); - const MotionEvent* motionEvent = eventInfo.mEvent; + const MotionEvent* motionEvent = eventInfo.m_event; const EventDataSet& eventDataSet = motionEvent->GetEventDatas(); for (const EventDataPtr& eventData : eventDataSet) { @@ -1021,7 +1021,7 @@ namespace EMotionFX // Adjust the hip position by moving it up or down if that would result in a more natural look. float hipHeightAdjustment = 0.0f; - if (GetAdjustHip(animGraphInstance) && uniqueData->m_hipJointIndex != MCORE_INVALIDINDEX32) + if (GetAdjustHip(animGraphInstance) && uniqueData->m_hipJointIndex != InvalidIndex) { hipHeightAdjustment = AdjustHip(animGraphInstance, uniqueData, inputPose->GetPose(), outputPose->GetPose(), intersectionResults, true /* allowHipAdjust */); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.h index ed2d8113f4..0e46f156af 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeFootIKNode.h @@ -87,7 +87,7 @@ namespace EMotionFX struct Leg { - AZ::u32 m_jointIndices[4]; // Use LegJointId as index into this array. + size_t m_jointIndices[4]; // Use LegJointId as index into this array. AZ::u8 m_flags = static_cast(LegFlags::FirstUpdate); AZ::Vector3 m_footLockPosition = AZ::Vector3::CreateZero(); AZ::Quaternion m_footLockRotation; @@ -138,7 +138,7 @@ namespace EMotionFX float m_hipCorrectionTarget = 0.0f; float m_curHipCorrection = 0.0f; float m_timeDelta = 0.0f; - AZ::u32 m_hipJointIndex = MCORE_INVALIDINDEX32; + size_t m_hipJointIndex = InvalidIndex; AnimGraphEventBuffer m_eventBuffer; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp index 4947836da8..b836188757 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.cpp @@ -33,15 +33,15 @@ namespace EMotionFX void BlendTreeGetTransformNode::UniqueData::Update() { - BlendTreeGetTransformNode* transformNode = azdynamic_cast(mObject); + BlendTreeGetTransformNode* transformNode = azdynamic_cast(m_object); AZ_Assert(transformNode, "Unique data linked to incorrect node type."); - m_nodeIndex = InvalidIndex32; + m_nodeIndex = InvalidIndex; const AZStd::string& nodeName = transformNode->GetNodeName(); const int actorInstanceParentDepth = transformNode->GetActorInstanceParentDepth(); // lookup the actor instance to get the node from - const ActorInstance* alignInstance = mAnimGraphInstance->FindActorInstanceFromParentDepth(actorInstanceParentDepth); + const ActorInstance* alignInstance = m_animGraphInstance->FindActorInstanceFromParentDepth(actorInstanceParentDepth); if (alignInstance) { const Node* alignNode = alignInstance->GetActor()->GetSkeleton()->FindNodeByName(nodeName); @@ -106,18 +106,18 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode()) { - SetHasError(uniqueData, uniqueData->m_nodeIndex == MCORE_INVALIDINDEX32); + SetHasError(uniqueData, uniqueData->m_nodeIndex == InvalidIndex); } // make sure we have at least an input pose, otherwise output the bind pose - if (GetInputPort(INPUTPORT_POSE).mConnection) + if (GetInputPort(INPUTPORT_POSE).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_POSE)); inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); } Pose* pose = nullptr; - if (uniqueData->m_nodeIndex != MCORE_INVALIDINDEX32) + if (uniqueData->m_nodeIndex != InvalidIndex) { if (m_actorNode.second == 0) { @@ -162,11 +162,11 @@ namespace EMotionFX inputTransform.Identity(); } - GetOutputVector3(animGraphInstance, OUTPUTPORT_TRANSLATION)->SetValue(inputTransform.mPosition); - GetOutputQuaternion(animGraphInstance, OUTPUTPORT_ROTATION)->SetValue(inputTransform.mRotation); + GetOutputVector3(animGraphInstance, OUTPUTPORT_TRANSLATION)->SetValue(inputTransform.m_position); + GetOutputQuaternion(animGraphInstance, OUTPUTPORT_ROTATION)->SetValue(inputTransform.m_rotation); #ifndef EMFX_SCALE_DISABLED - GetOutputVector3(animGraphInstance, OUTPUTPORT_SCALE)->SetValue(inputTransform.mScale); + GetOutputVector3(animGraphInstance, OUTPUTPORT_SCALE)->SetValue(inputTransform.m_scale); #else GetOutputVector3(animGraphInstance, OUTPUTPORT_SCALE)->SetValue(AZ::Vector3::CreateOne()); #endif diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.h index 83e07103d8..ab441fab62 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeGetTransformNode.h @@ -64,7 +64,7 @@ namespace EMotionFX void Update() override; public: - AZ::u32 m_nodeIndex = InvalidIndex32; + size_t m_nodeIndex = InvalidIndex; }; BlendTreeGetTransformNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp index 895739b315..84eeca094d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.cpp @@ -34,13 +34,13 @@ namespace EMotionFX void BlendTreeLookAtNode::UniqueData::Update() { - BlendTreeLookAtNode* lookAtNode = azdynamic_cast(mObject); + BlendTreeLookAtNode* lookAtNode = azdynamic_cast(m_object); AZ_Assert(lookAtNode, "Unique data linked to incorrect node type."); - const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + const ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); const Actor* actor = actorInstance->GetActor(); - mNodeIndex = InvalidIndex32; + m_nodeIndex = InvalidIndex; SetHasError(true); const AZStd::string& targetJointName = lookAtNode->GetTargetNodeName(); @@ -49,7 +49,7 @@ namespace EMotionFX const Node* targetNode = actor->GetSkeleton()->FindNodeByName(targetJointName); if (targetNode) { - mNodeIndex = targetNode->GetNodeIndex(); + m_nodeIndex = targetNode->GetNodeIndex(); SetHasError(false); } } @@ -112,7 +112,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // make sure we have at least an input pose, otherwise output the bind pose - if (GetInputPort(INPUTPORT_POSE).mConnection == nullptr) + if (GetInputPort(INPUTPORT_POSE).m_connection == nullptr) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -123,7 +123,7 @@ namespace EMotionFX // get the weight float weight = 1.0f; - if (GetInputPort(INPUTPORT_WEIGHT).mConnection) + if (GetInputPort(INPUTPORT_WEIGHT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_WEIGHT)); weight = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT); @@ -131,7 +131,7 @@ namespace EMotionFX } // if the weight is near zero, we can skip all calculations and act like a pass-trough node - if (weight < MCore::Math::epsilon || mDisabled) + if (weight < MCore::Math::epsilon || m_disabled) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_POSE)); RequestPoses(animGraphInstance); @@ -139,7 +139,7 @@ namespace EMotionFX const AnimGraphPose* inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); *outputPose = *inputPose; UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - uniqueData->mFirstUpdate = true; + uniqueData->m_firstUpdate = true; return; } @@ -177,7 +177,7 @@ namespace EMotionFX ActorInstance* actorInstance = animGraphInstance->GetActorInstance(); // get a shortcut to the local transform object - const uint32 nodeIndex = uniqueData->mNodeIndex; + const size_t nodeIndex = uniqueData->m_nodeIndex; Pose& outTransformPose = outputPose->GetPose(); Transform globalTransform = outTransformPose.GetWorldSpaceTransform(nodeIndex); @@ -185,7 +185,7 @@ namespace EMotionFX Skeleton* skeleton = actorInstance->GetActor()->GetSkeleton(); // Prevent invalid float values inside the LookAt matrix construction when both position and goal are the same - const AZ::Vector3 diff = globalTransform.mPosition - goal; + const AZ::Vector3 diff = globalTransform.m_position - goal; if (diff.GetLengthSq() < AZ::Constants::FloatEpsilon) { goal += AZ::Vector3(0.0f, 0.000001f, 0.0f); @@ -194,7 +194,7 @@ namespace EMotionFX // calculate the lookat transform // TODO: a quaternion lookat function would be nicer, so that there are no matrix operations involved AZ::Matrix4x4 lookAt; - MCore::LookAt(lookAt, globalTransform.mPosition, goal, AZ::Vector3(0.0f, 0.0f, 1.0f)); + MCore::LookAt(lookAt, globalTransform.m_position, goal, AZ::Vector3(0.0f, 0.0f, 1.0f)); AZ::Quaternion destRotation = AZ::Quaternion::CreateFromMatrix4x4(lookAt.GetTranspose()); // apply the post rotation @@ -203,13 +203,13 @@ namespace EMotionFX if (m_limitsEnabled) { // calculate the delta between the bind pose rotation and current target rotation and constraint that to our limits - const uint32 parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); + const size_t parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); AZ::Quaternion parentRotationGlobal; AZ::Quaternion bindRotationLocal; - if (parentIndex != MCORE_INVALIDINDEX32) + if (parentIndex != InvalidIndex) { - parentRotationGlobal = inputPose->GetPose().GetWorldSpaceTransform(parentIndex).mRotation; - bindRotationLocal = actorInstance->GetTransformData()->GetBindPose()->GetLocalSpaceTransform(parentIndex).mRotation; + parentRotationGlobal = inputPose->GetPose().GetWorldSpaceTransform(parentIndex).m_rotation; + bindRotationLocal = actorInstance->GetTransformData()->GetBindPose()->GetLocalSpaceTransform(parentIndex).m_rotation; } else { @@ -228,47 +228,47 @@ namespace EMotionFX constraint.SetMinTwistAngle(0.0f); constraint.SetMaxTwistAngle(0.0f); constraint.SetTwistAxis(m_twistAxis); - constraint.GetTransform().mRotation = (deltaRotLocal * m_constraintRotation.GetConjugate()); + constraint.GetTransform().m_rotation = (deltaRotLocal * m_constraintRotation.GetConjugate()); constraint.Execute(); if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { AZ::Transform offset = AZ::Transform::CreateFromQuaternion(m_postRotation.GetInverseFull() * bindRotationLocal * m_constraintRotation * parentRotationGlobal); - offset.SetTranslation(globalTransform.mPosition); + offset.SetTranslation(globalTransform.m_position); constraint.DebugDraw(actorInstance, offset, GetVisualizeColor(), 0.5f); } // convert back into world space - destRotation = (bindRotationLocal * (constraint.GetTransform().mRotation * m_constraintRotation)) * parentRotationGlobal; + destRotation = (bindRotationLocal * (constraint.GetTransform().m_rotation * m_constraintRotation)) * parentRotationGlobal; } // init the rotation quaternion to the initial rotation - if (uniqueData->mFirstUpdate) + if (uniqueData->m_firstUpdate) { - uniqueData->mRotationQuat = destRotation; - uniqueData->mFirstUpdate = false; + uniqueData->m_rotationQuat = destRotation; + uniqueData->m_firstUpdate = false; } // interpolate between the current rotation and the destination rotation if (m_smoothing) { - const float speed = m_followSpeed * uniqueData->mTimeDelta * 10.0f; + const float speed = m_followSpeed * uniqueData->m_timeDelta * 10.0f; if (speed < 1.0f) { - uniqueData->mRotationQuat = uniqueData->mRotationQuat.Slerp(destRotation, speed); + uniqueData->m_rotationQuat = uniqueData->m_rotationQuat.Slerp(destRotation, speed); } else { - uniqueData->mRotationQuat = destRotation; + uniqueData->m_rotationQuat = destRotation; } } else { - uniqueData->mRotationQuat = destRotation; + uniqueData->m_rotationQuat = destRotation; } - uniqueData->mRotationQuat.Normalize(); - globalTransform.mRotation = uniqueData->mRotationQuat; + uniqueData->m_rotationQuat.Normalize(); + globalTransform.m_rotation = uniqueData->m_rotationQuat; // only blend when needed if (weight < 0.999f) @@ -294,11 +294,11 @@ namespace EMotionFX DebugDraw& debugDraw = GetDebugDraw(); DebugDraw::ActorInstanceData* drawData = debugDraw.GetActorInstanceData(animGraphInstance->GetActorInstance()); drawData->Lock(); - drawData->DrawLine(goal - AZ::Vector3(s, 0, 0), goal + AZ::Vector3(s, 0, 0), mVisualizeColor); - drawData->DrawLine(goal - AZ::Vector3(0, s, 0), goal + AZ::Vector3(0, s, 0), mVisualizeColor); - drawData->DrawLine(goal - AZ::Vector3(0, 0, s), goal + AZ::Vector3(0, 0, s), mVisualizeColor); - drawData->DrawLine(globalTransform.mPosition, goal, mVisualizeColor); - drawData->DrawLine(globalTransform.mPosition, globalTransform.mPosition + MCore::CalcUpAxis(globalTransform.mRotation) * s * 50.0f, AZ::Color(0.0f, 0.0f, 1.0f, 1.0f)); + drawData->DrawLine(goal - AZ::Vector3(s, 0, 0), goal + AZ::Vector3(s, 0, 0), m_visualizeColor); + drawData->DrawLine(goal - AZ::Vector3(0, s, 0), goal + AZ::Vector3(0, s, 0), m_visualizeColor); + drawData->DrawLine(goal - AZ::Vector3(0, 0, s), goal + AZ::Vector3(0, 0, s), m_visualizeColor); + drawData->DrawLine(globalTransform.m_position, goal, m_visualizeColor); + drawData->DrawLine(globalTransform.m_position, globalTransform.m_position + MCore::CalcUpAxis(globalTransform.m_rotation) * s * 50.0f, AZ::Color(0.0f, 0.0f, 1.0f, 1.0f)); drawData->Unlock(); } } @@ -335,7 +335,7 @@ namespace EMotionFX uniqueData->Clear(); } - uniqueData->mTimeDelta = timePassedInSeconds; + uniqueData->m_timeDelta = timePassedInSeconds; } AZ::Crc32 BlendTreeLookAtNode::GetLimitWidgetsVisibility() const diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h index a7494b2514..098ce5ca08 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeLookAtNode.h @@ -63,10 +63,10 @@ namespace EMotionFX void Update() override; public: - AZ::Quaternion mRotationQuat = AZ::Quaternion::CreateIdentity(); - float mTimeDelta = 0.0f; - uint32 mNodeIndex = InvalidIndex32; - bool mFirstUpdate = true; + AZ::Quaternion m_rotationQuat = AZ::Quaternion::CreateIdentity(); + float m_timeDelta = 0.0f; + size_t m_nodeIndex = InvalidIndex; + bool m_firstUpdate = true; }; BlendTreeLookAtNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp index ac85704381..ca409fe6d7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.cpp @@ -21,7 +21,7 @@ namespace EMotionFX { - size_t BlendTreeMaskLegacyNode::m_numMasks = 4; + size_t BlendTreeMaskLegacyNode::s_numMasks = 4; AZ_CLASS_ALLOCATOR_IMPL(BlendTreeMaskLegacyNode, AnimGraphAllocator, 0) AZ_CLASS_ALLOCATOR_IMPL(BlendTreeMaskLegacyNode::UniqueData, AnimGraphObjectUniqueDataAllocator, 0) @@ -33,17 +33,17 @@ namespace EMotionFX void BlendTreeMaskLegacyNode::UniqueData::Update() { - BlendTreeMaskLegacyNode* maskNode = azdynamic_cast(mObject); + BlendTreeMaskLegacyNode* maskNode = azdynamic_cast(m_object); AZ_Assert(maskNode, "Unique data linked to incorrect node type."); - Actor* actor = mAnimGraphInstance->GetActorInstance()->GetActor(); + Actor* actor = m_animGraphInstance->GetActorInstance()->GetActor(); const size_t numMasks = BlendTreeMaskLegacyNode::GetNumMasks(); - mMasks.resize(numMasks); - AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask0(), mMasks[0]); - AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask1(), mMasks[1]); - AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask2(), mMasks[2]); - AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask3(), mMasks[3]); + m_masks.resize(numMasks); + AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask0(), m_masks[0]); + AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask1(), m_masks[1]); + AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask2(), m_masks[2]); + AnimGraphPropertyUtils::ReinitJointIndices(actor, maskNode->GetMask3(), m_masks[3]); } BlendTreeMaskLegacyNode::BlendTreeMaskLegacyNode() @@ -54,7 +54,7 @@ namespace EMotionFX , m_outputEvents3(true) { // setup the input ports - InitInputPorts(static_cast(m_numMasks)); + InitInputPorts(s_numMasks); SetupInputPort("Pose 0", INPUTPORT_POSE_0, AttributePose::TYPE_ID, PORTID_INPUT_POSE_0); SetupInputPort("Pose 1", INPUTPORT_POSE_1, AttributePose::TYPE_ID, PORTID_INPUT_POSE_1); SetupInputPort("Pose 2", INPUTPORT_POSE_2, AttributePose::TYPE_ID, PORTID_INPUT_POSE_2); @@ -104,10 +104,10 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); // for all input ports - for (uint32 i = 0; i < m_numMasks; ++i) + for (size_t i = 0; i < s_numMasks; ++i) { // if there is no connection plugged in - if (mInputPorts[INPUTPORT_POSE_0 + i].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE_0 + i].m_connection == nullptr) { continue; } @@ -121,10 +121,10 @@ namespace EMotionFX outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_RESULT)->GetValue(); outputPose->InitFromBindPose(animGraphInstance->GetActorInstance()); - for (uint32 i = 0; i < m_numMasks; ++i) + for (size_t i = 0; i < s_numMasks; ++i) { // if there is no connection plugged in - if (mInputPorts[INPUTPORT_POSE_0 + i].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE_0 + i].m_connection == nullptr) { continue; } @@ -135,14 +135,13 @@ namespace EMotionFX const Pose& localPose = pose->GetPose(); // get the number of nodes inside the mask and default them to all nodes in the local pose in case there aren't any selected - const size_t numNodes = uniqueData->mMasks[i].size(); + const size_t numNodes = uniqueData->m_masks[i].size(); if (numNodes > 0) { // for all nodes in the mask, output their transforms - for (size_t n = 0; n < numNodes; ++n) + for (size_t nodeIndex : uniqueData->m_masks[i]) { - const uint32 nodeIndex = uniqueData->mMasks[i][n]; - outputLocalPose.SetLocalSpaceTransform(nodeIndex, localPose.GetLocalSpaceTransform(nodeIndex)); + outputLocalPose.SetLocalSpaceTransform(nodeIndex, localPose.GetLocalSpaceTransform(nodeIndex)); } } else @@ -154,7 +153,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -183,7 +182,7 @@ namespace EMotionFX void BlendTreeMaskLegacyNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // post update all incoming nodes - for (uint32 i = 0; i < m_numMasks; ++i) + for (size_t i = 0; i < s_numMasks; ++i) { // if the port has no input, skip it AnimGraphNode* inputNode = GetInputNode(INPUTPORT_POSE_0 + i); @@ -203,7 +202,7 @@ namespace EMotionFX data->ClearEventBuffer(); data->ZeroTrajectoryDelta(); - for (uint32 i = 0; i < m_numMasks; ++i) + for (size_t i = 0; i < s_numMasks; ++i) { // if the port has no input, skip it AnimGraphNode* inputNode = GetInputNode(INPUTPORT_POSE_0 + i); @@ -213,13 +212,12 @@ namespace EMotionFX } // get the number of nodes inside the mask and default them to all nodes in the local pose in case there aren't any selected - const size_t numNodes = uniqueData->mMasks[i].size(); + const size_t numNodes = uniqueData->m_masks[i].size(); if (numNodes > 0) { // for all nodes in the mask, output their transforms - for (size_t n = 0; n < numNodes; ++n) + for (size_t nodeIndex : uniqueData->m_masks[i]) { - const uint32 nodeIndex = uniqueData->mMasks[i][n]; if (nodeIndex == animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex()) { AnimGraphRefCountedData* sourceData = inputNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData(); @@ -244,14 +242,14 @@ namespace EMotionFX // get the input event buffer const AnimGraphEventBuffer& inputEventBuffer = inputNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData()->GetEventBuffer(); AnimGraphEventBuffer& outputEventBuffer = data->GetEventBuffer(); - const uint32 startIndex = outputEventBuffer.GetNumEvents(); + const size_t startIndex = outputEventBuffer.GetNumEvents(); // resize the buffer already, so that we don't do this for every event outputEventBuffer.Resize(outputEventBuffer.GetNumEvents() + inputEventBuffer.GetNumEvents()); // copy over all the events - const uint32 numInputEvents = inputEventBuffer.GetNumEvents(); - for (uint32 e = 0; e < numInputEvents; ++e) + const size_t numInputEvents = inputEventBuffer.GetNumEvents(); + for (size_t e = 0; e < numInputEvents; ++e) { outputEventBuffer.SetEvent(startIndex + e, inputEventBuffer.GetEvent(e)); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.h index d2f50f918d..2abc5dc5cf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskLegacyNode.h @@ -53,7 +53,7 @@ namespace EMotionFX void Update() override; public: - AZStd::vector< AZStd::vector > mMasks; + AZStd::vector< AZStd::vector > m_masks; }; BlendTreeMaskLegacyNode(); @@ -77,7 +77,7 @@ namespace EMotionFX void SetMask2(const AZStd::vector& mask2); void SetMask3(const AZStd::vector& mask3); - static size_t GetNumMasks() { return m_numMasks; } + static size_t GetNumMasks() { return s_numMasks; } const AZStd::vector& GetMask0() const { return m_mask0; } const AZStd::vector& GetMask1() const { return m_mask1; } const AZStd::vector& GetMask2() const { return m_mask2; } @@ -109,6 +109,6 @@ namespace EMotionFX bool m_outputEvents2; bool m_outputEvents3; - static size_t m_numMasks; + static size_t s_numMasks; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp index 8b65f76dbd..039d11d881 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.cpp @@ -30,16 +30,16 @@ namespace EMotionFX void BlendTreeMaskNode::UniqueData::Update() { - BlendTreeMaskNode* maskNode = azdynamic_cast(mObject); + BlendTreeMaskNode* maskNode = azdynamic_cast(m_object); AZ_Assert(maskNode, "Unique data linked to incorrect node type."); - const Actor* actor = mAnimGraphInstance->GetActorInstance()->GetActor(); + const Actor* actor = m_animGraphInstance->GetActorInstance()->GetActor(); const size_t numMaskInstances = maskNode->GetNumUsedMasks(); m_maskInstances.resize(numMaskInstances); - AZ::u32 maskInstanceIndex = 0; + size_t maskInstanceIndex = 0; m_motionExtractionInputPortNr.reset(); - const AZ::u32 motionExtractionJointIndex = mAnimGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex(); + const size_t motionExtractionJointIndex = m_animGraphInstance->GetActorInstance()->GetActor()->GetMotionExtractionNodeIndex(); const AZStd::vector& masks = maskNode->GetMasks(); const size_t numMasks = masks.size(); @@ -48,7 +48,7 @@ namespace EMotionFX const Mask& mask = masks[i]; if (!mask.m_jointNames.empty()) { - const AZ::u32 inputPortNr = INPUTPORT_START + static_cast(i); + const size_t inputPortNr = INPUTPORT_START + i; // Get the joint indices by joint names and cache them in the unique data // so that we don't have to look them up at runtime. @@ -57,7 +57,7 @@ namespace EMotionFX maskInstance.m_inputPortNr = inputPortNr; // Check if the motion extraction node is part of this mask and cache the mask index in that case. - for (AZ::u32 jointIndex : maskInstance.m_jointIndices) + for (size_t jointIndex : maskInstance.m_jointIndices) { if (jointIndex == motionExtractionJointIndex) { @@ -77,16 +77,16 @@ namespace EMotionFX m_masks.resize(s_numMasks); // Setup the input ports. - InitInputPorts(1 + static_cast(s_numMasks)); // Base pose and the input poses for the masks. + InitInputPorts(1 + s_numMasks); // Base pose and the input poses for the masks. SetupInputPort("Base Pose", INPUTPORT_BASEPOSE, AttributePose::TYPE_ID, INPUTPORT_BASEPOSE); for (size_t i = 0; i < s_numMasks; ++i) { - const AZ::u32 portNr = static_cast(i + INPUTPORT_START); + const uint32 portId = static_cast(i) + INPUTPORT_START; SetupInputPort( AZStd::string::format("Pose %zu", i).c_str(), - portNr, + portId, AttributePose::TYPE_ID, - portNr); + portId); } // Setup the output ports. @@ -129,16 +129,16 @@ namespace EMotionFX void BlendTreeMaskNode::OnMotionExtractionNodeChanged(Actor* actor, [[maybe_unused]] Node* newMotionExtractionNode) { - if (!mAnimGraph) + if (!m_animGraph) { return; } bool needsReinit = false; - const size_t numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numAnimGraphInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numAnimGraphInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); if (actor == animGraphInstance->GetActorInstance()->GetActor()) { needsReinit = true; @@ -176,14 +176,14 @@ namespace EMotionFX // Iterate over the non-empty masks and copy over its transforms. for (const UniqueData::MaskInstance& maskInstance : uniqueData->m_maskInstances) { - const AZ::u32 inputPortNr = maskInstance.m_inputPortNr; + const size_t inputPortNr = maskInstance.m_inputPortNr; AnimGraphNode* inputNode = GetInputNode(inputPortNr); if (inputNode) { OutputIncomingNode(animGraphInstance, inputNode); const Pose& inputPose = GetInputPose(animGraphInstance, inputPortNr)->GetValue()->GetPose(); - for (AZ::u32 jointIndex : maskInstance.m_jointIndices) + for (size_t jointIndex : maskInstance.m_jointIndices) { outputPose.SetLocalSpaceTransform(jointIndex, inputPose.GetLocalSpaceTransform(jointIndex)); } @@ -192,7 +192,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputAnimGraphPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputAnimGraphPose->GetPose(), m_visualizeColor); } } @@ -238,11 +238,9 @@ namespace EMotionFX data->SetEventBuffer(basePoseNodeUniqueData->GetRefCountedData()->GetEventBuffer()); } - const size_t numMaskInstances = uniqueData->m_maskInstances.size(); - for (size_t i = 0; i < numMaskInstances; ++i) + for (const UniqueData::MaskInstance& maskInstance : uniqueData->m_maskInstances) { - const UniqueData::MaskInstance& maskInstance = uniqueData->m_maskInstances[i]; - const AZ::u32 inputPortNr = maskInstance.m_inputPortNr; + const size_t inputPortNr = maskInstance.m_inputPortNr; AnimGraphNode* inputNode = GetInputNode(inputPortNr); if (!inputNode) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.h index 7577995434..258e8a475d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMaskNode.h @@ -49,12 +49,12 @@ namespace EMotionFX public: struct MaskInstance { - AZ::u32 m_inputPortNr; - AZStd::vector m_jointIndices; + size_t m_inputPortNr; + AZStd::vector m_jointIndices; }; AZStd::vector m_maskInstances; - AZStd::optional m_motionExtractionInputPortNr; + AZStd::optional m_motionExtractionInputPortNr; }; BlendTreeMaskNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp index 9ab1dbf817..f1e738d56d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMirrorPoseNode.cpp @@ -79,7 +79,7 @@ namespace EMotionFX { // check the enabled state bool isEnabled = true; - if (mInputPorts[INPUTPORT_ENABLED].mConnection) + if (m_inputPorts[INPUTPORT_ENABLED].m_connection) { isEnabled = GetInputNumberAsBool(animGraphInstance, INPUTPORT_ENABLED); } @@ -107,7 +107,7 @@ namespace EMotionFX uniqueData->Init(animGraphInstance, sourceNode); // apply mirroring to the sync track - if (GetIsMirroringEnabled(animGraphInstance) && !mDisabled) + if (GetIsMirroringEnabled(animGraphInstance) && !m_disabled) { EMotionFX::AnimGraphNodeData* sourceNodeData = sourceNode->FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->SetSyncTrack(sourceNodeData->GetSyncTrack()); @@ -119,7 +119,7 @@ namespace EMotionFX // perform the calculations / actions void BlendTreeMirrorPoseNode::Output(AnimGraphInstance* animGraphInstance) { - if (mInputPorts[INPUTPORT_POSE].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE].m_connection == nullptr) { // get the output pose RequestPoses(animGraphInstance); @@ -129,7 +129,7 @@ namespace EMotionFX } // if we're disabled just forward the input pose - if (mDisabled) + if (m_disabled) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_POSE)); const AnimGraphPose* inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); @@ -164,20 +164,20 @@ namespace EMotionFX Transform outputTransform; // for all enabled nodes - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { // get the node index that we sample the motion data from - const uint32 nodeIndex = actorInstance->GetEnabledNode(i); + const uint16 nodeIndex = actorInstance->GetEnabledNode(i); const Actor::NodeMirrorInfo& mirrorInfo = actor->GetNodeMirrorInfo(nodeIndex); // build the mirror plane normal, based on the mirror axis for this node AZ::Vector3 mirrorPlaneNormal(0.0f, 0.0f, 0.0f); - mirrorPlaneNormal.SetElement(mirrorInfo.mAxis, 1.0f); + mirrorPlaneNormal.SetElement(mirrorInfo.m_axis, 1.0f); // apply the mirrored delta to the bind pose of the current node outputTransform = bindPose->GetLocalSpaceTransform(nodeIndex); - outputTransform.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(mirrorInfo.mSourceNode), inPose.GetLocalSpaceTransform(mirrorInfo.mSourceNode), mirrorPlaneNormal, mirrorInfo.mFlags); + outputTransform.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(mirrorInfo.m_sourceNode), inPose.GetLocalSpaceTransform(mirrorInfo.m_sourceNode), mirrorPlaneNormal, mirrorInfo.m_flags); // update the pose with the new transform outPose.SetLocalSpaceTransform(nodeIndex, outputTransform); @@ -187,7 +187,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -196,7 +196,7 @@ namespace EMotionFX void BlendTreeMirrorPoseNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // check if we have three incoming connections, if not, we can't really continue - if (mConnections.size() == 0 || mInputPorts[INPUTPORT_POSE].mConnection == nullptr) + if (m_connections.size() == 0 || m_inputPorts[INPUTPORT_POSE].m_connection == nullptr) { RequestRefDatas(animGraphInstance); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); @@ -216,7 +216,7 @@ namespace EMotionFX AnimGraphRefCountedData* sourceData = inputNode->FindOrCreateUniqueNodeData(animGraphInstance)->GetRefCountedData(); data->SetEventBuffer(sourceData->GetEventBuffer()); - if (GetIsMirroringEnabled(animGraphInstance) && mDisabled == false) + if (GetIsMirroringEnabled(animGraphInstance) && m_disabled == false) { data->SetTrajectoryDelta(sourceData->GetTrajectoryDeltaMirrored()); data->SetTrajectoryDeltaMirrored(sourceData->GetTrajectoryDelta()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp index 7420c005a9..69e93971fd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.cpp @@ -27,11 +27,11 @@ namespace EMotionFX void BlendTreeMorphTargetNode::UniqueData::Update() { - BlendTreeMorphTargetNode* morphTargetNode = azdynamic_cast(mObject); + BlendTreeMorphTargetNode* morphTargetNode = azdynamic_cast(m_object); AZ_Assert(morphTargetNode, "Unique data linked to incorrect node type."); // Force update the morph target indices. - morphTargetNode->UpdateMorphIndices(mAnimGraphInstance->GetActorInstance(), this, true); + morphTargetNode->UpdateMorphIndices(m_animGraphInstance->GetActorInstance(), this, true); } BlendTreeMorphTargetNode::BlendTreeMorphTargetNode() @@ -95,9 +95,11 @@ namespace EMotionFX void BlendTreeMorphTargetNode::UpdateMorphIndices(ActorInstance* actorInstance, UniqueData* uniqueData, bool forceUpdate) { // Check if our LOD level changed, if not, we don't need to refresh it. - const uint32 lodLevel = actorInstance->GetLODLevel(); + const size_t lodLevel = actorInstance->GetLODLevel(); if (!forceUpdate && uniqueData->m_lastLodLevel == lodLevel) + { return; + } // Convert the morph target name into an index for fast lookup. if (!m_morphTargetNames.empty()) @@ -111,7 +113,7 @@ namespace EMotionFX } else { - uniqueData->m_morphTargetIndex = MCORE_INVALIDINDEX32; + uniqueData->m_morphTargetIndex = InvalidIndex; } uniqueData->m_lastLodLevel = lodLevel; @@ -133,7 +135,7 @@ namespace EMotionFX } else { - SetHasError(uniqueData, uniqueData->m_morphTargetIndex == MCORE_INVALIDINDEX32); + SetHasError(uniqueData, uniqueData->m_morphTargetIndex == InvalidIndex); } } @@ -144,7 +146,7 @@ namespace EMotionFX // If there is no input pose init the uutput pose to the bind pose. AnimGraphPose* outputPose; - if (!mInputPorts[INPUTPORT_POSE].mConnection) + if (!m_inputPorts[INPUTPORT_POSE].m_connection) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -160,10 +162,10 @@ namespace EMotionFX } // Try to modify the morph target weight with the value we specified as input. - if (!mDisabled && uniqueData->m_morphTargetIndex != MCORE_INVALIDINDEX32) + if (!m_disabled && uniqueData->m_morphTargetIndex != InvalidIndex) { // If we have an input to the weight port, read that value use that value to overwrite the pose value with. - if (mInputPorts[INPUTPORT_WEIGHT].mConnection) + if (m_inputPorts[INPUTPORT_WEIGHT].m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_WEIGHT)); const float morphWeight = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT); @@ -176,7 +178,7 @@ namespace EMotionFX // Debug visualize the output pose. if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.h index 693ebcaef5..daa41c2a24 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMorphTargetNode.h @@ -48,8 +48,8 @@ namespace EMotionFX void Update() override; public: - uint32 m_lastLodLevel = InvalidIndex32; - uint32 m_morphTargetIndex = InvalidIndex32; + size_t m_lastLodLevel = InvalidIndex; + size_t m_morphTargetIndex = InvalidIndex; }; BlendTreeMorphTargetNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.cpp index 73494c6ab3..3822d5a2e1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.cpp @@ -82,7 +82,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // get the motion instance object - BlendTreeConnection* motionConnection = mInputPorts[INPUTPORT_MOTION].mConnection; + BlendTreeConnection* motionConnection = m_inputPorts[INPUTPORT_MOTION].m_connection; if (motionConnection == nullptr) { RequestPoses(animGraphInstance); @@ -92,7 +92,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } @@ -109,14 +109,14 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } // get the time value float timeValue = 0.0f; - BlendTreeConnection* timeConnection = mInputPorts[INPUTPORT_TIME].mConnection; + BlendTreeConnection* timeConnection = m_inputPorts[INPUTPORT_TIME].m_connection; if (!timeConnection) // get it from the parameter value if there is no connection { timeValue = m_normalizedTimeValue; @@ -149,7 +149,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + actorInstance->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -158,7 +158,7 @@ namespace EMotionFX void BlendTreeMotionFrameNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // clear the event buffer - if (mDisabled) + if (m_disabled) { RequestRefDatas(animGraphInstance); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); @@ -169,14 +169,14 @@ namespace EMotionFX } // update the time input - BlendTreeConnection* timeConnection = mInputPorts[INPUTPORT_TIME].mConnection; + BlendTreeConnection* timeConnection = m_inputPorts[INPUTPORT_TIME].m_connection; if (timeConnection) { timeConnection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); } // update the input motion - BlendTreeConnection* motionConnection = mInputPorts[INPUTPORT_MOTION].mConnection; + BlendTreeConnection* motionConnection = m_inputPorts[INPUTPORT_MOTION].m_connection; if (motionConnection) { motionConnection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); @@ -195,7 +195,7 @@ namespace EMotionFX MotionInstance* motionInstance = motionNode->FindMotionInstance(animGraphInstance); if (triggerEvents && motionInstance) { - motionInstance->ExtractEventsNonLoop(uniqueData->mOldTime, uniqueData->mNewTime, &uniqueData->GetRefCountedData()->GetEventBuffer()); + motionInstance->ExtractEventsNonLoop(uniqueData->m_oldTime, uniqueData->m_newTime, &uniqueData->GetRefCountedData()->GetEventBuffer()); data->GetEventBuffer().UpdateEmitters(this); } } @@ -214,14 +214,14 @@ namespace EMotionFX void BlendTreeMotionFrameNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // update the time input - BlendTreeConnection* timeConnection = mInputPorts[INPUTPORT_TIME].mConnection; + BlendTreeConnection* timeConnection = m_inputPorts[INPUTPORT_TIME].m_connection; if (timeConnection) { UpdateIncomingNode(animGraphInstance, timeConnection->GetSourceNode(), timePassedInSeconds); } // update the input motion - BlendTreeConnection* motionConnection = mInputPorts[INPUTPORT_MOTION].mConnection; + BlendTreeConnection* motionConnection = m_inputPorts[INPUTPORT_MOTION].m_connection; if (motionConnection) { UpdateIncomingNode(animGraphInstance, motionConnection->GetSourceNode(), timePassedInSeconds); @@ -246,14 +246,14 @@ namespace EMotionFX { if (m_emitEventsFromStart) { - uniqueData->mNewTime = 0.0f; - uniqueData->mOldTime = 0.0f; + uniqueData->m_newTime = 0.0f; + uniqueData->m_oldTime = 0.0f; } else { const float newTimeValue = uniqueData->GetDuration() * timeValue; - uniqueData->mNewTime = newTimeValue; - uniqueData->mOldTime = newTimeValue; + uniqueData->m_newTime = newTimeValue; + uniqueData->m_oldTime = newTimeValue; } uniqueData->m_rewindRequested = false; } @@ -264,8 +264,8 @@ namespace EMotionFX uniqueData->Init(animGraphInstance, motionNode); uniqueData->SetCurrentPlayTime(uniqueData->GetDuration() * timeValue); - uniqueData->mOldTime = uniqueData->mNewTime; - uniqueData->mNewTime = uniqueData->GetDuration() * timeValue; + uniqueData->m_oldTime = uniqueData->m_newTime; + uniqueData->m_newTime = uniqueData->GetDuration() * timeValue; } else { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.h index 6268012828..184a0bbc98 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeMotionFrameNode.h @@ -55,14 +55,14 @@ namespace EMotionFX void Reset() override { - mOldTime = 0.0f; - mNewTime = 0.0f; + m_oldTime = 0.0f; + m_newTime = 0.0f; m_rewindRequested = false; } public: - float mOldTime; - float mNewTime; + float m_oldTime; + float m_newTime; bool m_rewindRequested; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeParameterNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeParameterNode.cpp index 8197cae9d0..ae24769584 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeParameterNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeParameterNode.cpp @@ -37,14 +37,14 @@ namespace EMotionFX void BlendTreeParameterNode::Reinit() { // Sort the parameter name mask in the way the parameters are stored in the anim graph. - SortParameterNames(mAnimGraph, m_parameterNames); + SortParameterNames(m_animGraph, m_parameterNames); // Iterate through the parameter name mask and find the corresponding cached value parameter indices. // This expects the parameter names to be sorted in the way the parameters are stored in the anim graph. m_parameterIndices.clear(); for (const AZStd::string& parameterName : m_parameterNames) { - const AZ::Outcome parameterIndex = mAnimGraph->FindValueParameterIndexByName(parameterName); + const AZ::Outcome parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); // during removal of parameters, we could end up with a parameter that was removed until the node gets the mask updated if (parameterIndex.IsSuccess()) { @@ -57,7 +57,7 @@ namespace EMotionFX if (m_parameterIndices.empty()) { // Parameter mask is empty, add ports for all parameters. - const ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); + const ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); const uint32 valueParameterCount = static_cast(valueParameters.size()); InitOutputPorts(valueParameterCount); @@ -66,12 +66,12 @@ namespace EMotionFX const ValueParameter* parameter = valueParameters[i]; SetOutputPortName(static_cast(i), parameter->GetName().c_str()); - mOutputPorts[i].mPortID = i; - mOutputPorts[i].ClearCompatibleTypes(); - mOutputPorts[i].mCompatibleTypes[0] = parameter->GetType(); + m_outputPorts[i].m_portId = i; + m_outputPorts[i].ClearCompatibleTypes(); + m_outputPorts[i].m_compatibleTypes[0] = parameter->GetType(); if (GetTypeSupportsFloat(parameter->GetType())) { - mOutputPorts[i].mCompatibleTypes[1] = MCore::AttributeFloat::TYPE_ID; + m_outputPorts[i].m_compatibleTypes[1] = MCore::AttributeFloat::TYPE_ID; } } } @@ -83,15 +83,15 @@ namespace EMotionFX for (size_t i = 0; i < parameterCount; ++i) { - const ValueParameter* parameter = mAnimGraph->FindValueParameter(m_parameterIndices[i]); + const ValueParameter* parameter = m_animGraph->FindValueParameter(m_parameterIndices[i]); SetOutputPortName(static_cast(i), parameter->GetName().c_str()); - mOutputPorts[i].mPortID = static_cast(i); - mOutputPorts[i].ClearCompatibleTypes(); - mOutputPorts[i].mCompatibleTypes[0] = parameter->GetType(); + m_outputPorts[i].m_portId = static_cast(i); + m_outputPorts[i].ClearCompatibleTypes(); + m_outputPorts[i].m_compatibleTypes[0] = parameter->GetType(); if (GetTypeSupportsFloat(parameter->GetType())) { - mOutputPorts[i].mCompatibleTypes[1] = MCore::AttributeFloat::TYPE_ID; + m_outputPorts[i].m_compatibleTypes[1] = MCore::AttributeFloat::TYPE_ID; } } } @@ -139,7 +139,7 @@ namespace EMotionFX if (m_parameterIndices.empty()) { // output all anim graph instance parameter values into the output ports - const uint32 numParameters = static_cast(mOutputPorts.size()); + const uint32 numParameters = static_cast(m_outputPorts.size()); for (uint32 i = 0; i < numParameters; ++i) { GetOutputValue(animGraphInstance, i)->InitFrom(animGraphInstance->GetParameterValue(i)); @@ -235,7 +235,7 @@ namespace EMotionFX void BlendTreeParameterNode::SetParameters(const AZStd::vector& parameterNames) { m_parameterNames = parameterNames; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -299,7 +299,7 @@ namespace EMotionFX void BlendTreeParameterNode::RemoveParameterByName(const AZStd::string& parameterName) { m_parameterNames.erase(AZStd::remove(m_parameterNames.begin(), m_parameterNames.end(), parameterName), m_parameterNames.end()); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -376,7 +376,7 @@ namespace EMotionFX // Add all connected parameters for (const AnimGraphNode::Port& port : GetOutputPorts()) { - if (port.mConnection) + if (port.m_connection) { parameterNames.emplace_back(port.GetNameString()); } @@ -435,10 +435,10 @@ namespace EMotionFX // Rename the actual output ports in all cases // (also when the parameter mask is empty and showing all parameters). - const size_t numOutputPorts = mOutputPorts.size(); + const size_t numOutputPorts = m_outputPorts.size(); for (size_t i = 0; i < numOutputPorts; ++i) { - AnimGraphNode::Port& outputPort = mOutputPorts[i]; + AnimGraphNode::Port& outputPort = m_outputPorts[i]; if (outputPort.GetNameString() == oldParameterName) { SetOutputPortName(static_cast(i), newParameterName.c_str()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSubtractNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSubtractNode.cpp index c70dee1de0..be40cb6749 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSubtractNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSubtractNode.cpp @@ -78,7 +78,7 @@ namespace EMotionFX AnimGraphNode* subtractNode = GetInputNode(INPUTPORT_POSE_B); // If we are disabled and we have an input node, or if we are no disabled but have no subtract input. - if ((mDisabled && inputNode) || (!mDisabled && inputNode && !subtractNode)) + if ((m_disabled && inputNode) || (!m_disabled && inputNode && !subtractNode)) { OutputIncomingNode(animGraphInstance, inputNode); RequestPoses(animGraphInstance); @@ -86,7 +86,7 @@ namespace EMotionFX *outputPose = *inputNode->GetMainOutputPose(animGraphInstance); return; } - else if (mDisabled || !inputNode) // If we are disabled or have no inputs. + else if (m_disabled || !inputNode) // If we are disabled or have no inputs. { RequestPoses(animGraphInstance); AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -116,7 +116,7 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { AnimGraphPose* visualOutputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); - animGraphInstance->GetActorInstance()->DrawSkeleton(visualOutputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(visualOutputPose->GetPose(), m_visualizeColor); } } @@ -127,14 +127,14 @@ namespace EMotionFX AnimGraphNode* subtractNode = GetInputNode(INPUTPORT_POSE_B); // If we are disabled and we have an input node, or if we are no disabled but have no subtract input. - if ((mDisabled && inputNode) || (!mDisabled && inputNode && !subtractNode)) + if ((m_disabled && inputNode) || (!m_disabled && inputNode && !subtractNode)) { UpdateIncomingNode(animGraphInstance, inputNode, timePassedInSeconds); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Init(animGraphInstance, inputNode); return; } - else if (mDisabled || (!inputNode && !subtractNode)) // If we are disabled or have no inputs. + else if (m_disabled || (!inputNode && !subtractNode)) // If we are disabled or have no inputs. { AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); uniqueData->Clear(); @@ -166,7 +166,7 @@ namespace EMotionFX data->ZeroTrajectoryDelta(); // We are disabled and have no input pose, so output no delta. - if (mDisabled || !nodeA) + if (m_disabled || !nodeA) { return; } @@ -191,7 +191,7 @@ namespace EMotionFX AnimGraphNode* inputNode = GetInputNode(INPUTPORT_POSE_A); AnimGraphNode* subtractNode = GetInputNode(INPUTPORT_POSE_B); - if (mDisabled) + if (m_disabled) { if (inputNode) { @@ -211,7 +211,7 @@ namespace EMotionFX { // Sync the input node to this node. inputNode->AutoSync(animGraphInstance, this, 0.0f, SYNCMODE_TRACKBASED, false); - if (animGraphInstance->GetIsObjectFlagEnabled(mObjectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) + if (animGraphInstance->GetIsObjectFlagEnabled(m_objectIndex, AnimGraphInstance::OBJECTFLAGS_SYNCED) == false) { inputNode->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphInstance::OBJECTFLAGS_SYNCED, true); } @@ -255,7 +255,7 @@ namespace EMotionFX // We are disabled but had an input pose, just forward that in this case. // Do the same if we are not disabled but have no second pose. - if ((mDisabled && inputNode) || (!mDisabled && inputNode && !subtractNode)) + if ((m_disabled && inputNode) || (!m_disabled && inputNode && !subtractNode)) { inputNode->PerformPostUpdate(animGraphInstance, timePassedInSeconds); RequestRefDatas(animGraphInstance); @@ -267,7 +267,7 @@ namespace EMotionFX data->SetTrajectoryDeltaMirrored(inputData->GetTrajectoryDelta()); return; } - else if (mDisabled || !inputNode) // If we are disabled or have no inputs. + else if (m_disabled || !inputNode) // If we are disabled or have no inputs. { RequestRefDatas(animGraphInstance); AnimGraphNodeData* uniqueData = FindOrCreateUniqueNodeData(animGraphInstance); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.cpp index 0eb1f3d06a..78fe49894d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.cpp @@ -85,7 +85,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // if the decision port has no incomming connection, there is nothing we can do - if (mInputPorts[INPUTPORT_DECISIONVALUE].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_DECISIONVALUE].m_connection == nullptr) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -98,7 +98,7 @@ namespace EMotionFX const int32 decisionValue = MCore::Clamp(GetInputNumberAsInt32(animGraphInstance, INPUTPORT_DECISIONVALUE), 0, 9); // max 10 cases // check if there is an incoming connection from this port - if (mInputPorts[INPUTPORT_POSE_0 + decisionValue].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE_0 + decisionValue].m_connection == nullptr) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -107,7 +107,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } return; } @@ -124,7 +124,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } @@ -133,7 +133,7 @@ namespace EMotionFX void BlendTreePoseSwitchNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if the decision port has no incomming connection, there is nothing we can do - if (mInputPorts[INPUTPORT_DECISIONVALUE].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_DECISIONVALUE].m_connection == nullptr) { UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); uniqueData->Clear(); @@ -141,13 +141,13 @@ namespace EMotionFX } // update the node that plugs into the decision value port - UpdateIncomingNode(animGraphInstance, mInputPorts[INPUTPORT_DECISIONVALUE].mConnection->GetSourceNode(), timePassedInSeconds); + UpdateIncomingNode(animGraphInstance, m_inputPorts[INPUTPORT_DECISIONVALUE].m_connection->GetSourceNode(), timePassedInSeconds); // get the index we choose const int32 decisionValue = MCore::Clamp(GetInputNumberAsInt32(animGraphInstance, INPUTPORT_DECISIONVALUE), 0, 9); // max 10 cases // check if there is an incoming connection from this port - if (mInputPorts[INPUTPORT_POSE_0 + decisionValue].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE_0 + decisionValue].m_connection == nullptr) { UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); uniqueData->Clear(); @@ -155,14 +155,14 @@ namespace EMotionFX } // pass through the motion extraction of the selected node - AnimGraphNode* sourceNode = mInputPorts[INPUTPORT_POSE_0 + decisionValue].mConnection->GetSourceNode(); + AnimGraphNode* sourceNode = m_inputPorts[INPUTPORT_POSE_0 + decisionValue].m_connection->GetSourceNode(); // if our decision value changed since last time, specify that we want to resync // this basically means that the motion extraction delta will be zero for one frame UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); - if (uniqueData->mDecisionIndex != decisionValue) + if (uniqueData->m_decisionIndex != decisionValue) { - uniqueData->mDecisionIndex = decisionValue; + uniqueData->m_decisionIndex = decisionValue; //sourceNode->RecursiveSetUniqueDataFlag(animGraphInstance, AnimGraphObjectData::FLAGS_RESYNC, true); } @@ -176,7 +176,7 @@ namespace EMotionFX void BlendTreePoseSwitchNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if the decision port has no incomming connection, there is nothing we can do - if (mInputPorts[INPUTPORT_DECISIONVALUE].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_DECISIONVALUE].m_connection == nullptr) { RequestRefDatas(animGraphInstance); UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); @@ -187,13 +187,13 @@ namespace EMotionFX } // update the node that plugs into the decision value port - mInputPorts[INPUTPORT_DECISIONVALUE].mConnection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); + m_inputPorts[INPUTPORT_DECISIONVALUE].m_connection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds); // get the index we choose const int32 decisionValue = MCore::Clamp(GetInputNumberAsInt32(animGraphInstance, INPUTPORT_DECISIONVALUE), 0, 9); // max 10 cases // check if there is an incoming connection from this port - if (mInputPorts[INPUTPORT_POSE_0 + decisionValue].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE_0 + decisionValue].m_connection == nullptr) { RequestRefDatas(animGraphInstance); UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); @@ -204,7 +204,7 @@ namespace EMotionFX } // pass through the motion extraction of the selected node - AnimGraphNode* sourceNode = mInputPorts[INPUTPORT_POSE_0 + decisionValue].mConnection->GetSourceNode(); + AnimGraphNode* sourceNode = m_inputPorts[INPUTPORT_POSE_0 + decisionValue].m_connection->GetSourceNode(); sourceNode->PerformPostUpdate(animGraphInstance, timePassedInSeconds); // output the events of the source node we picked @@ -223,7 +223,7 @@ namespace EMotionFX void BlendTreePoseSwitchNode::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds) { // if the decision port has no incomming connection, there is nothing we can do - if (mInputPorts[INPUTPORT_DECISIONVALUE].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_DECISIONVALUE].m_connection == nullptr) { return; } @@ -232,7 +232,7 @@ namespace EMotionFX const int32 decisionValue = MCore::Clamp(GetInputNumberAsInt32(animGraphInstance, INPUTPORT_DECISIONVALUE), 0, 9); // max 10 cases // check if there is an incoming connection from this port - if (mInputPorts[INPUTPORT_POSE_0 + decisionValue].mConnection == nullptr) + if (m_inputPorts[INPUTPORT_POSE_0 + decisionValue].m_connection == nullptr) { return; } @@ -242,7 +242,7 @@ namespace EMotionFX HierarchicalSyncAllInputNodes(animGraphInstance, uniqueData); // top down update all incoming connections - for (BlendTreeConnection* connection : mConnections) + for (BlendTreeConnection* connection : m_connections) { connection->GetSourceNode()->PerformTopDownUpdate(animGraphInstance, timePassedInSeconds); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.h index 1b8c958c27..9e24eff232 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreePoseSwitchNode.h @@ -67,7 +67,7 @@ namespace EMotionFX : AnimGraphNodeData(node, animGraphInstance) {} public: - int32 mDecisionIndex = -1; + int32 m_decisionIndex = -1; }; BlendTreePoseSwitchNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp index 4cf82cc77b..1d3c623215 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollNode.cpp @@ -30,10 +30,10 @@ namespace EMotionFX void BlendTreeRagdollNode::UniqueData::Update() { - BlendTreeRagdollNode* ragdollNode = azdynamic_cast(mObject); + BlendTreeRagdollNode* ragdollNode = azdynamic_cast(m_object); AZ_Assert(ragdollNode, "Unique data linked to incorrect node type."); - const Actor* actor = mAnimGraphInstance->GetActorInstance()->GetActor(); + const Actor* actor = m_animGraphInstance->GetActorInstance()->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); const size_t jointCount = skeleton->GetNumNodes(); @@ -54,7 +54,7 @@ namespace EMotionFX } // Check if we selected the ragdoll root node to be added to the simulation. - const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + const ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); const RagdollInstance* ragdollInstance = actorInstance->GetRagdollInstance(); m_isRagdollRootNodeSimulated = false; if (ragdollInstance) @@ -126,7 +126,7 @@ namespace EMotionFX RequestRefDatas(animGraphInstance); AnimGraphRefCountedData* data = uniqueData->GetRefCountedData(); - if (mDisabled) + if (m_disabled) { data->ClearEventBuffer(); data->ZeroTrajectoryDelta(); @@ -170,13 +170,13 @@ namespace EMotionFX if (ragdollInstance && motionExtractionNode) { // Move the trajectory node based on the ragdoll's movement. - trajectoryDelta.mPosition = ragdollInstance->GetTrajectoryDeltaPos(); + trajectoryDelta.m_position = ragdollInstance->GetTrajectoryDeltaPos(); // Do the same for rotation, but extract and apply z rotation only to the trajectory node. - trajectoryDelta.mRotation = ragdollInstance->GetTrajectoryDeltaRot(); - trajectoryDelta.mRotation.SetX(0.0f); - trajectoryDelta.mRotation.SetY(0.0f); - trajectoryDelta.mRotation.Normalize(); + trajectoryDelta.m_rotation = ragdollInstance->GetTrajectoryDeltaRot(); + trajectoryDelta.m_rotation.SetX(0.0f); + trajectoryDelta.m_rotation.SetY(0.0f); + trajectoryDelta.m_rotation.Normalize(); } data->SetTrajectoryDelta(trajectoryDelta); @@ -207,7 +207,7 @@ namespace EMotionFX } // As we already forwarded the target pose at this point, we can just return in case the node is disabled. - if (mDisabled) + if (m_disabled) { return; } @@ -215,7 +215,7 @@ namespace EMotionFX Pose& outputPose = animGraphOutputPose->GetPose(); if (GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose, mVisualizeColor); + actorInstance->DrawSkeleton(outputPose, m_visualizeColor); } if (HasConnectionAtInputPort(INPUTPORT_ACTIVATE)) @@ -241,8 +241,8 @@ namespace EMotionFX // Copy ragdoll transforms (world space) and reconstruct the rest of the skeleton using the target input pose. // If the current node is part of the ragdoll, copy the world transforms from the ragdoll node to the pose and recalculate the local transform. // In case the current node is not part of the ragdoll, update the world transforms based on the local transform from the bind pose. - const AZ::u32 jointCount = skeleton->GetNumNodes(); - for (AZ::u32 jointIndex = 0; jointIndex < jointCount; ++jointIndex) + const size_t jointCount = skeleton->GetNumNodes(); + for (size_t jointIndex = 0; jointIndex < jointCount; ++jointIndex) { Node* joint = skeleton->GetNode(jointIndex); const AZ::Outcome ragdollNodeIndex = ragdollInstance->GetRagdollNodeIndex(jointIndex); @@ -264,7 +264,7 @@ namespace EMotionFX Transform newGlobalTransform( currentRagdollRootNodeState.m_position, currentRagdollRootNodeState.m_orientation, - outputPose.GetWorldSpaceTransform(jointIndex).mScale); + outputPose.GetWorldSpaceTransform(jointIndex).m_scale); #else Transform newGlobalTransform( currentRagdollRootNodeState.m_position, @@ -298,7 +298,7 @@ namespace EMotionFX Transform newGlobalTransform = Transform( currentRagdollNodeState.m_position, currentRagdollNodeState.m_orientation, - outputPose.GetWorldSpaceTransform(jointIndex).mScale); + outputPose.GetWorldSpaceTransform(jointIndex).m_scale); #else Transform newGlobalTransform = Transform( currentRagdollNodeState.m_position, @@ -315,12 +315,12 @@ namespace EMotionFX Transform globalTransform = Transform( currentRagdollNodeState.m_position, currentRagdollNodeState.m_orientation, - outputPose.GetWorldSpaceTransform(jointIndex).mScale); + outputPose.GetWorldSpaceTransform(jointIndex).m_scale); Transform parentGlobalTransform = Transform( currentParentRagdollNodeState.m_position, currentParentRagdollNodeState.m_orientation, - outputPose.GetWorldSpaceTransform(ragdollParentJoint->GetNodeIndex()).mScale); + outputPose.GetWorldSpaceTransform(ragdollParentJoint->GetNodeIndex()).m_scale); #else Transform globalTransform = Transform( currentRagdollNodeState.m_position, @@ -343,15 +343,15 @@ namespace EMotionFX // Set the target pose for the selected and thus simulated joints in the anim graph node has a target pose connected to its input port. // Set the local space transform for powered ragdoll nodes. const Transform& localTransform = targetPose->GetLocalSpaceTransform(jointIndex); - targetRagdollNodeState.m_position = localTransform.mPosition; - targetRagdollNodeState.m_orientation = localTransform.mRotation; + targetRagdollNodeState.m_position = localTransform.m_position; + targetRagdollNodeState.m_orientation = localTransform.m_rotation; } else { // We do not have a target pose connected to the input port, just forward what is currently in the output pose (bind pose). const Transform& localTransform = outputPose.GetLocalSpaceTransform(jointIndex); - targetRagdollNodeState.m_position = localTransform.mPosition; - targetRagdollNodeState.m_orientation = localTransform.mRotation; + targetRagdollNodeState.m_position = localTransform.m_position; + targetRagdollNodeState.m_orientation = localTransform.m_rotation; } } else diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.cpp index dbf6009c9a..ef5767eef8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.cpp @@ -27,11 +27,11 @@ namespace EMotionFX void BlendTreeRagdollStrenghModifierNode::UniqueData::Update() { - BlendTreeRagdollStrenghModifierNode* ragdollModifierNode = azdynamic_cast(mObject); + BlendTreeRagdollStrenghModifierNode* ragdollModifierNode = azdynamic_cast(m_object); AZ_Assert(ragdollModifierNode, "Unique data linked to incorrect node type."); const AZStd::vector& modifiedJointNames = ragdollModifierNode->GetModifiedJointNames(); - const Actor* actor = mAnimGraphInstance->GetActorInstance()->GetActor(); + const Actor* actor = m_animGraphInstance->GetActorInstance()->GetActor(); AnimGraphPropertyUtils::ReinitJointIndices(actor, modifiedJointNames, m_modifiedJointIndices); } @@ -87,7 +87,7 @@ namespace EMotionFX } // As we already forwarded the input pose at this point, we can just return in case the node is disabled. - if (mDisabled) + if (m_disabled) { return; } @@ -95,7 +95,7 @@ namespace EMotionFX Pose& outputPose = animGraphOutputPose->GetPose(); if (GetCanVisualize(animGraphInstance)) { - actorInstance->DrawSkeleton(outputPose, mVisualizeColor); + actorInstance->DrawSkeleton(outputPose, m_visualizeColor); } UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.h index 763ccd812c..05891a488f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRagdollStrengthModifierNode.h @@ -62,7 +62,7 @@ namespace EMotionFX void Update() override; public: - AZStd::vector m_modifiedJointIndices; + AZStd::vector m_modifiedJointIndices; }; BlendTreeRagdollStrenghModifierNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRangeRemapperNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRangeRemapperNode.cpp index 1672bd6177..9215db80a1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRangeRemapperNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRangeRemapperNode.cpp @@ -72,8 +72,8 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // if there are no incoming connections, there is nothing to do - const size_t numConnections = mConnections.size(); - if (numConnections == 0 || mDisabled) + const size_t numConnections = m_connections.size(); + if (numConnections == 0 || m_disabled) { if (numConnections > 0) // pass the input value as output in case we are disabled { @@ -89,7 +89,7 @@ namespace EMotionFX float x = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_X); // output the original input, so without remapping, if this node is disabled - if (mDisabled) + if (m_disabled) { GetOutputFloat(animGraphInstance, OUTPUTPORT_RESULT)->SetValue(x); return; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRaycastNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRaycastNode.cpp index e9563cfb6f..2d11abc4ff 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRaycastNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRaycastNode.cpp @@ -30,7 +30,7 @@ namespace EMotionFX SetupOutputPort("Normal", OUTPUTPORT_NORMAL, MCore::AttributeVector3::TYPE_ID, PORTID_OUTPUT_NORMAL); SetupOutputPort("Intersected", OUTPUTPORT_INTERSECTED, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_INTERSECTED); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp index d4eaf9fcf1..cf8ebd2a46 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationLimitNode.cpp @@ -155,13 +155,13 @@ namespace EMotionFX void BlendTreeRotationLimitNode::ExecuteMathLogic(EMotionFX::AnimGraphInstance * animGraphInstance) { // If there are no incoming connections, there is nothing to do - if (mConnections.empty()) + if (m_connections.empty()) { return; } m_constraintTransformRotationAngles.SetTwistAxis(m_twistAxis); - m_constraintTransformRotationAngles.GetTransform().mRotation = GetInputQuaternion(animGraphInstance, INPUTPORT_ROTATION)->GetValue(); + m_constraintTransformRotationAngles.GetTransform().m_rotation = GetInputQuaternion(animGraphInstance, INPUTPORT_ROTATION)->GetValue(); m_constraintTransformRotationAngles.SetMaxRotationAngles(AZ::Vector2(GetRotationLimitY().m_max, GetRotationLimitX().m_max)); m_constraintTransformRotationAngles.SetMinRotationAngles(AZ::Vector2(GetRotationLimitY().m_min, GetRotationLimitX().m_min)); @@ -169,7 +169,7 @@ namespace EMotionFX m_constraintTransformRotationAngles.SetMaxTwistAngle(GetRotationLimitZ().m_max); m_constraintTransformRotationAngles.Execute(); - GetOutputQuaternion(animGraphInstance, OUTPUTPORT_RESULT_QUATERNION)->SetValue(m_constraintTransformRotationAngles.GetTransform().mRotation); + GetOutputQuaternion(animGraphInstance, OUTPUTPORT_RESULT_QUATERNION)->SetValue(m_constraintTransformRotationAngles.GetTransform().m_rotation); } void BlendTreeRotationLimitNode::Reflect(AZ::ReflectContext* context) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp index d01a6e5f0d..effe6c8477 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeRotationMath2Node.cpp @@ -33,7 +33,7 @@ namespace EMotionFX InitOutputPorts(1); SetupOutputPort("Rotation", INPUTPORT_X, MCore::AttributeQuaternion::TYPE_ID, PORTID_OUTPUT_QUATERNION); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -99,16 +99,15 @@ namespace EMotionFX void BlendTreeRotationMath2Node::ExecuteMathLogic(EMotionFX::AnimGraphInstance * animGraphInstance) { // If there are no incoming connections, there is nothing to do - if (mConnections.empty()) + if (m_connections.empty()) { return; } // If both x and y inputs have connections - //MCore::Quaternion x = MCore::AzQuatToEmfxQuat(m_defaultValue); AZ::Quaternion x = m_defaultValue; AZ::Quaternion y = x; - if (mConnections.size() == 2) + if (m_connections.size() == 2) { x = GetInputQuaternion(animGraphInstance, INPUTPORT_X)->GetValue(); @@ -117,13 +116,13 @@ namespace EMotionFX else // Only x or y is connected { // If only x has something plugged in - if (mConnections[0]->GetTargetPort() == INPUTPORT_X) + if (m_connections[0]->GetTargetPort() == INPUTPORT_X) { x = GetInputQuaternion(animGraphInstance, INPUTPORT_X)->GetValue(); } else // Only y has an input { - MCORE_ASSERT(mConnections[0]->GetTargetPort() == INPUTPORT_Y); + MCORE_ASSERT(m_connections[0]->GetTargetPort() == INPUTPORT_Y); y = GetInputQuaternion(animGraphInstance, INPUTPORT_Y)->GetValue(); } } @@ -139,7 +138,7 @@ namespace EMotionFX void BlendTreeRotationMath2Node::SetMathFunction(EMathFunction func) { m_mathFunction = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp index b922eb9b59..87bd31d942 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.cpp @@ -32,13 +32,13 @@ namespace EMotionFX void BlendTreeSetTransformNode::UniqueData::Update() { - BlendTreeSetTransformNode* transformNode = azdynamic_cast(mObject); + BlendTreeSetTransformNode* transformNode = azdynamic_cast(m_object); AZ_Assert(transformNode, "Unique data linked to incorrect node type."); - ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); Actor* actor = actorInstance->GetActor(); - m_nodeIndex = InvalidIndex32; + m_nodeIndex = InvalidIndex; const AZStd::string& jointName = transformNode->GetJointName(); if (!jointName.empty()) @@ -106,13 +106,13 @@ namespace EMotionFX if (GetEMotionFX().GetIsInEditorMode()) { - SetHasError(uniqueData, uniqueData->m_nodeIndex == MCORE_INVALIDINDEX32); + SetHasError(uniqueData, uniqueData->m_nodeIndex == InvalidIndex); } OutputAllIncomingNodes(animGraphInstance); // make sure we have at least an input pose, otherwise output the bind pose - if (GetInputPort(INPUTPORT_POSE).mConnection) + if (GetInputPort(INPUTPORT_POSE).m_connection) { const AnimGraphPose* inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); RequestPoses(animGraphInstance); @@ -129,7 +129,7 @@ namespace EMotionFX if (GetIsEnabled()) { // get the local transform from our node - if (uniqueData->m_nodeIndex != MCORE_INVALIDINDEX32) + if (uniqueData->m_nodeIndex != InvalidIndex) { Transform outputTransform; @@ -154,14 +154,14 @@ namespace EMotionFX AZ::Vector3 translation; if (TryGetInputVector3(animGraphInstance, INPUTPORT_TRANSLATION, translation)) { - outputTransform.mPosition = translation; + outputTransform.m_position = translation; } // process the rotation - if (GetInputPort(INPUTPORT_ROTATION).mConnection) + if (GetInputPort(INPUTPORT_ROTATION).m_connection) { const AZ::Quaternion& rotation = GetInputQuaternion(animGraphInstance, INPUTPORT_ROTATION)->GetValue(); - outputTransform.mRotation = rotation; + outputTransform.m_rotation = rotation; } // process the scale @@ -170,7 +170,7 @@ namespace EMotionFX AZ::Vector3 scale; if (TryGetInputVector3(animGraphInstance, INPUTPORT_SCALE, scale)) { - outputTransform.mScale = scale; + outputTransform.m_scale = scale; } ) @@ -197,7 +197,7 @@ namespace EMotionFX // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.h index be088a2c46..de60fa57f7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSetTransformNode.h @@ -66,7 +66,7 @@ namespace EMotionFX void Update() override; public: - uint32 m_nodeIndex = InvalidIndex32; + size_t m_nodeIndex = InvalidIndex; }; BlendTreeSetTransformNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSimulatedObjectNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSimulatedObjectNode.cpp index d54ef4ffd4..4c2f2c8f31 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSimulatedObjectNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSimulatedObjectNode.cpp @@ -38,7 +38,7 @@ namespace EMotionFX void BlendTreeSimulatedObjectNode::UniqueData::Update() { - BlendTreeSimulatedObjectNode* simulatedObjectNode = azdynamic_cast(mObject); + BlendTreeSimulatedObjectNode* simulatedObjectNode = azdynamic_cast(m_object); AZ_Assert(simulatedObjectNode, "Unique data linked to incorrect node type."); const bool solverInitResult = simulatedObjectNode->InitSolvers(GetAnimGraphInstance(), this); @@ -68,7 +68,7 @@ namespace EMotionFX void BlendTreeSimulatedObjectNode::Reinit() { - if (!mAnimGraph) + if (!m_animGraph) { return; } @@ -212,7 +212,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // If nothing is connected to the input pose, output a bind pose. - if (!GetInputPort(INPUTPORT_POSE).mConnection) + if (!GetInputPort(INPUTPORT_POSE).m_connection) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -223,14 +223,14 @@ namespace EMotionFX // Check whether we are active or not. bool isActive = true; - if (GetInputPort(INPUTPORT_ACTIVE).mConnection) + if (GetInputPort(INPUTPORT_ACTIVE).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_ACTIVE)); isActive = GetInputNumberAsBool(animGraphInstance, INPUTPORT_ACTIVE); } // If we're not active or if this node is disabled or it is optimized for server, we can skip all calculations and just output the input pose. - if (!isActive || mDisabled || GetEMotionFX().GetEnableServerOptimization()) + if (!isActive || m_disabled || GetEMotionFX().GetEnableServerOptimization()) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_POSE)); const AnimGraphPose* inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); @@ -291,7 +291,7 @@ namespace EMotionFX { for (const Simulation* sim : uniqueData->m_simulations) { - sim->m_solver.DebugRender(outputPose->GetPose(), m_collisionDetection, true, mVisualizeColor); + sim->m_solver.DebugRender(outputPose->GetPose(), m_collisionDetection, true, m_visualizeColor); } } } @@ -308,15 +308,15 @@ namespace EMotionFX void BlendTreeSimulatedObjectNode::AdjustParticles(const SpringSolver::ParticleAdjustFunction& func) { - if (!mAnimGraph) + if (!m_animGraph) { return; } - const size_t numInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueNodeData(this)); if (!uniqueData) { @@ -332,15 +332,15 @@ namespace EMotionFX void BlendTreeSimulatedObjectNode::OnPropertyChanged(const PropertyChangeFunction& func) { - if (!mAnimGraph) + if (!m_animGraph) { return; } - const size_t numInstances = mAnimGraph->GetNumAnimGraphInstances(); + const size_t numInstances = m_animGraph->GetNumAnimGraphInstances(); for (size_t i = 0; i < numInstances; ++i) { - AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i); + AnimGraphInstance* animGraphInstance = m_animGraph->GetAnimGraphInstance(i); UniqueData* uniqueData = static_cast(animGraphInstance->FindOrCreateUniqueNodeData(this)); if (!uniqueData) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.cpp index b835cbc12b..77703ea467 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.cpp @@ -27,12 +27,12 @@ namespace EMotionFX void BlendTreeSmoothingNode::UniqueData::Update() { - BlendTreeSmoothingNode* smoothingNode = azdynamic_cast(mObject); + BlendTreeSmoothingNode* smoothingNode = azdynamic_cast(m_object); AZ_Assert(smoothingNode, "Unique data linked to incorrect node type."); if (!smoothingNode->GetInputNode(BlendTreeSmoothingNode::INPUTPORT_DEST)) { - mCurrentValue = 0.0f; + m_currentValue = 0.0f; } } @@ -91,7 +91,7 @@ namespace EMotionFX UniqueData* uniqueData = static_cast(FindOrCreateUniqueNodeData(animGraphInstance)); // if there are no incoming connections, there is nothing to do - if (mConnections.size() == 0) + if (m_connections.size() == 0) { GetOutputFloat(animGraphInstance, OUTPUTPORT_RESULT)->SetValue(0.0f); return; @@ -100,29 +100,29 @@ namespace EMotionFX // if we are disabled, output the dest value directly //OutputIncomingNode( animGraphInstance, GetInputNode(INPUTPORT_DEST) ); const float destValue = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_DEST); - if (mDisabled) + if (m_disabled) { GetOutputFloat(animGraphInstance, OUTPUTPORT_RESULT)->SetValue(destValue); return; } // perform interpolation - const float sourceValue = uniqueData->mCurrentValue; - const float interpolationSpeed = m_interpolationSpeed * uniqueData->mFrameDeltaTime * 10.0f; + const float sourceValue = uniqueData->m_currentValue; + const float interpolationSpeed = m_interpolationSpeed * uniqueData->m_frameDeltaTime * 10.0f; const float interpolationResult = (interpolationSpeed < 0.99999f) ? MCore::LinearInterpolate(sourceValue, destValue, interpolationSpeed) : destValue; // If the interpolation result is close to the dest value within the tolerance, snap to the destination value. if (AZ::IsClose((interpolationResult - destValue), 0.0f, m_snapTolerance)) { - uniqueData->mCurrentValue = destValue; + uniqueData->m_currentValue = destValue; } else { // pass the interpolated result to the output port and the current value of the unique data - uniqueData->mCurrentValue = interpolationResult; + uniqueData->m_currentValue = interpolationResult; } GetOutputFloat(animGraphInstance, OUTPUTPORT_RESULT)->SetValue(interpolationResult); - uniqueData->mFrameDeltaTime = timePassedInSeconds; + uniqueData->m_frameDeltaTime = timePassedInSeconds; } @@ -135,13 +135,13 @@ namespace EMotionFX // check if the current value needs to be reset to the input or the start value when rewinding the node if (m_useStartValue) { - uniqueData->mCurrentValue = m_startValue; + uniqueData->m_currentValue = m_startValue; } else { // set the current value to the current input value UpdateAllIncomingNodes(animGraphInstance, 0.0f); - uniqueData->mCurrentValue = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_DEST); + uniqueData->m_currentValue = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_DEST); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.h index ef16fd397f..e0c65f9fe0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeSmoothingNode.h @@ -48,8 +48,8 @@ namespace EMotionFX void Update() override; public: - float mFrameDeltaTime = 0.0f; - float mCurrentValue = 0.0f; + float m_frameDeltaTime = 0.0f; + float m_currentValue = 0.0f; }; BlendTreeSmoothingNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp index e8005cee28..4b6a42b785 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.cpp @@ -33,15 +33,15 @@ namespace EMotionFX void BlendTreeTransformNode::UniqueData::Update() { - BlendTreeTransformNode* transformNode = azdynamic_cast(mObject); + BlendTreeTransformNode* transformNode = azdynamic_cast(m_object); AZ_Assert(transformNode, "Unique data linked to incorrect node type."); - const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + const ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); const Actor* actor = actorInstance->GetActor(); const AZStd::string& targetJointName = transformNode->GetTargetJointName(); - mNodeIndex = InvalidIndex32; + m_nodeIndex = InvalidIndex; SetHasError(true); if (!targetJointName.empty()) @@ -49,7 +49,7 @@ namespace EMotionFX const Node* joint = actor->GetSkeleton()->FindNodeByName(targetJointName); if (joint) { - mNodeIndex = joint->GetNodeIndex(); + m_nodeIndex = joint->GetNodeIndex(); SetHasError(false); } } @@ -132,7 +132,7 @@ namespace EMotionFX } // make sure we have at least an input pose, otherwise output the bind pose - if (GetInputPort(INPUTPORT_POSE).mConnection == nullptr) + if (GetInputPort(INPUTPORT_POSE).m_connection == nullptr) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_RESULT)->GetValue(); @@ -148,48 +148,48 @@ namespace EMotionFX } // get the local transform from our node - Transform inputTransform = outputPose->GetPose().GetLocalSpaceTransform(uniqueData->mNodeIndex); + Transform inputTransform = outputPose->GetPose().GetLocalSpaceTransform(uniqueData->m_nodeIndex); Transform outputTransform = inputTransform; // process the rotation - if (GetInputPort(INPUTPORT_ROTATE_AMOUNT).mConnection) + if (GetInputPort(INPUTPORT_ROTATE_AMOUNT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_ROTATE_AMOUNT)); const float rotateFactor = MCore::Clamp(GetInputNumberAsFloat(animGraphInstance, INPUTPORT_ROTATE_AMOUNT), 0.0f, 1.0f); const AZ::Vector3 newAngles = MCore::LinearInterpolate(m_minRotation, m_maxRotation, rotateFactor); - outputTransform.mRotation = inputTransform.mRotation * MCore::AzEulerAnglesToAzQuat(MCore::Math::DegreesToRadians(newAngles.GetX()), + outputTransform.m_rotation = inputTransform.m_rotation * MCore::AzEulerAnglesToAzQuat(MCore::Math::DegreesToRadians(newAngles.GetX()), MCore::Math::DegreesToRadians(newAngles.GetY()), MCore::Math::DegreesToRadians(newAngles.GetZ())); } // process the translation - if (GetInputPort(INPUTPORT_TRANSLATE_AMOUNT).mConnection) + if (GetInputPort(INPUTPORT_TRANSLATE_AMOUNT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_TRANSLATE_AMOUNT)); const float factor = MCore::Clamp(GetInputNumberAsFloat(animGraphInstance, INPUTPORT_TRANSLATE_AMOUNT), 0.0f, 1.0f); const AZ::Vector3 newValue = MCore::LinearInterpolate(m_minTranslation, m_maxTranslation, factor); - outputTransform.mPosition = inputTransform.mPosition + newValue; + outputTransform.m_position = inputTransform.m_position + newValue; } // process the scale EMFX_SCALECODE ( - if (GetInputPort(INPUTPORT_SCALE_AMOUNT).mConnection) + if (GetInputPort(INPUTPORT_SCALE_AMOUNT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_SCALE_AMOUNT)); const float factor = MCore::Clamp(GetInputNumberAsFloat(animGraphInstance, INPUTPORT_SCALE_AMOUNT), 0.0f, 1.0f); const AZ::Vector3 newValue = MCore::LinearInterpolate(m_minScale, m_maxScale, factor); - outputTransform.mScale = inputTransform.mScale + newValue; + outputTransform.m_scale = inputTransform.m_scale + newValue; } ) // update the transformation of the node - outputPose->GetPose().SetLocalSpaceTransform(uniqueData->mNodeIndex, outputTransform); + outputPose->GetPose().SetLocalSpaceTransform(uniqueData->m_nodeIndex, outputTransform); // visualize it if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) { - animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor); + animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), m_visualizeColor); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.h index 7d685c2528..b632041f77 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTransformNode.h @@ -70,7 +70,7 @@ namespace EMotionFX void Update() override; public: - uint32 mNodeIndex = InvalidIndex32; + size_t m_nodeIndex = InvalidIndex; }; BlendTreeTransformNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp index 1cfafb11d1..9a91a59390 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.cpp @@ -31,20 +31,20 @@ namespace EMotionFX void BlendTreeTwoLinkIKNode::UniqueData::Update() { - BlendTreeTwoLinkIKNode* twoLinkIKNode = azdynamic_cast(mObject); + BlendTreeTwoLinkIKNode* twoLinkIKNode = azdynamic_cast(m_object); AZ_Assert(twoLinkIKNode, "Unique data linked to incorrect node type."); - const ActorInstance* actorInstance = mAnimGraphInstance->GetActorInstance(); + const ActorInstance* actorInstance = m_animGraphInstance->GetActorInstance(); const Actor* actor = actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); // don't update the next time again - mNodeIndexA = InvalidIndex32; - mNodeIndexB = InvalidIndex32; - mNodeIndexC = InvalidIndex32; - mAlignNodeIndex = InvalidIndex32; - mBendDirNodeIndex = InvalidIndex32; - mEndEffectorNodeIndex = InvalidIndex32; + m_nodeIndexA = InvalidIndex; + m_nodeIndexB = InvalidIndex; + m_nodeIndexC = InvalidIndex; + m_alignNodeIndex = InvalidIndex; + m_bendDirNodeIndex = InvalidIndex; + m_endEffectorNodeIndex = InvalidIndex; SetHasError(true); // Find the end joint. @@ -58,18 +58,18 @@ namespace EMotionFX { return; } - mNodeIndexC = jointC->GetNodeIndex(); + m_nodeIndexC = jointC->GetNodeIndex(); // Get the second joint. - mNodeIndexB = jointC->GetParentIndex(); - if (mNodeIndexB == InvalidIndex32) + m_nodeIndexB = jointC->GetParentIndex(); + if (m_nodeIndexB == InvalidIndex) { return; } // Get the third joint. - mNodeIndexA = skeleton->GetNode(mNodeIndexB)->GetParentIndex(); - if (mNodeIndexA == InvalidIndex32) + m_nodeIndexA = skeleton->GetNode(m_nodeIndexB)->GetParentIndex(); + if (m_nodeIndexA == InvalidIndex) { return; } @@ -79,7 +79,7 @@ namespace EMotionFX const Node* endEffectorJoint = skeleton->FindNodeByName(endEffectorJointName); if (endEffectorJoint) { - mEndEffectorNodeIndex = endEffectorJoint->GetNodeIndex(); + m_endEffectorNodeIndex = endEffectorJoint->GetNodeIndex(); } // Find the bend direction joint. @@ -87,12 +87,12 @@ namespace EMotionFX const Node* bendDirJoint = skeleton->FindNodeByName(bendDirJointName); if (bendDirJoint) { - mBendDirNodeIndex = bendDirJoint->GetNodeIndex(); + m_bendDirNodeIndex = bendDirJoint->GetNodeIndex(); } // lookup the actor instance to get the alignment node from const NodeAlignmentData& alignToJointData = twoLinkIKNode->GetAlignToJointData(); - const ActorInstance* alignInstance = mAnimGraphInstance->FindActorInstanceFromParentDepth(alignToJointData.second); + const ActorInstance* alignInstance = m_animGraphInstance->FindActorInstanceFromParentDepth(alignToJointData.second); if (alignInstance) { if (!alignToJointData.first.empty()) @@ -100,7 +100,7 @@ namespace EMotionFX const Node* alignJoint = alignInstance->GetActor()->GetSkeleton()->FindNodeByName(alignToJointData.first.c_str()); if (alignJoint) { - mAlignNodeIndex = alignJoint->GetNodeIndex(); + m_alignNodeIndex = alignJoint->GetNodeIndex(); } } } @@ -210,7 +210,7 @@ namespace EMotionFX AnimGraphPose* outputPose; // make sure we have at least an input pose, otherwise output the bind pose - if (GetInputPort(INPUTPORT_POSE).mConnection == nullptr) + if (GetInputPort(INPUTPORT_POSE).m_connection == nullptr) { RequestPoses(animGraphInstance); outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue(); @@ -221,7 +221,7 @@ namespace EMotionFX // get the weight float weight = 1.0f; - if (GetInputPort(INPUTPORT_WEIGHT).mConnection) + if (GetInputPort(INPUTPORT_WEIGHT).m_connection) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_WEIGHT)); weight = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_WEIGHT); @@ -229,7 +229,7 @@ namespace EMotionFX } // if the IK weight is near zero, we can skip all calculations and act like a pass-trough node - if (weight < MCore::Math::epsilon || mDisabled) + if (weight < MCore::Math::epsilon || m_disabled) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_POSE)); const AnimGraphPose* inputPose = GetInputPose(animGraphInstance, INPUTPORT_POSE)->GetValue(); @@ -260,15 +260,15 @@ namespace EMotionFX } // get the node indices - const uint32 nodeIndexA = uniqueData->mNodeIndexA; - const uint32 nodeIndexB = uniqueData->mNodeIndexB; - const uint32 nodeIndexC = uniqueData->mNodeIndexC; - const uint32 bendDirIndex = uniqueData->mBendDirNodeIndex; - uint32 alignNodeIndex = uniqueData->mAlignNodeIndex; - uint32 endEffectorNodeIndex = uniqueData->mEndEffectorNodeIndex; + const size_t nodeIndexA = uniqueData->m_nodeIndexA; + const size_t nodeIndexB = uniqueData->m_nodeIndexB; + const size_t nodeIndexC = uniqueData->m_nodeIndexC; + const size_t bendDirIndex = uniqueData->m_bendDirNodeIndex; + size_t alignNodeIndex = uniqueData->m_alignNodeIndex; + size_t endEffectorNodeIndex = uniqueData->m_endEffectorNodeIndex; // use the end node as end effector node if no goal node has been specified - if (endEffectorNodeIndex == MCORE_INVALIDINDEX32) + if (endEffectorNodeIndex == InvalidIndex) { endEffectorNodeIndex = nodeIndexC; } @@ -289,7 +289,7 @@ namespace EMotionFX EMotionFX::Transform alignNodeTransform; // adjust the gizmo offset value - if (alignNodeIndex != MCORE_INVALIDINDEX32) + if (alignNodeIndex != InvalidIndex) { // update the alignment actor instance alignInstance = animGraphInstance->FindActorInstanceFromParentDepth(m_alignToNode.second); @@ -303,13 +303,13 @@ namespace EMotionFX { alignNodeTransform = alignInstance->GetTransformData()->GetCurrentPose()->GetWorldSpaceTransform(alignNodeIndex); } - const AZ::Vector3& offset = alignNodeTransform.mPosition; + const AZ::Vector3& offset = alignNodeTransform.m_position; goal += offset; if (GetEMotionFX().GetIsInEditorMode()) { // check if the offset goal pos values comes from a param node - const BlendTreeConnection* posConnection = GetInputPort(INPUTPORT_GOALPOS).mConnection; + const BlendTreeConnection* posConnection = GetInputPort(INPUTPORT_GOALPOS).m_connection; if (posConnection) { if (azrtti_typeid(posConnection->GetSourceNode()) == azrtti_typeid()) @@ -322,12 +322,12 @@ namespace EMotionFX } else { - alignNodeIndex = MCORE_INVALIDINDEX32; // we were not able to get the align instance, so set the align node index to the invalid index + alignNodeIndex = InvalidIndex; // we were not able to get the align instance, so set the align node index to the invalid index } } else if (GetEMotionFX().GetIsInEditorMode()) { - const BlendTreeConnection* posConnection = GetInputPort(INPUTPORT_GOALPOS).mConnection; + const BlendTreeConnection* posConnection = GetInputPort(INPUTPORT_GOALPOS).m_connection; if (posConnection) { if (azrtti_typeid(posConnection->GetSourceNode()) == azrtti_typeid()) @@ -350,13 +350,13 @@ namespace EMotionFX AZ::Vector3 bendDir; if (m_extractBendDir) { - if (bendDirIndex != MCORE_INVALIDINDEX32) + if (bendDirIndex != InvalidIndex) { - bendDir = outTransformPose.GetWorldSpaceTransform(bendDirIndex).mPosition - globalTransformA.mPosition; + bendDir = outTransformPose.GetWorldSpaceTransform(bendDirIndex).m_position - globalTransformA.m_position; } else { - bendDir = globalTransformB.mPosition - globalTransformA.mPosition; + bendDir = globalTransformB.m_position - globalTransformA.m_position; } } else @@ -371,7 +371,7 @@ namespace EMotionFX // if we want a relative bend dir, rotate it with the actor (only do this if we don't extract the bend dir) if (m_relativeBendDir && !m_extractBendDir) { - bendDir = actorInstance->GetWorldSpaceTransform().mRotation.TransformVector(bendDir); + bendDir = actorInstance->GetWorldSpaceTransform().m_rotation.TransformVector(bendDir); bendDir = MCore::SafeNormalize(bendDir); } else @@ -386,14 +386,14 @@ namespace EMotionFX const MCore::AttributeQuaternion* inputGoalRot = GetInputQuaternion(animGraphInstance, INPUTPORT_GOALROT); // if we don't want to align the rotation and position to another given node - if (alignNodeIndex == MCORE_INVALIDINDEX32) + if (alignNodeIndex == InvalidIndex) { AZ::Quaternion newRotation = AZ::Quaternion::CreateIdentity(); // identity quat if (inputGoalRot) { newRotation = inputGoalRot->GetValue(); // use our new rotation directly } - globalTransformC.mRotation = newRotation; + globalTransformC.m_rotation = newRotation; outTransformPose.SetWorldSpaceTransform(nodeIndexC, globalTransformC); } else // align to another node @@ -401,11 +401,11 @@ namespace EMotionFX if (inputGoalRot) { OutputIncomingNode(animGraphInstance, GetInputNode(INPUTPORT_GOALROT)); - globalTransformC.mRotation = GetInputQuaternion(animGraphInstance, INPUTPORT_GOALROT)->GetValue() * alignNodeTransform.mRotation; + globalTransformC.m_rotation = GetInputQuaternion(animGraphInstance, INPUTPORT_GOALROT)->GetValue() * alignNodeTransform.m_rotation; } else { - globalTransformC.mRotation = alignNodeTransform.mRotation; + globalTransformC.m_rotation = alignNodeTransform.m_rotation; } outTransformPose.SetWorldSpaceTransform(nodeIndexC, globalTransformC); @@ -413,15 +413,15 @@ namespace EMotionFX } // adjust the goal and get the end effector position - AZ::Vector3 endEffectorNodePos = outTransformPose.GetWorldSpaceTransform(endEffectorNodeIndex).mPosition; - const AZ::Vector3 posCToEndEffector = endEffectorNodePos - globalTransformC.mPosition; + AZ::Vector3 endEffectorNodePos = outTransformPose.GetWorldSpaceTransform(endEffectorNodeIndex).m_position; + const AZ::Vector3 posCToEndEffector = endEffectorNodePos - globalTransformC.m_position; if (m_rotationEnabled) { goal -= posCToEndEffector; } // store the desired rotation - AZ::Quaternion newNodeRotationC = globalTransformC.mRotation; + AZ::Quaternion newNodeRotationC = globalTransformC.m_rotation; // draw debug lines if (GetEMotionFX().GetIsInEditorMode() && GetCanVisualize(animGraphInstance)) @@ -441,15 +441,15 @@ namespace EMotionFX DebugDraw& debugDraw = GetDebugDraw(); DebugDraw::ActorInstanceData* drawData = debugDraw.GetActorInstanceData(animGraphInstance->GetActorInstance()); drawData->Lock(); - drawData->DrawLine(realGoal - AZ::Vector3(s, 0, 0), realGoal + AZ::Vector3(s, 0, 0), mVisualizeColor); - drawData->DrawLine(realGoal - AZ::Vector3(0, s, 0), realGoal + AZ::Vector3(0, s, 0), mVisualizeColor); - drawData->DrawLine(realGoal - AZ::Vector3(0, 0, s), realGoal + AZ::Vector3(0, 0, s), mVisualizeColor); + drawData->DrawLine(realGoal - AZ::Vector3(s, 0, 0), realGoal + AZ::Vector3(s, 0, 0), m_visualizeColor); + drawData->DrawLine(realGoal - AZ::Vector3(0, s, 0), realGoal + AZ::Vector3(0, s, 0), m_visualizeColor); + drawData->DrawLine(realGoal - AZ::Vector3(0, 0, s), realGoal + AZ::Vector3(0, 0, s), m_visualizeColor); const AZ::Color color(0.0f, 1.0f, 1.0f, 1.0f); - drawData->DrawLine(globalTransformA.mPosition, globalTransformA.mPosition + bendDir * s * 2.5f, color); - drawData->DrawLine(globalTransformA.mPosition - AZ::Vector3(s, 0, 0), globalTransformA.mPosition + AZ::Vector3(s, 0, 0), color); - drawData->DrawLine(globalTransformA.mPosition - AZ::Vector3(0, s, 0), globalTransformA.mPosition + AZ::Vector3(0, s, 0), color); - drawData->DrawLine(globalTransformA.mPosition - AZ::Vector3(0, 0, s), globalTransformA.mPosition + AZ::Vector3(0, 0, s), color); + drawData->DrawLine(globalTransformA.m_position, globalTransformA.m_position + bendDir * s * 2.5f, color); + drawData->DrawLine(globalTransformA.m_position - AZ::Vector3(s, 0, 0), globalTransformA.m_position + AZ::Vector3(s, 0, 0), color); + drawData->DrawLine(globalTransformA.m_position - AZ::Vector3(0, s, 0), globalTransformA.m_position + AZ::Vector3(0, s, 0), color); + drawData->DrawLine(globalTransformA.m_position - AZ::Vector3(0, 0, s), globalTransformA.m_position + AZ::Vector3(0, 0, s), color); drawData->Unlock(); } @@ -457,19 +457,19 @@ namespace EMotionFX AZ::Vector3 midPos; if (m_rotationEnabled) { - Solve2LinkIK(globalTransformA.mPosition, globalTransformB.mPosition, globalTransformC.mPosition, goal, bendDir, &midPos); + Solve2LinkIK(globalTransformA.m_position, globalTransformB.m_position, globalTransformC.m_position, goal, bendDir, &midPos); } else { - Solve2LinkIK(globalTransformA.mPosition, globalTransformB.mPosition, endEffectorNodePos, goal, bendDir, &midPos); + Solve2LinkIK(globalTransformA.m_position, globalTransformB.m_position, endEffectorNodePos, goal, bendDir, &midPos); } // -------------------------------------- // calculate the new node transforms // -------------------------------------- // calculate the differences between the current forward vector and the new one after IK - AZ::Vector3 oldForward = globalTransformB.mPosition - globalTransformA.mPosition; - AZ::Vector3 newForward = midPos - globalTransformA.mPosition; + AZ::Vector3 oldForward = globalTransformB.m_position - globalTransformA.m_position; + AZ::Vector3 newForward = midPos - globalTransformA.m_position; oldForward = MCore::SafeNormalize(oldForward); newForward = MCore::SafeNormalize(newForward); @@ -478,7 +478,7 @@ namespace EMotionFX float deltaAngle = MCore::Math::ACos(MCore::Clamp(dotProduct, -1.0f, 1.0f)); AZ::Vector3 axis = oldForward.Cross(newForward); AZ::Quaternion deltaRot = MCore::CreateFromAxisAndAngle(axis, deltaAngle); - globalTransformA.mRotation = deltaRot * globalTransformA.mRotation; + globalTransformA.m_rotation = deltaRot * globalTransformA.m_rotation; outTransformPose.SetWorldSpaceTransform(nodeIndexA, globalTransformA); // globalTransformA = outTransformPose.GetGlobalTransformIncludingActorInstanceTransform(nodeIndexA); @@ -486,21 +486,21 @@ namespace EMotionFX globalTransformC = outTransformPose.GetWorldSpaceTransform(nodeIndexC); // get the new current node positions - midPos = globalTransformB.mPosition; - endEffectorNodePos = outTransformPose.GetWorldSpaceTransform(endEffectorNodeIndex).mPosition; + midPos = globalTransformB.m_position; + endEffectorNodePos = outTransformPose.GetWorldSpaceTransform(endEffectorNodeIndex).m_position; // second node if (m_rotationEnabled) { - oldForward = globalTransformC.mPosition - globalTransformB.mPosition; + oldForward = globalTransformC.m_position - globalTransformB.m_position; } else { - oldForward = endEffectorNodePos - globalTransformB.mPosition; + oldForward = endEffectorNodePos - globalTransformB.m_position; } oldForward = MCore::SafeNormalize(oldForward); - newForward = goal - globalTransformB.mPosition; + newForward = goal - globalTransformB.m_position; newForward = MCore::SafeNormalize(newForward); // calculate the delta rotation @@ -516,15 +516,15 @@ namespace EMotionFX deltaRot = AZ::Quaternion::CreateIdentity(); } - globalTransformB.mRotation = deltaRot * globalTransformB.mRotation; - globalTransformB.mPosition = midPos; + globalTransformB.m_rotation = deltaRot * globalTransformB.m_rotation; + globalTransformB.m_position = midPos; outTransformPose.SetWorldSpaceTransform(nodeIndexB, globalTransformB); // update the rotation of node C if (m_rotationEnabled) { globalTransformC = outTransformPose.GetWorldSpaceTransform(nodeIndexC); - globalTransformC.mRotation = newNodeRotationC; + globalTransformC.m_rotation = newNodeRotationC; outTransformPose.SetWorldSpaceTransform(nodeIndexC, globalTransformC); } @@ -556,8 +556,8 @@ namespace EMotionFX DebugDraw& debugDraw = GetDebugDraw(); DebugDraw::ActorInstanceData* drawData = debugDraw.GetActorInstanceData(animGraphInstance->GetActorInstance()); drawData->Lock(); - drawData->DrawLine(outTransformPose.GetWorldSpaceTransform(nodeIndexA).mPosition, outTransformPose.GetWorldSpaceTransform(nodeIndexB).mPosition, mVisualizeColor); - drawData->DrawLine(outTransformPose.GetWorldSpaceTransform(nodeIndexB).mPosition, outTransformPose.GetWorldSpaceTransform(nodeIndexC).mPosition, mVisualizeColor); + drawData->DrawLine(outTransformPose.GetWorldSpaceTransform(nodeIndexA).m_position, outTransformPose.GetWorldSpaceTransform(nodeIndexB).m_position, m_visualizeColor); + drawData->DrawLine(outTransformPose.GetWorldSpaceTransform(nodeIndexB).m_position, outTransformPose.GetWorldSpaceTransform(nodeIndexC).m_position, m_visualizeColor); drawData->Unlock(); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h index 7a1a858804..e39cd7258e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeTwoLinkIKNode.h @@ -60,12 +60,12 @@ namespace EMotionFX void Update() override; public: - uint32 mNodeIndexA = InvalidIndex32; - uint32 mNodeIndexB = InvalidIndex32; - uint32 mNodeIndexC = InvalidIndex32; - uint32 mEndEffectorNodeIndex = InvalidIndex32; - uint32 mAlignNodeIndex = InvalidIndex32; - uint32 mBendDirNodeIndex = InvalidIndex32; + size_t m_nodeIndexA = InvalidIndex; + size_t m_nodeIndexB = InvalidIndex; + size_t m_nodeIndexC = InvalidIndex; + size_t m_endEffectorNodeIndex = InvalidIndex; + size_t m_alignNodeIndex = InvalidIndex; + size_t m_bendDirNodeIndex = InvalidIndex; }; BlendTreeTwoLinkIKNode(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math1Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math1Node.cpp index 94ab0ecac0..a70e6a3c61 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math1Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math1Node.cpp @@ -30,7 +30,7 @@ namespace EMotionFX SetupOutputPort("Vector3", OUTPUTPORT_RESULT_VECTOR3, MCore::AttributeVector3::TYPE_ID, PORTID_OUTPUT_VECTOR3); SetupOutputPort("Float", OUTPUTPORT_RESULT_FLOAT, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_FLOAT); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -153,7 +153,7 @@ namespace EMotionFX void BlendTreeVector3Math1Node::SetMathFunction(EMathFunction func) { m_mathFunction = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math2Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math2Node.cpp index cf00b8bc2c..d305ad6dd7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math2Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector3Math2Node.cpp @@ -33,7 +33,7 @@ namespace EMotionFX SetupOutputPort("Vector3", OUTPUTPORT_RESULT_VECTOR3, MCore::AttributeVector3::TYPE_ID, PORTID_OUTPUT_VECTOR3); SetupOutputPort("Float", OUTPUTPORT_RESULT_FLOAT, MCore::AttributeFloat::TYPE_ID, PORTID_OUTPUT_FLOAT); - if (mAnimGraph) + if (m_animGraph) { Reinit(); } @@ -118,7 +118,7 @@ namespace EMotionFX UpdateAllIncomingNodes(animGraphInstance, timePassedInSeconds); // if there are no incoming connections, there is nothing to do - if (mConnections.empty()) + if (m_connections.empty()) { return; } @@ -147,7 +147,7 @@ namespace EMotionFX void BlendTreeVector3Math2Node::SetMathFunction(EMathFunction func) { m_mathFunction = func; - if (mAnimGraph) + if (m_animGraph) { Reinit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector4DecomposeNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector4DecomposeNode.cpp index 0694cad02d..7cea0bbce1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector4DecomposeNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/BlendTreeVector4DecomposeNode.cpp @@ -72,7 +72,7 @@ namespace EMotionFX void BlendTreeVector4DecomposeNode::UpdateOutputPortValues(AnimGraphInstance* animGraphInstance) { // If there are no incoming connections, there is nothing to do. - if (mConnections.size() == 0) + if (m_connections.size() == 0) { return; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/CompressedKeyFrames.h b/Gems/EMotionFX/Code/EMotionFX/Source/CompressedKeyFrames.h index 1acd492587..6919f22188 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/CompressedKeyFrames.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/CompressedKeyFrames.h @@ -24,22 +24,22 @@ namespace EMotionFX //-------------------------------------------------------------------------------------- // compress a quaternion template<> - MCORE_INLINE void KeyFrame::SetValue(const AZ::Quaternion& value) { mValue.FromQuaternion(value); } + MCORE_INLINE void KeyFrame::SetValue(const AZ::Quaternion& value) { m_value.FromQuaternion(value); } // decompress into a quaternion template<> - MCORE_INLINE AZ::Quaternion KeyFrame::GetValue() const { return mValue.ToQuaternion(); } + MCORE_INLINE AZ::Quaternion KeyFrame::GetValue() const { return m_value.ToQuaternion(); } // decompress into a quaternion (without return value) template<> - MCORE_INLINE void KeyFrame::GetValue(AZ::Quaternion* outValue) { mValue.UnCompress(outValue); } + MCORE_INLINE void KeyFrame::GetValue(AZ::Quaternion* outValue) { m_value.UnCompress(outValue); } // direct access to compressed values template<> - MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed8BitQuaternion& value) { mValue = value; } + MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed8BitQuaternion& value) { m_value = value; } template<> - MCORE_INLINE const MCore::Compressed8BitQuaternion& KeyFrame::GetStorageTypeValue() const { return mValue; } + MCORE_INLINE const MCore::Compressed8BitQuaternion& KeyFrame::GetStorageTypeValue() const { return m_value; } //-------------------------------------------------------------------------------------- @@ -49,22 +49,22 @@ namespace EMotionFX //-------------------------------------------------------------------------------------- // compress a quaternion template<> - MCORE_INLINE void KeyFrame::SetValue(const AZ::Quaternion& value) { mValue.FromQuaternion(value); } + MCORE_INLINE void KeyFrame::SetValue(const AZ::Quaternion& value) { m_value.FromQuaternion(value); } // decompress into a quaternion template<> - MCORE_INLINE AZ::Quaternion KeyFrame::GetValue() const { return mValue.ToQuaternion(); } + MCORE_INLINE AZ::Quaternion KeyFrame::GetValue() const { return m_value.ToQuaternion(); } // decompress into a quaternion template<> - MCORE_INLINE void KeyFrame::GetValue(AZ::Quaternion* outValue) { return mValue.UnCompress(outValue); } + MCORE_INLINE void KeyFrame::GetValue(AZ::Quaternion* outValue) { return m_value.UnCompress(outValue); } // direct access to compressed values template<> - MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed16BitQuaternion& value) { mValue = value; } + MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed16BitQuaternion& value) { m_value = value; } template<> - MCORE_INLINE const MCore::Compressed16BitQuaternion& KeyFrame::GetStorageTypeValue() const { return mValue; } + MCORE_INLINE const MCore::Compressed16BitQuaternion& KeyFrame::GetStorageTypeValue() const { return m_value; } //-------------------------------------------------------------------------------------- @@ -74,22 +74,22 @@ namespace EMotionFX //-------------------------------------------------------------------------------------- // compress a float template<> - MCORE_INLINE void KeyFrame::SetValue(const float& value) { mValue.FromFloat(value, 0.0f, 1.0f); } + MCORE_INLINE void KeyFrame::SetValue(const float& value) { m_value.FromFloat(value, 0.0f, 1.0f); } // decompress into a float template<> - MCORE_INLINE float KeyFrame::GetValue() const { return mValue.ToFloat(0.0f, 1.0f); } + MCORE_INLINE float KeyFrame::GetValue() const { return m_value.ToFloat(0.0f, 1.0f); } // decompress into a float template<> - MCORE_INLINE void KeyFrame::GetValue(float* outValue) { mValue.UnCompress(outValue, 0.0f, 1.0f); } + MCORE_INLINE void KeyFrame::GetValue(float* outValue) { m_value.UnCompress(outValue, 0.0f, 1.0f); } // direct access to compressed values template<> - MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed8BitFloat& value) { mValue = value; } + MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed8BitFloat& value) { m_value = value; } template<> - MCORE_INLINE const MCore::Compressed8BitFloat& KeyFrame::GetStorageTypeValue() const { return mValue; } + MCORE_INLINE const MCore::Compressed8BitFloat& KeyFrame::GetStorageTypeValue() const { return m_value; } //-------------------------------------------------------------------------------------- @@ -99,21 +99,21 @@ namespace EMotionFX //-------------------------------------------------------------------------------------- // compress a float template<> - MCORE_INLINE void KeyFrame::SetValue(const float& value) { mValue.FromFloat(value, 0.0f, 1.0f); } + MCORE_INLINE void KeyFrame::SetValue(const float& value) { m_value.FromFloat(value, 0.0f, 1.0f); } // decompress into a float template<> - MCORE_INLINE float KeyFrame::GetValue() const { return mValue.ToFloat(0.0f, 1.0f); } + MCORE_INLINE float KeyFrame::GetValue() const { return m_value.ToFloat(0.0f, 1.0f); } // decompress into a float template<> - MCORE_INLINE void KeyFrame::GetValue(float* outValue) { return mValue.UnCompress(outValue, 0.0f, 1.0f); } + MCORE_INLINE void KeyFrame::GetValue(float* outValue) { return m_value.UnCompress(outValue, 0.0f, 1.0f); } // direct access to compressed values template<> - MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed16BitFloat& value) { mValue = value; } + MCORE_INLINE void KeyFrame::SetStorageTypeValue(const MCore::Compressed16BitFloat& value) { m_value = value; } template<> - MCORE_INLINE const MCore::Compressed16BitFloat& KeyFrame::GetStorageTypeValue() const { return mValue; } + MCORE_INLINE const MCore::Compressed16BitFloat& KeyFrame::GetStorageTypeValue() const { return m_value; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransform.h b/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransform.h index 46547eec5d..5316ae3319 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransform.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransform.h @@ -27,15 +27,15 @@ namespace EMotionFX AZ_RTTI(ConstraintTransform, "{8C821457-C3C2-4DAD-B552-A7318B420A9C}", Constraint) AZ_CLASS_ALLOCATOR(ConstraintTransform, EMotionFX::Integration::EMotionFXAllocator, 0) - ConstraintTransform() : Constraint() { mTransform.Identity(); } + ConstraintTransform() : Constraint() { m_transform.Identity(); } ~ConstraintTransform() override { } - void SetTransform(const Transform& transform) { mTransform = transform; } - MCORE_INLINE const Transform& GetTransform() const { return mTransform; } - MCORE_INLINE Transform& GetTransform() { return mTransform; } + void SetTransform(const Transform& transform) { m_transform = transform; } + MCORE_INLINE const Transform& GetTransform() const { return m_transform; } + MCORE_INLINE Transform& GetTransform() { return m_transform; } protected: - Transform mTransform = Transform::CreateIdentity(); + Transform m_transform = Transform::CreateIdentity(); }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.cpp index bc571e7cd0..6b23e050ca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.cpp @@ -24,11 +24,11 @@ namespace EMotionFX const float angleY = 0.382683f; // 45 degrees const float twistAngle = 0.0f; // 0 degrees - mMinRotationAngles.Set(-angleX, -angleY); - mMaxRotationAngles.Set(angleX, angleY); - mMinTwist = twistAngle; - mMaxTwist = twistAngle; - mTwistAxis = AXIS_Y; + m_minRotationAngles.Set(-angleX, -angleY); + m_maxRotationAngles.Set(angleX, angleY); + m_minTwist = twistAngle; + m_maxTwist = twistAngle; + m_twistAxis = AXIS_Y; } uint32 ConstraintTransformRotationAngles::GetType() const @@ -45,74 +45,74 @@ namespace EMotionFX { const float angleX = MCore::Math::Sin(MCore::Math::DegreesToRadians(minSwingDegrees.GetX()) * 0.5f); const float angleY = MCore::Math::Sin(MCore::Math::DegreesToRadians(minSwingDegrees.GetY()) * 0.5f); - mMinRotationAngles.Set(angleX, angleY); + m_minRotationAngles.Set(angleX, angleY); } void ConstraintTransformRotationAngles::SetMaxRotationAngles(const AZ::Vector2& maxSwingDegrees) { const float angleX = MCore::Math::Sin(MCore::Math::DegreesToRadians(maxSwingDegrees.GetX()) * 0.5f); const float angleY = MCore::Math::Sin(MCore::Math::DegreesToRadians(maxSwingDegrees.GetY()) * 0.5f); - mMaxRotationAngles.Set(angleX, angleY); + m_maxRotationAngles.Set(angleX, angleY); } void ConstraintTransformRotationAngles::SetMinTwistAngle(float minTwistDegrees) { - mMinTwist = MCore::Math::Sin(MCore::Math::DegreesToRadians(minTwistDegrees) * 0.5f); + m_minTwist = MCore::Math::Sin(MCore::Math::DegreesToRadians(minTwistDegrees) * 0.5f); } void ConstraintTransformRotationAngles::SetMaxTwistAngle(float maxTwistDegrees) { - mMaxTwist = MCore::Math::Sin(MCore::Math::DegreesToRadians(maxTwistDegrees) * 0.5f); + m_maxTwist = MCore::Math::Sin(MCore::Math::DegreesToRadians(maxTwistDegrees) * 0.5f); } void ConstraintTransformRotationAngles::SetTwistAxis(ConstraintTransformRotationAngles::EAxis axis) { - mTwistAxis = axis; + m_twistAxis = axis; } AZ::Vector2 ConstraintTransformRotationAngles::GetMinRotationAnglesDegrees() const { - return AZ::Vector2(MCore::Math::RadiansToDegrees(MCore::Math::ASin(mMinRotationAngles.GetX()) * 2.0f), - MCore::Math::RadiansToDegrees(MCore::Math::ASin(mMinRotationAngles.GetY()) * 2.0f)); + return AZ::Vector2(MCore::Math::RadiansToDegrees(MCore::Math::ASin(m_minRotationAngles.GetX()) * 2.0f), + MCore::Math::RadiansToDegrees(MCore::Math::ASin(m_minRotationAngles.GetY()) * 2.0f)); } AZ::Vector2 ConstraintTransformRotationAngles::GetMaxRotationAnglesDegrees() const { - return AZ::Vector2(MCore::Math::RadiansToDegrees(MCore::Math::ASin(mMaxRotationAngles.GetX()) * 2.0f), - MCore::Math::RadiansToDegrees(MCore::Math::ASin(mMaxRotationAngles.GetY()) * 2.0f)); + return AZ::Vector2(MCore::Math::RadiansToDegrees(MCore::Math::ASin(m_maxRotationAngles.GetX()) * 2.0f), + MCore::Math::RadiansToDegrees(MCore::Math::ASin(m_maxRotationAngles.GetY()) * 2.0f)); } AZ::Vector2 ConstraintTransformRotationAngles::GetMinRotationAnglesRadians() const { - return AZ::Vector2(MCore::Math::ASin(mMinRotationAngles.GetX()) * 2.0f, - MCore::Math::ASin(mMinRotationAngles.GetY()) * 2.0f); + return AZ::Vector2(MCore::Math::ASin(m_minRotationAngles.GetX()) * 2.0f, + MCore::Math::ASin(m_minRotationAngles.GetY()) * 2.0f); } AZ::Vector2 ConstraintTransformRotationAngles::GetMaxRotationAnglesRadians() const { - return AZ::Vector2(MCore::Math::ASin(mMaxRotationAngles.GetX()) * 2.0f, - MCore::Math::ASin(mMaxRotationAngles.GetY()) * 2.0f); + return AZ::Vector2(MCore::Math::ASin(m_maxRotationAngles.GetX()) * 2.0f, + MCore::Math::ASin(m_maxRotationAngles.GetY()) * 2.0f); } float ConstraintTransformRotationAngles::GetMinTwistAngle() const { - return MCore::Math::RadiansToDegrees(MCore::Math::ASin(mMinTwist) * 2.0f); + return MCore::Math::RadiansToDegrees(MCore::Math::ASin(m_minTwist) * 2.0f); } float ConstraintTransformRotationAngles::GetMaxTwistAngle() const { - return MCore::Math::RadiansToDegrees(MCore::Math::ASin(mMaxTwist) * 2.0f); + return MCore::Math::RadiansToDegrees(MCore::Math::ASin(m_maxTwist) * 2.0f); } ConstraintTransformRotationAngles::EAxis ConstraintTransformRotationAngles::GetTwistAxis() const { - return mTwistAxis; + return m_twistAxis; } // The main execution function, which performs the actual constraint. void ConstraintTransformRotationAngles::Execute() { - AZ::Quaternion q = mTransform.mRotation; + AZ::Quaternion q = m_transform.m_rotation; // Always keep w positive. if (q.GetW() < 0.0f) @@ -123,7 +123,7 @@ namespace EMotionFX // Get the axes indices for swing uint32 swingX; uint32 swingY; - switch (mTwistAxis) + switch (m_twistAxis) { // Twist is the X-axis. case AXIS_X: @@ -151,15 +151,15 @@ namespace EMotionFX // Calculate the twist quaternion, based on over which axis we assume there is twist. AZ::Quaternion twist; - const float twistAngle = q.GetElement(mTwistAxis); + const float twistAngle = q.GetElement(m_twistAxis); const float s = twistAngle * twistAngle + q.GetW() * q.GetW(); if (!MCore::Math::IsFloatZero(s)) { const float r = MCore::Math::InvSqrt(s); twist.SetElement(swingX, 0.0f); twist.SetElement(swingY, 0.0f); - twist.SetElement(mTwistAxis, MCore::Clamp(twistAngle * r, mMinTwist, mMaxTwist)); - twist.SetW(MCore::Math::Sqrt(MCore::Max(0.0f, 1.0f - twist.GetElement(mTwistAxis) * twist.GetElement(mTwistAxis)))); + twist.SetElement(m_twistAxis, MCore::Clamp(twistAngle * r, m_minTwist, m_maxTwist)); + twist.SetW(MCore::Math::Sqrt(MCore::Max(0.0f, 1.0f - twist.GetElement(m_twistAxis) * twist.GetElement(m_twistAxis)))); } else { @@ -168,13 +168,13 @@ namespace EMotionFX // Remove the twist from the input rotation so that we are left with a swing and then limit the swing. AZ::Quaternion swing = q * twist.GetConjugate(); - swing.SetElement(swingX, MCore::Clamp(static_cast(swing.GetElement(swingX)), mMinRotationAngles.GetX(), mMaxRotationAngles.GetX())); - swing.SetElement(swingY, MCore::Clamp(static_cast(swing.GetElement(swingY)), mMinRotationAngles.GetY(), mMaxRotationAngles.GetY())); - swing.SetElement(mTwistAxis, 0.0f); + swing.SetElement(swingX, MCore::Clamp(static_cast(swing.GetElement(swingX)), m_minRotationAngles.GetX(), m_maxRotationAngles.GetX())); + swing.SetElement(swingY, MCore::Clamp(static_cast(swing.GetElement(swingY)), m_minRotationAngles.GetY(), m_maxRotationAngles.GetY())); + swing.SetElement(m_twistAxis, 0.0f); swing.SetW(MCore::Math::Sqrt(MCore::Max(0.0f, 1.0f - swing.GetElement(swingX) * swing.GetElement(swingX) - swing.GetElement(swingY) * swing.GetElement(swingY)))); // Combine the limited swing and twist again into a final rotation. - mTransform.mRotation = swing * twist; + m_transform.m_rotation = swing * twist; } AZ::Vector3 ConstraintTransformRotationAngles::GetSphericalPos(float x, float y) const diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.h b/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.h index 3af63c382e..65e141e6e2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ConstraintTransformRotationAngles.h @@ -74,11 +74,11 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); protected: - AZ::Vector2 mMinRotationAngles; ///< The minimum rotation angles, actually the precalculated sin(halfAngleRadians). - AZ::Vector2 mMaxRotationAngles; ///< The maximum rotation angles, actually the precalculated sin(halfAngleRadians). - float mMinTwist; ///< The minimum twist angle, actually the precalculated sin(halfAngleRadians). - float mMaxTwist; ///< The maximum twist angle, actually the precalculated sin(halfAngleRadians). - EAxis mTwistAxis; ///< The twist axis index, which has to be either 0, 1 or 2 (default=AXIS_X, which equals 0). + AZ::Vector2 m_minRotationAngles; ///< The minimum rotation angles, actually the precalculated sin(halfAngleRadians). + AZ::Vector2 m_maxRotationAngles; ///< The maximum rotation angles, actually the precalculated sin(halfAngleRadians). + float m_minTwist; ///< The minimum twist angle, actually the precalculated sin(halfAngleRadians). + float m_maxTwist; ///< The maximum twist angle, actually the precalculated sin(halfAngleRadians). + EAxis m_twistAxis; ///< The twist axis index, which has to be either 0, 1 or 2 (default=AXIS_X, which equals 0). void DrawSphericalLine(ActorInstance* actorInstance, const AZ::Vector2& start, const AZ::Vector2& end, uint32 numSteps, const AZ::Color& color, float radius, const AZ::Transform& offset) const; AZ::Vector3 GetSphericalPos(float x, float y) const; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp index 72c52edc66..0fd06000de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DebugDraw.cpp @@ -110,15 +110,15 @@ namespace EMotionFX { const Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton(); - const AZ::u32 numNodes = m_actorInstance->GetNumEnabledNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const AZ::u32 nodeIndex = m_actorInstance->GetEnabledNode(i); - const AZ::u32 parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + const size_t nodeIndex = m_actorInstance->GetEnabledNode(i); + const size_t parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); + if (parentIndex != InvalidIndex) { - const AZ::Vector3& startPos = pose.GetWorldSpaceTransform(nodeIndex).mPosition; - const AZ::Vector3& endPos = pose.GetWorldSpaceTransform(parentIndex).mPosition; + const AZ::Vector3& startPos = pose.GetWorldSpaceTransform(nodeIndex).m_position; + const AZ::Vector3& endPos = pose.GetWorldSpaceTransform(parentIndex).m_position; DrawLine(offset + startPos, offset + endPos, color); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp index 2daaac6a85..2d5d8e2a46 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp @@ -33,12 +33,12 @@ namespace EMotionFX { } - AZ::Outcome DualQuatSkinDeformer::FindLocalBoneIndex(uint32 nodeIndex) const + AZ::Outcome DualQuatSkinDeformer::FindLocalBoneIndex(size_t nodeIndex) const { const size_t numBones = m_bones.size(); for (size_t i = 0; i < numBones; ++i) { - if (m_bones[i].mNodeNr == nodeIndex) + if (m_bones[i].m_nodeNr == nodeIndex) { return AZ::Success(i); } @@ -62,7 +62,7 @@ namespace EMotionFX return SUBTYPE_ID; } - MeshDeformer* DualQuatSkinDeformer::Clone(Mesh* mesh) + MeshDeformer* DualQuatSkinDeformer::Clone(Mesh* mesh) const { // create the new cloned deformer DualQuatSkinDeformer* result = aznew DualQuatSkinDeformer(mesh); @@ -79,14 +79,14 @@ namespace EMotionFX { const Actor* actor = actorInstance->GetActor(); const Pose* pose = actorInstance->GetTransformData()->GetCurrentPose(); - const uint32 numVertices = mMesh->GetNumVertices(); + const uint32 numVertices = m_mesh->GetNumVertices(); // pre-calculate the skinning matrices for (BoneInfo& boneInfo : m_bones) { - const uint32 nodeIndex = boneInfo.mNodeNr; + const size_t nodeIndex = boneInfo.m_nodeNr; const Transform skinTransform = actor->GetInverseBindPoseTransform(nodeIndex) * pose->GetModelSpaceTransform(nodeIndex); - boneInfo.mDualQuat.FromRotationTranslation(skinTransform.mRotation, skinTransform.mPosition); + boneInfo.m_dualQuat.FromRotationTranslation(skinTransform.m_rotation, skinTransform.m_position); } AZ::JobCompletion jobCompletion; @@ -102,7 +102,7 @@ namespace EMotionFX AZ::JobContext* jobContext = nullptr; AZ::Job* job = AZ::CreateJobFunction([this, startVertex, endVertex]() { - SkinRange(mMesh, startVertex, endVertex, m_bones); + SkinRange(m_mesh, startVertex, endVertex, m_bones); }, /*isAutoDelete=*/true, jobContext); job->SetDependent(&jobCompletion); @@ -145,7 +145,7 @@ namespace EMotionFX if (numInfluences > 0) { // get the pivot quat, used for the dot product check - const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; + const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].m_dualQuat; // our skinning dual quaternion MCore::DualQuaternion skinQuat(AZ::Quaternion(0, 0, 0, 0), AZ::Quaternion(0, 0, 0, 0)); @@ -156,8 +156,8 @@ namespace EMotionFX weight = influence->GetWeight(); // check if we need to invert the dual quat - MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].mDualQuat; - if (influenceQuat.mReal.Dot(pivotQuat.mReal) < 0.0f) + MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].m_dualQuat; + if (influenceQuat.m_real.Dot(pivotQuat.m_real) < 0.0f) { influenceQuat *= -1.0f; } @@ -202,7 +202,7 @@ namespace EMotionFX if (numInfluences > 0) { // get the pivot quat, used for the dot product check - const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; + const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].m_dualQuat; // our skinning dual quaternion MCore::DualQuaternion skinQuat(AZ::Quaternion(0, 0, 0, 0), AZ::Quaternion(0, 0, 0, 0)); @@ -213,8 +213,8 @@ namespace EMotionFX weight = influence->GetWeight(); // check if we need to invert the dual quat - MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].mDualQuat; - if (influenceQuat.mReal.Dot(pivotQuat.mReal) < 0.0f) + MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].m_dualQuat; + if (influenceQuat.m_real.Dot(pivotQuat.m_real) < 0.0f) { influenceQuat *= -1.0f; } @@ -255,7 +255,7 @@ namespace EMotionFX if (numInfluences > 0) { // get the pivot quat, used for the dot product check - const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; + const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].m_dualQuat; // our skinning dual quaternion MCore::DualQuaternion skinQuat(AZ::Quaternion(0, 0, 0, 0), AZ::Quaternion(0, 0, 0, 0)); @@ -266,8 +266,8 @@ namespace EMotionFX weight = influence->GetWeight(); // check if we need to invert the dual quat - MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].mDualQuat; - if (influenceQuat.mReal.Dot(pivotQuat.mReal) < 0.0f) + MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].m_dualQuat; + if (influenceQuat.m_real.Dot(pivotQuat.m_real) < 0.0f) { influenceQuat *= -1.0f; } @@ -294,7 +294,7 @@ namespace EMotionFX } // initialize the mesh deformer - void DualQuatSkinDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) + void DualQuatSkinDeformer::Reinitialize(Actor* actor, Node* node, size_t lodLevel) { MCORE_UNUSED(actor); MCORE_UNUSED(node); @@ -304,16 +304,16 @@ namespace EMotionFX m_bones.clear(); // if there is no mesh - if (mMesh == nullptr) + if (m_mesh == nullptr) { return; } - SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)mMesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); + SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)m_mesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); MCORE_ASSERT(skinningLayer); // find out what bones this mesh uses - const uint32 numOrgVerts = mMesh->GetNumOrgVertices(); + const uint32 numOrgVerts = m_mesh->GetNumOrgVertices(); for (uint32 i = 0; i < numOrgVerts; i++) { // now we have located the skinning information for this vertex, we can see if our bones array @@ -327,14 +327,14 @@ namespace EMotionFX AZ::Outcome boneIndexOutcome = FindLocalBoneIndex(influence->GetNodeNr()); if (boneIndexOutcome.IsSuccess()) { - influence->SetBoneNr(static_cast(boneIndexOutcome.GetValue())); + influence->SetBoneNr(aznumeric_caster(boneIndexOutcome.GetValue())); } else { // add the bone to the array of bones in this deformer BoneInfo lastBone; - lastBone.mNodeNr = influence->GetNodeNr(); - lastBone.mDualQuat.Identity(); + lastBone.m_nodeNr = influence->GetNodeNr(); + lastBone.m_dualQuat.Identity(); m_bones.emplace_back(lastBone); influence->SetBoneNr(static_cast(m_bones.size() - 1)); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h index 1775eb4789..434f2920ee 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -68,14 +68,14 @@ namespace EMotionFX * @param node The node where the mesh belongs to during this initialization. * @param lodLevel The LOD level of the mesh the mesh deformer works on. */ - void Reinitialize(Actor* actor, Node* node, uint32 lodLevel) override; + void Reinitialize(Actor* actor, Node* node, size_t lodLevel) override; /** * Creates an exact clone (copy) of this deformer, and returns a pointer to it. * @param mesh The mesh to apply the deformer on. * @result A pointer to the newly created clone of this deformer. */ - MeshDeformer* Clone(Mesh* mesh) override; + MeshDeformer* Clone(Mesh* mesh) const override; /** * Returns the unique type ID of the deformer. @@ -97,21 +97,21 @@ 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 static_cast(m_bones.size()); } + MCORE_INLINE size_t GetNumLocalBones() const { return 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 m_bones[index].mNodeNr; } + MCORE_INLINE size_t GetLocalBone(size_t index) const { return m_bones[index].m_nodeNr; } /** * 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) { m_bones.reserve(numBones); } + MCORE_INLINE void ReserveLocalBones(size_t numBones) { m_bones.reserve(numBones); } protected: /** @@ -119,11 +119,11 @@ namespace EMotionFX */ struct EMFX_API BoneInfo { - uint32 mNodeNr; /**< The node number. */ - MCore::DualQuaternion mDualQuat; /**< The dual quat of the pre-calculated matrix that contains the "globalMatrix * inverse(bindPoseMatrix)". */ + size_t m_nodeNr; /**< The node number. */ + MCore::DualQuaternion m_dualQuat; /**< The dual quat of the pre-calculated matrix that contains the "globalMatrix * inverse(bindPoseMatrix)". */ MCORE_INLINE BoneInfo() - : mNodeNr(MCORE_INVALIDINDEX32) {} + : m_nodeNr(InvalidIndex) {} }; AZStd::vector m_bones; /**< The array of bone information used for pre-calculation. */ @@ -153,8 +153,8 @@ namespace EMotionFX /** * Find the entry number that uses a specified node number. * @param nodeIndex The node number to search for. - * @result The index inside the mBones member array, which uses the given node. + * @result The index inside the m_bones member array, which uses the given node. */ - AZ::Outcome FindLocalBoneIndex(uint32 nodeIndex) const; + AZ::Outcome FindLocalBoneIndex(size_t nodeIndex) const; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp index ba81cc41b5..82b06c8171 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.cpp @@ -62,7 +62,7 @@ namespace EMotionFX } // set the unit type - gEMFX.Get()->SetUnitType(finalSettings.mUnitType); + gEMFX.Get()->SetUnitType(finalSettings.m_unitType); // create and set the objects gEMFX.Get()->SetImporter (Importer::Create()); @@ -107,25 +107,24 @@ namespace EMotionFX // constructor EMotionFXManager::EMotionFXManager() { - mThreadDatas.SetMemoryCategory(EMFX_MEMCATEGORY_EMOTIONFXMANAGER); // build the low version string AZStd::string lowVersionString; BuildLowVersionString(lowVersionString); - mVersionString = AZStd::string::format("EMotion FX v%d.%s RC4", EMFX_HIGHVERSION, lowVersionString.c_str()); - mCompilationDate = MCORE_DATE; - mHighVersion = EMFX_HIGHVERSION; - mLowVersion = EMFX_LOWVERSION; - mImporter = nullptr; - mActorManager = nullptr; - mMotionManager = nullptr; - mEventManager = nullptr; - mSoftSkinManager = nullptr; - mRecorder = nullptr; - mMotionInstancePool = nullptr; - mDebugDraw = nullptr; - mUnitType = MCore::Distance::UNITTYPE_METERS; - mGlobalSimulationSpeed = 1.0f; + m_versionString = AZStd::string::format("EMotion FX v%d.%s RC4", EMFX_HIGHVERSION, lowVersionString.c_str()); + m_compilationDate = MCORE_DATE; + m_highVersion = EMFX_HIGHVERSION; + m_lowVersion = EMFX_LOWVERSION; + m_importer = nullptr; + m_actorManager = nullptr; + m_motionManager = nullptr; + m_eventManager = nullptr; + m_softSkinManager = nullptr; + m_recorder = nullptr; + m_motionInstancePool = nullptr; + m_debugDraw = nullptr; + m_unitType = MCore::Distance::UNITTYPE_METERS; + m_globalSimulationSpeed = 1.0f; m_isInEditorMode = false; m_isInServerMode = false; @@ -144,41 +143,40 @@ namespace EMotionFX { // the motion manager has to get destructed before the anim graph manager as the motion manager kills all motion instances // from the motion nodes when destructing the motions itself - //mRigManager->Destroy(); - mMotionManager->Destroy(); - mMotionManager = nullptr; + m_motionManager->Destroy(); + m_motionManager = nullptr; - mAnimGraphManager->Destroy(); - mAnimGraphManager = nullptr; + m_animGraphManager->Destroy(); + m_animGraphManager = nullptr; - mImporter->Destroy(); - mImporter = nullptr; + m_importer->Destroy(); + m_importer = nullptr; - mActorManager->Destroy(); - mActorManager = nullptr; + m_actorManager->Destroy(); + m_actorManager = nullptr; - mMotionInstancePool->Destroy(); - mMotionInstancePool = nullptr; + m_motionInstancePool->Destroy(); + m_motionInstancePool = nullptr; - mSoftSkinManager->Destroy(); - mSoftSkinManager = nullptr; + m_softSkinManager->Destroy(); + m_softSkinManager = nullptr; - mRecorder->Destroy(); - mRecorder = nullptr; + m_recorder->Destroy(); + m_recorder = nullptr; - delete mDebugDraw; - mDebugDraw = nullptr; + delete m_debugDraw; + m_debugDraw = nullptr; - mEventManager->Destroy(); - mEventManager = nullptr; + m_eventManager->Destroy(); + m_eventManager = nullptr; // delete the thread datas - for (uint32 i = 0; i < mThreadDatas.GetLength(); ++i) + for (uint32 i = 0; i < m_threadDatas.size(); ++i) { - mThreadDatas[i]->Destroy(); + m_threadDatas[i]->Destroy(); } - mThreadDatas.Clear(); + m_threadDatas.clear(); } @@ -194,16 +192,16 @@ namespace EMotionFX { AZ_PROFILE_SCOPE(AZ::Debug::ProfileCategory::Animation, "EMotionFXManager::Update"); - mDebugDraw->Clear(); - mRecorder->UpdatePlayMode(timePassedInSeconds); - mActorManager->UpdateActorInstances(timePassedInSeconds); - mEventManager->OnSimulatePhysics(timePassedInSeconds); - mRecorder->Update(timePassedInSeconds); + m_debugDraw->Clear(); + m_recorder->UpdatePlayMode(timePassedInSeconds); + m_actorManager->UpdateActorInstances(timePassedInSeconds); + m_eventManager->OnSimulatePhysics(timePassedInSeconds); + m_recorder->Update(timePassedInSeconds); // sample and apply all anim graphs we recorded - if (mRecorder->GetIsInPlayMode() && mRecorder->GetRecordSettings().mRecordAnimGraphStates) + if (m_recorder->GetIsInPlayMode() && m_recorder->GetRecordSettings().m_recordAnimGraphStates) { - mRecorder->SampleAndApplyAnimGraphs(mRecorder->GetCurrentPlayTime()); + m_recorder->SampleAndApplyAnimGraphs(m_recorder->GetCurrentPlayTime()); } } @@ -218,9 +216,9 @@ namespace EMotionFX MCore::LogInfo("-----------------------------------------------"); MCore::LogInfo("EMotion FX - Information"); MCore::LogInfo("-----------------------------------------------"); - MCore::LogInfo("Version: v%d.%s", mHighVersion, lowVersionString.c_str()); - MCore::LogInfo("Version string: %s", mVersionString.c_str()); - MCore::LogInfo("Compilation date: %s", mCompilationDate.c_str()); + MCore::LogInfo("Version: v%d.%s", m_highVersion, lowVersionString.c_str()); + MCore::LogInfo("Version string: %s", m_versionString.c_str()); + MCore::LogInfo("Compilation date: %s", m_compilationDate.c_str()); #ifdef MCORE_OPENMP_ENABLED MCore::LogInfo("OpenMP enabled: Yes"); @@ -235,88 +233,88 @@ namespace EMotionFX // get the version string const char* EMotionFXManager::GetVersionString() const { - return mVersionString.c_str(); + return m_versionString.c_str(); } // get the compilation date string const char* EMotionFXManager::GetCompilationDate() const { - return mCompilationDate.c_str(); + return m_compilationDate.c_str(); } // get the high version uint32 EMotionFXManager::GetHighVersion() const { - return mHighVersion; + return m_highVersion; } // get the low version uint32 EMotionFXManager::GetLowVersion() const { - return mLowVersion; + return m_lowVersion; } // set the importer void EMotionFXManager::SetImporter(Importer* importer) { - mImporter = importer; + m_importer = importer; } // set the actor manager void EMotionFXManager::SetActorManager(ActorManager* manager) { - mActorManager = manager; + m_actorManager = manager; } // set the motion manager void EMotionFXManager::SetMotionManager(MotionManager* manager) { - mMotionManager = manager; + m_motionManager = manager; } // set the event manager void EMotionFXManager::SetEventManager(EventManager* manager) { - mEventManager = manager; + m_eventManager = manager; } // set the softskin manager void EMotionFXManager::SetSoftSkinManager(SoftSkinManager* manager) { - mSoftSkinManager = manager; + m_softSkinManager = manager; } // set the anim graph manager void EMotionFXManager::SetAnimGraphManager(AnimGraphManager* manager) { - mAnimGraphManager = manager; + m_animGraphManager = manager; } // set the recorder void EMotionFXManager::SetRecorder(Recorder* recorder) { - mRecorder = recorder; + m_recorder = recorder; } void EMotionFXManager::SetDebugDraw(DebugDraw* draw) { - mDebugDraw = draw; + m_debugDraw = draw; } // set the motion instance pool void EMotionFXManager::SetMotionInstancePool(MotionInstancePool* pool) { - mMotionInstancePool = pool; + m_motionInstancePool = pool; pool->Init(); } @@ -324,19 +322,19 @@ namespace EMotionFX // set the path of the media root directory void EMotionFXManager::SetMediaRootFolder(const char* path) { - mMediaRootFolder = path; + m_mediaRootFolder = path; // Make sure the media root folder has an ending slash. - if (mMediaRootFolder.empty() == false) + if (m_mediaRootFolder.empty() == false) { - const char lastChar = AzFramework::StringFunc::LastCharacter(mMediaRootFolder.c_str()); + const char lastChar = AzFramework::StringFunc::LastCharacter(m_mediaRootFolder.c_str()); if (lastChar != AZ_CORRECT_FILESYSTEM_SEPARATOR && lastChar != AZ_WRONG_FILESYSTEM_SEPARATOR) { - AzFramework::StringFunc::Path::AppendSeparator(mMediaRootFolder); + AzFramework::StringFunc::Path::AppendSeparator(m_mediaRootFolder); } } - EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, mMediaRootFolder); + EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, m_mediaRootFolder); } @@ -346,20 +344,20 @@ namespace EMotionFX const char* assetSourcePath = AZ::IO::FileIOBase::GetInstance()->GetAlias("@devassets@"); if (assetSourcePath) { - mAssetSourceFolder = assetSourcePath; + m_assetSourceFolder = assetSourcePath; // Add an ending slash in case there is none yet. // TODO: Remove this and adopt EMotionFX code to work with folder paths without slash at the end like Open 3D Engine does. - if (mAssetSourceFolder.empty() == false) + if (m_assetSourceFolder.empty() == false) { - const char lastChar = AzFramework::StringFunc::LastCharacter(mAssetSourceFolder.c_str()); + const char lastChar = AzFramework::StringFunc::LastCharacter(m_assetSourceFolder.c_str()); if (lastChar != AZ_CORRECT_FILESYSTEM_SEPARATOR && lastChar != AZ_WRONG_FILESYSTEM_SEPARATOR) { - AzFramework::StringFunc::Path::AppendSeparator(mAssetSourceFolder); + AzFramework::StringFunc::Path::AppendSeparator(m_assetSourceFolder); } } - EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, mAssetSourceFolder); + EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, m_assetSourceFolder); } else { @@ -371,20 +369,20 @@ namespace EMotionFX const char* assetCachePath = AZ::IO::FileIOBase::GetInstance()->GetAlias("@assets@"); if (assetCachePath) { - mAssetCacheFolder = assetCachePath; + m_assetCacheFolder = assetCachePath; // Add an ending slash in case there is none yet. // TODO: Remove this and adopt EMotionFX code to work with folder paths without slash at the end like Open 3D Engine does. - if (mAssetCacheFolder.empty() == false) + if (m_assetCacheFolder.empty() == false) { - const char lastChar = AzFramework::StringFunc::LastCharacter(mAssetCacheFolder.c_str()); + const char lastChar = AzFramework::StringFunc::LastCharacter(m_assetCacheFolder.c_str()); if (lastChar != AZ_CORRECT_FILESYSTEM_SEPARATOR && lastChar != AZ_WRONG_FILESYSTEM_SEPARATOR) { - AzFramework::StringFunc::Path::AppendSeparator(mAssetCacheFolder); + AzFramework::StringFunc::Path::AppendSeparator(m_assetCacheFolder); } } - EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, mAssetCacheFolder); + EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, m_assetCacheFolder); } else { @@ -397,7 +395,7 @@ namespace EMotionFX { outAbsoluteFilename = relativeFilename; EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, outAbsoluteFilename); - AzFramework::StringFunc::Replace(outAbsoluteFilename, EMFX_MEDIAROOTFOLDER_STRING, mMediaRootFolder.c_str(), true); + AzFramework::StringFunc::Replace(outAbsoluteFilename, EMFX_MEDIAROOTFOLDER_STRING, m_mediaRootFolder.c_str(), true); } @@ -457,14 +455,14 @@ namespace EMotionFX // get the global speed factor float EMotionFXManager::GetGlobalSimulationSpeed() const { - return mGlobalSimulationSpeed; + return m_globalSimulationSpeed; } // set the global speed factor void EMotionFXManager::SetGlobalSimulationSpeed(float speedFactor) { - mGlobalSimulationSpeed = MCore::Max(0.0f, speedFactor); + m_globalSimulationSpeed = MCore::Max(0.0f, speedFactor); } @@ -477,23 +475,23 @@ namespace EMotionFX numThreads = 1; } - if (mThreadDatas.GetLength() == numThreads) + if (m_threadDatas.size() == numThreads) { return; } // get rid of old data - for (uint32 i = 0; i < mThreadDatas.GetLength(); ++i) + for (uint32 i = 0; i < m_threadDatas.size(); ++i) { - mThreadDatas[i]->Destroy(); + m_threadDatas[i]->Destroy(); } - mThreadDatas.Clear(false); // force calling constructors again to reset everything - mThreadDatas.Resize(numThreads); + m_threadDatas.clear(); // force calling constructors again to reset everything + m_threadDatas.resize(numThreads); for (uint32 i = 0; i < numThreads; ++i) { - mThreadDatas[i] = ThreadData::Create(i); + m_threadDatas[i] = ThreadData::Create(i); } } @@ -502,21 +500,21 @@ namespace EMotionFX void EMotionFXManager::ShrinkPools() { Allocators::ShrinkPools(); - mMotionInstancePool->Shrink(); + m_motionInstancePool->Shrink(); } // get the unit type MCore::Distance::EUnitType EMotionFXManager::GetUnitType() const { - return mUnitType; + return m_unitType; } // set the unit type void EMotionFXManager::SetUnitType(MCore::Distance::EUnitType unitType) { - mUnitType = unitType; + m_unitType = unitType; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h index 824cc95850..d5c5247de6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EMotionFXManager.h @@ -10,7 +10,7 @@ // include the required headers #include "EMotionFXConfig.h" -#include +#include #include #include "ThreadData.h" #include "BaseObject.h" @@ -124,28 +124,28 @@ namespace EMotionFX * This can also be accessed with the GetImporter() macro. * @result A pointer to the importer. */ - MCORE_INLINE Importer* GetImporter() const { return mImporter; } + MCORE_INLINE Importer* GetImporter() const { return m_importer; } /** * Get the actor manager. * This can also be accessed with the GetActorManager() macro. * @result A pointer to the actor manager. */ - MCORE_INLINE ActorManager* GetActorManager() const { return mActorManager; } + MCORE_INLINE ActorManager* GetActorManager() const { return m_actorManager; } /** * Get the motion manager. * This can also be accessed with the GetMotionManager() macro. * @result A pointer to the motion manager. */ - MCORE_INLINE MotionManager* GetMotionManager() const { return mMotionManager; } + MCORE_INLINE MotionManager* GetMotionManager() const { return m_motionManager; } /** * Get the event manager. * This can also be accessed with the GetEventManager() macro. * @result A pointer to the event manager. */ - MCORE_INLINE EventManager* GetEventManager() const { return mEventManager; } + MCORE_INLINE EventManager* GetEventManager() const { return m_eventManager; } /** * Get the soft-skin manager. @@ -155,41 +155,34 @@ namespace EMotionFX * This can also be accessed with the GetSoftSkinManager() macro. * @result A pointer to the soft-skinning manager. */ - MCORE_INLINE SoftSkinManager* GetSoftSkinManager() const { return mSoftSkinManager; } + MCORE_INLINE SoftSkinManager* GetSoftSkinManager() const { return m_softSkinManager; } /** * Get the motion instance pool. * This can also be accessed with the GetMotionInstancePool() macro. * @result A pointer to the motion instance pool. */ - MCORE_INLINE MotionInstancePool* GetMotionInstancePool() const { return mMotionInstancePool; } + MCORE_INLINE MotionInstancePool* GetMotionInstancePool() const { return m_motionInstancePool; } /** * Get the animgraph manager; * This can also be accessed with the GetAnimGraphManager() macro. * @result A pointer to the animgraph manager. */ - MCORE_INLINE AnimGraphManager* GetAnimGraphManager() const { return mAnimGraphManager; } - - /** - * Get the rig manager; - * This can also be accessed with the GetRigManager() macro. - * @result A pointer to the animgraph manager. - */ - // MCORE_INLINE RigManager* GetRigManager() const { return mRigManager; } + MCORE_INLINE AnimGraphManager* GetAnimGraphManager() const { return m_animGraphManager; } /** * Get the recorder. * This can also be accessed with the EMFX_RECODRER macro. * @result A pointer to the recorder. */ - MCORE_INLINE Recorder* GetRecorder() const { return mRecorder; } + MCORE_INLINE Recorder* GetRecorder() const { return m_recorder; } /** * Get the debug drawing class. * @result A pointer to the wavelet cache. */ - MCORE_INLINE DebugDraw* GetDebugDraw() const { return mDebugDraw; } + MCORE_INLINE DebugDraw* GetDebugDraw() const { return m_debugDraw; } /** * Set the path of the media root directory. @@ -243,38 +236,38 @@ namespace EMotionFX * Get the path of the media root folder. * @result The path of the media root directory. */ - MCORE_INLINE const char* GetMediaRootFolder() const { return mMediaRootFolder.c_str(); } + MCORE_INLINE const char* GetMediaRootFolder() const { return m_mediaRootFolder.c_str(); } /** * Get the path of the media root folder as a string object. * @result The path of the media root directory. */ - MCORE_INLINE const AZStd::string& GetMediaRootFolderString() const { return mMediaRootFolder; } + MCORE_INLINE const AZStd::string& GetMediaRootFolderString() const { return m_mediaRootFolder; } /** * Get the asset source folder path. * @result The path of the asset source folder. */ - MCORE_INLINE const AZStd::string& GetAssetSourceFolder() const { return mAssetSourceFolder; } + MCORE_INLINE const AZStd::string& GetAssetSourceFolder() const { return m_assetSourceFolder; } /** * Get the asset cache folder path. * @result The path of the asset cache folder. */ - MCORE_INLINE const AZStd::string& GetAssetCacheFolder() const { return mAssetCacheFolder; } + MCORE_INLINE const AZStd::string& GetAssetCacheFolder() const { return m_assetCacheFolder; } /** * Get the unique per thread data for a given thread by index. * @param threadIndex The thread index, which must be between [0..GetNumThreads()-1]. * @return The unique thread data for this thread. */ - MCORE_INLINE ThreadData* GetThreadData(uint32 threadIndex) const { MCORE_ASSERT(threadIndex < mThreadDatas.GetLength()); return mThreadDatas[threadIndex]; } + MCORE_INLINE ThreadData* GetThreadData(uint32 threadIndex) const { MCORE_ASSERT(threadIndex < m_threadDatas.size()); return m_threadDatas[threadIndex]; } /** * Get the number of threads that are internally created. * @return The number of threads that we have internally created. */ - MCORE_INLINE uint32 GetNumThreads() const { return mThreadDatas.GetLength(); } + MCORE_INLINE size_t GetNumThreads() const { return m_threadDatas.size(); } /** * Shrink the memory pools, to reduce memory usage. @@ -338,25 +331,25 @@ namespace EMotionFX bool GetEnableServerOptimization() const { return m_isInServerMode && m_enableServerOptimization; } private: - AZStd::string mVersionString; /**< The version string. */ - AZStd::string mCompilationDate; /**< The compilation date string. */ - AZStd::string mMediaRootFolder; /**< The path of the media root directory. */ - AZStd::string mAssetSourceFolder; /**< The absolute path of the asset source folder. */ - AZStd::string mAssetCacheFolder; /**< The absolute path of the asset cache folder. */ - uint32 mHighVersion; /**< The higher version, which would be 3 in case of v3.01. */ - uint32 mLowVersion; /**< The low version, which would be 100 in case of v3.10 or 10 in case of v3.01. */ - Importer* mImporter; /**< The importer that can load actors and motions. */ - ActorManager* mActorManager; /**< The actor manager. */ - MotionManager* mMotionManager; /**< The motion manager. */ - EventManager* mEventManager; /**< The motion event manager. */ - SoftSkinManager* mSoftSkinManager; /**< The softskin manager. */ - AnimGraphManager* mAnimGraphManager; /**< The animgraph manager. */ - Recorder* mRecorder; /**< The recorder. */ - MotionInstancePool* mMotionInstancePool; /**< The motion instance pool. */ - DebugDraw* mDebugDraw; /**< The debug drawing system. */ - MCore::Array mThreadDatas; /**< The per thread data. */ - MCore::Distance::EUnitType mUnitType; /**< The unit type, on default it is MCore::Distance::UNITTYPE_METERS. */ - float mGlobalSimulationSpeed; /**< The global simulation speed, default is 1.0. */ + AZStd::string m_versionString; /**< The version string. */ + AZStd::string m_compilationDate; /**< The compilation date string. */ + AZStd::string m_mediaRootFolder; /**< The path of the media root directory. */ + AZStd::string m_assetSourceFolder; /**< The absolute path of the asset source folder. */ + AZStd::string m_assetCacheFolder; /**< The absolute path of the asset cache folder. */ + uint32 m_highVersion; /**< The higher version, which would be 3 in case of v3.01. */ + uint32 m_lowVersion; /**< The low version, which would be 100 in case of v3.10 or 10 in case of v3.01. */ + Importer* m_importer; /**< The importer that can load actors and motions. */ + ActorManager* m_actorManager; /**< The actor manager. */ + MotionManager* m_motionManager; /**< The motion manager. */ + EventManager* m_eventManager; /**< The motion event manager. */ + SoftSkinManager* m_softSkinManager; /**< The softskin manager. */ + AnimGraphManager* m_animGraphManager; /**< The animgraph manager. */ + Recorder* m_recorder; /**< The recorder. */ + MotionInstancePool* m_motionInstancePool; /**< The motion instance pool. */ + DebugDraw* m_debugDraw; /**< The debug drawing system. */ + AZStd::vector m_threadDatas; /**< The per thread data. */ + MCore::Distance::EUnitType m_unitType; /**< The unit type, on default it is MCore::Distance::UNITTYPE_METERS. */ + float m_globalSimulationSpeed; /**< The global simulation speed, default is 1.0. */ bool m_isInEditorMode; /**< True when the runtime requires to support an editor. Optimizations can be made if there is no need for editor support. */ bool m_isInServerMode; /**< True when emotionfx is running on server. */ bool m_enableServerOptimization; /**< True when optimization can be made when emotionfx is running in server mode. */ @@ -454,11 +447,11 @@ namespace EMotionFX */ struct EMFX_API InitSettings { - MCore::Distance::EUnitType mUnitType; /**< The unit type to use. This specifies the size of one unit. On default this is a meter. */ + MCore::Distance::EUnitType m_unitType; /**< The unit type to use. This specifies the size of one unit. On default this is a meter. */ InitSettings() { - mUnitType = MCore::Distance::UNITTYPE_METERS; + m_unitType = MCore::Distance::UNITTYPE_METERS; } }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h b/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h index 19024bb351..9c8b0ecbfb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EventHandler.h @@ -121,7 +121,7 @@ namespace EMotionFX { MCORE_UNUSED(eventInfo); // find the event index in the array - // const uint32 eventIndex = GetEventManager().FindEventTypeIndex( eventInfo.mEventTypeID ); + // const uint32 eventIndex = GetEventManager().FindEventTypeIndex( eventInfo.m_eventTypeID ); // get the name of the event // const char* eventName = (eventIndex != MCORE_INVALIDINDEX32) ? GetEventManager().GetEventTypeString( eventIndex ) : ""; @@ -273,7 +273,7 @@ namespace EMotionFX /** * This event gets triggered once the given motion instance gets added to the motion queue. - * This happens when you set the PlayBackInfo::mPlayNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) + * This happens when you set the PlayBackInfo::m_playNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) * will not directly start playing the motion (OnStartMotionInstance), but will add it to the motion queue instead. * The motion queue will then start playing the motion instance once it should. * @param motionInstance The motion instance that gets added to the motion queue. @@ -316,7 +316,7 @@ namespace EMotionFX /** * Perform a ray intersection test and return the intersection info. - * The first event handler registered that sets the IntersectionInfo::mIsValid to true will be outputting to the outIntersectInfo parameter. + * The first event handler registered that sets the IntersectionInfo::m_isValid to true will be outputting to the outIntersectInfo parameter. * @param start The start point, in world space. * @param end The end point, in world space. * @param outIntersectInfo The resulting intersection info. @@ -330,7 +330,7 @@ namespace EMotionFX virtual void OnStateEnd(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(state); } virtual void OnStartTransition(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(transition); } virtual void OnEndTransition(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(transition); } - virtual void OnSetVisualManipulatorOffset(AnimGraphInstance* animGraphInstance, uint32 paramIndex, const AZ::Vector3& offset) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(paramIndex); MCORE_UNUSED(offset); } + virtual void OnSetVisualManipulatorOffset(AnimGraphInstance* animGraphInstance, size_t paramIndex, const AZ::Vector3& offset) { MCORE_UNUSED(animGraphInstance); MCORE_UNUSED(paramIndex); MCORE_UNUSED(offset); } virtual void OnInputPortsChanged(AnimGraphNode* node, const AZStd::vector& newInputPorts, const AZStd::string& memberName, const AZStd::vector& memberValue) { AZ_UNUSED(node); AZ_UNUSED(newInputPorts); AZ_UNUSED(memberName); AZ_UNUSED(memberValue); } virtual void OnOutputPortsChanged(AnimGraphNode* node, const AZStd::vector& newOutputPorts, const AZStd::string& memberName, const AZStd::vector& memberValue) { AZ_UNUSED(node); AZ_UNUSED(newOutputPorts); AZ_UNUSED(memberName); AZ_UNUSED(memberValue); } @@ -395,8 +395,8 @@ namespace EMotionFX */ virtual const AZStd::vector GetHandledEventTypes() const = 0; - void SetMotionInstance(MotionInstance* motionInstance) { mMotionInstance = motionInstance; } - MCORE_INLINE MotionInstance* GetMotionInstance() { return mMotionInstance; } + void SetMotionInstance(MotionInstance* motionInstance) { m_motionInstance = motionInstance; } + MCORE_INLINE MotionInstance* GetMotionInstance() { return m_motionInstance; } /** * The method that processes an event. @@ -495,7 +495,7 @@ namespace EMotionFX /** * This event gets triggered once the given motion instance gets added to the motion queue. - * This happens when you set the PlayBackInfo::mPlayNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) + * This happens when you set the PlayBackInfo::m_playNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) * will not directly start playing the motion (OnStartMotionInstance), but will add it to the motion queue instead. * The motion queue will then start playing the motion instance once it should. * @param info The playback information used to play this motion instance. @@ -503,6 +503,6 @@ namespace EMotionFX virtual void OnQueueMotionInstance(PlayBackInfo* info) { MCORE_UNUSED(info); } protected: - MotionInstance* mMotionInstance = nullptr; + MotionInstance* m_motionInstance = nullptr; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EventInfo.h b/Gems/EMotionFX/Code/EMotionFX/Source/EventInfo.h index 1633d4fae7..6b97974fd3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EventInfo.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EventInfo.h @@ -37,13 +37,13 @@ namespace EMotionFX END }; - float mTimeValue; /**< The time value of the event, in seconds. */ - ActorInstance* mActorInstance; /**< The actor instance that triggered this event. */ - const MotionInstance* mMotionInstance; /**< The motion instance which triggered this event, can be nullptr. */ - AnimGraphNode* mEmitter; /**< The animgraph node which originally did emit this event. This parameter can be nullptr. */ - const MotionEvent* mEvent; /**< The event itself. */ - float mGlobalWeight; /**< The global weight of the event. */ - float mLocalWeight; /**< The local weight of the event. */ + float m_timeValue; /**< The time value of the event, in seconds. */ + ActorInstance* m_actorInstance; /**< The actor instance that triggered this event. */ + const MotionInstance* m_motionInstance; /**< The motion instance which triggered this event, can be nullptr. */ + AnimGraphNode* m_emitter; /**< The animgraph node which originally did emit this event. This parameter can be nullptr. */ + const MotionEvent* m_event; /**< The event itself. */ + float m_globalWeight; /**< The global weight of the event. */ + float m_localWeight; /**< The local weight of the event. */ EventState m_eventState; /**< Is this the start of a ranged event? Ticked events will always have this set to true. */ bool IsEventStart() const @@ -58,13 +58,13 @@ namespace EMotionFX MotionEvent* event = nullptr, EventState eventState = START ) - : mTimeValue(timeValue) - , mActorInstance(actorInstance) - , mMotionInstance(motionInstance) - , mEmitter(nullptr) - , mEvent(event) - , mGlobalWeight(1.0f) - , mLocalWeight(1.0f) + : m_timeValue(timeValue) + , m_actorInstance(actorInstance) + , m_motionInstance(motionInstance) + , m_emitter(nullptr) + , m_event(event) + , m_globalWeight(1.0f) + , m_localWeight(1.0f) , m_eventState(eventState) { } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.cpp index e3b4c351ef..b39fcbab99 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.cpp @@ -53,21 +53,21 @@ namespace EMotionFX // lock the event manager void EventManager::Lock() { - mLock.Lock(); + m_lock.Lock(); } // unlock the event manager void EventManager::Unlock() { - mLock.Unlock(); + m_lock.Unlock(); } // register event handler to the manager void EventManager::AddEventHandler(EventHandler* eventHandler) { - MCore::LockGuardRecursive lock(mLock); + MCore::LockGuardRecursive lock(m_lock); AZ_Assert(eventHandler, "Expected non-null event handler"); for (const EventTypes eventType : eventHandler->GetHandledEventTypes()) @@ -82,7 +82,7 @@ namespace EMotionFX // unregister event handler from the manager void EventManager::RemoveEventHandler(EventHandler* eventHandler) { - MCore::LockGuardRecursive lock(mLock); + MCore::LockGuardRecursive lock(m_lock); for (const EventTypes eventType : eventHandler->GetHandledEventTypes()) { @@ -101,9 +101,9 @@ namespace EMotionFX } // trigger the event handlers inside the motion instance - if (eventInfo.mMotionInstance) + if (eventInfo.m_motionInstance) { - eventInfo.mMotionInstance->OnEvent(eventInfo); + eventInfo.m_motionInstance->OnEvent(eventInfo); } // Call event handlers @@ -570,7 +570,7 @@ namespace EMotionFX for (EventHandler* eventHandler : eventHandlers) { const bool result = eventHandler->OnRayIntersectionTest(start, end, outIntersectInfo); - if (outIntersectInfo->mIsValid) + if (outIntersectInfo->m_isValid) { return result; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h index 5f87b66388..356ffe05ae 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/EventManager.h @@ -11,7 +11,7 @@ // include the required headers #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include #include #include "MemoryCategories.h" #include "MotionInstance.h" @@ -40,31 +40,31 @@ namespace EMotionFX */ struct EMFX_API IntersectionInfo { - AZ::Vector3 mPosition; - AZ::Vector3 mNormal; - AZ::Vector2 mUV; - float mBaryCentricU; - float mBaryCentricV; - ActorInstance* mActorInstance; - ActorInstance* mIgnoreActorInstance; - Node* mNode; - Mesh* mMesh; - uint32 mStartIndex; - bool mIsValid; + AZ::Vector3 m_position; + AZ::Vector3 m_normal; + AZ::Vector2 m_uv; + float m_baryCentricU; + float m_baryCentricV; + ActorInstance* m_actorInstance; + ActorInstance* m_ignoreActorInstance; + Node* m_node; + Mesh* m_mesh; + uint32 m_startIndex; + bool m_isValid; IntersectionInfo() { - mPosition = AZ::Vector3::CreateZero(); - mNormal.Set(0.0f, 1.0f, 0.0f); - mUV = AZ::Vector2::CreateZero(); - mBaryCentricU = 0.0f; - mBaryCentricV = 0.0f; - mActorInstance = nullptr; - mStartIndex = 0; - mIgnoreActorInstance = nullptr; - mNode = nullptr; - mMesh = nullptr; - mIsValid = false; + m_position = AZ::Vector3::CreateZero(); + m_normal.Set(0.0f, 1.0f, 0.0f); + m_uv = AZ::Vector2::CreateZero(); + m_baryCentricU = 0.0f; + m_baryCentricV = 0.0f; + m_actorInstance = nullptr; + m_startIndex = 0; + m_ignoreActorInstance = nullptr; + m_node = nullptr; + m_mesh = nullptr; + m_isValid = false; } }; @@ -263,7 +263,7 @@ namespace EMotionFX /** * This event gets triggered once the given motion instance gets added to the motion queue. - * This happens when you set the PlayBackInfo::mPlayNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) + * This happens when you set the PlayBackInfo::m_playNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) * will not directly start playing the motion (OnStartMotionInstance), but will add it to the motion queue instead. * The motion queue will then start playing the motion instance once it should. * @param motionInstance The motion instance that gets added to the motion queue. @@ -292,7 +292,7 @@ namespace EMotionFX /** * Perform a ray intersection test and return the intersection info. - * The first event handler registered that sets the IntersectionInfo::mIsValid to true will be outputting to the outIntersectInfo parameter. + * The first event handler registered that sets the IntersectionInfo::m_isValid to true will be outputting to the outIntersectInfo parameter. * @param start The start point, in world space. * @param end The end point, in world space. * @param outIntersectInfo The resulting intersection info. @@ -347,14 +347,14 @@ namespace EMotionFX */ struct EMFX_API RegisteredEventType { - AZStd::string mEventType; /**< The string that describes the event, this is what artists type in 3DSMax/Maya. */ - uint32 mEventID; /**< The unique ID for this event. */ + AZStd::string m_eventType; /**< The string that describes the event, this is what artists type in 3DSMax/Maya. */ + uint32 m_eventId; /**< The unique ID for this event. */ }; using EventHandlerVector = AZStd::vector; AZStd::vector m_eventHandlersByEventType; /**< The event handler to use to process events organized by EventTypes. */ - MCore::MutexRecursive mLock; + MCore::MutexRecursive m_lock; AZStd::mutex m_eventDataLock; AZStd::vector > m_allEventData; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h index b8a5cc9616..e4df8d0cc8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ActorFileFormat.h @@ -38,23 +38,23 @@ namespace EMotionFX // (aligned) struct Actor_Header { - uint8 mFourcc[4]; // must be "ACTR" - uint8 mHiVersion; // high version (2 in case of v2.34) - uint8 mLoVersion; // low version (34 in case of v2.34) - uint8 mEndianType; // the endian in which the data is saved [0=little, 1=big] + uint8 m_fourcc[4]; // must be "ACTR" + uint8 m_hiVersion; // high version (2 in case of v2.34) + uint8 m_loVersion; // low version (34 in case of v2.34) + uint8 m_endianType; // the endian in which the data is saved [0=little, 1=big] }; // (not aligned) struct Actor_Info { - uint32 mNumLODs; // the number of level of details - uint32 mTrajectoryNodeIndex; // the node number of the trajectory node used for motion extraction (NOTE: unused as there is no more trajectory node) - uint32 mMotionExtractionNodeIndex;// the node number of the trajectory node used for motion extraction - float mRetargetRootOffset; - uint8 mUnitType; // maps to EMotionFX::EUnitType - uint8 mExporterHighVersion; - uint8 mExporterLowVersion; + uint32 m_numLoDs; // the number of level of details + uint32 m_trajectoryNodeIndex; // the node number of the trajectory node used for motion extraction (NOTE: unused as there is no more trajectory node) + uint32 m_motionExtractionNodeIndex;// the node number of the trajectory node used for motion extraction + float m_retargetRootOffset; + uint8 m_unitType; // maps to EMotionFX::EUnitType + uint8 m_exporterHighVersion; + uint8 m_exporterLowVersion; // followed by: // string : source application (e.g. "3ds Max 2011", "Maya 2011") @@ -67,12 +67,12 @@ namespace EMotionFX // (not aligned) struct Actor_Info2 { - uint32 mNumLODs; // the number of level of details - uint32 mMotionExtractionNodeIndex;// the node number of the trajectory node used for motion extraction - uint32 mRetargetRootNodeIndex; // the retargeting root node index, most likely pointing to the hip or pelvis or MCORE_INVALIDINDEX32 when not set - uint8 mUnitType; // maps to EMotionFX::EUnitType - uint8 mExporterHighVersion; - uint8 mExporterLowVersion; + uint32 m_numLoDs; // the number of level of details + uint32 m_motionExtractionNodeIndex;// the node number of the trajectory node used for motion extraction + uint32 m_retargetRootNodeIndex; // the retargeting root node index, most likely pointing to the hip or pelvis or MCORE_INVALIDINDEX32 when not set + uint8 m_unitType; // maps to EMotionFX::EUnitType + uint8 m_exporterHighVersion; + uint8 m_exporterLowVersion; // followed by: // string : source application (e.g. "3ds Max 2011", "Maya 2011") @@ -85,13 +85,13 @@ namespace EMotionFX // (aligned) struct Actor_Info3 { - uint32 mNumLODs; // the number of level of details - uint32 mMotionExtractionNodeIndex;// the node number of the trajectory node used for motion extraction - uint32 mRetargetRootNodeIndex; // the retargeting root node index, most likely pointing to the hip or pelvis or MCORE_INVALIDINDEX32 when not set - uint8 mUnitType; // maps to EMotionFX::EUnitType - uint8 mExporterHighVersion; - uint8 mExporterLowVersion; - uint8 mOptimizeSkeleton; + uint32 m_numLoDs; // the number of level of details + uint32 m_motionExtractionNodeIndex;// the node number of the trajectory node used for motion extraction + uint32 m_retargetRootNodeIndex; // the retargeting root node index, most likely pointing to the hip or pelvis or MCORE_INVALIDINDEX32 when not set + uint8 m_unitType; // maps to EMotionFX::EUnitType + uint8 m_exporterHighVersion; + uint8 m_exporterLowVersion; + uint8 m_optimizeSkeleton; // followed by: // string : source application (e.g. "3ds Max 2011", "Maya 2011") @@ -108,16 +108,15 @@ namespace EMotionFX // a node header // (not aligned) - struct Actor_Node + struct Actor_Node2 { - FileQuaternion mLocalQuat; // the local rotation (before hierarchy) - FileVector3 mLocalPos; // the local translation (before hierarchy) - FileVector3 mLocalScale;// the local scale (before hierarchy) - uint32 mSkeletalLODs;// each bit representing if the node is active or not, in the give LOD (bit number) - uint32 mParentIndex;// parent node number, or 0xFFFFFFFF in case of a root node - uint32 mNumChilds; // the number of child nodes - uint8 mNodeFlags; // #1 bit boolean specifies whether we have to include this node in the bounds calculation or not - float mOBB[16]; + FileQuaternion m_localQuat; // the local rotation (before hierarchy) + FileVector3 m_localPos; // the local translation (before hierarchy) + FileVector3 m_localScale;// the local scale (before hierarchy) + uint32 m_skeletalLoDs;// each bit representing if the node is active or not, in the give LOD (bit number) + uint32 m_parentIndex;// parent node number, or 0xFFFFFFFF in case of a root node + uint32 m_numChilds; // the number of child nodes + uint8 m_nodeFlags; // #1 bit boolean specifies whether we have to include this node in the bounds calculation or not // followed by: // string : node name (the unique name of the node) @@ -127,8 +126,8 @@ namespace EMotionFX // (aligned) struct Actor_UV { - float mU; - float mV; + float m_u; + float m_v; }; //------------------------------------------------------- @@ -137,14 +136,14 @@ namespace EMotionFX // (aligned) struct Actor_Limit { - FileVector3 mTranslationMin;// the minimum translation values - FileVector3 mTranslationMax;// the maximum translation value. - FileVector3 mRotationMin; // the minimum rotation values - FileVector3 mRotationMax; // the maximum rotation values - FileVector3 mScaleMin; // the minimum scale values - FileVector3 mScaleMax; // the maximum scale values - uint8 mLimitFlags[9]; // the limit type activation flags - uint32 mNodeNumber; // the node number where this info belongs to + FileVector3 m_translationMin;// the minimum translation values + FileVector3 m_translationMax;// the maximum translation value. + FileVector3 m_rotationMin; // the minimum rotation values + FileVector3 m_rotationMax; // the maximum rotation values + FileVector3 m_scaleMin; // the minimum scale values + FileVector3 m_scaleMax; // the maximum scale values + uint8 m_limitFlags[9]; // the limit type activation flags + uint32 m_nodeNumber; // the node number where this info belongs to }; @@ -152,15 +151,15 @@ namespace EMotionFX // (aligned) struct Actor_MorphTarget { - float mRangeMin; // the slider min - float mRangeMax; // the slider max - uint32 mLOD; // the level of detail to which this expression part belongs to - uint32 mNumTransformations;// the number of transformations to follow - uint32 mPhonemeSets; // the number of phoneme sets to follow + float m_rangeMin; // the slider min + float m_rangeMax; // the slider max + uint32 m_lod; // the level of detail to which this expression part belongs to + uint32 m_numTransformations;// the number of transformations to follow + uint32 m_phonemeSets; // the number of phoneme sets to follow // followed by: // string : morph target name - // Actor_MorphTargetTransform[ mNumTransformations ] + // Actor_MorphTargetTransform[ m_numTransformations ] }; @@ -168,11 +167,11 @@ namespace EMotionFX // (aligned) struct Actor_MorphTargets { - uint32 mNumMorphTargets; // the number of morph targets to follow - uint32 mLOD; // the LOD level the morph targets are for + uint32 m_numMorphTargets; // the number of morph targets to follow + uint32 m_lod; // the LOD level the morph targets are for // followed by: - // Actor_MorphTarget[ mNumMorphTargets ] + // Actor_MorphTarget[ m_numMorphTargets ] }; @@ -180,11 +179,11 @@ namespace EMotionFX // (aligned) struct Actor_MorphTargetTransform { - uint32 mNodeIndex; // the node name where the transform belongs to - FileQuaternion mRotation; // the node rotation - FileQuaternion mScaleRotation; // the node delta scale rotation - FileVector3 mPosition; // the node delta position - FileVector3 mScale; // the node delta scale + uint32 m_nodeIndex; // the node name where the transform belongs to + FileQuaternion m_rotation; // the node rotation + FileQuaternion m_scaleRotation; // the node delta scale rotation + FileVector3 m_position; // the node delta position + FileVector3 m_scale; // the node delta scale }; @@ -192,33 +191,30 @@ namespace EMotionFX // (not aligned) struct Actor_NodeGroup { - uint16 mNumNodes; - uint8 mDisabledOnDefault; // 0 = no, 1 = yes + uint16 m_numNodes; + uint8 m_disabledOnDefault; // 0 = no, 1 = yes // followed by: // string : name - // uint16 [mNumNodes] + // uint16 [m_numNodes] }; - // (aligned) - struct Actor_Nodes + struct Actor_Nodes2 { - uint32 mNumNodes; - uint32 mNumRootNodes; - FileVector3 mStaticBoxMin; - FileVector3 mStaticBoxMax; - // followed by Actor_Node4[mNumNodes] or Actor_NODE5[mNumNodes] (for v2) + uint32 m_numNodes; + uint32 m_numRootNodes; + // followed by Actor_Node4[m_numNodes] or Actor_NODE5[m_numNodes] (for v2) }; // node motion sources used for the motion mirroring feature // (aligned) struct Actor_NodeMotionSources2 { - uint32 mNumNodes; - // followed by uint16[mNumNodes] // an index per node, which indicates the index of the node to extract the motion data from in case mirroring for a given motion is enabled. This array can be nullptr in case no mirroring data has been setup. - // followed by uint8[mNumNodes] // axis identifier (0=X, 1=Y, 2=Z) - // followed by uint8[mNumNodes] // flags identifier (see Actor::MirrorFlags) + uint32 m_numNodes; + // followed by uint16[m_numNodes] // an index per node, which indicates the index of the node to extract the motion data from in case mirroring for a given motion is enabled. This array can be nullptr in case no mirroring data has been setup. + // followed by uint8[m_numNodes] // axis identifier (0=X, 1=Y, 2=Z) + // followed by uint8[m_numNodes] // flags identifier (see Actor::MirrorFlags) }; @@ -226,8 +222,8 @@ namespace EMotionFX // (aligned) struct Actor_AttachmentNodes { - uint32 mNumNodes; - // followed by uint16[mNumNodes] // an index per attachment node + uint32 m_numNodes; + // followed by uint16[m_numNodes] // an index per attachment node }; } // namespace FileFormat } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp index 3cec3b599c..7d800f8928 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp @@ -244,12 +244,12 @@ namespace EMotionFX // constructor SharedHelperData::SharedHelperData() { - mFileHighVersion = 1; - mFileLowVersion = 0; + m_fileHighVersion = 1; + m_fileLowVersion = 0; // allocate the string buffer used for reading in variable sized strings - mStringStorageSize = 256; - mStringStorage = (char*)MCore::Allocate(mStringStorageSize, EMFX_MEMCATEGORY_IMPORTER); + m_stringStorageSize = 256; + m_stringStorage = (char*)MCore::Allocate(m_stringStorageSize, EMFX_MEMCATEGORY_IMPORTER); } @@ -271,16 +271,16 @@ namespace EMotionFX void SharedHelperData::Reset() { // free the string buffer - if (mStringStorage) + if (m_stringStorage) { - MCore::Free(mStringStorage); + MCore::Free(m_stringStorage); } - mStringStorage = nullptr; - mStringStorageSize = 0; + m_stringStorage = nullptr; + m_stringStorageSize = 0; } - const char* SharedHelperData::ReadString(MCore::Stream* file, MCore::Array* sharedData, MCore::Endian::EEndianType endianType) + const char* SharedHelperData::ReadString(MCore::Stream* file, AZStd::vector* sharedData, MCore::Endian::EEndianType endianType) { MCORE_ASSERT(file); MCORE_ASSERT(sharedData); @@ -295,23 +295,17 @@ namespace EMotionFX MCore::Endian::ConvertUnsignedInt32(&numCharacters, endianType); // if we need to enlarge the buffer - if (helperData->mStringStorageSize < numCharacters + 1) + if (helperData->m_stringStorageSize < numCharacters + 1) { - helperData->mStringStorageSize = numCharacters + 1; - helperData->mStringStorage = (char*)MCore::Realloc(helperData->mStringStorage, helperData->mStringStorageSize, EMFX_MEMCATEGORY_IMPORTER); + helperData->m_stringStorageSize = numCharacters + 1; + helperData->m_stringStorage = (char*)MCore::Realloc(helperData->m_stringStorage, helperData->m_stringStorageSize, EMFX_MEMCATEGORY_IMPORTER); } // receive the actual string - file->Read(helperData->mStringStorage, numCharacters * sizeof(uint8)); - helperData->mStringStorage[numCharacters] = '\0'; + file->Read(helperData->m_stringStorage, numCharacters * sizeof(uint8)); + helperData->m_stringStorage[numCharacters] = '\0'; - //if (helperData->mIsUnicodeFile) - //helperData->mConvertString = helperData->mStringStorage; - //else - // helperData->mConvertString = helperData->mStringStorage; - - //result = helperData->mStringStorage; - return helperData->mStringStorage; + return helperData->m_stringStorage; } //----------------------------------------------------------------------------- @@ -320,9 +314,9 @@ namespace EMotionFX ChunkProcessor::ChunkProcessor(uint32 chunkID, uint32 version) : BaseObject() { - mChunkID = chunkID; - mVersion = version; - mLoggingActive = false; + m_chunkId = chunkID; + m_version = version; + m_loggingActive = false; } @@ -334,100 +328,80 @@ namespace EMotionFX uint32 ChunkProcessor::GetChunkID() const { - return mChunkID; + return m_chunkId; } uint32 ChunkProcessor::GetVersion() const { - return mVersion; + return m_version; } void ChunkProcessor::SetLogging(bool loggingActive) { - mLoggingActive = loggingActive; + m_loggingActive = loggingActive; } bool ChunkProcessor::GetLogging() const { - return mLoggingActive; + return m_loggingActive; } - //================================================================================================= - - // a chunk that contains all nodes in one chunk - bool ChunkProcessorActorNodes::Process(MCore::File* file, Importer::ImportParameters& importParams) + bool ChunkProcessorActorNodes2::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; - Importer::ActorSettings* actorSettings = importParams.mActorSettings; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; + Importer::ActorSettings* actorSettings = importParams.m_actorSettings; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); - FileFormat::Actor_Nodes nodesHeader; - file->Read(&nodesHeader, sizeof(FileFormat::Actor_Nodes)); + FileFormat::Actor_Nodes2 nodesHeader; + file->Read(&nodesHeader, sizeof(FileFormat::Actor_Nodes2)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&nodesHeader.mNumNodes, endianType); - MCore::Endian::ConvertUnsignedInt32(&nodesHeader.mNumRootNodes, endianType); - MCore::Endian::ConvertFloat(&nodesHeader.mStaticBoxMin.mX, endianType); - MCore::Endian::ConvertFloat(&nodesHeader.mStaticBoxMin.mY, endianType); - MCore::Endian::ConvertFloat(&nodesHeader.mStaticBoxMin.mZ, endianType); - MCore::Endian::ConvertFloat(&nodesHeader.mStaticBoxMax.mX, endianType); - MCore::Endian::ConvertFloat(&nodesHeader.mStaticBoxMax.mY, endianType); - MCore::Endian::ConvertFloat(&nodesHeader.mStaticBoxMax.mZ, endianType); - - // convert endian and coord system of the static box - AZ::Vector3 boxMin(nodesHeader.mStaticBoxMin.mX, nodesHeader.mStaticBoxMin.mY, nodesHeader.mStaticBoxMin.mZ); - AZ::Vector3 boxMax(nodesHeader.mStaticBoxMax.mX, nodesHeader.mStaticBoxMax.mY, nodesHeader.mStaticBoxMax.mZ); - - // build the box and set it - MCore::AABB staticBox; - staticBox.SetMin(boxMin); - staticBox.SetMax(boxMax); - actor->SetStaticAABB(staticBox); + MCore::Endian::ConvertUnsignedInt32(&nodesHeader.m_numNodes, endianType); + MCore::Endian::ConvertUnsignedInt32(&nodesHeader.m_numRootNodes, endianType); // pre-allocate space for the nodes - actor->SetNumNodes(nodesHeader.mNumNodes); + actor->SetNumNodes(nodesHeader.m_numNodes); // pre-allocate space for the root nodes - skeleton->ReserveRootNodes(nodesHeader.mNumRootNodes); + skeleton->ReserveRootNodes(nodesHeader.m_numRootNodes); if (GetLogging()) { - MCore::LogDetailedInfo("- Nodes: %d (%d root nodes)", nodesHeader.mNumNodes, nodesHeader.mNumRootNodes); + MCore::LogDetailedInfo("- Nodes: %d (%d root nodes)", nodesHeader.m_numNodes, nodesHeader.m_numRootNodes); } // add the transform actor->ResizeTransformData(); // read all nodes - for (uint32 n = 0; n < nodesHeader.mNumNodes; ++n) + for (uint32 n = 0; n < nodesHeader.m_numNodes; ++n) { // read the node header - FileFormat::Actor_Node nodeChunk; - file->Read(&nodeChunk, sizeof(FileFormat::Actor_Node)); + FileFormat::Actor_Node2 nodeChunk; + file->Read(&nodeChunk, sizeof(FileFormat::Actor_Node2)); // read the node name - const char* nodeName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* nodeName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // convert endian - MCore::Endian::ConvertUnsignedInt32(&nodeChunk.mParentIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&nodeChunk.mSkeletalLODs, endianType); - MCore::Endian::ConvertUnsignedInt32(&nodeChunk.mNumChilds, endianType); - MCore::Endian::ConvertFloat(&nodeChunk.mOBB[0], endianType, 16); + MCore::Endian::ConvertUnsignedInt32(&nodeChunk.m_parentIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&nodeChunk.m_skeletalLoDs, endianType); + MCore::Endian::ConvertUnsignedInt32(&nodeChunk.m_numChilds, endianType); // show the name of the node, the parent and the number of children if (GetLogging()) { MCore::LogDetailedInfo(" + Node name = '%s'", nodeName); - MCore::LogDetailedInfo(" - Parent = '%s'", (nodeChunk.mParentIndex != MCORE_INVALIDINDEX32) ? skeleton->GetNode(nodeChunk.mParentIndex)->GetName() : ""); - MCore::LogDetailedInfo(" - NumChild Nodes = %d", nodeChunk.mNumChilds); + MCore::LogDetailedInfo(" - Parent = '%s'", (nodeChunk.m_parentIndex != MCORE_INVALIDINDEX32) ? skeleton->GetNode(nodeChunk.m_parentIndex)->GetName() : ""); + MCore::LogDetailedInfo(" - NumChild Nodes = %d", nodeChunk.m_numChilds); } // create the new node @@ -438,63 +412,58 @@ namespace EMotionFX node->SetNodeIndex(nodeIndex); // pre-allocate space for the number of child nodes - node->PreAllocNumChildNodes(nodeChunk.mNumChilds); + node->PreAllocNumChildNodes(nodeChunk.m_numChilds); // add it to the actor skeleton->SetNode(n, node); // create Core objects from the data - AZ::Vector3 pos(nodeChunk.mLocalPos.mX, nodeChunk.mLocalPos.mY, nodeChunk.mLocalPos.mZ); - AZ::Vector3 scale(nodeChunk.mLocalScale.mX, nodeChunk.mLocalScale.mY, nodeChunk.mLocalScale.mZ); - AZ::Quaternion rot(nodeChunk.mLocalQuat.mX, nodeChunk.mLocalQuat.mY, nodeChunk.mLocalQuat.mZ, nodeChunk.mLocalQuat.mW); + AZ::Vector3 pos(nodeChunk.m_localPos.m_x, nodeChunk.m_localPos.m_y, nodeChunk.m_localPos.m_z); + AZ::Vector3 scale(nodeChunk.m_localScale.m_x, nodeChunk.m_localScale.m_y, nodeChunk.m_localScale.m_z); + AZ::Quaternion rot(nodeChunk.m_localQuat.m_x, nodeChunk.m_localQuat.m_y, nodeChunk.m_localQuat.m_z, nodeChunk.m_localQuat.m_w); // convert endian and coordinate system ConvertVector3(&pos, endianType); ConvertScale(&scale, endianType); ConvertQuaternion(&rot, endianType); - // make sure the input data is normalized - // TODO: this isn't really needed as we already normalized? - //rot.FastNormalize(); - //scaleRot.FastNormalize(); - // set the local transform Transform bindTransform; - bindTransform.mPosition = pos; - bindTransform.mRotation = rot.GetNormalized(); + bindTransform.m_position = pos; + bindTransform.m_rotation = rot.GetNormalized(); EMFX_SCALECODE ( - bindTransform.mScale = scale; + bindTransform.m_scale = scale; ) actor->GetBindPose()->SetLocalSpaceTransform(nodeIndex, bindTransform); // set the skeletal LOD levels - if (actorSettings->mLoadSkeletalLODs) + if (actorSettings->m_loadSkeletalLoDs) { - node->SetSkeletalLODLevelBits(nodeChunk.mSkeletalLODs); + node->SetSkeletalLODLevelBits(nodeChunk.m_skeletalLoDs); } // set if this node has to be taken into the bounding volume calculation - const bool includeInBoundsCalc = (nodeChunk.mNodeFlags & Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC); // first bit + const bool includeInBoundsCalc = (nodeChunk.m_nodeFlags & Node::ENodeFlags::FLAG_INCLUDEINBOUNDSCALC); // first bit node->SetIncludeInBoundsCalc(includeInBoundsCalc); // Set if this node is critical and cannot be optimized out. - const bool isCritical = (nodeChunk.mNodeFlags & Node::ENodeFlags::FLAG_CRITICAL); // third bit + const bool isCritical = (nodeChunk.m_nodeFlags & Node::ENodeFlags::FLAG_CRITICAL); // third bit node->SetIsCritical(isCritical); // set the parent, and add this node as child inside the parent - if (nodeChunk.mParentIndex != MCORE_INVALIDINDEX32) // if this node has a parent and the parent node is valid + if (nodeChunk.m_parentIndex != MCORE_INVALIDINDEX32) // if this node has a parent and the parent node is valid { - if (nodeChunk.mParentIndex < n) + if (nodeChunk.m_parentIndex < n) { - node->SetParentIndex(nodeChunk.mParentIndex); - Node* parentNode = skeleton->GetNode(nodeChunk.mParentIndex); + node->SetParentIndex(nodeChunk.m_parentIndex); + Node* parentNode = skeleton->GetNode(nodeChunk.m_parentIndex); parentNode->AddChild(nodeIndex); } else { - MCore::LogError("Cannot assign parent node index (%d) for node '%s' as the parent node is not yet loaded. Making '%s' a root node.", nodeChunk.mParentIndex, node->GetName(), node->GetName()); + MCore::LogError("Cannot assign parent node index (%d) for node '%s' as the parent node is not yet loaded. Making '%s' a root node.", nodeChunk.m_parentIndex, node->GetName(), node->GetName()); skeleton->AddRootNode(nodeIndex); } } @@ -503,23 +472,6 @@ namespace EMotionFX skeleton->AddRootNode(nodeIndex); } - // OBB - AZ::Matrix4x4 obbMatrix4x4 = AZ::Matrix4x4::CreateFromRowMajorFloat16(nodeChunk.mOBB); - - const AZ::Vector3 obbCenter = obbMatrix4x4.GetTranslation(); - const AZ::Vector3 obbExtents = obbMatrix4x4.GetRowAsVector3(3); - - // initialize the OBB - MCore::OBB obb; - obb.SetCenter(obbCenter); - obb.SetExtents(obbExtents); - - // need to transpose to go from row major to column major - const AZ::Matrix3x3 obbMatrix3x3 = AZ::Matrix3x3::CreateFromMatrix4x4(obbMatrix4x4).GetTranspose(); - const AZ::Transform obbTransform = AZ::Transform::CreateFromMatrix3x3AndTranslation(obbMatrix3x3, obbExtents); - obb.SetTransformation(obbTransform); - actor->SetNodeOBB(nodeIndex, obb); - if (GetLogging()) { MCore::LogDetailedInfo(" - Position: x=%f, y=%f, z=%f", @@ -547,42 +499,42 @@ namespace EMotionFX // read all submotions in one chunk bool ChunkProcessorMotionSubMotions::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Motion* motion = importParams.mMotion; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Motion* motion = importParams.m_motion; AZ_Assert(motion, "Expected a valid motion object."); // read the header FileFormat::Motion_SubMotions subMotionsHeader; file->Read(&subMotionsHeader, sizeof(FileFormat::Motion_SubMotions)); - MCore::Endian::ConvertUnsignedInt32(&subMotionsHeader.mNumSubMotions, endianType); + MCore::Endian::ConvertUnsignedInt32(&subMotionsHeader.m_numSubMotions, endianType); // Create a uniform motion data. NonUniformMotionData* motionData = aznew NonUniformMotionData(); motion->SetMotionData(motionData); - motionData->Resize(subMotionsHeader.mNumSubMotions, motionData->GetNumMorphs(), motionData->GetNumFloats()); + motionData->Resize(subMotionsHeader.m_numSubMotions, motionData->GetNumMorphs(), motionData->GetNumFloats()); // for all submotions - for (uint32 s = 0; s < subMotionsHeader.mNumSubMotions; ++s) + for (uint32 s = 0; s < subMotionsHeader.m_numSubMotions; ++s) { FileFormat::Motion_SkeletalSubMotion fileSubMotion; file->Read(&fileSubMotion, sizeof(FileFormat::Motion_SkeletalSubMotion)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileSubMotion.mNumPosKeys, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileSubMotion.mNumRotKeys, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileSubMotion.mNumScaleKeys, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileSubMotion.m_numPosKeys, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileSubMotion.m_numRotKeys, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileSubMotion.m_numScaleKeys, endianType); // read the motion part name - const char* motionJointName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* motionJointName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // convert into Core objects - AZ::Vector3 posePos(fileSubMotion.mPosePos.mX, fileSubMotion.mPosePos.mY, fileSubMotion.mPosePos.mZ); - AZ::Vector3 poseScale(fileSubMotion.mPoseScale.mX, fileSubMotion.mPoseScale.mY, fileSubMotion.mPoseScale.mZ); - MCore::Compressed16BitQuaternion poseRot(fileSubMotion.mPoseRot.mX, fileSubMotion.mPoseRot.mY, fileSubMotion.mPoseRot.mZ, fileSubMotion.mPoseRot.mW); + AZ::Vector3 posePos(fileSubMotion.m_posePos.m_x, fileSubMotion.m_posePos.m_y, fileSubMotion.m_posePos.m_z); + AZ::Vector3 poseScale(fileSubMotion.m_poseScale.m_x, fileSubMotion.m_poseScale.m_y, fileSubMotion.m_poseScale.m_z); + MCore::Compressed16BitQuaternion poseRot(fileSubMotion.m_poseRot.m_x, fileSubMotion.m_poseRot.m_y, fileSubMotion.m_poseRot.m_z, fileSubMotion.m_poseRot.m_w); - AZ::Vector3 bindPosePos(fileSubMotion.mBindPosePos.mX, fileSubMotion.mBindPosePos.mY, fileSubMotion.mBindPosePos.mZ); - AZ::Vector3 bindPoseScale(fileSubMotion.mBindPoseScale.mX, fileSubMotion.mBindPoseScale.mY, fileSubMotion.mBindPoseScale.mZ); - MCore::Compressed16BitQuaternion bindPoseRot(fileSubMotion.mBindPoseRot.mX, fileSubMotion.mBindPoseRot.mY, fileSubMotion.mBindPoseRot.mZ, fileSubMotion.mBindPoseRot.mW); + AZ::Vector3 bindPosePos(fileSubMotion.m_bindPosePos.m_x, fileSubMotion.m_bindPosePos.m_y, fileSubMotion.m_bindPosePos.m_z); + AZ::Vector3 bindPoseScale(fileSubMotion.m_bindPoseScale.m_x, fileSubMotion.m_bindPoseScale.m_y, fileSubMotion.m_bindPoseScale.m_z); + MCore::Compressed16BitQuaternion bindPoseRot(fileSubMotion.m_bindPoseRot.m_x, fileSubMotion.m_bindPoseRot.m_y, fileSubMotion.m_bindPoseRot.m_z, fileSubMotion.m_bindPoseRot.m_w); // convert endian and coordinate system ConvertVector3(&posePos, endianType); @@ -624,9 +576,9 @@ namespace EMotionFX static_cast(bindPoseScale.GetX()), static_cast(bindPoseScale.GetY()), static_cast(bindPoseScale.GetZ())); - MCore::LogDetailedInfo(" + Num Pos Keys: %d", fileSubMotion.mNumPosKeys); - MCore::LogDetailedInfo(" + Num Rot Keys: %d", fileSubMotion.mNumRotKeys); - MCore::LogDetailedInfo(" + Num Scale Keys: %d", fileSubMotion.mNumScaleKeys); + MCore::LogDetailedInfo(" + Num Pos Keys: %d", fileSubMotion.m_numPosKeys); + MCore::LogDetailedInfo(" + Num Rot Keys: %d", fileSubMotion.m_numRotKeys); + MCore::LogDetailedInfo(" + Num Scale Keys: %d", fileSubMotion.m_numScaleKeys); } motionData->SetJointName(s, motionJointName); @@ -642,62 +594,62 @@ namespace EMotionFX // now read the animation data uint32 i; - if (fileSubMotion.mNumPosKeys > 0) + if (fileSubMotion.m_numPosKeys > 0) { - motionData->AllocateJointPositionSamples(s, fileSubMotion.mNumPosKeys); - for (i = 0; i < fileSubMotion.mNumPosKeys; ++i) + motionData->AllocateJointPositionSamples(s, fileSubMotion.m_numPosKeys); + for (i = 0; i < fileSubMotion.m_numPosKeys; ++i) { FileFormat::Motion_Vector3Key key; file->Read(&key, sizeof(FileFormat::Motion_Vector3Key)); - MCore::Endian::ConvertFloat(&key.mTime, endianType); - AZ::Vector3 pos(key.mValue.mX, key.mValue.mY, key.mValue.mZ); + MCore::Endian::ConvertFloat(&key.m_time, endianType); + AZ::Vector3 pos(key.m_value.m_x, key.m_value.m_y, key.m_value.m_z); ConvertVector3(&pos, endianType); - motionData->SetJointPositionSample(s, i, {key.mTime, pos}); + motionData->SetJointPositionSample(s, i, {key.m_time, pos}); } } // now the rotation keys - if (fileSubMotion.mNumRotKeys > 0) + if (fileSubMotion.m_numRotKeys > 0) { - motionData->AllocateJointRotationSamples(s, fileSubMotion.mNumRotKeys); - for (i = 0; i < fileSubMotion.mNumRotKeys; ++i) + motionData->AllocateJointRotationSamples(s, fileSubMotion.m_numRotKeys); + for (i = 0; i < fileSubMotion.m_numRotKeys; ++i) { FileFormat::Motion_16BitQuaternionKey key; file->Read(&key, sizeof(FileFormat::Motion_16BitQuaternionKey)); - MCore::Endian::ConvertFloat(&key.mTime, endianType); - MCore::Compressed16BitQuaternion rot(key.mValue.mX, key.mValue.mY, key.mValue.mZ, key.mValue.mW); + MCore::Endian::ConvertFloat(&key.m_time, endianType); + MCore::Compressed16BitQuaternion rot(key.m_value.m_x, key.m_value.m_y, key.m_value.m_z, key.m_value.m_w); Convert16BitQuaternion(&rot, endianType); - motionData->SetJointRotationSample(s, i, {key.mTime, rot.ToQuaternion().GetNormalized()}); + motionData->SetJointRotationSample(s, i, {key.m_time, rot.ToQuaternion().GetNormalized()}); } } #ifndef EMFX_SCALE_DISABLED // and the scale keys - if (fileSubMotion.mNumScaleKeys > 0) + if (fileSubMotion.m_numScaleKeys > 0) { - motionData->AllocateJointScaleSamples(s, fileSubMotion.mNumScaleKeys); - for (i = 0; i < fileSubMotion.mNumScaleKeys; ++i) + motionData->AllocateJointScaleSamples(s, fileSubMotion.m_numScaleKeys); + for (i = 0; i < fileSubMotion.m_numScaleKeys; ++i) { FileFormat::Motion_Vector3Key key; file->Read(&key, sizeof(FileFormat::Motion_Vector3Key)); - MCore::Endian::ConvertFloat(&key.mTime, endianType); - AZ::Vector3 scale(key.mValue.mX, key.mValue.mY, key.mValue.mZ); + MCore::Endian::ConvertFloat(&key.m_time, endianType); + AZ::Vector3 scale(key.m_value.m_x, key.m_value.m_y, key.m_value.m_z); ConvertScale(&scale, endianType); - motionData->SetJointScaleSample(s, i, {key.mTime, scale}); + motionData->SetJointScaleSample(s, i, {key.m_time, scale}); } } #else // no scaling // and the scale keys - if (fileSubMotion.mNumScaleKeys > 0) + if (fileSubMotion.m_numScaleKeys > 0) { - for (i = 0; i < fileSubMotion.mNumScaleKeys; ++i) + for (i = 0; i < fileSubMotion.m_numScaleKeys; ++i) { FileFormat::Motion_Vector3Key key; file->Read(&key, sizeof(FileFormat::Motion_Vector3Key)); @@ -715,8 +667,8 @@ namespace EMotionFX bool ChunkProcessorMotionInfo::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Motion* motion = importParams.mMotion; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Motion* motion = importParams.m_motion; MCORE_ASSERT(motion); @@ -725,8 +677,8 @@ namespace EMotionFX file->Read(&fileInformation, sizeof(FileFormat::Motion_Info)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionMask, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionMask, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionNodeIndex, endianType); if (GetLogging()) { @@ -735,15 +687,15 @@ namespace EMotionFX if (GetLogging()) { - MCore::LogDetailedInfo(" + Unit Type = %d", fileInformation.mUnitType); + MCore::LogDetailedInfo(" + Unit Type = %d", fileInformation.m_unitType); } - motion->SetUnitType(static_cast(fileInformation.mUnitType)); + motion->SetUnitType(static_cast(fileInformation.m_unitType)); motion->SetFileUnitType(motion->GetUnitType()); // Try to remain backward compatible by still capturing height when this was enabled in the old mask system. - if (fileInformation.mMotionExtractionMask & (1 << 2)) // The 1<<2 was the mask used for position Z in the old motion extraction mask settings + if (fileInformation.m_motionExtractionMask & (1 << 2)) // The 1<<2 was the mask used for position Z in the old motion extraction mask settings { motion->SetMotionExtractionFlags(MOTIONEXTRACT_CAPTURE_Z); } @@ -755,8 +707,8 @@ namespace EMotionFX bool ChunkProcessorMotionInfo2::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Motion* motion = importParams.mMotion; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Motion* motion = importParams.m_motion; MCORE_ASSERT(motion); // read the chunk @@ -764,8 +716,8 @@ namespace EMotionFX file->Read(&fileInformation, sizeof(FileFormat::Motion_Info2)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionFlags, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionFlags, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionNodeIndex, endianType); if (GetLogging()) { @@ -774,13 +726,13 @@ namespace EMotionFX if (GetLogging()) { - MCore::LogDetailedInfo(" + Unit Type = %d", fileInformation.mUnitType); - MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", fileInformation.mMotionExtractionFlags, (fileInformation.mMotionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0); + MCore::LogDetailedInfo(" + Unit Type = %d", fileInformation.m_unitType); + MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", fileInformation.m_motionExtractionFlags, (fileInformation.m_motionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0); } - motion->SetUnitType(static_cast(fileInformation.mUnitType)); + motion->SetUnitType(static_cast(fileInformation.m_unitType)); motion->SetFileUnitType(motion->GetUnitType()); - motion->SetMotionExtractionFlags(static_cast(fileInformation.mMotionExtractionFlags)); + motion->SetMotionExtractionFlags(static_cast(fileInformation.m_motionExtractionFlags)); return true; } @@ -789,8 +741,8 @@ namespace EMotionFX bool ChunkProcessorMotionInfo3::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Motion* motion = importParams.mMotion; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Motion* motion = importParams.m_motion; MCORE_ASSERT(motion); // read the chunk @@ -798,8 +750,8 @@ namespace EMotionFX file->Read(&fileInformation, sizeof(FileFormat::Motion_Info3)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionFlags, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionFlags, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionNodeIndex, endianType); if (GetLogging()) { @@ -808,15 +760,15 @@ namespace EMotionFX if (GetLogging()) { - MCore::LogDetailedInfo(" + Unit Type = %d", fileInformation.mUnitType); - MCore::LogDetailedInfo(" + Is Additive Motion = %d", fileInformation.mIsAdditive); - MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", fileInformation.mMotionExtractionFlags, (fileInformation.mMotionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0); + MCore::LogDetailedInfo(" + Unit Type = %d", fileInformation.m_unitType); + MCore::LogDetailedInfo(" + Is Additive Motion = %d", fileInformation.m_isAdditive); + MCore::LogDetailedInfo(" + Motion Extraction Flags = 0x%x [capZ=%d]", fileInformation.m_motionExtractionFlags, (fileInformation.m_motionExtractionFlags & EMotionFX::MOTIONEXTRACT_CAPTURE_Z) ? 1 : 0); } - motion->SetUnitType(static_cast(fileInformation.mUnitType)); - importParams.m_additiveMotion = (fileInformation.mIsAdditive == 0 ? false : true); + motion->SetUnitType(static_cast(fileInformation.m_unitType)); + importParams.m_additiveMotion = (fileInformation.m_isAdditive == 0 ? false : true); motion->SetFileUnitType(motion->GetUnitType()); - motion->SetMotionExtractionFlags(static_cast(fileInformation.mMotionExtractionFlags)); + motion->SetMotionExtractionFlags(static_cast(fileInformation.m_motionExtractionFlags)); return true; } @@ -825,8 +777,8 @@ namespace EMotionFX bool ChunkProcessorActorPhysicsSetup::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; AZ::u32 bufferSize; file->Read(&bufferSize, sizeof(AZ::u32)); @@ -849,7 +801,7 @@ namespace EMotionFX if (resultPhysicsSetup) { - if (importParams.mActorSettings->mOptimizeForServer) + if (importParams.m_actorSettings->m_optimizeForServer) { resultPhysicsSetup->OptimizeForServer(); } @@ -863,8 +815,8 @@ namespace EMotionFX bool ChunkProcessorActorSimulatedObjectSetup::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; AZ::u32 bufferSize; file->Read(&bufferSize, sizeof(AZ::u32)); @@ -896,13 +848,13 @@ namespace EMotionFX bool ChunkProcessorMeshAsset::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; AZ_Assert(actor, "Actor needs to be valid."); EMotionFX::FileFormat::Actor_MeshAsset meshAssetChunk; file->Read(&meshAssetChunk, sizeof(FileFormat::Actor_MeshAsset)); - const char* meshAssetIdString = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* meshAssetIdString = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); const AZ::Data::AssetId meshAssetId = AZ::Data::AssetId::CreateString(meshAssetIdString); if (meshAssetId.IsValid()) { @@ -922,8 +874,8 @@ namespace EMotionFX bool ChunkProcessorMotionEventTrackTable::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Motion* motion = importParams.mMotion; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Motion* motion = importParams.m_motion; MCORE_ASSERT(motion); @@ -932,53 +884,53 @@ namespace EMotionFX file->Read(&fileEventTable, sizeof(FileFormat::FileMotionEventTable)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileEventTable.mNumTracks, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileEventTable.m_numTracks, endianType); if (GetLogging()) { MCore::LogDetailedInfo("- Motion Event Table:"); - MCore::LogDetailedInfo(" + Num Tracks = %d", fileEventTable.mNumTracks); + MCore::LogDetailedInfo(" + Num Tracks = %d", fileEventTable.m_numTracks); } // get the motion event table the reserve the event tracks MotionEventTable* motionEventTable = motion->GetEventTable(); - motionEventTable->ReserveNumTracks(fileEventTable.mNumTracks); + motionEventTable->ReserveNumTracks(fileEventTable.m_numTracks); // read all tracks AZStd::string trackName; - MCore::Array typeStrings; - MCore::Array paramStrings; - MCore::Array mirrorTypeStrings; - for (uint32 t = 0; t < fileEventTable.mNumTracks; ++t) + AZStd::vector typeStrings; + AZStd::vector paramStrings; + AZStd::vector mirrorTypeStrings; + for (uint32 t = 0; t < fileEventTable.m_numTracks; ++t) { // read the motion event table header FileFormat::FileMotionEventTrack fileTrack; file->Read(&fileTrack, sizeof(FileFormat::FileMotionEventTrack)); // read the track name - trackName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + trackName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileTrack.mNumEvents, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileTrack.mNumTypeStrings, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileTrack.mNumParamStrings, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileTrack.mNumMirrorTypeStrings, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileTrack.m_numEvents, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileTrack.m_numTypeStrings, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileTrack.m_numParamStrings, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileTrack.m_numMirrorTypeStrings, endianType); if (GetLogging()) { MCore::LogDetailedInfo("- Motion Event Track:"); MCore::LogDetailedInfo(" + Name = %s", trackName.c_str()); - MCore::LogDetailedInfo(" + Num events = %d", fileTrack.mNumEvents); - MCore::LogDetailedInfo(" + Num types = %d", fileTrack.mNumTypeStrings); - MCore::LogDetailedInfo(" + Num params = %d", fileTrack.mNumParamStrings); - MCore::LogDetailedInfo(" + Num mirror = %d", fileTrack.mNumMirrorTypeStrings); - MCore::LogDetailedInfo(" + Enabled = %d", fileTrack.mIsEnabled); + MCore::LogDetailedInfo(" + Num events = %d", fileTrack.m_numEvents); + MCore::LogDetailedInfo(" + Num types = %d", fileTrack.m_numTypeStrings); + MCore::LogDetailedInfo(" + Num params = %d", fileTrack.m_numParamStrings); + MCore::LogDetailedInfo(" + Num mirror = %d", fileTrack.m_numMirrorTypeStrings); + MCore::LogDetailedInfo(" + Enabled = %d", fileTrack.m_isEnabled); } // the even type and parameter strings - typeStrings.Resize(fileTrack.mNumTypeStrings); - paramStrings.Resize(fileTrack.mNumParamStrings); - mirrorTypeStrings.Resize(fileTrack.mNumMirrorTypeStrings); + typeStrings.resize(fileTrack.m_numTypeStrings); + paramStrings.resize(fileTrack.m_numParamStrings); + mirrorTypeStrings.resize(fileTrack.m_numMirrorTypeStrings); // read all type strings if (GetLogging()) @@ -986,9 +938,9 @@ namespace EMotionFX MCore::LogDetailedInfo(" + Event types:"); } uint32 i; - for (i = 0; i < fileTrack.mNumTypeStrings; ++i) + for (i = 0; i < fileTrack.m_numTypeStrings; ++i) { - typeStrings[i] = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + typeStrings[i] = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); if (GetLogging()) { MCore::LogDetailedInfo(" [%d] = '%s'", i, typeStrings[i].c_str()); @@ -1000,9 +952,9 @@ namespace EMotionFX { MCore::LogDetailedInfo(" + Parameters:"); } - for (i = 0; i < fileTrack.mNumParamStrings; ++i) + for (i = 0; i < fileTrack.m_numParamStrings; ++i) { - paramStrings[i] = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + paramStrings[i] = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); if (GetLogging()) { MCore::LogDetailedInfo(" [%d] = '%s'", i, paramStrings[i].c_str()); @@ -1013,9 +965,9 @@ namespace EMotionFX { MCore::LogDetailedInfo(" + Mirror Type Strings:"); } - for (i = 0; i < fileTrack.mNumMirrorTypeStrings; ++i) + for (i = 0; i < fileTrack.m_numMirrorTypeStrings; ++i) { - mirrorTypeStrings[i] = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + mirrorTypeStrings[i] = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); if (GetLogging()) { MCore::LogDetailedInfo(" [%d] = '%s'", i, mirrorTypeStrings[i].c_str()); @@ -1024,8 +976,8 @@ namespace EMotionFX // create the default event track MotionEventTrack* track = MotionEventTrack::Create(trackName.c_str(), motion); - track->SetIsEnabled(fileTrack.mIsEnabled != 0); - track->ReserveNumEvents(fileTrack.mNumEvents); + track->SetIsEnabled(fileTrack.m_isEnabled != 0); + track->ReserveNumEvents(fileTrack.m_numEvents); motionEventTable->AddTrack(track); // read all motion events @@ -1033,35 +985,35 @@ namespace EMotionFX { MCore::LogDetailedInfo(" + Motion Events:"); } - for (i = 0; i < fileTrack.mNumEvents; ++i) + for (i = 0; i < fileTrack.m_numEvents; ++i) { // read the event header FileFormat::FileMotionEvent fileEvent; file->Read(&fileEvent, sizeof(FileFormat::FileMotionEvent)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileEvent.mEventTypeIndex, endianType); - MCore::Endian::ConvertUnsignedInt16(&fileEvent.mParamIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileEvent.mMirrorTypeIndex, endianType); - MCore::Endian::ConvertFloat(&fileEvent.mStartTime, endianType); - MCore::Endian::ConvertFloat(&fileEvent.mEndTime, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileEvent.m_eventTypeIndex, endianType); + MCore::Endian::ConvertUnsignedInt16(&fileEvent.m_paramIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileEvent.m_mirrorTypeIndex, endianType); + MCore::Endian::ConvertFloat(&fileEvent.m_startTime, endianType); + MCore::Endian::ConvertFloat(&fileEvent.m_endTime, endianType); // print motion event information if (GetLogging()) { - MCore::LogDetailedInfo(" [%d] StartTime = %f - EndTime = %f - Type = '%s' - Param = '%s' - Mirror = '%s'", i, fileEvent.mStartTime, fileEvent.mEndTime, typeStrings[fileEvent.mEventTypeIndex].c_str(), paramStrings[fileEvent.mParamIndex].c_str(), mirrorTypeStrings[fileEvent.mMirrorTypeIndex].c_str()); + MCore::LogDetailedInfo(" [%d] StartTime = %f - EndTime = %f - Type = '%s' - Param = '%s' - Mirror = '%s'", i, fileEvent.m_startTime, fileEvent.m_endTime, typeStrings[fileEvent.m_eventTypeIndex].c_str(), paramStrings[fileEvent.m_paramIndex].c_str(), mirrorTypeStrings[fileEvent.m_mirrorTypeIndex].c_str()); } - const AZStd::string eventTypeName = fileEvent.mEventTypeIndex != MCORE_INVALIDINDEX32 ? - typeStrings[fileEvent.mEventTypeIndex] : ""; - const AZStd::string mirrorTypeName = fileEvent.mMirrorTypeIndex != MCORE_INVALIDINDEX32 ? - mirrorTypeStrings[fileEvent.mMirrorTypeIndex] : ""; - const AZStd::string params = paramStrings[fileEvent.mParamIndex]; + const AZStd::string eventTypeName = fileEvent.m_eventTypeIndex != MCORE_INVALIDINDEX32 ? + typeStrings[fileEvent.m_eventTypeIndex] : ""; + const AZStd::string mirrorTypeName = fileEvent.m_mirrorTypeIndex != MCORE_INVALIDINDEX32 ? + mirrorTypeStrings[fileEvent.m_mirrorTypeIndex] : ""; + const AZStd::string params = paramStrings[fileEvent.m_paramIndex]; // add the event track->AddEvent( - fileEvent.mStartTime, - fileEvent.mEndTime, + fileEvent.m_startTime, + fileEvent.m_endTime, GetEventManager().FindOrCreateEventData(eventTypeName, params, mirrorTypeName) ); } @@ -1074,7 +1026,7 @@ namespace EMotionFX bool ChunkProcessorMotionEventTrackTable2::Process(MCore::File* file, Importer::ImportParameters& importParams) { - Motion* motion = importParams.mMotion; + Motion* motion = importParams.m_motion; MCORE_ASSERT(motion); @@ -1113,7 +1065,7 @@ namespace EMotionFX bool ChunkProcessorMotionEventTrackTable3::Process(MCore::File* file, Importer::ImportParameters& importParams) { - Motion* motion = importParams.mMotion; + Motion* motion = importParams.m_motion; MCORE_ASSERT(motion); FileFormat::FileMotionEventTableSerialized fileEventTable; @@ -1164,8 +1116,8 @@ namespace EMotionFX bool ChunkProcessorActorInfo::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; MCORE_ASSERT(actor); @@ -1174,10 +1126,10 @@ namespace EMotionFX file->Read(&fileInformation, sizeof(FileFormat::Actor_Info)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionNodeIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mTrajectoryNodeIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mNumLODs, endianType); - MCore::Endian::ConvertFloat(&fileInformation.mRetargetRootOffset, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_trajectoryNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_numLoDs, endianType); + MCore::Endian::ConvertFloat(&fileInformation.m_retargetRootOffset, endianType); if (GetLogging()) { @@ -1185,11 +1137,11 @@ namespace EMotionFX } // read the source application, original filename and the compilation date of the exporter string - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); - const char* name = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* name = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); actor->SetName(name); if (GetLogging()) { @@ -1199,16 +1151,19 @@ namespace EMotionFX // print motion event information if (GetLogging()) { - MCore::LogDetailedInfo(" + Exporter version = v%d.%d", fileInformation.mExporterHighVersion, fileInformation.mExporterLowVersion); - MCore::LogDetailedInfo(" + Num LODs = %d", fileInformation.mNumLODs); - MCore::LogDetailedInfo(" + Motion Extraction node = %d", fileInformation.mMotionExtractionNodeIndex); - MCore::LogDetailedInfo(" + Retarget root offset = %f", fileInformation.mRetargetRootOffset); - MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.mUnitType); + MCore::LogDetailedInfo(" + Exporter version = v%d.%d", fileInformation.m_exporterHighVersion, fileInformation.m_exporterLowVersion); + MCore::LogDetailedInfo(" + Num LODs = %d", fileInformation.m_numLoDs); + MCore::LogDetailedInfo(" + Motion Extraction node = %d", fileInformation.m_motionExtractionNodeIndex); + MCore::LogDetailedInfo(" + Retarget root offset = %f", fileInformation.m_retargetRootOffset); + MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.m_unitType); } - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); - // actor->SetRetargetOffset( fileInformation.mRetargetRootOffset ); - actor->SetUnitType(static_cast(fileInformation.mUnitType)); + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); + if (fileInformation.m_motionExtractionNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); + } + actor->SetUnitType(static_cast(fileInformation.m_unitType)); actor->SetFileUnitType(actor->GetUnitType()); return true; @@ -1218,17 +1173,17 @@ namespace EMotionFX bool ChunkProcessorActorInfo2::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; // read the chunk FileFormat::Actor_Info2 fileInformation; file->Read(&fileInformation, sizeof(FileFormat::Actor_Info2)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionNodeIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mRetargetRootNodeIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mNumLODs, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_retargetRootNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_numLoDs, endianType); if (GetLogging()) { @@ -1236,26 +1191,32 @@ namespace EMotionFX } // read the source application, original filename and the compilation date of the exporter string - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); - const char* name = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* name = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); actor->SetName(name); if (GetLogging()) { MCore::LogDetailedInfo(" + Actor name = '%s'", name); - MCore::LogDetailedInfo(" + Exporter version = v%d.%d", fileInformation.mExporterHighVersion, fileInformation.mExporterLowVersion); - MCore::LogDetailedInfo(" + Num LODs = %d", fileInformation.mNumLODs); - MCore::LogDetailedInfo(" + Motion Extraction node = %d", fileInformation.mMotionExtractionNodeIndex); - MCore::LogDetailedInfo(" + Retarget root node = %d", fileInformation.mRetargetRootNodeIndex); - MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.mUnitType); + MCore::LogDetailedInfo(" + Exporter version = v%d.%d", fileInformation.m_exporterHighVersion, fileInformation.m_exporterLowVersion); + MCore::LogDetailedInfo(" + Num LODs = %d", fileInformation.m_numLoDs); + MCore::LogDetailedInfo(" + Motion Extraction node = %d", fileInformation.m_motionExtractionNodeIndex); + MCore::LogDetailedInfo(" + Retarget root node = %d", fileInformation.m_retargetRootNodeIndex); + MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.m_unitType); } - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); - actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); - actor->SetUnitType(static_cast(fileInformation.mUnitType)); + if (fileInformation.m_motionExtractionNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); + } + if (fileInformation.m_retargetRootNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetRetargetRootNodeIndex(fileInformation.m_retargetRootNodeIndex); + } + actor->SetUnitType(static_cast(fileInformation.m_unitType)); actor->SetFileUnitType(actor->GetUnitType()); return true; @@ -1265,17 +1226,17 @@ namespace EMotionFX bool ChunkProcessorActorInfo3::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; // read the chunk FileFormat::Actor_Info3 fileInformation; file->Read(&fileInformation, sizeof(FileFormat::Actor_Info3)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mMotionExtractionNodeIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mRetargetRootNodeIndex, endianType); - MCore::Endian::ConvertUnsignedInt32(&fileInformation.mNumLODs, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_motionExtractionNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_retargetRootNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileInformation.m_numLoDs, endianType); if (GetLogging()) { @@ -1283,28 +1244,34 @@ namespace EMotionFX } // read the source application, original filename and the compilation date of the exporter string - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); - const char* name = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* name = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); actor->SetName(name); if (GetLogging()) { MCore::LogDetailedInfo(" + Actor name = '%s'", name); - MCore::LogDetailedInfo(" + Exporter version = v%d.%d", fileInformation.mExporterHighVersion, fileInformation.mExporterLowVersion); - MCore::LogDetailedInfo(" + Num LODs = %d", fileInformation.mNumLODs); - MCore::LogDetailedInfo(" + Motion Extraction node = %d", fileInformation.mMotionExtractionNodeIndex); - MCore::LogDetailedInfo(" + Retarget root node = %d", fileInformation.mRetargetRootNodeIndex); - MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.mUnitType); + MCore::LogDetailedInfo(" + Exporter version = v%d.%d", fileInformation.m_exporterHighVersion, fileInformation.m_exporterLowVersion); + MCore::LogDetailedInfo(" + Num LODs = %d", fileInformation.m_numLoDs); + MCore::LogDetailedInfo(" + Motion Extraction node = %d", fileInformation.m_motionExtractionNodeIndex); + MCore::LogDetailedInfo(" + Retarget root node = %d", fileInformation.m_retargetRootNodeIndex); + MCore::LogDetailedInfo(" + UnitType = %d", fileInformation.m_unitType); } - actor->SetMotionExtractionNodeIndex(fileInformation.mMotionExtractionNodeIndex); - actor->SetRetargetRootNodeIndex(fileInformation.mRetargetRootNodeIndex); - actor->SetUnitType(static_cast(fileInformation.mUnitType)); + if (fileInformation.m_motionExtractionNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetMotionExtractionNodeIndex(fileInformation.m_motionExtractionNodeIndex); + } + if (fileInformation.m_retargetRootNodeIndex != MCORE_INVALIDINDEX32) + { + actor->SetRetargetRootNodeIndex(fileInformation.m_retargetRootNodeIndex); + } + actor->SetUnitType(static_cast(fileInformation.m_unitType)); actor->SetFileUnitType(actor->GetUnitType()); - actor->SetOptimizeSkeleton(fileInformation.mOptimizeSkeleton == 0? false : true); + actor->SetOptimizeSkeleton(fileInformation.m_optimizeSkeleton == 0? false : true); return true; } @@ -1314,8 +1281,8 @@ namespace EMotionFX // morph targets bool ChunkProcessorActorProgMorphTarget::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); @@ -1325,27 +1292,27 @@ namespace EMotionFX file->Read(&morphTargetChunk, sizeof(FileFormat::Actor_MorphTarget)); // convert endian - MCore::Endian::ConvertFloat(&morphTargetChunk.mRangeMin, endianType); - MCore::Endian::ConvertFloat(&morphTargetChunk.mRangeMax, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mLOD, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mNumTransformations, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mPhonemeSets, endianType); + MCore::Endian::ConvertFloat(&morphTargetChunk.m_rangeMin, endianType); + MCore::Endian::ConvertFloat(&morphTargetChunk.m_rangeMax, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_lod, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_numTransformations, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_phonemeSets, endianType); // get the expression name - const char* morphTargetName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* morphTargetName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // get the level of detail of the expression part - const uint32 morphTargetLOD = morphTargetChunk.mLOD; + const uint32 morphTargetLOD = morphTargetChunk.m_lod; if (GetLogging()) { MCore::LogDetailedInfo(" - Morph Target:"); MCore::LogDetailedInfo(" + Name = '%s'", morphTargetName); - MCore::LogDetailedInfo(" + LOD Level = %d", morphTargetChunk.mLOD); - MCore::LogDetailedInfo(" + RangeMin = %f", morphTargetChunk.mRangeMin); - MCore::LogDetailedInfo(" + RangeMax = %f", morphTargetChunk.mRangeMax); - MCore::LogDetailedInfo(" + NumTransformations = %d", morphTargetChunk.mNumTransformations); - MCore::LogDetailedInfo(" + PhonemeSets: %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphTargetChunk.mPhonemeSets).c_str()); + MCore::LogDetailedInfo(" + LOD Level = %d", morphTargetChunk.m_lod); + MCore::LogDetailedInfo(" + RangeMin = %f", morphTargetChunk.m_rangeMin); + MCore::LogDetailedInfo(" + RangeMax = %f", morphTargetChunk.m_rangeMax); + MCore::LogDetailedInfo(" + NumTransformations = %d", morphTargetChunk.m_numTransformations); + MCore::LogDetailedInfo(" + PhonemeSets: %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphTargetChunk.m_phonemeSets).c_str()); } // check if the morph setup has already been created, if not create it @@ -1362,59 +1329,59 @@ namespace EMotionFX MorphTargetStandard* morphTarget = MorphTargetStandard::Create(morphTargetName); // set the slider range - morphTarget->SetRangeMin(morphTargetChunk.mRangeMin); - morphTarget->SetRangeMax(morphTargetChunk.mRangeMax); + morphTarget->SetRangeMin(morphTargetChunk.m_rangeMin); + morphTarget->SetRangeMax(morphTargetChunk.m_rangeMax); // set the phoneme sets - morphTarget->SetPhonemeSets((MorphTarget::EPhonemeSet)morphTargetChunk.mPhonemeSets); + morphTarget->SetPhonemeSets((MorphTarget::EPhonemeSet)morphTargetChunk.m_phonemeSets); // add the morph target actor->GetMorphSetup(morphTargetLOD)->AddMorphTarget(morphTarget); // read the facial transformations - for (uint32 i = 0; i < morphTargetChunk.mNumTransformations; ++i) + for (uint32 i = 0; i < morphTargetChunk.m_numTransformations; ++i) { // read the facial transformation from disk FileFormat::Actor_MorphTargetTransform transformChunk; file->Read(&transformChunk, sizeof(FileFormat::Actor_MorphTargetTransform)); // create Core objects from the data - AZ::Vector3 pos(transformChunk.mPosition.mX, transformChunk.mPosition.mY, transformChunk.mPosition.mZ); - AZ::Vector3 scale(transformChunk.mScale.mX, transformChunk.mScale.mY, transformChunk.mScale.mZ); - AZ::Quaternion rot(transformChunk.mRotation.mX, transformChunk.mRotation.mY, transformChunk.mRotation.mZ, transformChunk.mRotation.mW); - AZ::Quaternion scaleRot(transformChunk.mScaleRotation.mX, transformChunk.mScaleRotation.mY, transformChunk.mScaleRotation.mZ, transformChunk.mScaleRotation.mW); + AZ::Vector3 pos(transformChunk.m_position.m_x, transformChunk.m_position.m_y, transformChunk.m_position.m_z); + AZ::Vector3 scale(transformChunk.m_scale.m_x, transformChunk.m_scale.m_y, transformChunk.m_scale.m_z); + AZ::Quaternion rot(transformChunk.m_rotation.m_x, transformChunk.m_rotation.m_y, transformChunk.m_rotation.m_z, transformChunk.m_rotation.m_w); + AZ::Quaternion scaleRot(transformChunk.m_scaleRotation.m_x, transformChunk.m_scaleRotation.m_y, transformChunk.m_scaleRotation.m_z, transformChunk.m_scaleRotation.m_w); // convert endian and coordinate system ConvertVector3(&pos, endianType); ConvertScale(&scale, endianType); ConvertQuaternion(&rot, endianType); ConvertQuaternion(&scaleRot, endianType); - MCore::Endian::ConvertUnsignedInt32(&transformChunk.mNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&transformChunk.m_nodeIndex, endianType); // create our transformation MorphTargetStandard::Transformation transform; - transform.mPosition = pos; - transform.mScale = scale; - transform.mRotation = rot; - transform.mScaleRotation = scaleRot; - transform.mNodeIndex = transformChunk.mNodeIndex; + transform.m_position = pos; + transform.m_scale = scale; + transform.m_rotation = rot; + transform.m_scaleRotation = scaleRot; + transform.m_nodeIndex = transformChunk.m_nodeIndex; if (GetLogging()) { - MCore::LogDetailedInfo(" - Transform #%d: Node='%s' (index=%d)", i, skeleton->GetNode(transform.mNodeIndex)->GetName(), transform.mNodeIndex); + MCore::LogDetailedInfo(" - Transform #%d: Node='%s' (index=%d)", i, skeleton->GetNode(transform.m_nodeIndex)->GetName(), transform.m_nodeIndex); MCore::LogDetailedInfo(" + Pos: %f, %f, %f", - static_cast(transform.mPosition.GetX()), - static_cast(transform.mPosition.GetY()), - static_cast(transform.mPosition.GetZ())); + static_cast(transform.m_position.GetX()), + static_cast(transform.m_position.GetY()), + static_cast(transform.m_position.GetZ())); MCore::LogDetailedInfo(" + Rotation: %f, %f, %f %f", - static_cast(transform.mRotation.GetX()), - static_cast(transform.mRotation.GetY()), - static_cast(transform.mRotation.GetZ()), - static_cast(transform.mRotation.GetW())); + static_cast(transform.m_rotation.GetX()), + static_cast(transform.m_rotation.GetY()), + static_cast(transform.m_rotation.GetZ()), + static_cast(transform.m_rotation.GetW())); MCore::LogDetailedInfo(" + Scale: %f, %f, %f", - static_cast(transform.mScale.GetX()), - static_cast(transform.mScale.GetY()), - static_cast(transform.mScale.GetZ())); + static_cast(transform.m_scale.GetX()), + static_cast(transform.m_scale.GetY()), + static_cast(transform.m_scale.GetZ())); MCore::LogDetailedInfo(" + ScaleRot: %f, %f, %f %f", static_cast(scaleRot.GetX()), static_cast(scaleRot.GetY()), @@ -1434,8 +1401,8 @@ namespace EMotionFX // the node groups chunk bool ChunkProcessorActorNodeGroups::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; MCORE_ASSERT(actor); @@ -1455,25 +1422,25 @@ namespace EMotionFX // read the group header FileFormat::Actor_NodeGroup fileGroup; file->Read(&fileGroup, sizeof(FileFormat::Actor_NodeGroup)); - MCore::Endian::ConvertUnsignedInt16(&fileGroup.mNumNodes, endianType); + MCore::Endian::ConvertUnsignedInt16(&fileGroup.m_numNodes, endianType); // read the group name - const char* groupName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* groupName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // log some info if (GetLogging()) { MCore::LogDetailedInfo(" + Group '%s'", groupName); - MCore::LogDetailedInfo(" - Num nodes: %d", fileGroup.mNumNodes); - MCore::LogDetailedInfo(" - Disabled on default: %s", fileGroup.mDisabledOnDefault ? "Yes" : "No"); + MCore::LogDetailedInfo(" - Num nodes: %d", fileGroup.m_numNodes); + MCore::LogDetailedInfo(" - Disabled on default: %s", fileGroup.m_disabledOnDefault ? "Yes" : "No"); } // create the new group inside the actor - NodeGroup* newGroup = aznew NodeGroup(groupName, fileGroup.mNumNodes, fileGroup.mDisabledOnDefault ? false : true); + NodeGroup* newGroup = aznew NodeGroup(groupName, fileGroup.m_numNodes, fileGroup.m_disabledOnDefault ? false : true); // read the node numbers uint16 nodeIndex; - for (uint16 n = 0; n < fileGroup.mNumNodes; ++n) + for (uint16 n = 0; n < fileGroup.m_numNodes; ++n) { file->Read(&nodeIndex, sizeof(uint16)); MCore::Endian::ConvertUnsignedInt16(&nodeIndex, endianType); @@ -1491,8 +1458,8 @@ namespace EMotionFX // all submotions in one chunk bool ChunkProcessorMotionMorphSubMotions::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Motion* motion = importParams.mMotion; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Motion* motion = importParams.m_motion; AZ_Assert(motion, "Expecting a valid motion pointer."); // cast to morph motion @@ -1504,54 +1471,54 @@ namespace EMotionFX file->Read(&subMotionsHeader, sizeof(FileFormat::Motion_MorphSubMotions)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&subMotionsHeader.mNumSubMotions, endianType); + MCore::Endian::ConvertUnsignedInt32(&subMotionsHeader.m_numSubMotions, endianType); // pre-allocate the number of submotions motionData->SetAdditive(importParams.m_additiveMotion); - motionData->Resize(motionData->GetNumJoints(), subMotionsHeader.mNumSubMotions, motionData->GetNumFloats()); + motionData->Resize(motionData->GetNumJoints(), subMotionsHeader.m_numSubMotions, motionData->GetNumFloats()); // for all submotions - for (uint32 s = 0; s < subMotionsHeader.mNumSubMotions; ++s) + for (uint32 s = 0; s < subMotionsHeader.m_numSubMotions; ++s) { // get the morph motion part FileFormat::Motion_MorphSubMotion morphSubMotionChunk; file->Read(&morphSubMotionChunk, sizeof(FileFormat::Motion_MorphSubMotion)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&morphSubMotionChunk.mNumKeys, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphSubMotionChunk.mPhonemeSet, endianType); - MCore::Endian::ConvertFloat(&morphSubMotionChunk.mPoseWeight, endianType); - MCore::Endian::ConvertFloat(&morphSubMotionChunk.mMinWeight, endianType); - MCore::Endian::ConvertFloat(&morphSubMotionChunk.mMaxWeight, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphSubMotionChunk.m_numKeys, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphSubMotionChunk.m_phonemeSet, endianType); + MCore::Endian::ConvertFloat(&morphSubMotionChunk.m_poseWeight, endianType); + MCore::Endian::ConvertFloat(&morphSubMotionChunk.m_minWeight, endianType); + MCore::Endian::ConvertFloat(&morphSubMotionChunk.m_maxWeight, endianType); // read the name of the submotion - const char* name = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* name = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); motionData->SetMorphName(s, name); - motionData->AllocateMorphSamples(s, morphSubMotionChunk.mNumKeys); - motionData->SetMorphStaticValue(s, morphSubMotionChunk.mPoseWeight); + motionData->AllocateMorphSamples(s, morphSubMotionChunk.m_numKeys); + motionData->SetMorphStaticValue(s, morphSubMotionChunk.m_poseWeight); if (GetLogging()) { MCore::LogDetailedInfo(" - Morph Submotion: %s", name); - MCore::LogDetailedInfo(" + NrKeys = %d", morphSubMotionChunk.mNumKeys); - MCore::LogDetailedInfo(" + Pose Weight = %f", morphSubMotionChunk.mPoseWeight); - MCore::LogDetailedInfo(" + Minimum Weight = %f", morphSubMotionChunk.mMinWeight); - MCore::LogDetailedInfo(" + Maximum Weight = %f", morphSubMotionChunk.mMaxWeight); - MCore::LogDetailedInfo(" + PhonemeSet = %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphSubMotionChunk.mPhonemeSet).c_str()); + MCore::LogDetailedInfo(" + NrKeys = %d", morphSubMotionChunk.m_numKeys); + MCore::LogDetailedInfo(" + Pose Weight = %f", morphSubMotionChunk.m_poseWeight); + MCore::LogDetailedInfo(" + Minimum Weight = %f", morphSubMotionChunk.m_minWeight); + MCore::LogDetailedInfo(" + Maximum Weight = %f", morphSubMotionChunk.m_maxWeight); + MCore::LogDetailedInfo(" + PhonemeSet = %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphSubMotionChunk.m_phonemeSet).c_str()); } // add keyframes - for (uint32 i = 0; i < morphSubMotionChunk.mNumKeys; ++i) + for (uint32 i = 0; i < morphSubMotionChunk.m_numKeys; ++i) { FileFormat::Motion_UnsignedShortKey keyframeChunk; file->Read(&keyframeChunk, sizeof(FileFormat::Motion_UnsignedShortKey)); - MCore::Endian::ConvertFloat(&keyframeChunk.mTime, endianType); - MCore::Endian::ConvertUnsignedInt16(&keyframeChunk.mValue, endianType); + MCore::Endian::ConvertFloat(&keyframeChunk.m_time, endianType); + MCore::Endian::ConvertUnsignedInt16(&keyframeChunk.m_value, endianType); - const float value = keyframeChunk.mValue / static_cast(std::numeric_limits::max()); - motionData->SetMorphSample(s, i, {keyframeChunk.mTime, value}); + const float value = keyframeChunk.m_value / static_cast(std::numeric_limits::max()); + motionData->SetMorphSample(s, i, {keyframeChunk.m_time, value}); } } // for all submotions @@ -1565,8 +1532,8 @@ namespace EMotionFX // morph targets bool ChunkProcessorActorProgMorphTargets::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); @@ -1576,122 +1543,122 @@ namespace EMotionFX file->Read(&morphTargetsHeader, sizeof(FileFormat::Actor_MorphTargets)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.mNumMorphTargets, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.mLOD, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.m_numMorphTargets, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.m_lod, endianType); if (GetLogging()) { - MCore::LogDetailedInfo("- Morph targets: %d (LOD=%d)", morphTargetsHeader.mNumMorphTargets, morphTargetsHeader.mLOD); + MCore::LogDetailedInfo("- Morph targets: %d (LOD=%d)", morphTargetsHeader.m_numMorphTargets, morphTargetsHeader.m_lod); } // check if the morph setup has already been created, if not create it - if (actor->GetMorphSetup(morphTargetsHeader.mLOD) == nullptr) + if (actor->GetMorphSetup(morphTargetsHeader.m_lod) == nullptr) { // create the morph setup MorphSetup* morphSetup = MorphSetup::Create(); // set the morph setup - actor->SetMorphSetup(morphTargetsHeader.mLOD, morphSetup); + actor->SetMorphSetup(morphTargetsHeader.m_lod, morphSetup); } // pre-allocate the morph targets - MorphSetup* setup = actor->GetMorphSetup(morphTargetsHeader.mLOD); - setup->ReserveMorphTargets(morphTargetsHeader.mNumMorphTargets); + MorphSetup* setup = actor->GetMorphSetup(morphTargetsHeader.m_lod); + setup->ReserveMorphTargets(morphTargetsHeader.m_numMorphTargets); // read in all morph targets - for (uint32 mt = 0; mt < morphTargetsHeader.mNumMorphTargets; ++mt) + for (uint32 mt = 0; mt < morphTargetsHeader.m_numMorphTargets; ++mt) { // read the expression part from disk FileFormat::Actor_MorphTarget morphTargetChunk; file->Read(&morphTargetChunk, sizeof(FileFormat::Actor_MorphTarget)); // convert endian - MCore::Endian::ConvertFloat(&morphTargetChunk.mRangeMin, endianType); - MCore::Endian::ConvertFloat(&morphTargetChunk.mRangeMax, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mLOD, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mNumTransformations, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mPhonemeSets, endianType); + MCore::Endian::ConvertFloat(&morphTargetChunk.m_rangeMin, endianType); + MCore::Endian::ConvertFloat(&morphTargetChunk.m_rangeMax, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_lod, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_numTransformations, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_phonemeSets, endianType); // make sure they match - MCORE_ASSERT(morphTargetChunk.mLOD == morphTargetsHeader.mLOD); + MCORE_ASSERT(morphTargetChunk.m_lod == morphTargetsHeader.m_lod); // get the expression name - const char* morphTargetName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* morphTargetName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // get the level of detail of the expression part - const uint32 morphTargetLOD = morphTargetChunk.mLOD; + const uint32 morphTargetLOD = morphTargetChunk.m_lod; if (GetLogging()) { MCore::LogDetailedInfo(" + Morph Target:"); MCore::LogDetailedInfo(" - Name = '%s'", morphTargetName); - MCore::LogDetailedInfo(" - LOD Level = %d", morphTargetChunk.mLOD); - MCore::LogDetailedInfo(" - RangeMin = %f", morphTargetChunk.mRangeMin); - MCore::LogDetailedInfo(" - RangeMax = %f", morphTargetChunk.mRangeMax); - MCore::LogDetailedInfo(" - NumTransformations = %d", morphTargetChunk.mNumTransformations); - MCore::LogDetailedInfo(" - PhonemeSets: %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphTargetChunk.mPhonemeSets).c_str()); + MCore::LogDetailedInfo(" - LOD Level = %d", morphTargetChunk.m_lod); + MCore::LogDetailedInfo(" - RangeMin = %f", morphTargetChunk.m_rangeMin); + MCore::LogDetailedInfo(" - RangeMax = %f", morphTargetChunk.m_rangeMax); + MCore::LogDetailedInfo(" - NumTransformations = %d", morphTargetChunk.m_numTransformations); + MCore::LogDetailedInfo(" - PhonemeSets: %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphTargetChunk.m_phonemeSets).c_str()); } // create the morph target MorphTargetStandard* morphTarget = MorphTargetStandard::Create(morphTargetName); // set the slider range - morphTarget->SetRangeMin(morphTargetChunk.mRangeMin); - morphTarget->SetRangeMax(morphTargetChunk.mRangeMax); + morphTarget->SetRangeMin(morphTargetChunk.m_rangeMin); + morphTarget->SetRangeMax(morphTargetChunk.m_rangeMax); // set the phoneme sets - morphTarget->SetPhonemeSets((MorphTarget::EPhonemeSet)morphTargetChunk.mPhonemeSets); + morphTarget->SetPhonemeSets((MorphTarget::EPhonemeSet)morphTargetChunk.m_phonemeSets); // add the morph target setup->AddMorphTarget(morphTarget); // the same for the transformations - morphTarget->ReserveTransformations(morphTargetChunk.mNumTransformations); + morphTarget->ReserveTransformations(morphTargetChunk.m_numTransformations); // read the facial transformations - for (uint32 i = 0; i < morphTargetChunk.mNumTransformations; ++i) + for (uint32 i = 0; i < morphTargetChunk.m_numTransformations; ++i) { // read the facial transformation from disk FileFormat::Actor_MorphTargetTransform transformChunk; file->Read(&transformChunk, sizeof(FileFormat::Actor_MorphTargetTransform)); // create Core objects from the data - AZ::Vector3 pos(transformChunk.mPosition.mX, transformChunk.mPosition.mY, transformChunk.mPosition.mZ); - AZ::Vector3 scale(transformChunk.mScale.mX, transformChunk.mScale.mY, transformChunk.mScale.mZ); - AZ::Quaternion rot(transformChunk.mRotation.mX, transformChunk.mRotation.mY, transformChunk.mRotation.mZ, transformChunk.mRotation.mW); - AZ::Quaternion scaleRot(transformChunk.mScaleRotation.mX, transformChunk.mScaleRotation.mY, transformChunk.mScaleRotation.mZ, transformChunk.mScaleRotation.mW); + AZ::Vector3 pos(transformChunk.m_position.m_x, transformChunk.m_position.m_y, transformChunk.m_position.m_z); + AZ::Vector3 scale(transformChunk.m_scale.m_x, transformChunk.m_scale.m_y, transformChunk.m_scale.m_z); + AZ::Quaternion rot(transformChunk.m_rotation.m_x, transformChunk.m_rotation.m_y, transformChunk.m_rotation.m_z, transformChunk.m_rotation.m_w); + AZ::Quaternion scaleRot(transformChunk.m_scaleRotation.m_x, transformChunk.m_scaleRotation.m_y, transformChunk.m_scaleRotation.m_z, transformChunk.m_scaleRotation.m_w); // convert endian and coordinate system ConvertVector3(&pos, endianType); ConvertScale(&scale, endianType); ConvertQuaternion(&rot, endianType); ConvertQuaternion(&scaleRot, endianType); - MCore::Endian::ConvertUnsignedInt32(&transformChunk.mNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&transformChunk.m_nodeIndex, endianType); // create our transformation MorphTargetStandard::Transformation transform; - transform.mPosition = pos; - transform.mScale = scale; - transform.mRotation = rot; - transform.mScaleRotation = scaleRot; - transform.mNodeIndex = transformChunk.mNodeIndex; + transform.m_position = pos; + transform.m_scale = scale; + transform.m_rotation = rot; + transform.m_scaleRotation = scaleRot; + transform.m_nodeIndex = transformChunk.m_nodeIndex; if (GetLogging()) { - MCore::LogDetailedInfo(" + Transform #%d: Node='%s' (index=%d)", i, skeleton->GetNode(transform.mNodeIndex)->GetName(), transform.mNodeIndex); + MCore::LogDetailedInfo(" + Transform #%d: Node='%s' (index=%d)", i, skeleton->GetNode(transform.m_nodeIndex)->GetName(), transform.m_nodeIndex); MCore::LogDetailedInfo(" - Pos: %f, %f, %f", - static_cast(transform.mPosition.GetX()), - static_cast(transform.mPosition.GetY()), - static_cast(transform.mPosition.GetZ())); + static_cast(transform.m_position.GetX()), + static_cast(transform.m_position.GetY()), + static_cast(transform.m_position.GetZ())); MCore::LogDetailedInfo(" - Rotation: %f, %f, %f %f", - static_cast(transform.mRotation.GetX()), - static_cast(transform.mRotation.GetY()), - static_cast(transform.mRotation.GetZ()), - static_cast(transform.mRotation.GetW())); + static_cast(transform.m_rotation.GetX()), + static_cast(transform.m_rotation.GetY()), + static_cast(transform.m_rotation.GetZ()), + static_cast(transform.m_rotation.GetW())); MCore::LogDetailedInfo(" - Scale: %f, %f, %f", - static_cast(transform.mScale.GetX()), - static_cast(transform.mScale.GetY()), - static_cast(transform.mScale.GetZ())); + static_cast(transform.m_scale.GetX()), + static_cast(transform.m_scale.GetY()), + static_cast(transform.m_scale.GetZ())); MCore::LogDetailedInfo(" - ScaleRot: %f, %f, %f %f", static_cast(scaleRot.GetX()), static_cast(scaleRot.GetY()), @@ -1712,8 +1679,8 @@ namespace EMotionFX // morph targets bool ChunkProcessorActorProgMorphTargets2::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); @@ -1723,122 +1690,122 @@ namespace EMotionFX file->Read(&morphTargetsHeader, sizeof(FileFormat::Actor_MorphTargets)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.mNumMorphTargets, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.mLOD, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.m_numMorphTargets, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetsHeader.m_lod, endianType); if (GetLogging()) { - MCore::LogDetailedInfo("- Morph targets: %d (LOD=%d)", morphTargetsHeader.mNumMorphTargets, morphTargetsHeader.mLOD); + MCore::LogDetailedInfo("- Morph targets: %d (LOD=%d)", morphTargetsHeader.m_numMorphTargets, morphTargetsHeader.m_lod); } // check if the morph setup has already been created, if not create it - if (actor->GetMorphSetup(morphTargetsHeader.mLOD) == nullptr) + if (actor->GetMorphSetup(morphTargetsHeader.m_lod) == nullptr) { // create the morph setup MorphSetup* morphSetup = MorphSetup::Create(); // set the morph setup - actor->SetMorphSetup(morphTargetsHeader.mLOD, morphSetup); + actor->SetMorphSetup(morphTargetsHeader.m_lod, morphSetup); } // pre-allocate the morph targets - MorphSetup* setup = actor->GetMorphSetup(morphTargetsHeader.mLOD); - setup->ReserveMorphTargets(morphTargetsHeader.mNumMorphTargets); + MorphSetup* setup = actor->GetMorphSetup(morphTargetsHeader.m_lod); + setup->ReserveMorphTargets(morphTargetsHeader.m_numMorphTargets); // read in all morph targets - for (uint32 mt = 0; mt < morphTargetsHeader.mNumMorphTargets; ++mt) + for (uint32 mt = 0; mt < morphTargetsHeader.m_numMorphTargets; ++mt) { // read the expression part from disk FileFormat::Actor_MorphTarget morphTargetChunk; file->Read(&morphTargetChunk, sizeof(FileFormat::Actor_MorphTarget)); // convert endian - MCore::Endian::ConvertFloat(&morphTargetChunk.mRangeMin, endianType); - MCore::Endian::ConvertFloat(&morphTargetChunk.mRangeMax, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mLOD, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mNumTransformations, endianType); - MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.mPhonemeSets, endianType); + MCore::Endian::ConvertFloat(&morphTargetChunk.m_rangeMin, endianType); + MCore::Endian::ConvertFloat(&morphTargetChunk.m_rangeMax, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_lod, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_numTransformations, endianType); + MCore::Endian::ConvertUnsignedInt32(&morphTargetChunk.m_phonemeSets, endianType); // make sure they match - MCORE_ASSERT(morphTargetChunk.mLOD == morphTargetsHeader.mLOD); + MCORE_ASSERT(morphTargetChunk.m_lod == morphTargetsHeader.m_lod); // get the expression name - const char* morphTargetName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + const char* morphTargetName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // get the level of detail of the expression part - const uint32 morphTargetLOD = morphTargetChunk.mLOD; + const uint32 morphTargetLOD = morphTargetChunk.m_lod; if (GetLogging()) { MCore::LogDetailedInfo(" + Morph Target:"); MCore::LogDetailedInfo(" - Name = '%s'", morphTargetName); - MCore::LogDetailedInfo(" - LOD Level = %d", morphTargetChunk.mLOD); - MCore::LogDetailedInfo(" - RangeMin = %f", morphTargetChunk.mRangeMin); - MCore::LogDetailedInfo(" - RangeMax = %f", morphTargetChunk.mRangeMax); - MCore::LogDetailedInfo(" - NumTransformations = %d", morphTargetChunk.mNumTransformations); - MCore::LogDetailedInfo(" - PhonemeSets: %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphTargetChunk.mPhonemeSets).c_str()); + MCore::LogDetailedInfo(" - LOD Level = %d", morphTargetChunk.m_lod); + MCore::LogDetailedInfo(" - RangeMin = %f", morphTargetChunk.m_rangeMin); + MCore::LogDetailedInfo(" - RangeMax = %f", morphTargetChunk.m_rangeMax); + MCore::LogDetailedInfo(" - NumTransformations = %d", morphTargetChunk.m_numTransformations); + MCore::LogDetailedInfo(" - PhonemeSets: %s", MorphTarget::GetPhonemeSetString((MorphTarget::EPhonemeSet)morphTargetChunk.m_phonemeSets).c_str()); } // create the morph target MorphTargetStandard* morphTarget = MorphTargetStandard::Create(morphTargetName); // set the slider range - morphTarget->SetRangeMin(morphTargetChunk.mRangeMin); - morphTarget->SetRangeMax(morphTargetChunk.mRangeMax); + morphTarget->SetRangeMin(morphTargetChunk.m_rangeMin); + morphTarget->SetRangeMax(morphTargetChunk.m_rangeMax); // set the phoneme sets - morphTarget->SetPhonemeSets((MorphTarget::EPhonemeSet)morphTargetChunk.mPhonemeSets); + morphTarget->SetPhonemeSets((MorphTarget::EPhonemeSet)morphTargetChunk.m_phonemeSets); // add the morph target setup->AddMorphTarget(morphTarget); // the same for the transformations - morphTarget->ReserveTransformations(morphTargetChunk.mNumTransformations); + morphTarget->ReserveTransformations(morphTargetChunk.m_numTransformations); // read the facial transformations - for (uint32 i = 0; i < morphTargetChunk.mNumTransformations; ++i) + for (uint32 i = 0; i < morphTargetChunk.m_numTransformations; ++i) { // read the facial transformation from disk FileFormat::Actor_MorphTargetTransform transformChunk; file->Read(&transformChunk, sizeof(FileFormat::Actor_MorphTargetTransform)); // create Core objects from the data - AZ::Vector3 pos(transformChunk.mPosition.mX, transformChunk.mPosition.mY, transformChunk.mPosition.mZ); - AZ::Vector3 scale(transformChunk.mScale.mX, transformChunk.mScale.mY, transformChunk.mScale.mZ); - AZ::Quaternion rot(transformChunk.mRotation.mX, transformChunk.mRotation.mY, transformChunk.mRotation.mZ, transformChunk.mRotation.mW); - AZ::Quaternion scaleRot(transformChunk.mScaleRotation.mX, transformChunk.mScaleRotation.mY, transformChunk.mScaleRotation.mZ, transformChunk.mScaleRotation.mW); + AZ::Vector3 pos(transformChunk.m_position.m_x, transformChunk.m_position.m_y, transformChunk.m_position.m_z); + AZ::Vector3 scale(transformChunk.m_scale.m_x, transformChunk.m_scale.m_y, transformChunk.m_scale.m_z); + AZ::Quaternion rot(transformChunk.m_rotation.m_x, transformChunk.m_rotation.m_y, transformChunk.m_rotation.m_z, transformChunk.m_rotation.m_w); + AZ::Quaternion scaleRot(transformChunk.m_scaleRotation.m_x, transformChunk.m_scaleRotation.m_y, transformChunk.m_scaleRotation.m_z, transformChunk.m_scaleRotation.m_w); // convert endian and coordinate system ConvertVector3(&pos, endianType); ConvertScale(&scale, endianType); ConvertQuaternion(&rot, endianType); ConvertQuaternion(&scaleRot, endianType); - MCore::Endian::ConvertUnsignedInt32(&transformChunk.mNodeIndex, endianType); + MCore::Endian::ConvertUnsignedInt32(&transformChunk.m_nodeIndex, endianType); // create our transformation MorphTargetStandard::Transformation transform; - transform.mPosition = pos; - transform.mScale = scale; - transform.mRotation = rot; - transform.mScaleRotation = scaleRot; - transform.mNodeIndex = transformChunk.mNodeIndex; + transform.m_position = pos; + transform.m_scale = scale; + transform.m_rotation = rot; + transform.m_scaleRotation = scaleRot; + transform.m_nodeIndex = transformChunk.m_nodeIndex; if (GetLogging()) { - MCore::LogDetailedInfo(" + Transform #%d: Node='%s' (index=%d)", i, skeleton->GetNode(transform.mNodeIndex)->GetName(), transform.mNodeIndex); + MCore::LogDetailedInfo(" + Transform #%d: Node='%s' (index=%d)", i, skeleton->GetNode(transform.m_nodeIndex)->GetName(), transform.m_nodeIndex); MCore::LogDetailedInfo(" - Pos: %f, %f, %f", - static_cast(transform.mPosition.GetX()), - static_cast(transform.mPosition.GetY()), - static_cast(transform.mPosition.GetZ())); + static_cast(transform.m_position.GetX()), + static_cast(transform.m_position.GetY()), + static_cast(transform.m_position.GetZ())); MCore::LogDetailedInfo(" - Rotation: %f, %f, %f %f", - static_cast(transform.mRotation.GetX()), - static_cast(transform.mRotation.GetY()), - static_cast(transform.mRotation.GetZ()), - static_cast(transform.mRotation.GetW())); + static_cast(transform.m_rotation.GetX()), + static_cast(transform.m_rotation.GetY()), + static_cast(transform.m_rotation.GetZ()), + static_cast(transform.m_rotation.GetW())); MCore::LogDetailedInfo(" - Scale: %f, %f, %f", - static_cast(transform.mScale.GetX()), - static_cast(transform.mScale.GetY()), - static_cast(transform.mScale.GetZ())); + static_cast(transform.m_scale.GetX()), + static_cast(transform.m_scale.GetY()), + static_cast(transform.m_scale.GetZ())); MCore::LogDetailedInfo(" - ScaleRot: %f, %f, %f %f", static_cast(scaleRot.GetX()), static_cast(scaleRot.GetY()), @@ -1860,8 +1827,8 @@ namespace EMotionFX // the node motion sources chunk bool ChunkProcessorActorNodeMotionSources::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; uint32 i; MCORE_ASSERT(actor); @@ -1872,8 +1839,8 @@ namespace EMotionFX file->Read(&nodeMotionSourcesChunk, sizeof(FileFormat::Actor_NodeMotionSources2)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&nodeMotionSourcesChunk.mNumNodes, endianType); - const uint32 numNodes = nodeMotionSourcesChunk.mNumNodes; + MCore::Endian::ConvertUnsignedInt32(&nodeMotionSourcesChunk.m_numNodes, endianType); + const uint32 numNodes = nodeMotionSourcesChunk.m_numNodes; if (numNodes == 0) { return true; @@ -1890,7 +1857,7 @@ namespace EMotionFX uint16 sourceNode; file->Read(&sourceNode, sizeof(uint16)); MCore::Endian::ConvertUnsignedInt16(&sourceNode, endianType); - actor->GetNodeMirrorInfo(i).mSourceNode = sourceNode; + actor->GetNodeMirrorInfo(i).m_sourceNode = sourceNode; } // read all axes @@ -1898,7 +1865,7 @@ namespace EMotionFX { uint8 axis; file->Read(&axis, sizeof(uint8)); - actor->GetNodeMirrorInfo(i).mAxis = axis; + actor->GetNodeMirrorInfo(i).m_axis = axis; } // read all flags @@ -1906,7 +1873,7 @@ namespace EMotionFX { uint8 flags; file->Read(&flags, sizeof(uint8)); - actor->GetNodeMirrorInfo(i).mFlags = flags; + actor->GetNodeMirrorInfo(i).m_flags = flags; } // log details @@ -1915,9 +1882,9 @@ namespace EMotionFX MCore::LogDetailedInfo("- Node Motion Sources (%i):", numNodes); for (i = 0; i < numNodes; ++i) { - if (actor->GetNodeMirrorInfo(i).mSourceNode != MCORE_INVALIDINDEX16) + if (actor->GetNodeMirrorInfo(i).m_sourceNode != MCORE_INVALIDINDEX16) { - MCore::LogDetailedInfo(" + '%s' (%i) -> '%s' (%i) [axis=%d] [flags=%d]", skeleton->GetNode(i)->GetName(), i, skeleton->GetNode(actor->GetNodeMirrorInfo(i).mSourceNode)->GetName(), actor->GetNodeMirrorInfo(i).mSourceNode, actor->GetNodeMirrorInfo(i).mAxis, actor->GetNodeMirrorInfo(i).mFlags); + MCore::LogDetailedInfo(" + '%s' (%i) -> '%s' (%i) [axis=%d] [flags=%d]", skeleton->GetNode(i)->GetName(), i, skeleton->GetNode(actor->GetNodeMirrorInfo(i).m_sourceNode)->GetName(), actor->GetNodeMirrorInfo(i).m_sourceNode, actor->GetNodeMirrorInfo(i).m_axis, actor->GetNodeMirrorInfo(i).m_flags); } } } @@ -1930,10 +1897,9 @@ namespace EMotionFX bool ChunkProcessorActorAttachmentNodes::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - Actor* actor = importParams.mActor; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + Actor* actor = importParams.m_actor; - uint32 i; MCORE_ASSERT(actor); Skeleton* skeleton = actor->GetSkeleton(); @@ -1942,11 +1908,11 @@ namespace EMotionFX file->Read(&attachmentNodesChunk, sizeof(FileFormat::Actor_AttachmentNodes)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&attachmentNodesChunk.mNumNodes, endianType); - const uint32 numAttachmentNodes = attachmentNodesChunk.mNumNodes; + MCore::Endian::ConvertUnsignedInt32(&attachmentNodesChunk.m_numNodes, endianType); + const uint32 numAttachmentNodes = attachmentNodesChunk.m_numNodes; // read all node attachment nodes - for (i = 0; i < numAttachmentNodes; ++i) + for (uint32 i = 0; i < numAttachmentNodes; ++i) { // get the attachment node index and endian convert it uint16 nodeNr; @@ -1966,8 +1932,8 @@ namespace EMotionFX { MCore::LogDetailedInfo("- Attachment Nodes (%i):", numAttachmentNodes); - const uint32 numNodes = actor->GetNumNodes(); - for (i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // get the current node Node* node = skeleton->GetNode(i); @@ -1975,7 +1941,7 @@ namespace EMotionFX // only log the attachment nodes if (node->GetIsAttachmentNode()) { - MCore::LogDetailedInfo(" + '%s' (%i)", node->GetName(), node->GetNodeIndex()); + MCore::LogDetailedInfo(" + '%s' (%zu)", node->GetName(), node->GetNodeIndex()); } } } @@ -1990,35 +1956,35 @@ namespace EMotionFX // node map bool ChunkProcessorNodeMap::Process(MCore::File* file, Importer::ImportParameters& importParams) { - const MCore::Endian::EEndianType endianType = importParams.mEndianType; + const MCore::Endian::EEndianType endianType = importParams.m_endianType; // read the header FileFormat::NodeMapChunk nodeMapChunk; file->Read(&nodeMapChunk, sizeof(FileFormat::NodeMapChunk)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&nodeMapChunk.mNumEntries, endianType); + MCore::Endian::ConvertUnsignedInt32(&nodeMapChunk.m_numEntries, endianType); // load the source actor filename string, but discard it - SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); // log some info if (GetLogging()) { MCore::LogDetailedInfo("- Node Map:"); - MCore::LogDetailedInfo(" + Num entries = %d", nodeMapChunk.mNumEntries); + MCore::LogDetailedInfo(" + Num entries = %d", nodeMapChunk.m_numEntries); } // for all entries - const uint32 numEntries = nodeMapChunk.mNumEntries; - importParams.mNodeMap->Reserve(numEntries); + const uint32 numEntries = nodeMapChunk.m_numEntries; + importParams.m_nodeMap->Reserve(numEntries); AZStd::string firstName; AZStd::string secondName; for (uint32 i = 0; i < numEntries; ++i) { // read both names - firstName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); - secondName = SharedHelperData::ReadString(file, importParams.mSharedData, endianType); + firstName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); + secondName = SharedHelperData::ReadString(file, importParams.m_sharedData, endianType); if (GetLogging()) { @@ -2026,9 +1992,9 @@ namespace EMotionFX } // create the entry - if (importParams.mNodeMapSettings->mLoadNodes) + if (importParams.m_nodeMapSettings->m_loadNodes) { - importParams.mNodeMap->AddEntry(firstName.c_str(), secondName.c_str()); + importParams.m_nodeMap->AddEntry(firstName.c_str(), secondName.c_str()); } } @@ -2046,12 +2012,12 @@ namespace EMotionFX { return false; } - MCore::Endian::ConvertUnsignedInt32(&dataHeader.m_sizeInBytes, importParams.mEndianType); - MCore::Endian::ConvertUnsignedInt32(&dataHeader.m_dataVersion, importParams.mEndianType); + MCore::Endian::ConvertUnsignedInt32(&dataHeader.m_sizeInBytes, importParams.m_endianType); + MCore::Endian::ConvertUnsignedInt32(&dataHeader.m_dataVersion, importParams.m_endianType); // Read the strings. - const AZStd::string uuidString = SharedHelperData::ReadString(file, importParams.mSharedData, importParams.mEndianType); - const AZStd::string className = SharedHelperData::ReadString(file, importParams.mSharedData, importParams.mEndianType); + const AZStd::string uuidString = SharedHelperData::ReadString(file, importParams.m_sharedData, importParams.m_endianType); + const AZStd::string className = SharedHelperData::ReadString(file, importParams.m_sharedData, importParams.m_endianType); // Create the motion data of this type. const AZ::Uuid uuid = AZ::Uuid::CreateString(uuidString.c_str(), uuidString.size()); @@ -2062,25 +2028,25 @@ namespace EMotionFX { AZ_Assert(false, "Unsupported motion data type '%s' using uuid '%s'", className.c_str(), uuidString.c_str()); motionData = aznew UniformMotionData(); // Create an empty dummy motion data, so we don't break things. - importParams.mMotion->SetMotionData(motionData); + importParams.m_motion->SetMotionData(motionData); file->Forward(dataHeader.m_sizeInBytes); return false; } // Read the data. MotionData::ReadSettings readSettings; - readSettings.m_sourceEndianType = importParams.mEndianType; + readSettings.m_sourceEndianType = importParams.m_endianType; readSettings.m_logDetails = GetLogging(); readSettings.m_version = dataHeader.m_dataVersion; if (!motionData->Read(file, readSettings)) { AZ_Error("EMotionFX", false, "Failed to load motion data of type '%s'", className.c_str()); motionData = aznew UniformMotionData(); // Create an empty dummy motion data, so we don't break things. - importParams.mMotion->SetMotionData(motionData); + importParams.m_motion->SetMotionData(motionData); return false; } - importParams.mMotion->SetMotionData(motionData); + importParams.m_motion->SetMotionData(motionData); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h index 306e4af0c8..4dc6d11acb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.h @@ -9,7 +9,7 @@ #pragma once #include "../EMotionFXConfig.h" -#include +#include #include #include "../MemoryCategories.h" #include "../BaseObject.h" @@ -94,14 +94,14 @@ namespace EMotionFX * @param endianType The endian type to read the string in. * @return The actual string. */ - static const char* ReadString(MCore::Stream* file, MCore::Array* sharedData, MCore::Endian::EEndianType endianType); + static const char* ReadString(MCore::Stream* file, AZStd::vector* sharedData, MCore::Endian::EEndianType endianType); public: - uint32 mFileHighVersion; /**< The high file version. For example 3 in case of v3.10. */ - uint32 mFileLowVersion; /**< The low file version. For example 10 in case of v3.10. */ - uint32 mStringStorageSize; /**< The size of the string buffer. */ - bool mIsUnicodeFile; /**< True in case strings in the file are saved using unicode character set, false in case they are saved using multi-byte. */ - char* mStringStorage; /**< The shared string buffer. */ + uint32 m_fileHighVersion; /**< The high file version. For example 3 in case of v3.10. */ + uint32 m_fileLowVersion; /**< The low file version. For example 10 in case of v3.10. */ + uint32 m_stringStorageSize; /**< The size of the string buffer. */ + bool m_isUnicodeFile; /**< True in case strings in the file are saved using unicode character set, false in case they are saved using multi-byte. */ + char* m_stringStorage; /**< The shared string buffer. */ protected: /** * The constructor. @@ -213,12 +213,12 @@ namespace EMotionFX // rmalize and make sure their w components are positive for (uint32 i = 0; i < count; ++i) { - if (value[i].mW < 0) + if (value[i].m_w < 0) { - value[i].mX = -value[i].mX; - value[i].mY = -value[i].mY; - value[i].mZ = -value[i].mZ; - value[i].mW = -value[i].mW; + value[i].m_x = -value[i].m_x; + value[i].m_y = -value[i].m_y; + value[i].m_z = -value[i].m_z; + value[i].m_w = -value[i].m_w; } } } @@ -238,9 +238,9 @@ namespace EMotionFX } protected: - uint32 mChunkID; /**< The id of the chunk processor. */ - uint32 mVersion; /**< The version number of the chunk processor, to provide backward compatibility. */ - bool mLoggingActive; /**< When set to true the processor chunk will log events, otherwise no logging will be performed. */ + uint32 m_chunkId; /**< The id of the chunk processor. */ + uint32 m_version; /**< The version number of the chunk processor, to provide backward compatibility. */ + bool m_loggingActive; /**< When set to true the processor chunk will log events, otherwise no logging will be performed. */ /** * The constructor. @@ -256,7 +256,6 @@ namespace EMotionFX virtual ~ChunkProcessor(); }; - //------------------------------------------------------------------------------------------------- /** @@ -287,7 +286,7 @@ namespace EMotionFX EMFX_CHUNKPROCESSOR(ChunkProcessorActorInfo3, FileFormat::ACTOR_CHUNK_INFO, 3) EMFX_CHUNKPROCESSOR(ChunkProcessorActorProgMorphTarget, FileFormat::ACTOR_CHUNK_STDPROGMORPHTARGET, 1) EMFX_CHUNKPROCESSOR(ChunkProcessorActorNodeGroups, FileFormat::ACTOR_CHUNK_NODEGROUPS, 1) - EMFX_CHUNKPROCESSOR(ChunkProcessorActorNodes, FileFormat::ACTOR_CHUNK_NODES, 1) + EMFX_CHUNKPROCESSOR(ChunkProcessorActorNodes2, FileFormat::ACTOR_CHUNK_NODES, 2) EMFX_CHUNKPROCESSOR(ChunkProcessorActorProgMorphTargets, FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS, 1) EMFX_CHUNKPROCESSOR(ChunkProcessorActorProgMorphTargets2, FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS, 2) EMFX_CHUNKPROCESSOR(ChunkProcessorActorNodeMotionSources, FileFormat::ACTOR_CHUNK_NODEMOTIONSOURCES, 1) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp index 67cbb91c06..762fd29dcb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.cpp @@ -47,15 +47,12 @@ namespace EMotionFX Importer::Importer() : BaseObject() { - // set the memory category - mChunkProcessors.SetMemoryCategory(EMFX_MEMCATEGORY_IMPORTER); - // register all standard chunks RegisterStandardChunks(); // init some default values - mLoggingActive = true; - mLogDetails = false; + m_loggingActive = true; + m_logDetails = false; } @@ -63,10 +60,9 @@ namespace EMotionFX Importer::~Importer() { // remove all chunk processors - const uint32 numProcessors = mChunkProcessors.GetLength(); - for (uint32 i = 0; i < numProcessors; ++i) + for (ChunkProcessor* chunkProcessor : m_chunkProcessors) { - mChunkProcessors[i]->Destroy(); + chunkProcessor->Destroy(); } } @@ -92,13 +88,13 @@ namespace EMotionFX } // check the FOURCC - if (header.mFourcc[0] != 'A' || header.mFourcc[1] != 'C' || header.mFourcc[2] != 'T' || header.mFourcc[3] != 'R') + if (header.m_fourcc[0] != 'A' || header.m_fourcc[1] != 'C' || header.m_fourcc[2] != 'T' || header.m_fourcc[3] != 'R') { return false; } // read the chunks - switch (header.mEndianType) + switch (header.m_endianType) { case 0: *outEndianType = MCore::Endian::ENDIAN_LITTLE; @@ -107,10 +103,9 @@ namespace EMotionFX *outEndianType = MCore::Endian::ENDIAN_BIG; break; default: - MCore::LogError("Unsupported endian type used! (endian type = %d)", header.mEndianType); + MCore::LogError("Unsupported endian type used! (endian type = %d)", header.m_endianType); return false; } - ; // yes, it is a valid actor file! return true; @@ -132,13 +127,13 @@ namespace EMotionFX } // check the FOURCC - if ((header.mFourcc[0] != 'M' || header.mFourcc[1] != 'O' || header.mFourcc[2] != 'T' || header.mFourcc[3] != ' ')) + if ((header.m_fourcc[0] != 'M' || header.m_fourcc[1] != 'O' || header.m_fourcc[2] != 'T' || header.m_fourcc[3] != ' ')) { return false; } // read the chunks - switch (header.mEndianType) + switch (header.m_endianType) { case 0: *outEndianType = MCore::Endian::ENDIAN_LITTLE; @@ -147,10 +142,9 @@ namespace EMotionFX *outEndianType = MCore::Endian::ENDIAN_BIG; break; default: - MCore::LogError("Unsupported endian type used! (endian type = %d)", header.mEndianType); + MCore::LogError("Unsupported endian type used! (endian type = %d)", header.m_endianType); return false; } - ; // yes, it is a valid motion file! return true; @@ -170,13 +164,13 @@ namespace EMotionFX } // check the FOURCC - if (header.mFourCC[0] != 'N' || header.mFourCC[1] != 'O' || header.mFourCC[2] != 'M' || header.mFourCC[3] != 'P') + if (header.m_fourCc[0] != 'N' || header.m_fourCc[1] != 'O' || header.m_fourCc[2] != 'M' || header.m_fourCc[3] != 'P') { return false; } // read the chunks - switch (header.mEndianType) + switch (header.m_endianType) { case 0: *outEndianType = MCore::Endian::ENDIAN_LITTLE; @@ -185,7 +179,7 @@ namespace EMotionFX *outEndianType = MCore::Endian::ENDIAN_BIG; break; default: - MCore::LogError("Unsupported endian type used! (endian type = %d)", header.mEndianType); + MCore::LogError("Unsupported endian type used! (endian type = %d)", header.m_endianType); return false; } @@ -291,8 +285,7 @@ namespace EMotionFX MCORE_ASSERT(f->GetIsOpen()); // create the shared data - MCore::Array sharedData; - sharedData.SetMemoryCategory(EMFX_MEMCATEGORY_IMPORTER); + AZStd::vector sharedData; PrepareSharedData(sharedData); // verify if this is a valid actor file or not @@ -312,7 +305,7 @@ namespace EMotionFX actorSettings = *settings; } - if (actorSettings.mOptimizeForServer) + if (actorSettings.m_optimizeForServer) { actorSettings.OptimizeForServer(); } @@ -326,17 +319,17 @@ namespace EMotionFX if (actor) { - actor->SetThreadIndex(actorSettings.mThreadIndex); + actor->SetThreadIndex(actorSettings.m_threadIndex); // set the scale mode // actor->SetScaleMode( scaleMode ); // init the import parameters ImportParameters params; - params.mSharedData = &sharedData; - params.mEndianType = endianType; - params.mActorSettings = &actorSettings; - params.mActor = actor.get(); + params.m_sharedData = &sharedData; + params.m_endianType = endianType; + params.m_actorSettings = &actorSettings; + params.m_actor = actor.get(); // process all chunks while (ProcessChunk(f, params)) @@ -346,13 +339,13 @@ namespace EMotionFX actor->SetFileName(filename); // Generate an optimized version of skeleton for server. - if (actorSettings.mOptimizeForServer && actor->GetOptimizeSkeleton()) + if (actorSettings.m_optimizeForServer && actor->GetOptimizeSkeleton()) { actor->GenerateOptimizedSkeleton(); } // post create init - actor->PostCreateInit(actorSettings.mMakeGeomLODsCompatibleWithSkeletalLODs, false, actorSettings.mUnitTypeConvert); + actor->PostCreateInit(actorSettings.m_makeGeomLoDsCompatibleWithSkeletalLoDs, actorSettings.m_unitTypeConvert); } // close the file and return a pointer to the actor we loaded @@ -360,7 +353,7 @@ namespace EMotionFX // get rid of shared data ResetSharedData(sharedData); - sharedData.Clear(); + sharedData.clear(); // return the created actor return actor; @@ -374,7 +367,7 @@ namespace EMotionFX EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, filename); // check if we want to load the motion even if a motion with the given filename is already inside the motion manager - if (settings == nullptr || (settings && settings->mForceLoading == false)) + if (settings == nullptr || (settings && settings->m_forceLoading == false)) { // search the motion inside the motion manager and return it if it already got loaded Motion* motion = GetMotionManager().FindMotionByFileName(filename.c_str()); @@ -461,8 +454,7 @@ namespace EMotionFX MCORE_ASSERT(f->GetIsOpen()); // create the shared data - MCore::Array sharedData; - sharedData.SetMemoryCategory(EMFX_MEMCATEGORY_IMPORTER); + AZStd::vector sharedData; PrepareSharedData(sharedData); // verify if this is a valid actor file or not @@ -489,10 +481,10 @@ namespace EMotionFX // init the import parameters ImportParameters params; - params.mSharedData = &sharedData; - params.mEndianType = endianType; - params.mMotionSettings = &motionSettings; - params.mMotion = motion; + params.m_sharedData = &sharedData; + params.m_endianType = endianType; + params.m_motionSettings = &motionSettings; + params.m_motion = motion; // read the chunks while (ProcessChunk(f, params)) @@ -503,7 +495,7 @@ namespace EMotionFX motion->GetEventTable()->AutoCreateSyncTrack(motion); // scale to the EMotion FX unit type - if (motionSettings.mUnitTypeConvert) + if (motionSettings.m_unitTypeConvert) { motion->ScaleToUnitType(GetEMotionFX().GetUnitType()); } @@ -513,7 +505,7 @@ namespace EMotionFX // get rid of shared data ResetSharedData(sharedData); - sharedData.Clear(); + sharedData.clear(); return motion; } @@ -671,8 +663,7 @@ namespace EMotionFX } // create the shared data - MCore::Array sharedData; - sharedData.SetMemoryCategory(EMFX_MEMCATEGORY_IMPORTER); + AZStd::vector sharedData; PrepareSharedData(sharedData); //----------------------------------------------- @@ -680,7 +671,7 @@ namespace EMotionFX // load the file header FileFormat::NodeMap_Header fileHeader; f->Read(&fileHeader, sizeof(FileFormat::NodeMap_Header)); - if (fileHeader.mFourCC[0] != 'N' || fileHeader.mFourCC[1] != 'O' || fileHeader.mFourCC[2] != 'M' || fileHeader.mFourCC[3] != 'P') + if (fileHeader.m_fourCc[0] != 'N' || fileHeader.m_fourCc[1] != 'O' || fileHeader.m_fourCc[2] != 'M' || fileHeader.m_fourCc[3] != 'P') { MCore::LogError("The node map file is not a valid node map file."); f->Close(); @@ -688,17 +679,17 @@ namespace EMotionFX } // get the endian type - MCore::Endian::EEndianType endianType = (MCore::Endian::EEndianType)fileHeader.mEndianType; + MCore::Endian::EEndianType endianType = (MCore::Endian::EEndianType)fileHeader.m_endianType; // create the node map NodeMap* nodeMap = NodeMap::Create(); // init the import parameters ImportParameters params; - params.mSharedData = &sharedData; - params.mEndianType = endianType; - params.mNodeMap = nodeMap; - params.mNodeMapSettings = &nodeMapSettings; + params.m_sharedData = &sharedData; + params.m_endianType = endianType; + params.m_nodeMap = nodeMap; + params.m_nodeMapSettings = &nodeMapSettings; // process all chunks while (ProcessChunk(f, params)) @@ -710,7 +701,7 @@ namespace EMotionFX // get rid of shared data ResetSharedData(sharedData); - sharedData.Clear(); + sharedData.clear(); // return the created actor return nodeMap; @@ -722,72 +713,61 @@ namespace EMotionFX void Importer::RegisterChunkProcessor(ChunkProcessor* processorToRegister) { MCORE_ASSERT(processorToRegister); - mChunkProcessors.Add(processorToRegister); + m_chunkProcessors.emplace_back(processorToRegister); } // add shared data object to the importer - void Importer::AddSharedData(MCore::Array& sharedData, SharedData* data) + void Importer::AddSharedData(AZStd::vector& sharedData, SharedData* data) { MCORE_ASSERT(data); - sharedData.Add(data); + sharedData.emplace_back(data); } // search for shared data - SharedData* Importer::FindSharedData(MCore::Array* sharedDataArray, uint32 type) + SharedData* Importer::FindSharedData(AZStd::vector* sharedDataArray, uint32 type) { // for all shared data - const uint32 numSharedData = sharedDataArray->GetLength(); - for (uint32 i = 0; i < numSharedData; ++i) + const auto foundSharedData = AZStd::find_if(begin(*sharedDataArray), end(*sharedDataArray), [type](const SharedData* sharedData) { - SharedData* sharedData = sharedDataArray->GetItem(i); - - // check if it's the type we are searching for - if (sharedData->GetType() == type) - { - return sharedData; - } - } - - // nothing found - return nullptr; + return sharedData->GetType() == type; + }); + return foundSharedData != end(*sharedDataArray) ? *foundSharedData : nullptr; } void Importer::SetLoggingEnabled(bool enabled) { - mLoggingActive = enabled; + m_loggingActive = enabled; } bool Importer::GetLogging() const { - return mLoggingActive; + return m_loggingActive; } void Importer::SetLogDetails(bool detailLoggingActive) { - mLogDetails = detailLoggingActive; + m_logDetails = detailLoggingActive; // set the processors logging flag - const int32 numProcessors = mChunkProcessors.GetLength(); - for (int32 i = 0; i < numProcessors; i++) + for (ChunkProcessor* processor : m_chunkProcessors) { - ChunkProcessor* processor = mChunkProcessors[i]; - processor->SetLogging((mLoggingActive && detailLoggingActive)); // only enable if logging is also enabled + processor->SetLogging(m_loggingActive && detailLoggingActive); // only enable if logging is also enabled } } bool Importer::GetLogDetails() const { - return mLogDetails; + return m_logDetails; } - void Importer::PrepareSharedData(MCore::Array& sharedData) + void Importer::PrepareSharedData(AZStd::vector& sharedData) { // create standard shared objects AddSharedData(sharedData, SharedHelperData::Create()); @@ -795,16 +775,14 @@ namespace EMotionFX // reset shared objects so that the importer is ready for use again - void Importer::ResetSharedData(MCore::Array& sharedData) + void Importer::ResetSharedData(AZStd::vector& sharedData) { - const int32 numSharedData = sharedData.GetLength(); - for (int32 i = 0; i < numSharedData; i++) + for (SharedData* data : sharedData) { - SharedData* data = sharedData[i]; data->Reset(); data->Destroy(); } - sharedData.Clear(); + sharedData.clear(); } @@ -812,20 +790,11 @@ namespace EMotionFX ChunkProcessor* Importer::FindChunk(uint32 chunkID, uint32 version) const { // for all chunk processors - const uint32 numProcessors = mChunkProcessors.GetLength(); - for (uint32 i = 0; i < numProcessors; ++i) + const auto foundProcessor = AZStd::find_if(begin(m_chunkProcessors), end(m_chunkProcessors), [chunkID, version](const ChunkProcessor* processor) { - ChunkProcessor* processor = mChunkProcessors[i]; - - // if this chunk is the type we are searching for AND it can process our chunk version, return it - if (processor->GetChunkID() == chunkID && processor->GetVersion() == version) - { - return processor; - } - } - - // nothing found - return nullptr; + return processor->GetChunkID() == chunkID && processor->GetVersion() == version; + }); + return foundProcessor != end(m_chunkProcessors) ? *foundProcessor : nullptr; } @@ -833,7 +802,7 @@ namespace EMotionFX void Importer::RegisterStandardChunks() { // reserve space for 75 chunk processors - mChunkProcessors.Reserve(75); + m_chunkProcessors.reserve(75); // shared processors RegisterChunkProcessor(aznew ChunkProcessorMotionEventTrackTable()); @@ -846,7 +815,7 @@ namespace EMotionFX RegisterChunkProcessor(aznew ChunkProcessorActorInfo3()); RegisterChunkProcessor(aznew ChunkProcessorActorProgMorphTarget()); RegisterChunkProcessor(aznew ChunkProcessorActorNodeGroups()); - RegisterChunkProcessor(aznew ChunkProcessorActorNodes()); + RegisterChunkProcessor(aznew ChunkProcessorActorNodes2()); RegisterChunkProcessor(aznew ChunkProcessorActorProgMorphTargets()); RegisterChunkProcessor(aznew ChunkProcessorActorProgMorphTargets2()); RegisterChunkProcessor(aznew ChunkProcessorActorNodeMotionSources()); @@ -884,40 +853,40 @@ namespace EMotionFX return false; // failed reading chunk } // convert endian - const MCore::Endian::EEndianType endianType = importParams.mEndianType; - MCore::Endian::ConvertUnsignedInt32(&chunk.mChunkID, endianType); - MCore::Endian::ConvertUnsignedInt32(&chunk.mSizeInBytes, endianType); - MCore::Endian::ConvertUnsignedInt32(&chunk.mVersion, endianType); + const MCore::Endian::EEndianType endianType = importParams.m_endianType; + MCore::Endian::ConvertUnsignedInt32(&chunk.m_chunkId, endianType); + MCore::Endian::ConvertUnsignedInt32(&chunk.m_sizeInBytes, endianType); + MCore::Endian::ConvertUnsignedInt32(&chunk.m_version, endianType); // try to find the chunk processor which can process this chunk - ChunkProcessor* processor = FindChunk(chunk.mChunkID, chunk.mVersion); + ChunkProcessor* processor = FindChunk(chunk.m_chunkId, chunk.m_version); // if we cannot find the chunk, skip the chunk if (processor == nullptr) { if (GetLogging()) { - MCore::LogError("Importer::ProcessChunk() - Unknown chunk (ID=%d Size=%d bytes Version=%d), skipping...", chunk.mChunkID, chunk.mSizeInBytes, chunk.mVersion); + MCore::LogError("Importer::ProcessChunk() - Unknown chunk (ID=%d Size=%d bytes Version=%d), skipping...", chunk.m_chunkId, chunk.m_sizeInBytes, chunk.m_version); } - file->Forward(chunk.mSizeInBytes); + file->Forward(chunk.m_sizeInBytes); return true; } // get some shortcuts - Importer::ActorSettings* actorSettings = importParams.mActorSettings; - Importer::MotionSettings* skelMotionSettings = importParams.mMotionSettings; + Importer::ActorSettings* actorSettings = importParams.m_actorSettings; + Importer::MotionSettings* skelMotionSettings = importParams.m_motionSettings; // check if we still want to skip the chunk or not bool mustSkip = false; // check if we specified to ignore this chunk - if (actorSettings && actorSettings->mChunkIDsToIgnore.Contains(chunk.mChunkID)) + if (actorSettings && AZStd::find(begin(actorSettings->m_chunkIDsToIgnore), end(actorSettings->m_chunkIDsToIgnore), chunk.m_chunkId) != end(actorSettings->m_chunkIDsToIgnore)) { mustSkip = true; } - if (skelMotionSettings && skelMotionSettings->mChunkIDsToIgnore.Contains(chunk.mChunkID)) + if (skelMotionSettings && AZStd::find(begin(skelMotionSettings->m_chunkIDsToIgnore), end(skelMotionSettings->m_chunkIDsToIgnore), chunk.m_chunkId) != end(skelMotionSettings->m_chunkIDsToIgnore)) { mustSkip = true; } @@ -928,10 +897,10 @@ namespace EMotionFX // if we're loading an actor if (actorSettings) { - if ((actorSettings->mLoadLimits == false && chunk.mChunkID == FileFormat::ACTOR_CHUNK_LIMIT) || - (actorSettings->mLoadMorphTargets == false && chunk.mChunkID == FileFormat::ACTOR_CHUNK_STDPROGMORPHTARGET) || - (actorSettings->mLoadMorphTargets == false && chunk.mChunkID == FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS) || - (actorSettings->mLoadSimulatedObjects == false && chunk.mChunkID == FileFormat::ACTOR_CHUNK_SIMULATEDOBJECTSETUP)) + if ((actorSettings->m_loadLimits == false && chunk.m_chunkId == FileFormat::ACTOR_CHUNK_LIMIT) || + (actorSettings->m_loadMorphTargets == false && chunk.m_chunkId == FileFormat::ACTOR_CHUNK_STDPROGMORPHTARGET) || + (actorSettings->m_loadMorphTargets == false && chunk.m_chunkId == FileFormat::ACTOR_CHUNK_STDPMORPHTARGETS) || + (actorSettings->m_loadSimulatedObjects == false && chunk.m_chunkId == FileFormat::ACTOR_CHUNK_SIMULATEDOBJECTSETUP)) { mustSkip = true; } @@ -940,7 +909,7 @@ namespace EMotionFX // if we're loading a motion if (skelMotionSettings) { - if (skelMotionSettings->mLoadMotionEvents == false && chunk.mChunkID == FileFormat::MOTION_CHUNK_MOTIONEVENTTABLE) + if (skelMotionSettings->m_loadMotionEvents == false && chunk.m_chunkId == FileFormat::MOTION_CHUNK_MOTIONEVENTTABLE) { mustSkip = true; } @@ -950,7 +919,7 @@ namespace EMotionFX // if we want to skip this chunk if (mustSkip) { - file->Forward(chunk.mSizeInBytes); + file->Forward(chunk.m_sizeInBytes); return true; } @@ -963,20 +932,29 @@ namespace EMotionFX void Importer::ValidateActorSettings(ActorSettings* settings) { // After atom: Make sure we are not loading the tangents and bitangents - if (!settings->mLayerIDsToIgnore.Contains(Mesh::ATTRIB_TANGENTS)) + if (AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_TANGENTS) == end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.Add(Mesh::ATTRIB_TANGENTS); + settings->m_layerIDsToIgnore.emplace_back(Mesh::ATTRIB_TANGENTS); } - if (!settings->mLayerIDsToIgnore.Contains(Mesh::ATTRIB_BITANGENTS)) + if (AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_BITANGENTS) == end(settings->m_layerIDsToIgnore)) { - settings->mLayerIDsToIgnore.Add(Mesh::ATTRIB_BITANGENTS); + settings->m_layerIDsToIgnore.emplace_back(Mesh::ATTRIB_BITANGENTS); } // make sure we load at least the position and normals and org vertex numbers - settings->mLayerIDsToIgnore.RemoveByValue(Mesh::ATTRIB_ORGVTXNUMBERS); - settings->mLayerIDsToIgnore.RemoveByValue(Mesh::ATTRIB_NORMALS); - settings->mLayerIDsToIgnore.RemoveByValue(Mesh::ATTRIB_POSITIONS); + if(const auto it = AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_ORGVTXNUMBERS); it != end(settings->m_layerIDsToIgnore)) + { + settings->m_layerIDsToIgnore.erase(it); + } + if(const auto it = AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_NORMALS); it != end(settings->m_layerIDsToIgnore)) + { + settings->m_layerIDsToIgnore.erase(it); + } + if(const auto it = AZStd::find(begin(settings->m_layerIDsToIgnore), end(settings->m_layerIDsToIgnore), Mesh::ATTRIB_POSITIONS); it != end(settings->m_layerIDsToIgnore)) + { + settings->m_layerIDsToIgnore.erase(it); + } } @@ -1117,7 +1095,7 @@ namespace EMotionFX file.Close(); return false; } - outInfo->mEndianType = endianType; + outInfo->m_endianType = endianType; // as we seeked to the end of the header and we know the second chunk always is the time stamp, we can read this now FileFormat::FileChunk fileChunk; @@ -1126,8 +1104,8 @@ namespace EMotionFX file.Read(&timeChunk, sizeof(FileFormat::FileTime)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileChunk.mChunkID, endianType); - MCore::Endian::ConvertUnsignedInt16(&timeChunk.mYear, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileChunk.m_chunkId, endianType); + MCore::Endian::ConvertUnsignedInt16(&timeChunk.m_year, endianType); return true; } @@ -1150,7 +1128,7 @@ namespace EMotionFX file.Close(); return false; } - outInfo->mEndianType = endianType; + outInfo->m_endianType = endianType; // as we seeked to the end of the header and we know the second chunk always is the time stamp, we can read this now FileFormat::FileChunk fileChunk; @@ -1159,8 +1137,8 @@ namespace EMotionFX file.Read(&timeChunk, sizeof(FileFormat::FileTime)); // convert endian - MCore::Endian::ConvertUnsignedInt32(&fileChunk.mChunkID, endianType); - MCore::Endian::ConvertUnsignedInt16(&timeChunk.mYear, endianType); + MCore::Endian::ConvertUnsignedInt32(&fileChunk.m_chunkId, endianType); + MCore::Endian::ConvertUnsignedInt16(&timeChunk.m_year, endianType); return true; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h index 2b12f93a1a..1a9fdf3654 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/Importer.h @@ -9,7 +9,7 @@ #pragma once #include "../EMotionFXConfig.h" -#include +#include #include #include #include @@ -73,26 +73,26 @@ namespace EMotionFX */ struct EMFX_API ActorSettings { - bool mLoadLimits = true; /**< Set to false if you wish to disable loading of joint limits. */ - bool mLoadSkeletalLODs = true; /**< Set to false if you wish to disable loading of skeletal LOD levels. */ - bool mLoadMorphTargets = true; /**< Set to false if you wish to disable loading any morph targets. */ - bool mDualQuatSkinning = false; /**< Set to true if you wish to enable software skinning using dual quaternions. */ - bool mMakeGeomLODsCompatibleWithSkeletalLODs = false; /**< Set to true if you wish to disable the process that makes sure no skinning influences are mapped to disabled bones. Default is false. */ - bool mUnitTypeConvert = true; /**< Set to false to disable automatic unit type conversion (between cm, meters, etc). On default this is enabled. */ - bool mLoadSimulatedObjects = true; /**< Set to false if you wish to disable loading of simulated objects. */ - bool mOptimizeForServer = false; /**< Set to true if you witsh to optimize this actor to be used on server. */ - uint32 mThreadIndex = 0; - MCore::Array mChunkIDsToIgnore; /**< Add chunk ID's to this array. Chunks with these ID's will not be processed. */ - MCore::Array mLayerIDsToIgnore; /**< Add vertex attribute layer ID's to ignore. */ + bool m_loadLimits = true; /**< Set to false if you wish to disable loading of joint limits. */ + bool m_loadSkeletalLoDs = true; /**< Set to false if you wish to disable loading of skeletal LOD levels. */ + bool m_loadMorphTargets = true; /**< Set to false if you wish to disable loading any morph targets. */ + bool m_dualQuatSkinning = false; /**< Set to true if you wish to enable software skinning using dual quaternions. */ + bool m_makeGeomLoDsCompatibleWithSkeletalLoDs = false; /**< Set to true if you wish to disable the process that makes sure no skinning influences are mapped to disabled bones. Default is false. */ + bool m_unitTypeConvert = true; /**< Set to false to disable automatic unit type conversion (between cm, meters, etc). On default this is enabled. */ + bool m_loadSimulatedObjects = true; /**< Set to false if you wish to disable loading of simulated objects. */ + bool m_optimizeForServer = false; /**< Set to true if you witsh to optimize this actor to be used on server. */ + uint32 m_threadIndex = 0; + AZStd::vector m_chunkIDsToIgnore; /**< Add chunk ID's to this array. Chunks with these ID's will not be processed. */ + AZStd::vector m_layerIDsToIgnore; /**< Add vertex attribute layer ID's to ignore. */ /** * If the actor need to be optimized for server, will overwrite a few other actor settings. */ void OptimizeForServer() { - mLoadSkeletalLODs = false; - mLoadMorphTargets = false; - mLoadSimulatedObjects = false; + m_loadSkeletalLoDs = false; + m_loadMorphTargets = false; + m_loadSimulatedObjects = false; } }; @@ -102,10 +102,10 @@ namespace EMotionFX */ struct EMFX_API MotionSettings { - bool mForceLoading = false; /**< Set to true in case you want to load the motion even if a motion with the given filename is already inside the motion manager. */ - bool mLoadMotionEvents = true; /**< Set to false if you wish to disable loading of motion events. */ - bool mUnitTypeConvert = true; /**< Set to false to disable automatic unit type conversion (between cm, meters, etc). On default this is enabled. */ - MCore::Array mChunkIDsToIgnore; /**< Add the ID's of the chunks you wish to ignore. */ + bool m_forceLoading = false; /**< Set to true in case you want to load the motion even if a motion with the given filename is already inside the motion manager. */ + bool m_loadMotionEvents = true; /**< Set to false if you wish to disable loading of motion events. */ + bool m_unitTypeConvert = true; /**< Set to false to disable automatic unit type conversion (between cm, meters, etc). On default this is enabled. */ + AZStd::vector m_chunkIDsToIgnore; /**< Add the ID's of the chunks you wish to ignore. */ }; /** @@ -123,21 +123,21 @@ namespace EMotionFX */ struct EMFX_API NodeMapSettings { - bool mAutoLoadSourceActor = true; /**< Should we automatically try to load the source actor? (default=true) */ - bool mLoadNodes = true; /**< Add nodes to the map? (default=true) */ + bool m_autoLoadSourceActor = true; /**< Should we automatically try to load the source actor? (default=true) */ + bool m_loadNodes = true; /**< Add nodes to the map? (default=true) */ }; struct EMFX_API ImportParameters { - Actor* mActor = nullptr; - Motion* mMotion = nullptr; - Importer::ActorSettings* mActorSettings = nullptr; - Importer::MotionSettings* mMotionSettings = nullptr; - MCore::Array* mSharedData = nullptr; - MCore::Endian::EEndianType mEndianType = MCore::Endian::ENDIAN_LITTLE; - - NodeMap* mNodeMap = nullptr; - Importer::NodeMapSettings* mNodeMapSettings = nullptr; + Actor* m_actor = nullptr; + Motion* m_motion = nullptr; + Importer::ActorSettings* m_actorSettings = nullptr; + Importer::MotionSettings* m_motionSettings = nullptr; + AZStd::vector* m_sharedData = nullptr; + MCore::Endian::EEndianType m_endianType = MCore::Endian::ENDIAN_LITTLE; + + NodeMap* m_nodeMap = nullptr; + Importer::NodeMapSettings* m_nodeMapSettings = nullptr; bool m_isOwnedByRuntime = false; bool m_additiveMotion = false; }; @@ -159,7 +159,7 @@ namespace EMotionFX struct FileInfo { - MCore::Endian::EEndianType mEndianType; + MCore::Endian::EEndianType m_endianType; }; //------------------------------------------------------------------------------------------------- @@ -312,7 +312,7 @@ namespace EMotionFX * @param type The shared data ID to search for. * @return A pointer to the shared data object, or nullptr when no shared data of this type has been found. */ - static SharedData* FindSharedData(MCore::Array* sharedDataArray, uint32 type); + static SharedData* FindSharedData(AZStd::vector* sharedDataArray, uint32 type); /** * Enable or disable logging. @@ -355,9 +355,9 @@ namespace EMotionFX private: - MCore::Array mChunkProcessors; /**< The registered chunk processors. */ - bool mLoggingActive; /**< Contains if the importer should perform logging or not or not. */ - bool mLogDetails; /**< Contains if the importer should perform detail-logging or not. */ + AZStd::vector m_chunkProcessors; /**< The registered chunk processors. */ + bool m_loggingActive; /**< Contains if the importer should perform logging or not or not. */ + bool m_logDetails; /**< Contains if the importer should perform detail-logging or not. */ /** * The constructor. @@ -414,19 +414,19 @@ namespace EMotionFX * @param sharedData The array which holds the shared data objects. * @param data A pointer to your shared data object. */ - static void AddSharedData(MCore::Array& sharedData, SharedData* data); + static void AddSharedData(AZStd::vector& sharedData, SharedData* data); /* * Precreate the standard shared data objects. * @param sharedData The shared data array to work on. */ - static void PrepareSharedData(MCore::Array& sharedData); + static void PrepareSharedData(AZStd::vector& sharedData); /** * Reset all shared data objects. * Resetting these objects will clear/empty their internal data. */ - static void ResetSharedData(MCore::Array& sharedData); + static void ResetSharedData(AZStd::vector& sharedData); /** * Find the chunk processor which has a given ID and version number. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/MotionFileFormat.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/MotionFileFormat.h index f947b8abf6..40dac39f98 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/MotionFileFormat.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/MotionFileFormat.h @@ -33,10 +33,10 @@ namespace EMotionFX // (not aligned) struct Motion_Header { - uint8 mFourcc[4]; // must be "MOT " or "MOTW" - uint8 mHiVersion; // high version (2 in case of v2.34) - uint8 mLoVersion; // low version (34 in case of v2.34) - uint8 mEndianType; // the endian in which the data is saved [0=little, 1=big] + uint8 m_fourcc[4]; // must be "MOT " or "MOTW" + uint8 m_hiVersion; // high version (2 in case of v2.34) + uint8 m_loVersion; // low version (34 in case of v2.34) + uint8 m_endianType; // the endian in which the data is saved [0=little, 1=big] }; struct Motion_MotionData @@ -53,49 +53,49 @@ namespace EMotionFX // (not aligned) struct Motion_Info { - uint32 mMotionExtractionMask; // motion extraction mask - uint32 mMotionExtractionNodeIndex; // motion extraction node index - uint8 mUnitType; // maps to EMotionFX::EUnitType + uint32 m_motionExtractionMask; // motion extraction mask + uint32 m_motionExtractionNodeIndex; // motion extraction node index + uint8 m_unitType; // maps to EMotionFX::EUnitType }; // information chunk // (not aligned) struct Motion_Info2 { - uint32 mMotionExtractionFlags; // motion extraction flags - uint32 mMotionExtractionNodeIndex; // motion extraction node index - uint8 mUnitType; // maps to EMotionFX::EUnitType + uint32 m_motionExtractionFlags; // motion extraction flags + uint32 m_motionExtractionNodeIndex; // motion extraction node index + uint8 m_unitType; // maps to EMotionFX::EUnitType }; // information chunk // (not aligned) struct Motion_Info3 { - uint32 mMotionExtractionFlags; // motion extraction flags - uint32 mMotionExtractionNodeIndex; // motion extraction node index - uint8 mUnitType; // maps to EMotionFX::EUnitType - uint8 mIsAdditive; // if the motion is an additive motion [0=false, 1=true] + uint32 m_motionExtractionFlags; // motion extraction flags + uint32 m_motionExtractionNodeIndex; // motion extraction node index + uint8 m_unitType; // maps to EMotionFX::EUnitType + uint8 m_isAdditive; // if the motion is an additive motion [0=false, 1=true] }; // skeletal submotion // (aligned) struct Motion_SkeletalSubMotion { - File16BitQuaternion mPoseRot; // initial pose rotation - File16BitQuaternion mBindPoseRot; // bind pose rotation - FileVector3 mPosePos; // initial pose position - FileVector3 mPoseScale; // initial pose scale - FileVector3 mBindPosePos; // bind pose position - FileVector3 mBindPoseScale; // bind pose scale - uint32 mNumPosKeys; // number of position keyframes to follow - uint32 mNumRotKeys; // number of rotation keyframes to follow - uint32 mNumScaleKeys; // number of scale keyframes to follow + File16BitQuaternion m_poseRot; // initial pose rotation + File16BitQuaternion m_bindPoseRot; // bind pose rotation + FileVector3 m_posePos; // initial pose position + FileVector3 m_poseScale; // initial pose scale + FileVector3 m_bindPosePos; // bind pose position + FileVector3 m_bindPoseScale; // bind pose scale + uint32 m_numPosKeys; // number of position keyframes to follow + uint32 m_numRotKeys; // number of rotation keyframes to follow + uint32 m_numScaleKeys; // number of scale keyframes to follow // followed by: // string : motion part name - // Motion_Vector3Key[ mNumPosKeys ] - // Motion_16BitQuaternionKey[ mNumRotKeys ] - // Motion_Vector3Key[ mNumScaleKeys ] + // Motion_Vector3Key[ m_numPosKeys ] + // Motion_16BitQuaternionKey[ m_numRotKeys ] + // Motion_Vector3Key[ m_numScaleKeys ] }; @@ -103,8 +103,8 @@ namespace EMotionFX // (aligned) struct Motion_Vector3Key { - FileVector3 mValue; // the value - float mTime; // the time in seconds + FileVector3 m_value; // the value + float m_time; // the time in seconds }; @@ -112,8 +112,8 @@ namespace EMotionFX // (aligned) struct Motion_QuaternionKey { - FileQuaternion mValue; // the value - float mTime; // the time in seconds + FileQuaternion m_value; // the value + float m_time; // the time in seconds }; @@ -121,8 +121,8 @@ namespace EMotionFX // (aligned) struct Motion_16BitQuaternionKey { - File16BitQuaternion mValue; // the value - float mTime; // the time in seconds + File16BitQuaternion m_value; // the value + float m_time; // the time in seconds }; @@ -130,25 +130,25 @@ namespace EMotionFX // (aligned) struct Motion_SubMotions { - uint32 mNumSubMotions;// the number of skeletal motions + uint32 m_numSubMotions;// the number of skeletal motions // followed by: - // Motion_SkeletalSubMotion[ mNumSubMotions ] + // Motion_SkeletalSubMotion[ m_numSubMotions ] }; // morph sub motion // (aligned) struct Motion_MorphSubMotion { - float mPoseWeight;// pose weight to use in case no animation data is present - float mMinWeight; // minimum allowed weight value (used for unpacking the keyframe weights) - float mMaxWeight; // maximum allowed weight value (used for unpacking the keyframe weights) - uint32 mPhonemeSet;// the phoneme set of the submotion, 0 if this is a normal morph target submotion - uint32 mNumKeys; // number of keyframes to follow + float m_poseWeight;// pose weight to use in case no animation data is present + float m_minWeight; // minimum allowed weight value (used for unpacking the keyframe weights) + float m_maxWeight; // maximum allowed weight value (used for unpacking the keyframe weights) + uint32 m_phonemeSet;// the phoneme set of the submotion, 0 if this is a normal morph target submotion + uint32 m_numKeys; // number of keyframes to follow // followed by: // string : name (the name of this motion part) - // Motion_UnsignedShortKey[mNumKeys] + // Motion_UnsignedShortKey[m_numKeys] }; @@ -156,17 +156,17 @@ namespace EMotionFX // (not aligned) struct Motion_UnsignedShortKey { - float mTime; // the time in seconds - uint16 mValue; // the value + float m_time; // the time in seconds + uint16 m_value; // the value }; // (aligned) struct Motion_MorphSubMotions { - uint32 mNumSubMotions; + uint32 m_numSubMotions; // followed by: - // Motion_MorphSubMotion[ mNumSubMotions ] + // Motion_MorphSubMotion[ m_numSubMotions ] }; @@ -174,11 +174,11 @@ namespace EMotionFX // (not aligned) struct FileMotionEvent { - float mStartTime; - float mEndTime; - uint32 mEventTypeIndex;// index into the event type string table - uint32 mMirrorTypeIndex;// index into the event type string table - uint16 mParamIndex; // index into the parameter string table + float m_startTime; + float m_endTime; + uint32 m_eventTypeIndex;// index into the event type string table + uint32 m_mirrorTypeIndex;// index into the event type string table + uint16 m_paramIndex; // index into the parameter string table }; @@ -186,18 +186,18 @@ namespace EMotionFX // (not aligned) struct FileMotionEventTrack { - uint32 mNumEvents; - uint32 mNumTypeStrings; - uint32 mNumParamStrings; - uint32 mNumMirrorTypeStrings; - uint8 mIsEnabled; + uint32 m_numEvents; + uint32 m_numTypeStrings; + uint32 m_numParamStrings; + uint32 m_numMirrorTypeStrings; + uint8 m_isEnabled; // followed by: // String track name - // [mNumTypeStrings] string objects - // [mNumParamStrings] string objects - // [mNumMirrorTypeStrings] string objects - // FileMotionEvent[mNumEvents] + // [m_numTypeStrings] string objects + // [m_numParamStrings] string objects + // [m_numMirrorTypeStrings] string objects + // FileMotionEvent[m_numEvents] }; @@ -205,10 +205,10 @@ namespace EMotionFX // (aligned) struct FileMotionEventTable { - uint32 mNumTracks; + uint32 m_numTracks; // followed by: - // FileMotionEventTrack[mNumTracks] + // FileMotionEventTrack[m_numTracks] }; struct FileMotionEventTableSerialized diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/NodeMapFileFormat.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/NodeMapFileFormat.h index b68b283510..bd563aa0dd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/NodeMapFileFormat.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/NodeMapFileFormat.h @@ -25,20 +25,20 @@ namespace EMotionFX struct NodeMap_Header { - uint8 mFourCC[4]; // must be "MOS " - uint8 mHiVersion; // high version (2 in case of v2.34) - uint8 mLoVersion; // low version (34 in case of v2.34) - uint8 mEndianType; // the endian in which the data is saved [0=little, 1=big] + uint8 m_fourCc[4]; // must be "MOS " + uint8 m_hiVersion; // high version (2 in case of v2.34) + uint8 m_loVersion; // low version (34 in case of v2.34) + uint8 m_endianType; // the endian in which the data is saved [0=little, 1=big] }; struct NodeMapChunk { - uint32 mNumEntries;// the number of mapping entries + uint32 m_numEntries;// the number of mapping entries // followed by: // String sourceActorFileName - // for all mNumEntries + // for all m_numEntries // String firstNodeName; // String secondNodeName; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/SharedFileFormatStructs.h b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/SharedFileFormatStructs.h index 082bcbf0ef..b5828b98c8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/SharedFileFormatStructs.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/SharedFileFormatStructs.h @@ -23,75 +23,75 @@ namespace EMotionFX struct FileChunk { - uint32 mChunkID; // the chunk ID - uint32 mSizeInBytes; // the size in bytes of this chunk (excluding this chunk struct) - uint32 mVersion; // the version of the chunk + uint32 m_chunkId; // the chunk ID + uint32 m_sizeInBytes; // the size in bytes of this chunk (excluding this chunk struct) + uint32 m_version; // the version of the chunk }; // color [0..1] range struct FileColor { - float mR; // red - float mG; // green - float mB; // blue - float mA; // alpha + float m_r; // red + float m_g; // green + float m_b; // blue + float m_a; // alpha }; struct FileVector2 { - float mX; - float mY; + float m_x; + float m_y; }; struct FileVector3 { - float mX; // x+ = to the right - float mY; // y+ = forward - float mZ; // z+ = up + float m_x; // x+ = to the right + float m_y; // y+ = forward + float m_z; // z+ = up }; // a compressed 3D vector struct File16BitVector3 { - uint16 mX; // x+ = to the right - uint16 mY; // y+ = forward - uint16 mZ; // z+ = up + uint16 m_x; // x+ = to the right + uint16 m_y; // y+ = forward + uint16 m_z; // z+ = up }; // a compressed 3D vector struct File8BitVector3 { - uint8 mX; // x+ = to the right - uint8 mY; // y+ = forward - uint8 mZ; // z+ = up + uint8 m_x; // x+ = to the right + uint8 m_y; // y+ = forward + uint8 m_z; // z+ = up }; struct FileQuaternion { - float mX; - float mY; - float mZ; - float mW; + float m_x; + float m_y; + float m_z; + float m_w; }; // the 16 bit component quaternion struct File16BitQuaternion { - int16 mX; - int16 mY; - int16 mZ; - int16 mW; + int16 m_x; + int16 m_y; + int16 m_z; + int16 m_w; }; // a time stamp chunk struct FileTime { - uint16 mYear; - int8 mMonth; - int8 mDay; - int8 mHours; - int8 mMinutes; - int8 mSeconds; + uint16 m_year; + int8 m_month; + int8 m_day; + int8 m_hours; + int8 m_minutes; + int8 m_seconds; }; } // namespace FileFormat } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.h b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.h index 35435823d4..7312d94c69 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.h @@ -103,8 +103,8 @@ namespace EMotionFX MCORE_INLINE void SetStorageTypeValue(const StorageType& value); protected: - StorageType mValue; /**< The key value. */ - float mTime; /**< Time in seconds. */ + StorageType m_value; /**< The key value. */ + float m_time; /**< Time in seconds. */ }; // include inline code diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.inl b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.inl index 47df42f07f..5aaf871977 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrame.inl @@ -9,7 +9,7 @@ // default constructor template KeyFrame::KeyFrame() - : mTime(0) + : m_time(0) { } @@ -17,7 +17,7 @@ KeyFrame::KeyFrame() // extended constructor template KeyFrame::KeyFrame(float time, const ReturnType& value) - : mTime(time) + : m_time(time) { SetValue(value); } @@ -41,55 +41,55 @@ void KeyFrame::Reflect(AZ::ReflectContext* context) serializeContext->Class>() ->Version(1) - ->Field("time", &KeyFrame::mTime) - ->Field("value", &KeyFrame::mValue) + ->Field("time", &KeyFrame::m_time) + ->Field("value", &KeyFrame::m_value) ; } template MCORE_INLINE float KeyFrame::GetTime() const { - return mTime; + return m_time; } template MCORE_INLINE ReturnType KeyFrame::GetValue() const { - return mValue; + return m_value; } template MCORE_INLINE void KeyFrame::GetValue(ReturnType* outValue) { - *outValue = mValue; + *outValue = m_value; } template MCORE_INLINE const StorageType& KeyFrame::GetStorageTypeValue() const { - return mValue; + return m_value; } template MCORE_INLINE void KeyFrame::SetTime(float time) { - mTime = time; + m_time = time; } template MCORE_INLINE void KeyFrame::SetValue(const ReturnType& value) { - mValue = value; + m_value = value; } template MCORE_INLINE void KeyFrame::SetStorageTypeValue(const StorageType& value) { - mValue = value; + m_value = value; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.h b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.h index 760913ddd4..5d06964a88 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.h @@ -43,9 +43,9 @@ namespace EMotionFX * @param timeValue The time value you want to calculate a value at. * @param keyTrack The keyframe array to perform the search on. * @param numKeys The number of keyframes stored inside the keyTrack parameter buffer. - * @result The key number, or MCORE_INVALIDINDEX32 when no valid key could be found. + * @result The key number, or InvalidIndex when no valid key could be found. */ - static uint32 FindKey(float timeValue, const KeyFrame* keyTrack, uint32 numKeys); + static size_t FindKey(float timeValue, const KeyFrame* keyTrack, size_t numKeys); }; // include inline code diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.inl b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.inl index 4e9668638f..bc9b4cadba 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyFrameFinder.inl @@ -23,29 +23,29 @@ KeyFrameFinder::~KeyFrameFinder() // returns the keyframe number to use for interpolation template -uint32 KeyFrameFinder::FindKey(float timeValue, const KeyFrame* keyTrack, uint32 numKeys) +size_t KeyFrameFinder::FindKey(float timeValue, const KeyFrame* keyTrack, size_t numKeys) { - // if we haven't got any keys, return MCORE_INVALIDINDEX32, which means no key found + // if we haven't got any keys, return InvalidIndex, which means no key found if (numKeys == 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - uint32 low = 0; - uint32 high = numKeys - 1; + size_t low = 0; + size_t high = numKeys - 1; float lowValue = keyTrack[low].GetTime(); float highValue = keyTrack[high].GetTime(); // these can go if you're sure the value is going to be valid (between the min and max key's values) if (timeValue < lowValue || timeValue >= highValue) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } for (;; ) { // calculate the interpolated index - const uint32 mid = low + (int)((timeValue - lowValue) / (highValue - lowValue) * (high - low)); + const size_t mid = low + (int)((timeValue - lowValue) / (highValue - lowValue) * (high - low)); if (keyTrack[mid].GetTime() <= timeValue) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h index 2635e12a71..c94886a5f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.h @@ -41,21 +41,12 @@ namespace EMotionFX public: AZ_TYPE_INFO_LEGACY(EMotionFX::KeyTrackLinear, "{8C6EB52A-9720-467B-9D96-B4B967A113D1}", StorageType) - /** - * Default constructor. - */ - KeyTrackLinearDynamic(); + KeyTrackLinearDynamic() = default; /** - * Constructor. * @param nrKeys The number of keyframes which the keytrack contains (preallocates this amount of keyframes). */ - KeyTrackLinearDynamic(uint32 nrKeys); - - /** - * Destructor. - */ - ~KeyTrackLinearDynamic(); + KeyTrackLinearDynamic(size_t nrKeys); static void Reflect(AZ::ReflectContext* context); @@ -63,14 +54,14 @@ namespace EMotionFX * Reserve space for a given number of keys. This pre-allocates data, so that adding keys doesn't always do a reallocation. * @param numKeys The number of keys to reserve space for. This is the absolute number of keys, NOT the number to reserve extra. */ - void Reserve(uint32 numKeys); + void Reserve(size_t numKeys); /** * Calculate the memory usage, in bytes. * @param includeMembers Specifies whether to include member variables of the keytrack class itself or not (default=true). * @result The number of bytes used by this keytrack. */ - uint32 CalcMemoryUsage(bool includeMembers = true) const; + size_t CalcMemoryUsage(bool includeMembers = true) const; /** * Initialize all keyframes in this keytrack. @@ -90,7 +81,7 @@ namespace EMotionFX * @param currentTime The global time, in seconds. This time value has to be between the time value of the startKey and the one after that. * @result The interpolated value. */ - MCORE_INLINE ReturnType Interpolate(uint32 startKey, float currentTime) const; + MCORE_INLINE ReturnType Interpolate(size_t startKey, float currentTime) const; /** * Add a key to the track (at the back). @@ -116,7 +107,7 @@ namespace EMotionFX * recalculated when the key structure has changed. * @param keyNr The keyframe number, must be in range of [0..GetNumKeys()-1]. */ - MCORE_INLINE void RemoveKey(uint32 keyNr); + MCORE_INLINE void RemoveKey(size_t keyNr); /** * Clear all keys. @@ -142,14 +133,14 @@ namespace EMotionFX * @param interpolate Should we interpolate between the keyframes? * @result Returns the value at the specified time. */ - ReturnType GetValueAtTime(float currentTime, uint32* cachedKey = nullptr, uint8* outWasCacheHit = nullptr, bool interpolate = true) const; + ReturnType GetValueAtTime(float currentTime, size_t* cachedKey = nullptr, uint8* outWasCacheHit = nullptr, bool interpolate = true) const; /** * Get a given keyframe. * @param nr The index, so the keyframe number. * @result A pointer to the keyframe. */ - MCORE_INLINE KeyFrame* GetKey(uint32 nr); + MCORE_INLINE KeyFrame* GetKey(size_t nr); /** * Returns the first keyframe. @@ -168,7 +159,7 @@ namespace EMotionFX * @param nr The index, so the keyframe number. * @result A pointer to the keyframe. */ - MCORE_INLINE const KeyFrame* GetKey(uint32 nr) const; + MCORE_INLINE const KeyFrame* GetKey(size_t nr) const; /** * Returns the first keyframe. @@ -199,7 +190,7 @@ namespace EMotionFX * Returns the number of keyframes in this track. * @result The number of currently stored keyframes. */ - MCORE_INLINE uint32 GetNumKeys() const; + MCORE_INLINE size_t GetNumKeys() const; /** * Find a key at a given time. @@ -214,7 +205,7 @@ namespace EMotionFX * @param curTime The time to retreive the key for. * @result Returns the key number or MCORE_INVALIDINDEX32 when not found. */ - MCORE_INLINE uint32 FindKeyNumber(float curTime) const; + MCORE_INLINE size_t FindKeyNumber(float curTime) const; /** * Make the keytrack loopable, by adding a new keyframe at the end of the keytrack. @@ -237,7 +228,7 @@ namespace EMotionFX * @param maxError The maximum allowed error value. The higher you set this value, the more keyframes will be removed. * @result The method returns the number of removed keyframes. */ - uint32 Optimize(float maxError); + size_t Optimize(float maxError); /** * Pre-allocate a given number of keys. @@ -245,7 +236,7 @@ namespace EMotionFX * However, newly created keys will be uninitialized. * @param numKeys The number of keys to allocate. */ - void SetNumKeys(uint32 numKeys); + void SetNumKeys(size_t numKeys); /** * Set the value of a key. @@ -254,7 +245,7 @@ namespace EMotionFX * @param time The time value, in seconds. * @param value The value of the key. */ - MCORE_INLINE void SetKey(uint32 keyNr, float time, const ReturnType& value); + MCORE_INLINE void SetKey(size_t keyNr, float time, const ReturnType& value); /** * Set the storage type value of a key. @@ -263,10 +254,10 @@ namespace EMotionFX * @param time The time value, in seconds. * @param value The storage type value of the key. */ - MCORE_INLINE void SetStorageTypeKey(uint32 keyNr, float time, const StorageType& value); + MCORE_INLINE void SetStorageTypeKey(size_t keyNr, float time, const StorageType& value); protected: - AZStd::vector> mKeys; /**< The collection of keys which form the track. */ + AZStd::vector> m_keys; /**< The collection of keys which form the track. */ }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl index b28c9973fc..34598f0ae1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/KeyTrackLinearDynamic.inl @@ -6,28 +6,14 @@ * */ -// default constructor -template -KeyTrackLinearDynamic::KeyTrackLinearDynamic() -{ -} - - // extended constructor template -KeyTrackLinearDynamic::KeyTrackLinearDynamic(uint32 nrKeys) +KeyTrackLinearDynamic::KeyTrackLinearDynamic(size_t nrKeys) { SetNumKeys(nrKeys); } -// destructor -template -KeyTrackLinearDynamic::~KeyTrackLinearDynamic() -{ - ClearKeys(); -} - template void KeyTrackLinearDynamic::Reflect(AZ::ReflectContext* context) { @@ -39,7 +25,7 @@ void KeyTrackLinearDynamic::Reflect(AZ::ReflectContext* serializeContext->Class>() ->Version(1) - ->Field("keyValues", &KeyTrackLinearDynamic::mKeys) + ->Field("keyValues", &KeyTrackLinearDynamic::m_keys) ; } @@ -47,7 +33,7 @@ void KeyTrackLinearDynamic::Reflect(AZ::ReflectContext* template void KeyTrackLinearDynamic::ClearKeys() { - mKeys.clear(); + m_keys.clear(); } @@ -56,68 +42,67 @@ template void KeyTrackLinearDynamic::Init() { // check all key time values, so we are sure the first key start at time 0 - if (mKeys.empty()) + if (m_keys.empty()) { return; } // get the time value of the first key, which is our minimum time - const float minTime = mKeys[0].GetTime(); + const float minTime = m_keys[0].GetTime(); // if it's not equal to zero, we have to correct it (and all other keys as well) if (minTime > 0.0f) { - const size_t numKeys = mKeys.size(); - for (uint32 i = 0; i < numKeys; ++i) + for (KeyFrame& key : m_keys) { - mKeys[i].SetTime(mKeys[i].GetTime() - minTime); + key.SetTime(key.GetTime() - minTime); } } } template -MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetKey(uint32 nr) +MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetKey(size_t nr) { - MCORE_ASSERT(nr < mKeys.size()); - return &mKeys[nr]; + MCORE_ASSERT(nr < m_keys.size()); + return &m_keys[nr]; } template MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetFirstKey() { - return (mKeys.size() > 0) ? &mKeys[0] : nullptr; + return !m_keys.empty() ? &m_keys[0] : nullptr; } template MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::GetLastKey() { - return (mKeys.size() > 0) ? &mKeys.back() : nullptr; + return !m_keys.empty() ? &m_keys.back() : nullptr; } template -MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetKey(uint32 nr) const +MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetKey(size_t nr) const { - MCORE_ASSERT(nr < mKeys.size()); - return &mKeys[nr]; + MCORE_ASSERT(nr < m_keys.size()); + return &m_keys[nr]; } template MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetFirstKey() const { - return (mKeys.size() > 0) ? &mKeys[0] : nullptr; + return !m_keys.empty() ? &m_keys[0] : nullptr; } template MCORE_INLINE const KeyFrame* KeyTrackLinearDynamic::GetLastKey() const { - return (mKeys.size() > 0) ? &mKeys.back() : nullptr; + return !m_keys.empty() ? &m_keys.back() : nullptr; } @@ -138,9 +123,9 @@ MCORE_INLINE float KeyTrackLinearDynamic::GetLastTime() template -MCORE_INLINE uint32 KeyTrackLinearDynamic::GetNumKeys() const +MCORE_INLINE size_t KeyTrackLinearDynamic::GetNumKeys() const { - return static_cast(mKeys.size()); + return m_keys.size(); } @@ -148,29 +133,29 @@ template MCORE_INLINE void KeyTrackLinearDynamic::AddKey(float time, const ReturnType& value, bool smartPreAlloc) { #ifdef MCORE_DEBUG - if (mKeys.size() > 0) + if (!m_keys.empty()) { - MCORE_ASSERT(time >= mKeys.back().GetTime()); + MCORE_ASSERT(time >= m_keys.back().GetTime()); } #endif // if we need to prealloc - if (mKeys.capacity() == mKeys.size() && smartPreAlloc == true) + if (m_keys.capacity() == m_keys.size() && smartPreAlloc == true) { - const size_t numToReserve = mKeys.size() / 4; - mKeys.reserve(mKeys.capacity() + numToReserve); + const size_t numToReserve = m_keys.size() / 4; + m_keys.reserve(m_keys.capacity() + numToReserve); } // not the first key, so add on the end - mKeys.emplace_back(KeyFrame(time, value)); + m_keys.emplace_back(KeyFrame(time, value)); } // find a key at a given time template -MCORE_INLINE uint32 KeyTrackLinearDynamic::FindKeyNumber(float curTime) const +MCORE_INLINE size_t KeyTrackLinearDynamic::FindKeyNumber(float curTime) const { - return KeyFrameFinder::FindKey(curTime, &mKeys.front(), static_cast(mKeys.size())); + return KeyFrameFinder::FindKey(curTime, &m_keys.front(), static_cast(m_keys.size())); } @@ -179,36 +164,36 @@ template MCORE_INLINE KeyFrame* KeyTrackLinearDynamic::FindKey(float curTime) const { // find the key number - const uint32 keyNumber = KeyFrameFinder::FindKey(curTime, &mKeys.front(), mKeys.size()); + const size_t keyNumber = KeyFrameFinder::FindKey(curTime, &m_keys.front(), m_keys.size()); // if no key was found - return (keyNumber != MCORE_INVALIDINDEX32) ? &mKeys[keyNumber] : nullptr; + return (keyNumber != InvalidIndex) ? &m_keys[keyNumber] : nullptr; } // returns the interpolated value at a given time template -ReturnType KeyTrackLinearDynamic::GetValueAtTime(float currentTime, uint32* cachedKey, uint8* outWasCacheHit, bool interpolate) const +ReturnType KeyTrackLinearDynamic::GetValueAtTime(float currentTime, size_t* cachedKey, uint8* outWasCacheHit, bool interpolate) const { MCORE_ASSERT(currentTime >= 0.0); - MCORE_ASSERT(mKeys.size() > 0); + MCORE_ASSERT(!m_keys.empty()); // make a local copy of the cached key value - uint32 localCachedKey = (cachedKey) ? *cachedKey : MCORE_INVALIDINDEX32; + size_t localCachedKey = (cachedKey) ? *cachedKey : InvalidIndex; // find the first key to start interpolating from (between this one and the next) - uint32 keyNumber = MCORE_INVALIDINDEX32; + size_t keyNumber = InvalidIndex; // prevent searching in the set of keyframes when a cached key is available // of course we need to check first if the cached key is actually still valid or not - if (localCachedKey == MCORE_INVALIDINDEX32) // no cached key has been set, so simply perform a search + if (localCachedKey == InvalidIndex) // no cached key has been set, so simply perform a search { if (outWasCacheHit) { *outWasCacheHit = 0; } - keyNumber = KeyFrameFinder::FindKey(currentTime, &mKeys.front(), static_cast(mKeys.size())); + keyNumber = KeyFrameFinder::FindKey(currentTime, &m_keys.front(), m_keys.size()); if (cachedKey) { @@ -218,11 +203,11 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float else { // make sure we dont go out of bounds when checking - if (localCachedKey >= mKeys.size() - 2) + if (localCachedKey >= m_keys.size() - 2) { - if (mKeys.size() > 2) + if (m_keys.size() > 2) { - localCachedKey = static_cast(mKeys.size()) - 3; + localCachedKey = m_keys.size() - 3; } else { @@ -231,7 +216,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float } // check if the cached key is still valid (cache hit) - if ((mKeys[localCachedKey].GetTime() <= currentTime) && (mKeys[localCachedKey + 1].GetTime() >= currentTime)) + if ((m_keys[localCachedKey].GetTime() <= currentTime) && (m_keys[localCachedKey + 1].GetTime() >= currentTime)) { keyNumber = localCachedKey; if (outWasCacheHit) @@ -241,7 +226,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float } else { - if (localCachedKey < mKeys.size() - 2 && (mKeys[localCachedKey + 1].GetTime() <= currentTime) && (mKeys[localCachedKey + 2].GetTime() >= currentTime)) + if (localCachedKey < m_keys.size() - 2 && (m_keys[localCachedKey + 1].GetTime() <= currentTime) && (m_keys[localCachedKey + 2].GetTime() >= currentTime)) { if (outWasCacheHit) { @@ -257,7 +242,7 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float *outWasCacheHit = 0; } - keyNumber = KeyFrameFinder::FindKey(currentTime, &mKeys.front(), static_cast(mKeys.size())); + keyNumber = KeyFrameFinder::FindKey(currentTime, &m_keys.front(), m_keys.size()); if (cachedKey) { @@ -268,23 +253,23 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float } // if no key could be found - if (keyNumber == MCORE_INVALIDINDEX32) + if (keyNumber == InvalidIndex) { // if there are no keys at all, simply return an empty object - if (mKeys.size() == 0) + if (m_keys.size() == 0) { // return an empty object return ReturnType(); } // return the last key - return mKeys.back().GetValue(); + return m_keys.back().GetValue(); } // check if we didn't reach the end of the track - if ((keyNumber + 1) > (mKeys.size() - 1)) + if ((keyNumber + 1) > (m_keys.size() - 1)) { - return mKeys.back().GetValue(); + return m_keys.back().GetValue(); } // perform interpolation @@ -294,18 +279,18 @@ ReturnType KeyTrackLinearDynamic::GetValueAtTime(float } else { - return mKeys[keyNumber].GetValue(); + return m_keys[keyNumber].GetValue(); } } // perform interpolation template -MCORE_INLINE ReturnType KeyTrackLinearDynamic::Interpolate(uint32 startKey, float currentTime) const +MCORE_INLINE ReturnType KeyTrackLinearDynamic::Interpolate(size_t startKey, float currentTime) const { // get the keys to interpolate between - const KeyFrame& firstKey = mKeys[startKey]; - const KeyFrame& nextKey = mKeys[startKey + 1]; + const KeyFrame& firstKey = m_keys[startKey]; + const KeyFrame& nextKey = m_keys[startKey + 1]; // calculate the time value in range of [0..1] const float t = (currentTime - firstKey.GetTime()) / (nextKey.GetTime() - firstKey.GetTime()); @@ -317,11 +302,11 @@ MCORE_INLINE ReturnType KeyTrackLinearDynamic::Interpol template <> -MCORE_INLINE AZ::Quaternion KeyTrackLinearDynamic::Interpolate(uint32 startKey, float currentTime) const +MCORE_INLINE AZ::Quaternion KeyTrackLinearDynamic::Interpolate(size_t startKey, float currentTime) const { // get the keys to interpolate between - const KeyFrame& firstKey = mKeys[startKey]; - const KeyFrame& nextKey = mKeys[startKey + 1]; + const KeyFrame& firstKey = m_keys[startKey]; + const KeyFrame& nextKey = m_keys[startKey + 1]; // calculate the time value in range of [0..1] const float t = (currentTime - firstKey.GetTime()) / (nextKey.GetTime() - firstKey.GetTime()); @@ -332,11 +317,11 @@ MCORE_INLINE AZ::Quaternion KeyTrackLinearDynamic -MCORE_INLINE AZ::Quaternion KeyTrackLinearDynamic::Interpolate(uint32 startKey, float currentTime) const +MCORE_INLINE AZ::Quaternion KeyTrackLinearDynamic::Interpolate(size_t startKey, float currentTime) const { // get the keys to interpolate between - const KeyFrame& firstKey = mKeys[startKey]; - const KeyFrame& nextKey = mKeys[startKey + 1]; + const KeyFrame& firstKey = m_keys[startKey]; + const KeyFrame& nextKey = m_keys[startKey + 1]; // calculate the time value in range of [0..1] const float t = (currentTime - firstKey.GetTime()) / (nextKey.GetTime() - firstKey.GetTime()); @@ -353,17 +338,17 @@ void KeyTrackLinearDynamic::AddKeySorted(float time, co // if we need to prealloc if (smartPreAlloc) { - if (mKeys.capacity() == mKeys.size()) + if (m_keys.capacity() == m_keys.size()) { - const uint32 numToReserve = static_cast(mKeys.size() / 4); - mKeys.reserve(mKeys.capacity() + numToReserve); + const size_t numToReserve = m_keys.size() / 4; + m_keys.reserve(m_keys.capacity() + numToReserve); } } // if there are no keys yet, add it - if (mKeys.empty()) + if (m_keys.empty()) { - mKeys.emplace_back(KeyFrame(time, value)); + m_keys.emplace_back(KeyFrame(time, value)); return; } @@ -371,29 +356,29 @@ void KeyTrackLinearDynamic::AddKeySorted(float time, co const float keyTime = time; // if we must add it at the end - if (keyTime >= mKeys.back().GetTime()) + if (keyTime >= m_keys.back().GetTime()) { - mKeys.emplace_back(KeyFrame(time, value)); + m_keys.emplace_back(KeyFrame(time, value)); return; } // if we have to add it in the front - if (keyTime < mKeys.front().GetTime()) + if (keyTime < m_keys.front().GetTime()) { - mKeys.insert(mKeys.begin(), KeyFrame(time, value)); + m_keys.insert(m_keys.begin(), KeyFrame(time, value)); return; } // quickly find the location to insert, and insert it - const uint32 place = KeyFrameFinder::FindKey(keyTime, &mKeys.front(), static_cast(mKeys.size())); - mKeys.insert(mKeys.begin() + place + 1, KeyFrame(time, value)); + const size_t place = KeyFrameFinder::FindKey(keyTime, &m_keys.front(), m_keys.size()); + m_keys.insert(m_keys.begin() + place + 1, KeyFrame(time, value)); } template -MCORE_INLINE void KeyTrackLinearDynamic::RemoveKey(uint32 keyNr) +MCORE_INLINE void KeyTrackLinearDynamic::RemoveKey(size_t keyNr) { - mKeys.erase(AZStd::next(mKeys.begin(), keyNr)); + m_keys.erase(AZStd::next(m_keys.begin(), keyNr)); } @@ -402,7 +387,7 @@ void KeyTrackLinearDynamic::MakeLoopable(float fadeTime { MCORE_ASSERT(fadeTime > 0); - if (mKeys.empty()) + if (m_keys.empty()) { return; } @@ -418,27 +403,27 @@ void KeyTrackLinearDynamic::MakeLoopable(float fadeTime // optimize the keytrack template -uint32 KeyTrackLinearDynamic::Optimize(float maxError) +size_t KeyTrackLinearDynamic::Optimize(float maxError) { // if there aren't at least two keys, return, because we never remove the first and last key frames // and we'd need at least two keyframes to interpolate between - if (mKeys.size() <= 2) + if (m_keys.size() <= 2) { return 0; } // create a temparory copy of the keytrack data we're going to optimize KeyTrackLinearDynamic keyTrackCopy; - keyTrackCopy.mKeys = mKeys; + keyTrackCopy.m_keys = m_keys; keyTrackCopy.Init(); // while we want to continue optimizing - uint32 i = 1; - uint32 numRemoved = 0; // the number of removed keys + size_t i = 1; + size_t numRemoved = 0; // the number of removed keys do { // get the time of the current keyframe (starting from the second towards the last one) - const float time = mKeys[i].GetTime(); + const float time = m_keys[i].GetTime(); // remove the keyframe and reinit the keytrack (and interpolator's tangents etc) keyTrackCopy.RemoveKey(i); @@ -460,43 +445,42 @@ uint32 KeyTrackLinearDynamic::Optimize(float maxError) } else // if the "visual" difference is too high and we do not want ot remove the key, copy over the original keys again to restore it { - keyTrackCopy.mKeys = mKeys; // copy the keyframe array + keyTrackCopy.m_keys = m_keys; // copy the keyframe array keyTrackCopy.Init(); // reinit the keytrack i++; // go to the next keyframe, and try ot remove that one } - } while (i < mKeys.size() - 1); // while we haven't reached the last keyframe (minus one) + } while (i < m_keys.size() - 1); // while we haven't reached the last keyframe (minus one) - //mKeys.shrink_to_fit(); return numRemoved; } // pre-alloc keys template -void KeyTrackLinearDynamic::SetNumKeys(uint32 numKeys) +void KeyTrackLinearDynamic::SetNumKeys(size_t numKeys) { // resize the array of keys - mKeys.resize(numKeys); + m_keys.resize(numKeys); } // set a given key template -MCORE_INLINE void KeyTrackLinearDynamic::SetKey(uint32 keyNr, float time, const ReturnType& value) +MCORE_INLINE void KeyTrackLinearDynamic::SetKey(size_t keyNr, float time, const ReturnType& value) { // adjust the value and time of the key - mKeys[keyNr].SetValue(value); - mKeys[keyNr].SetTime(time); + m_keys[keyNr].SetValue(value); + m_keys[keyNr].SetTime(time); } // set a given key template -MCORE_INLINE void KeyTrackLinearDynamic::SetStorageTypeKey(uint32 keyNr, float time, const StorageType& value) +MCORE_INLINE void KeyTrackLinearDynamic::SetStorageTypeKey(size_t keyNr, float time, const StorageType& value) { // adjust the value and time of the key - mKeys[keyNr].SetStorageTypeValue(value); - mKeys[keyNr].SetTime(time); + m_keys[keyNr].SetStorageTypeValue(value); + m_keys[keyNr].SetTime(time); } @@ -504,39 +488,25 @@ MCORE_INLINE void KeyTrackLinearDynamic::SetStorageType template MCORE_INLINE bool KeyTrackLinearDynamic::CheckIfIsAnimated(const ReturnType& initialPose, float maxError) const { - // empty keytracks are never animated - if (mKeys.size() == 0) - { - return false; - } - - // get the number of keyframes and iterate through them - const uint32 numKeyFrames = GetNumKeys(); - for (uint32 i = 0; i < numKeyFrames; ++i) + return !m_keys.empty() && AZStd::any_of(begin(m_keys), end(m_keys), [&initialPose, maxError](const auto& key) { - // if the sampled value is not within the given maximum distance/error of the initial pose, it means we have an animated track - if (MCore::Compare::CheckIfIsClose(initialPose, GetKey(i)->GetValue(), maxError) == false) - { - return true; - } - } - - return false; + return !MCore::Compare::CheckIfIsClose(initialPose, key.GetValue(), maxError); + }); } // reserve memory for keys template -MCORE_INLINE void KeyTrackLinearDynamic::Reserve(uint32 numKeys) +MCORE_INLINE void KeyTrackLinearDynamic::Reserve(size_t numKeys) { - mKeys.reserve(numKeys); + m_keys.reserve(numKeys); } // calculate memory usage template -uint32 KeyTrackLinearDynamic::CalcMemoryUsage(bool includeMembers) const +size_t KeyTrackLinearDynamic::CalcMemoryUsage([[maybe_unused]] bool includeMembers) const { return 0; } @@ -546,5 +516,5 @@ uint32 KeyTrackLinearDynamic::CalcMemoryUsage(bool incl template void KeyTrackLinearDynamic::Shrink() { - mKeys.shrink_to_fit(); + m_keys.shrink_to_fit(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/LayerPass.h b/Gems/EMotionFX/Code/EMotionFX/Source/LayerPass.h index f4aef98b7e..ce0cb5607e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/LayerPass.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/LayerPass.h @@ -41,14 +41,14 @@ namespace EMotionFX protected: - MotionLayerSystem* mMotionSystem; /**< The motion system where this layer pass works on. */ + MotionLayerSystem* m_motionSystem; /**< The motion system where this layer pass works on. */ /** * The constructor. * @param motionLayerSystem The motion layer system where this pass will be added to. */ LayerPass(MotionLayerSystem* motionLayerSystem) - : BaseObject() { mMotionSystem = motionLayerSystem; } + : BaseObject() { m_motionSystem = motionLayerSystem; } /** * The destructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Material.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Material.cpp index c7157ba7c3..2602f3f281 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Material.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Material.cpp @@ -40,21 +40,21 @@ namespace EMotionFX void Material::SetName(const char* name) { // calculate the ID - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } // return the material name const char* Material::GetName() const { - return MCore::GetStringIdPool().GetName(mNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } // return the material name as a string const AZStd::string& Material::GetNameString() const { - return MCore::GetStringIdPool().GetName(mNameID); + return MCore::GetStringIdPool().GetName(m_nameId); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Material.h b/Gems/EMotionFX/Code/EMotionFX/Source/Material.h index 98c40e8b50..a462f9e25a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Material.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Material.h @@ -78,7 +78,7 @@ namespace EMotionFX void SetName(const char* name); protected: - uint32 mNameID; /**< The material id representing the name. */ + uint32 m_nameId; /**< The material id representing the name. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp index 993426f4c4..9845ec1939 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.cpp @@ -29,35 +29,25 @@ namespace EMotionFX Mesh::Mesh() : BaseObject() { - mNumVertices = 0; - mNumIndices = 0; - mNumOrgVerts = 0; - mNumPolygons = 0; - mIndices = nullptr; - mPolyVertexCounts = nullptr; - mIsCollisionMesh = false; - - // set memory categories of the arrays - mSubMeshes.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); - mVertexAttributes.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); - mSharedVertexAttributes.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); + m_numVertices = 0; + m_numIndices = 0; + m_numOrgVerts = 0; + m_numPolygons = 0; + m_indices = nullptr; + m_polyVertexCounts = nullptr; + m_isCollisionMesh = false; } // allocation constructor Mesh::Mesh(uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 numOrgVerts, bool isCollisionMesh) { - mNumVertices = 0; - mNumIndices = 0; - mNumPolygons = 0; - mNumOrgVerts = 0; - mIndices = nullptr; - mPolyVertexCounts = nullptr; - mIsCollisionMesh = isCollisionMesh; - - // set memory categories of the arrays - mSubMeshes.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); - mVertexAttributes.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); - mSharedVertexAttributes.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); + m_numVertices = 0; + m_numIndices = 0; + m_numPolygons = 0; + m_numOrgVerts = 0; + m_indices = nullptr; + m_polyVertexCounts = nullptr; + m_isCollisionMesh = isCollisionMesh; // allocate the mesh data Allocate(numVerts, numIndices, numPolygons, numOrgVerts); @@ -83,22 +73,22 @@ namespace EMotionFX // Local 2D and 4D packed vector structs as we don't have packed representations in AzCore and don't plan to add these. struct Vector2 { - float x; - float y; + float m_x; + float m_y; }; struct Vector4 { - float x; - float y; - float z; - float w; + float m_x; + float m_y; + float m_z; + float m_w; }; // Needed for converting the packed vectors from the Atom buffers that normally load directly into GPU into AzCore versions used by EMFX. AZ::Vector2 ConvertVector(const Vector2& input) { - return AZ::Vector2(input.x, input.y); + return AZ::Vector2(input.m_x, input.m_y); } AZ::Vector3 ConvertVector(const AZ::PackedVector3f& input) @@ -108,7 +98,7 @@ namespace EMotionFX AZ::Vector4 ConvertVector(const Vector4& input) { - return AZ::Vector4(input.x, input.y, input.z, input.w); + return AZ::Vector4(input.m_x, input.m_y, input.m_z, input.m_w); } // Convert Atom buffer storing elements of type SourceType to an EMFX vertex attribute layer storing elements of type TargetType. @@ -202,10 +192,10 @@ namespace EMotionFX AZ_ErrorOnce("EMotionFX", indexBufferViewDescriptor.m_elementSize == 4, "Index buffer must stored as 4 bytes."); const size_t indexBufferCountsInBytes = indexBufferViewDescriptor.m_elementCount * indexBufferViewDescriptor.m_elementSize; const size_t indexBufferOffsetInBytes = indexBufferViewDescriptor.m_elementOffset * indexBufferViewDescriptor.m_elementSize; - memcpy(mesh->mIndices, indexBuffer.begin() + indexBufferOffsetInBytes, indexBufferCountsInBytes); + memcpy(mesh->m_indices, indexBuffer.begin() + indexBufferOffsetInBytes, indexBufferCountsInBytes); // Set the polygon buffer - AZStd::fill(mesh->mPolyVertexCounts, mesh->mPolyVertexCounts + mesh->mNumPolygons, 3); + AZStd::fill(mesh->m_polyVertexCounts, mesh->m_polyVertexCounts + mesh->m_numPolygons, 3); // Skinning data from atom are stored in two separate buffer layer. AZ::u8 maxSkinInfluences = 255; // Later we will calculate this value from skinning data. @@ -266,7 +256,7 @@ namespace EMotionFX { // Atom stores the skin indices as uint16, but the buffer itself is a buffer of uint32 with two id's per element size_t influenceCount = elementCountInBytes / sizeof(AZ::u16); - maxSkinInfluences = static_cast(influenceCount / modelVertexCount); + maxSkinInfluences = aznumeric_caster(influenceCount / modelVertexCount); AZ_Assert(maxSkinInfluences > 0 && maxSkinInfluences < 100, "Expect max skin influences in a reasonable value range."); AZ_Assert(influenceCount % modelVertexCount == 0, "Expect an equal number of influences for each vertex."); AZ_Assert(bufferAssetViewDescriptor.m_elementSize == 4, "Expect skin joint indices to be stored in a raw 32-bit per element buffer"); @@ -279,7 +269,7 @@ namespace EMotionFX { // Atom stores joint weights as float (range 0 - 1) size_t influenceCount = elementCountInBytes / sizeof(float); - maxSkinInfluences = static_cast(influenceCount / modelVertexCount); + maxSkinInfluences = aznumeric_caster(influenceCount / modelVertexCount); AZ_Assert(maxSkinInfluences > 0 && maxSkinInfluences < 100, "Expect max skin influences in a reasonable value range."); skinWeights = static_cast(bufferData) + bufferAssetViewDescriptor.m_elementOffset; } @@ -288,7 +278,7 @@ namespace EMotionFX // Add the original vertex layer VertexAttributeLayerAbstractData* originalVertexData = VertexAttributeLayerAbstractData::Create(modelVertexCount, Mesh::ATTRIB_ORGVTXNUMBERS, sizeof(AZ::u32), false); AZ::u32* originalVertexDataRaw = static_cast(originalVertexData->GetData()); - for (size_t i = 0; i < modelVertexCount; ++i) + for (AZ::u32 i = 0; i < modelVertexCount; ++i) { originalVertexDataRaw[i] = static_cast(i); } @@ -369,25 +359,24 @@ namespace EMotionFX // allocate the indices if (numIndices > 0 && numPolygons > 0) { - mIndices = (uint32*)MCore::AlignedAllocate(sizeof(uint32) * numIndices, 32, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); - mPolyVertexCounts = (uint8*)MCore::AlignedAllocate(sizeof(uint8) * numPolygons, 16, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); + m_indices = (uint32*)MCore::AlignedAllocate(sizeof(uint32) * numIndices, 32, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); + m_polyVertexCounts = (uint8*)MCore::AlignedAllocate(sizeof(uint8) * numPolygons, 16, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); } // set number values - mNumVertices = numVerts; - mNumPolygons = numPolygons; - mNumIndices = numIndices; - mNumOrgVerts = numOrgVerts; + m_numVertices = numVerts; + m_numPolygons = numPolygons; + m_numIndices = numIndices; + m_numOrgVerts = numOrgVerts; } // copy all original data over the output data void Mesh::ResetToOriginalData() { - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + for (VertexAttributeLayer* vertexAttribute : m_vertexAttributes) { - mVertexAttributes[i]->ResetToOriginalData(); + vertexAttribute->ResetToOriginalData(); } } @@ -402,30 +391,29 @@ namespace EMotionFX RemoveAllVertexAttributeLayers(); // get rid of all sub meshes - const uint32 numSubMeshes = mSubMeshes.GetLength(); - for (uint32 i = 0; i < numSubMeshes; ++i) + for (SubMesh* subMesh : m_subMeshes) { - mSubMeshes[i]->Destroy(); + subMesh->Destroy(); } - mSubMeshes.Clear(); + m_subMeshes.clear(); - if (mIndices) + if (m_indices) { - MCore::AlignedFree(mIndices); + MCore::AlignedFree(m_indices); } - if (mPolyVertexCounts) + if (m_polyVertexCounts) { - MCore::AlignedFree(mPolyVertexCounts); + MCore::AlignedFree(m_polyVertexCounts); } // re-init members - mIndices = nullptr; - mPolyVertexCounts = nullptr; - mNumIndices = 0; - mNumVertices = 0; - mNumOrgVerts = 0; - mNumPolygons = 0; + m_indices = nullptr; + m_polyVertexCounts = nullptr; + m_numIndices = 0; + m_numVertices = 0; + m_numOrgVerts = 0; + m_numPolygons = 0; } @@ -505,25 +493,24 @@ namespace EMotionFX } // calculate the number of tangent layers that are already available - uint32 i, f; AZ::Vector4* tangents = nullptr; AZ::Vector4* orgTangents = nullptr; AZ::Vector3* bitangents = nullptr; AZ::Vector3* orgBitangents = nullptr; - const uint32 numTangentLayers = CalcNumAttributeLayers(Mesh::ATTRIB_TANGENTS); + const size_t numTangentLayers = CalcNumAttributeLayers(Mesh::ATTRIB_TANGENTS); // make sure we have tangent data allocated for all uv layers before the given one - for (i = numTangentLayers; i <= uvSet; ++i) + for (size_t i = numTangentLayers; i <= uvSet; ++i) { // add a new tangent layer - AddVertexAttributeLayer(VertexAttributeLayerAbstractData::Create(mNumVertices, Mesh::ATTRIB_TANGENTS, sizeof(AZ::Vector4), true)); + AddVertexAttributeLayer(VertexAttributeLayerAbstractData::Create(m_numVertices, Mesh::ATTRIB_TANGENTS, sizeof(AZ::Vector4), true)); tangents = static_cast(FindVertexData(Mesh::ATTRIB_TANGENTS, i)); orgTangents = static_cast(FindOriginalVertexData(Mesh::ATTRIB_TANGENTS, i)); // Add the bitangents layer. if (storeBitangents) { - AddVertexAttributeLayer(VertexAttributeLayerAbstractData::Create(mNumVertices, Mesh::ATTRIB_BITANGENTS, sizeof(AZ::PackedVector3f), true)); + AddVertexAttributeLayer(VertexAttributeLayerAbstractData::Create(m_numVertices, Mesh::ATTRIB_BITANGENTS, sizeof(AZ::PackedVector3f), true)); bitangents = static_cast(FindVertexData(Mesh::ATTRIB_BITANGENTS, i)); orgBitangents = static_cast(FindOriginalVertexData(Mesh::ATTRIB_BITANGENTS, i)); } @@ -531,7 +518,7 @@ namespace EMotionFX // default all tangents for the newly created layer AZ::Vector4 defaultTangent(1.0f, 0.0f, 0.0f, 0.0f); AZ::Vector3 defaultBitangent(0.0f, 0.0f, 1.0f); - for (uint32 vtx = 0; vtx < mNumVertices; ++vtx) + for (uint32 vtx = 0; vtx < m_numVertices; ++vtx) { tangents[vtx] = defaultTangent; orgTangents[vtx] = defaultTangent; @@ -558,7 +545,7 @@ namespace EMotionFX AZ::Vector3 curBitangent; // calculate for every vertex the tangent and bitangent - for (i = 0; i < mNumVertices; ++i) + for (uint32 i = 0; i < m_numVertices; ++i) { orgTangents[i] = AZ::Vector4::CreateZero(); tangents[i] = AZ::Vector4::CreateZero(); @@ -574,7 +561,7 @@ namespace EMotionFX uint32 polyStartIndex = 0; uint32 indexA, indexB, indexC; const uint32 numPolygons = GetNumPolygons(); - for (f = 0; f < numPolygons; f++) + for (uint32 f = 0; f < numPolygons; f++) { const uint32 numPolyVerts = vertCounts[f]; @@ -582,7 +569,7 @@ namespace EMotionFX // triangle has got 3 polygon vertices -> 1 triangle // quad has got 4 polygon vertices -> 2 triangles // pentagon has got 5 polygon vertices -> 3 triangles - for (i = 2; i < numPolyVerts; i++) + for (uint32 i = 2; i < numPolyVerts; i++) { indexA = indices[polyStartIndex]; indexB = indices[polyStartIndex + i]; @@ -614,7 +601,7 @@ namespace EMotionFX } // calculate the per vertex tangents now, fixing up orthogonality and handling mirroring of the bitangent - for (i = 0; i < mNumVertices; ++i) + for (uint32 i = 0; i < m_numVertices; ++i) { // get the normal AZ::Vector3 normal(normals[i]); @@ -668,10 +655,10 @@ namespace EMotionFX // creates an array of pointers to bones used by this face - void Mesh::GatherBonesForFace(uint32 startIndexOfFace, MCore::Array& outBones, Actor* actor) + void Mesh::GatherBonesForFace(uint32 startIndexOfFace, AZStd::vector& outBones, Actor* actor) { // get rid of existing data - outBones.Clear(); + outBones.clear(); // try to locate the skinning attribute information SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); @@ -703,9 +690,9 @@ namespace EMotionFX Node* bone = skeleton->GetNode(skinningLayer->GetInfluence(originalVertex, n)->GetNodeNr()); // if it isn't yet in the output array with bones, add it - if (outBones.Find(bone) == MCORE_INVALIDINDEX32) + if (AZStd::find(begin(outBones), end(outBones), bone) == end(outBones)) { - outBones.Add(bone); + outBones.emplace_back(bone); } } } @@ -750,7 +737,7 @@ namespace EMotionFX // returns the maximum number of weights/influences for this mesh - uint32 Mesh::CalcMaxNumInfluences() const + size_t Mesh::CalcMaxNumInfluences() const { // try to locate the skinning attribute information SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); @@ -770,37 +757,33 @@ namespace EMotionFX } // return the maximum number of influences - return aznumeric_cast(maxInfluences); + return maxInfluences; } // returns the maximum number of weights/influences for this mesh plus some extra information - uint32 Mesh::CalcMaxNumInfluences(AZStd::vector& outVertexCounts) const + size_t Mesh::CalcMaxNumInfluences(AZStd::vector& outVertexCounts) const { - size_t maxInfluences = 0; - // Reset values. outVertexCounts.resize(CalcMaxNumInfluences() + 1); - for (size_t j = 0; j < outVertexCounts.size(); ++j) - { - outVertexCounts[j] = 0; - } + AZStd::fill(begin(outVertexCounts), end(outVertexCounts), 0); // Does the mesh have a skinning layer? If no we can quit directly as this means there are only unskinned vertices. SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); if (!skinningLayer) { outVertexCounts[0] = GetNumVertices(); - return aznumeric_cast(maxInfluences); + return 0; } - uint32* orgVerts = (uint32*)FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); + const uint32* orgVerts = (uint32*)FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); // Get the vertex counts for the influences. + size_t maxInfluences = 0; const uint32 numVerts = GetNumVertices(); for (uint32 i = 0; i < numVerts; ++i) { - uint32 orgVertex = orgVerts[i]; + const uint32 orgVertex = orgVerts[i]; // Increase the number of vertices for the given influence value. const size_t numInfluences = skinningLayer->GetNumInfluences(orgVertex); @@ -810,15 +793,15 @@ namespace EMotionFX maxInfluences = AZStd::max(maxInfluences, numInfluences); } - return aznumeric_cast(maxInfluences); + return maxInfluences; } // remove a given submesh - void Mesh::RemoveSubMesh(uint32 nr, bool delFromMem) + void Mesh::RemoveSubMesh(size_t nr, bool delFromMem) { - SubMesh* subMesh = mSubMeshes[nr]; - mSubMeshes.Remove(nr); + SubMesh* subMesh = m_subMeshes[nr]; + m_subMeshes.erase(AZStd::next(begin(m_subMeshes), nr)); if (delFromMem) { subMesh->Destroy(); @@ -827,22 +810,21 @@ namespace EMotionFX // insert a given submesh - void Mesh::InsertSubMesh(uint32 insertIndex, SubMesh* subMesh) + void Mesh::InsertSubMesh(size_t insertIndex, SubMesh* subMesh) { - mSubMeshes.Insert(insertIndex, subMesh); + m_subMeshes.emplace(AZStd::next(begin(m_subMeshes), insertIndex), subMesh); } // count the given type of vertex attribute layers - uint32 Mesh::CalcNumAttributeLayers(uint32 type) const + size_t Mesh::CalcNumAttributeLayers(uint32 type) const { - uint32 numLayers = 0; + size_t numLayers = 0; // check the types of all vertex attribute layers - const uint32 numAttributes = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numAttributes; ++i) + for (auto* vertexAttribute : m_vertexAttributes) { - if (mVertexAttributes[i]->GetType() == type) + if (vertexAttribute->GetType() == type) { numLayers++; } @@ -853,68 +835,53 @@ namespace EMotionFX // get the number of UV layers - uint32 Mesh::CalcNumUVLayers() const + size_t Mesh::CalcNumUVLayers() const { return CalcNumAttributeLayers(Mesh::ATTRIB_UVCOORDS); } //--------------------------------------------------------------- - VertexAttributeLayer* Mesh::GetSharedVertexAttributeLayer(uint32 layerNr) + VertexAttributeLayer* Mesh::GetSharedVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mSharedVertexAttributes.GetLength()); - return mSharedVertexAttributes[layerNr]; + MCORE_ASSERT(layerNr < m_sharedVertexAttributes.size()); + return m_sharedVertexAttributes[layerNr]; } void Mesh::AddSharedVertexAttributeLayer(VertexAttributeLayer* layer) { - MCORE_ASSERT(mSharedVertexAttributes.Contains(layer) == false); - mSharedVertexAttributes.Add(layer); + MCORE_ASSERT(AZStd::find(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), layer) == end(m_sharedVertexAttributes)); + m_sharedVertexAttributes.emplace_back(layer); } - uint32 Mesh::GetNumSharedVertexAttributeLayers() const + size_t Mesh::GetNumSharedVertexAttributeLayers() const { - return mSharedVertexAttributes.GetLength(); + return m_sharedVertexAttributes.size(); } - uint32 Mesh::FindSharedVertexAttributeLayerNumber(uint32 layerTypeID, uint32 occurrence) const + size_t Mesh::FindSharedVertexAttributeLayerNumber(uint32 layerTypeID, size_t occurrence) const { - uint32 layerCounter = 0; - - // check all vertex attributes of our first vertex, and find where the specific attribute is - const uint32 numLayers = mSharedVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [layerTypeID, occurrence](const VertexAttributeLayer* layer) mutable { - VertexAttributeLayer* layer = mSharedVertexAttributes[i]; - if (layer->GetType() == layerTypeID) - { - if (occurrence == layerCounter) - { - return i; - } - - layerCounter++; - } - } - - // not found - return MCORE_INVALIDINDEX32; + return layer->GetType() == layerTypeID && occurrence-- == 0; + }); + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } // find the vertex attribute layer and return a pointer - VertexAttributeLayer* Mesh::FindSharedVertexAttributeLayer(uint32 layerTypeID, uint32 occurence) const + VertexAttributeLayer* Mesh::FindSharedVertexAttributeLayer(uint32 layerTypeID, size_t occurence) const { - uint32 layerNr = FindSharedVertexAttributeLayerNumber(layerTypeID, occurence); - if (layerNr == MCORE_INVALIDINDEX32) + size_t layerNr = FindSharedVertexAttributeLayerNumber(layerTypeID, occurence); + if (layerNr == InvalidIndex) { return nullptr; } - return mSharedVertexAttributes[layerNr]; + return m_sharedVertexAttributes[layerNr]; } @@ -922,132 +889,107 @@ namespace EMotionFX // delete all shared attribute layers void Mesh::RemoveAllSharedVertexAttributeLayers() { - while (mSharedVertexAttributes.GetLength()) + while (m_sharedVertexAttributes.size()) { - mSharedVertexAttributes.GetLast()->Destroy(); - mSharedVertexAttributes.RemoveLast(); + m_sharedVertexAttributes.back()->Destroy(); + m_sharedVertexAttributes.pop_back(); } } // remove a layer by its index - void Mesh::RemoveSharedVertexAttributeLayer(uint32 layerNr) + void Mesh::RemoveSharedVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mSharedVertexAttributes.GetLength()); - mSharedVertexAttributes[layerNr]->Destroy(); - mSharedVertexAttributes.Remove(layerNr); + MCORE_ASSERT(layerNr < m_sharedVertexAttributes.size()); + m_sharedVertexAttributes[layerNr]->Destroy(); + m_sharedVertexAttributes.erase(AZStd::next(begin(m_sharedVertexAttributes), layerNr)); } - uint32 Mesh::GetNumVertexAttributeLayers() const + size_t Mesh::GetNumVertexAttributeLayers() const { - return mVertexAttributes.GetLength(); + return m_vertexAttributes.size(); } - VertexAttributeLayer* Mesh::GetVertexAttributeLayer(uint32 layerNr) + VertexAttributeLayer* Mesh::GetVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mVertexAttributes.GetLength()); - return mVertexAttributes[layerNr]; + MCORE_ASSERT(layerNr < m_vertexAttributes.size()); + return m_vertexAttributes[layerNr]; } void Mesh::AddVertexAttributeLayer(VertexAttributeLayer* layer) { - MCORE_ASSERT(mVertexAttributes.Contains(layer) == false); - mVertexAttributes.Add(layer); + MCORE_ASSERT(AZStd::find(begin(m_vertexAttributes), end(m_vertexAttributes), layer) == end(m_vertexAttributes)); + m_vertexAttributes.emplace_back(layer); } // find the layer number - uint32 Mesh::FindVertexAttributeLayerNumber(uint32 layerTypeID, uint32 occurrence) const + size_t Mesh::FindVertexAttributeLayerNumber(uint32 layerTypeID, size_t occurrence) const { - uint32 layerCounter = 0; - - // check all vertex attributes of our first vertex, and find where the specific attribute is - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [layerTypeID, occurrence](const VertexAttributeLayer* layer) mutable { - VertexAttributeLayer* layer = mVertexAttributes[i]; - if (layer->GetType() == layerTypeID) - { - if (occurrence == layerCounter) - { - return i; - } - - layerCounter++; - } - } - - // not found - return MCORE_INVALIDINDEX32; + return layer->GetType() == layerTypeID && occurrence-- == 0; + }); + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find the layer number - uint32 Mesh::FindVertexAttributeLayerNumberByName(uint32 layerTypeID, const char* name) const + size_t Mesh::FindVertexAttributeLayerNumberByName(uint32 layerTypeID, const char* name) const { - // check all vertex attributes of our first vertex, and find where the specific attribute is - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [layerTypeID, name](const VertexAttributeLayer* layer) { - VertexAttributeLayer* layer = mVertexAttributes[i]; - if (layer->GetType() == layerTypeID) - { - if (layer->GetNameString() == name) - { - return i; - } - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetType() == layerTypeID && layer->GetNameString() == name; + }); + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find the vertex attribute layer and return a pointer - VertexAttributeLayer* Mesh::FindVertexAttributeLayer(uint32 layerTypeID, uint32 occurence) const + VertexAttributeLayer* Mesh::FindVertexAttributeLayer(uint32 layerTypeID, size_t occurence) const { - const uint32 layerNr = FindVertexAttributeLayerNumber(layerTypeID, occurence); - if (layerNr == MCORE_INVALIDINDEX32) + const size_t layerNr = FindVertexAttributeLayerNumber(layerTypeID, occurence); + if (layerNr == InvalidIndex) { return nullptr; } - return mVertexAttributes[layerNr]; + return m_vertexAttributes[layerNr]; } // find the vertex attribute layer and return a pointer VertexAttributeLayer* Mesh::FindVertexAttributeLayerByName(uint32 layerTypeID, const char* name) const { - const uint32 layerNr = FindVertexAttributeLayerNumberByName(layerTypeID, name); - if (layerNr == MCORE_INVALIDINDEX32) + const size_t layerNr = FindVertexAttributeLayerNumberByName(layerTypeID, name); + if (layerNr == InvalidIndex) { return nullptr; } - return mVertexAttributes[layerNr]; + return m_vertexAttributes[layerNr]; } void Mesh::RemoveAllVertexAttributeLayers() { - while (mVertexAttributes.GetLength()) + while (m_vertexAttributes.size()) { - mVertexAttributes.GetLast()->Destroy(); - mVertexAttributes.RemoveLast(); + m_vertexAttributes.back()->Destroy(); + m_vertexAttributes.pop_back(); } } - void Mesh::RemoveVertexAttributeLayer(uint32 layerNr) + void Mesh::RemoveVertexAttributeLayer(size_t layerNr) { - MCORE_ASSERT(layerNr < mVertexAttributes.GetLength()); - mVertexAttributes[layerNr]->Destroy(); - mVertexAttributes.Remove(layerNr); + MCORE_ASSERT(layerNr < m_vertexAttributes.size()); + m_vertexAttributes[layerNr]->Destroy(); + m_vertexAttributes.erase(AZStd::next(begin(m_vertexAttributes), layerNr)); } @@ -1056,35 +998,34 @@ namespace EMotionFX Mesh* Mesh::Clone() { // allocate a mesh of the same dimensions - Mesh* clone = aznew Mesh(mNumVertices, mNumIndices, mNumPolygons, mNumOrgVerts, mIsCollisionMesh); + Mesh* clone = aznew Mesh(m_numVertices, m_numIndices, m_numPolygons, m_numOrgVerts, m_isCollisionMesh); // copy the mesh data - MCore::MemCopy(clone->mIndices, mIndices, sizeof(uint32) * mNumIndices); - MCore::MemCopy(clone->mPolyVertexCounts, mPolyVertexCounts, sizeof(uint8) * mNumPolygons); + MCore::MemCopy(clone->m_indices, m_indices, sizeof(uint32) * m_numIndices); + MCore::MemCopy(clone->m_polyVertexCounts, m_polyVertexCounts, sizeof(uint8) * m_numPolygons); // copy the submesh data - uint32 i; - const uint32 numSubMeshes = mSubMeshes.GetLength(); - clone->mSubMeshes.Resize(numSubMeshes); - for (i = 0; i < numSubMeshes; ++i) + const size_t numSubMeshes = m_subMeshes.size(); + clone->m_subMeshes.resize(numSubMeshes); + for (size_t i = 0; i < numSubMeshes; ++i) { - clone->mSubMeshes[i] = mSubMeshes[i]->Clone(clone); + clone->m_subMeshes[i] = m_subMeshes[i]->Clone(clone); } // clone the shared vertex attributes - const uint32 numSharedAttributes = mSharedVertexAttributes.GetLength(); - clone->mSharedVertexAttributes.Resize(numSharedAttributes); - for (i = 0; i < numSharedAttributes; ++i) + const size_t numSharedAttributes = m_sharedVertexAttributes.size(); + clone->m_sharedVertexAttributes.resize(numSharedAttributes); + for (size_t i = 0; i < numSharedAttributes; ++i) { - clone->mSharedVertexAttributes[i] = mSharedVertexAttributes[i]->Clone(); + clone->m_sharedVertexAttributes[i] = m_sharedVertexAttributes[i]->Clone(); } // clone the non-shared vertex attributes - const uint32 numAttributes = mVertexAttributes.GetLength(); - clone->mVertexAttributes.Resize(numAttributes); - for (i = 0; i < numAttributes; ++i) + const size_t numAttributes = m_vertexAttributes.size(); + clone->m_vertexAttributes.resize(numAttributes); + for (size_t i = 0; i < numAttributes; ++i) { - clone->mVertexAttributes[i] = mVertexAttributes[i]->Clone(); + clone->m_vertexAttributes[i] = m_vertexAttributes[i]->Clone(); } // return the resulting cloned mesh @@ -1095,8 +1036,8 @@ namespace EMotionFX // swap the data for two vertices void Mesh::SwapVertex(uint32 vertexA, uint32 vertexB) { - MCORE_ASSERT(vertexA < mNumVertices); - MCORE_ASSERT(vertexB < mNumVertices); + MCORE_ASSERT(vertexA < m_numVertices); + MCORE_ASSERT(vertexB < m_numVertices); // if we try to swap itself then there is nothing to do if (vertexA == vertexB) @@ -1105,98 +1046,19 @@ namespace EMotionFX } // swap all vertex attribute layers - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const size_t numLayers = m_vertexAttributes.size(); + for (size_t i = 0; i < numLayers; ++i) { - mVertexAttributes[i]->SwapAttributes(vertexA, vertexB); + m_vertexAttributes[i]->SwapAttributes(vertexA, vertexB); } } - /* - // remove indexed null triangles (triangles that use 2 or 3 of the same vertices, so which are invisible) - uint32 Mesh::RemoveIndexedNullTriangles(bool removeEmptySubMeshes) - { - uint32 numRemoved = 0; - uint32 i; - - // for all triangles - uint32 numIndices = mNumIndices; - uint32 offset = 0; - for (i=0; i 0) - MCore::MemMove(((uint8*)mIndices + (offset * sizeof(uint32))), ((uint8*)mIndices + (offset+3)*sizeof(uint32)), numBytesToMove); - - numRemoved++; - numIndices -= 3; - - // adjust all submesh start index offsets changed - //const uint32 numSubMeshes = mSubMeshes.GetLength(); - for (uint32 s=0; sGetStartIndex() <= offset && mSubMeshes[s+1]->GetStartIndex() > offset) - subMesh->SetNumIndices( subMesh->GetNumIndices() - 3 ); - } - else - { - if (subMesh->GetStartIndex() <= offset) - subMesh->SetNumIndices( subMesh->GetNumIndices() - 3 ); - } - - // now find out if we need to adjust the index offset of the submesh - if (subMesh->GetStartIndex() >= offset) - { - if (subMesh->GetStartIndex() != offset) - subMesh->SetStartIndex( subMesh->GetStartIndex() - 3 ); - } - - - // remove the submesh if it's empty - if (subMesh->GetNumIndices() == 0 && removeEmptySubMeshes) - mSubMeshes.Remove(s); - else - s++; - - } - } // if we gotta remove - else - offset += 3; - } - - // reallocate the array, if we removed anything - if (numIndices != mNumIndices) - mIndices = (uint32*)MCore::AlignedRealloc(mIndices, sizeof(uint32) * numIndices, mNumIndices*sizeof(uint32), 32, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); - - // update the number of indices - MCORE_ASSERT(numRemoved == (mNumIndices - numIndices) / 3); - mNumIndices = numIndices; - - // return the number of removed triangles - return numRemoved; - } - */ - // remove vertex data from the mesh void Mesh::RemoveVertices(uint32 startVertexNr, uint32 endVertexNr, bool changeIndexBuffer, bool removeEmptySubMeshes) { // perform some checks on the input data - MCORE_ASSERT(endVertexNr < mNumVertices); - MCORE_ASSERT(startVertexNr < mNumVertices); + MCORE_ASSERT(endVertexNr < m_numVertices); + MCORE_ASSERT(startVertexNr < m_numVertices); // make sure the start vertex is before the end vertex in release mode, to prevent weirdness if (startVertexNr > endVertexNr) @@ -1212,11 +1074,11 @@ namespace EMotionFX const uint32 numVertsToRemove = (endVertexNr - startVertexNr) + 1; // +1 because we remove the end vertex as well // remove the num verices counter - mNumVertices -= numVertsToRemove; + m_numVertices -= numVertsToRemove; // remove the attributes from the vertex attribute layers - const uint32 numLayers = GetNumVertexAttributeLayers(); - for (uint32 i = 0; i < numLayers; ++i) + const size_t numLayers = GetNumVertexAttributeLayers(); + for (size_t i = 0; i < numLayers; ++i) { GetVertexAttributeLayer(i)->RemoveAttributes(startVertexNr, endVertexNr); } @@ -1229,9 +1091,9 @@ namespace EMotionFX for (uint32 w = 0; w < numVertsToRemove; ++w) { // adjust all submesh start index offsets changed - for (uint32 s = 0; s < mSubMeshes.GetLength();) + for (size_t s = 0; s < m_subMeshes.size();) { - SubMesh* subMesh = mSubMeshes[s]; + SubMesh* subMesh = m_subMeshes[s]; // if we remove a vertex from this submesh if (subMesh->GetStartVertex() <= v && subMesh->GetStartVertex() + subMesh->GetNumVertices() > v) @@ -1249,7 +1111,7 @@ namespace EMotionFX // remove the submesh if it's empty if (subMesh->GetNumVertices() == 0 && removeEmptySubMeshes) { - mSubMeshes.Remove(s); + m_subMeshes.erase(AZStd::next(begin(m_subMeshes), s)); } else { @@ -1266,11 +1128,11 @@ namespace EMotionFX //------------------------------------ if (changeIndexBuffer) { - for (uint32 i = 0; i < mNumIndices; ++i) + for (uint32 i = 0; i < m_numIndices; ++i) { - if (mIndices[i] > startVertexNr) + if (m_indices[i] > startVertexNr) { - mIndices[i] -= numVertsToRemove; + m_indices[i] -= numVertsToRemove; } } } @@ -1278,14 +1140,14 @@ namespace EMotionFX // remove empty submeshes - uint32 Mesh::RemoveEmptySubMeshes(bool onlyRemoveOnZeroVertsAndTriangles) + size_t Mesh::RemoveEmptySubMeshes(bool onlyRemoveOnZeroVertsAndTriangles) { - uint32 numRemoved = 0; + size_t numRemoved = 0; // for all the submeshes - for (uint32 i = 0; i < mSubMeshes.GetLength();) + for (size_t i = 0; i < m_subMeshes.size();) { - SubMesh* subMesh = mSubMeshes[i]; + SubMesh* subMesh = m_subMeshes[i]; // get some stats about the submesh bool mustRemove; @@ -1305,7 +1167,7 @@ namespace EMotionFX // remove or skip if (mustRemove) { - mSubMeshes.Remove(i); + m_subMeshes.erase(AZStd::next(begin(m_subMeshes), i)); numRemoved++; } else @@ -1320,7 +1182,7 @@ namespace EMotionFX // find vertex data - void* Mesh::FindVertexData(uint32 layerID, uint32 occurrence) const + void* Mesh::FindVertexData(uint32 layerID, size_t occurrence) const { VertexAttributeLayer* layer = FindVertexAttributeLayer(layerID, occurrence); if (layer) @@ -1347,7 +1209,7 @@ namespace EMotionFX // find original vertex data - void* Mesh::FindOriginalVertexData(uint32 layerID, uint32 occurrence) const + void* Mesh::FindOriginalVertexData(uint32 layerID, size_t occurrence) const { VertexAttributeLayer* layer = FindVertexAttributeLayer(layerID, occurrence); if (layer) @@ -1372,20 +1234,17 @@ namespace EMotionFX } - void Mesh::CalcAABB(MCore::AABB* outBoundingBox, const Transform& transform, uint32 vertexFrequency) + void Mesh::CalcAabb(AZ::Aabb* outBoundingBox, const Transform& transform, uint32 vertexFrequency) { MCORE_ASSERT(vertexFrequency >= 1); + *outBoundingBox = AZ::Aabb::CreateNull(); - // init the bounding box - outBoundingBox->Init(); - - // get the position data AZ::Vector3* positions = (AZ::Vector3*)FindVertexData(ATTRIB_POSITIONS); const uint32 numVerts = GetNumVertices(); for (uint32 i = 0; i < numVerts; i += vertexFrequency) { - outBoundingBox->Encapsulate(transform.TransformPoint(positions[i])); + outBoundingBox->AddPoint(transform.TransformPoint(positions[i])); } } @@ -1535,8 +1394,6 @@ namespace EMotionFX // log debugging information void Mesh::Log() { - uint32 i; - // get all current data // uint32* indices = GetIndices(); // never returns nullptr //uint32* orgVerts = (uint32*) FindVertexData( Mesh::ATTRIB_ORGVTXNUMBERS ); // never returns nullptr @@ -1573,8 +1430,8 @@ namespace EMotionFX LogDebug(" + Position: %f %f %f, Normal: %f %f %f", positions[i].x, positions[i].y, positions[i].z, normals[i].x, normals[i].y, normals[i].z); */ // iterate through all of its submeshes - const uint32 numSubMeshes = GetNumSubMeshes(); - for (uint32 s = 0; s < numSubMeshes; ++s) + const size_t numSubMeshes = GetNumSubMeshes(); + for (size_t s = 0; s < numSubMeshes; ++s) { // get the current submesh SubMesh* subMesh = GetSubMesh(s); @@ -1606,18 +1463,18 @@ namespace EMotionFX // output the bones used by this submesh MCore::LogDebug(" - Bone list:"); - const uint32 numBones = subMesh->GetNumBones(); - for (i = 0; i < numBones; ++i) + const size_t numBones = subMesh->GetNumBones(); + for (size_t j = 0; j < numBones; ++j) { - const uint32 nodeNr = subMesh->GetBone(i); - MCore::LogDebug(" + NodeNr %d", nodeNr); + const size_t nodeNr = subMesh->GetBone(j); + MCore::LogDebug(" + NodeNr %zu", nodeNr); } } } // check for a given mesh how we categorize it - Mesh::EMeshType Mesh::ClassifyMeshType(uint32 lodLevel, Actor* actor, uint32 nodeIndex, bool forceCPUSkinning, uint32 maxInfluences, uint32 maxBonesPerSubMesh) const + Mesh::EMeshType Mesh::ClassifyMeshType(size_t lodLevel, Actor* actor, size_t nodeIndex, bool forceCPUSkinning, uint32 maxInfluences, uint32 maxBonesPerSubMesh) const { // get the mesh deformer stack for the given node at the given detail level MeshDeformerStack* deformerStack = actor->GetMeshDeformerStack(lodLevel, nodeIndex); @@ -1644,7 +1501,7 @@ namespace EMotionFX // in that case use CPU skinning Mesh* mesh = actor->GetMesh(lodLevel, nodeIndex); Node* node = actor->GetSkeleton()->GetNode(nodeIndex); - uint32 meshMaxInfluences = mesh->CalcMaxNumInfluences(); + size_t meshMaxInfluences = mesh->CalcMaxNumInfluences(); if (meshMaxInfluences > maxInfluences) { MCore::LogWarning("*** PERFORMANCE WARNING *** Mesh for node '%s' in geometry LOD %d uses more than %d (%d) bones. Forcing CPU deforms for this mesh.", node->GetName(), lodLevel, maxInfluences, meshMaxInfluences); @@ -1653,8 +1510,8 @@ namespace EMotionFX // check if there is any submesh with more than the given number of bones, which would mean we cannot skin on the GPU // then force CPU skinning as well - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 i = 0; i < numSubMeshes; ++i) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t i = 0; i < numSubMeshes; ++i) { if (mesh->GetSubMesh(i)->GetNumBones() > maxBonesPerSubMesh) { @@ -1685,19 +1542,19 @@ namespace EMotionFX bool result = true; // check if the indices are valid and return false in case they aren't - if (mIndices == nullptr) + if (m_indices == nullptr) { return false; } // use our 32-bit index buffer as new 16-bit index array directly - uint16* indices = (uint16*)mIndices; + uint16* indices = (uint16*)m_indices; // iterate over all indices and convert the values - for (uint32 i = 0; i < mNumIndices; ++i) + for (uint32 i = 0; i < m_numIndices; ++i) { // create a temporary copy of our 32-bit vertex index - const uint32 oldVertexIndex = mIndices[i]; + const uint32 oldVertexIndex = m_indices[i]; // check if our index is in range of an unsigned short if (oldVertexIndex < 65536) @@ -1713,7 +1570,7 @@ namespace EMotionFX } // realloc the memory to the new index buffer size using 16-bit values and return the result - mIndices = (uint32*)MCore::AlignedRealloc(mIndices, sizeof(uint16) * mNumIndices, 32, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); + m_indices = (uint32*)MCore::AlignedRealloc(m_indices, sizeof(uint16) * m_numIndices, 32, EMFX_MEMCATEGORY_GEOMETRY_MESHES, Mesh::MEMORYBLOCK_ID); return result; } @@ -1753,19 +1610,19 @@ namespace EMotionFX void Mesh::ExtractOriginalVertexPositions(AZStd::vector& outPoints) const { // allocate space - outPoints.resize(mNumOrgVerts); + outPoints.resize(m_numOrgVerts); // get the mesh data const AZ::Vector3* positions = (AZ::Vector3*)FindOriginalVertexData(ATTRIB_POSITIONS); const uint32* orgVerts = (uint32*) FindVertexData(ATTRIB_ORGVTXNUMBERS); // init all org vertices - for (uint32 v = 0; v < mNumOrgVerts; ++v) + for (uint32 v = 0; v < m_numOrgVerts; ++v) { outPoints[v] = positions[0]; // init them, as there are some unused original vertices sometimes } // output the points - for (uint32 i = 0; i < mNumVertices; ++i) + for (uint32 i = 0; i < m_numVertices; ++i) { outPoints[ orgVerts[i] ] = positions[i]; } @@ -1783,8 +1640,8 @@ namespace EMotionFX if (useDuplicates == false) { // the smoothed normals array - AZStd::vector smoothNormals(mNumOrgVerts); - for (uint32 i = 0; i < mNumOrgVerts; ++i) + AZStd::vector smoothNormals(m_numOrgVerts); + for (uint32 i = 0; i < m_numOrgVerts; ++i) { smoothNormals[i] = AZ::Vector3::CreateZero(); } @@ -1824,39 +1681,20 @@ namespace EMotionFX polyStartIndex += numPolyVerts; } - /* - for (uint32 f=0; fScale(scaleFactor); + layer->Scale(scaleFactor); } - // scale all shared layers - const uint32 numSharedLayers = GetNumSharedVertexAttributeLayers(); - for (uint32 i = 0; i < numSharedLayers; ++i) + for (VertexAttributeLayer* layer : m_sharedVertexAttributes) { - GetSharedVertexAttributeLayer(i)->Scale(scaleFactor); + layer->Scale(scaleFactor); } // scale the positional data AZ::Vector3* positions = (AZ::Vector3*)FindVertexData(ATTRIB_POSITIONS); AZ::Vector3* orgPositions = (AZ::Vector3*)FindOriginalVertexData(ATTRIB_POSITIONS); - const uint32 numVerts = mNumVertices; + const uint32 numVerts = m_numVertices; for (uint32 i = 0; i < numVerts; ++i) { positions[i] = positions[i] * scaleFactor; @@ -2004,97 +1818,67 @@ namespace EMotionFX // find by name - uint32 Mesh::FindVertexAttributeLayerIndexByName(const char* name) const + size_t Mesh::FindVertexAttributeLayerIndexByName(const char* name) const { - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find by name as string - uint32 Mesh::FindVertexAttributeLayerIndexByNameString(const AZStd::string& name) const + size_t Mesh::FindVertexAttributeLayerIndexByNameString(const AZStd::string& name) const { - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find by name ID - uint32 Mesh::FindVertexAttributeLayerIndexByNameID(uint32 nameID) const + size_t Mesh::FindVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const uint32 numLayers = mVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_vertexAttributes), end(m_vertexAttributes), [nameID](const VertexAttributeLayer* layer) { - if (mVertexAttributes[i]->GetNameID() == nameID) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameID() == nameID; + }); + return foundLayer != end(m_vertexAttributes) ? AZStd::distance(begin(m_vertexAttributes), foundLayer) : InvalidIndex; } // find by name - uint32 Mesh::FindSharedVertexAttributeLayerIndexByName(const char* name) const + size_t Mesh::FindSharedVertexAttributeLayerIndexByName(const char* name) const { - const uint32 numLayers = mSharedVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mSharedVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } // find by name as string - uint32 Mesh::FindSharedVertexAttributeLayerIndexByNameString(const AZStd::string& name) const + size_t Mesh::FindSharedVertexAttributeLayerIndexByNameString(const AZStd::string& name) const { - const uint32 numLayers = mSharedVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [name](const VertexAttributeLayer* layer) { - if (mSharedVertexAttributes[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameString() == name; + }); + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } // find by name ID - uint32 Mesh::FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const + size_t Mesh::FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const { - const uint32 numLayers = mSharedVertexAttributes.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_sharedVertexAttributes), end(m_sharedVertexAttributes), [nameID](const VertexAttributeLayer* layer) { - if (mSharedVertexAttributes[i]->GetNameID() == nameID) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetNameID() == nameID; + }); + return foundLayer != end(m_sharedVertexAttributes) ? AZStd::distance(begin(m_sharedVertexAttributes), foundLayer) : InvalidIndex; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h index f9a9f960ce..c2d776bcdb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.h @@ -9,6 +9,7 @@ #pragma once #include "EMotionFXConfig.h" +#include #include #include #include @@ -17,7 +18,7 @@ #include "Transform.h" #include -#include +#include #include #include @@ -170,7 +171,7 @@ namespace EMotionFX * It is recommended NOT to put this function inside a loop, because it is not very fast. * @result The number of UV layers/sets currently present inside this mesh. */ - uint32 CalcNumUVLayers() const; + size_t CalcNumUVLayers() const; /** * Calculate the number of vertex attribute layers of the given type. @@ -178,7 +179,7 @@ namespace EMotionFX * @param[in] type The type of the vertex attribute layer to count. * @result The number of layers/sets currently present inside this mesh. */ - uint32 CalcNumAttributeLayers(uint32 type) const; + size_t CalcNumAttributeLayers(uint32 type) const; /** * Get the number of original vertices. This can be lower compared to the value returned by GetNumVertices(). @@ -234,21 +235,21 @@ namespace EMotionFX * Get the number of sub meshes currently in the mesh. * @result The number of sub meshes. */ - MCORE_INLINE uint32 GetNumSubMeshes() const; + MCORE_INLINE size_t GetNumSubMeshes() const; /** * Get a given SubMesh. * @param nr The SubMesh number to get. * @result A pointer to the SubMesh. */ - MCORE_INLINE SubMesh* GetSubMesh(uint32 nr) const; + MCORE_INLINE SubMesh* GetSubMesh(size_t nr) const; /** * Set the value for a given submesh. * @param nr The submesh number, which must be in range of [0..GetNumSubMeshes()-1]. * @param subMesh The submesh to use. */ - MCORE_INLINE void SetSubMesh(uint32 nr, SubMesh* subMesh) { mSubMeshes[nr] = subMesh; } + MCORE_INLINE void SetSubMesh(size_t nr, SubMesh* subMesh) { m_subMeshes[nr] = subMesh; } /** * Set the number of submeshes. @@ -256,21 +257,21 @@ namespace EMotionFX * Do not forget to use SetSubMesh() to initialize all submeshes! * @param numSubMeshes The number of submeshes to use. */ - MCORE_INLINE void SetNumSubMeshes(uint32 numSubMeshes) { mSubMeshes.Resize(numSubMeshes); } + MCORE_INLINE void SetNumSubMeshes(size_t numSubMeshes) { m_subMeshes.resize(numSubMeshes); } /** * Remove a given submesh from this mesh. * @param nr The submesh index number to remove, which must be in range of 0..GetNumSubMeshes()-1. * @param delFromMem Set to true when you want to delete the submesh from memory as well, otherwise set to false. */ - void RemoveSubMesh(uint32 nr, bool delFromMem = true); + void RemoveSubMesh(size_t nr, bool delFromMem = true); /** * Insert a submesh into the array of submeshes. * @param insertIndex The position in the submesh array to insert this new submesh. * @param subMesh A pointer to the submesh to insert into this mesh. */ - void InsertSubMesh(uint32 insertIndex, SubMesh* subMesh); + void InsertSubMesh(size_t insertIndex, SubMesh* subMesh); /** * Get the shared vertex attribute data of a given layer. @@ -278,7 +279,7 @@ namespace EMotionFX * @param layerNr The layer number to get the attributes from. Must be below the value returned by GetNumSharedVertexAttributeLayers(). * @result A pointer to the array of shared vertex attributes. You can typecast this pointer if you know the type of the vertex attributes. */ - VertexAttributeLayer* GetSharedVertexAttributeLayer(uint32 layerNr); + VertexAttributeLayer* GetSharedVertexAttributeLayer(size_t layerNr); /** * Adds a new layer of shared vertex attributes. @@ -292,7 +293,7 @@ namespace EMotionFX * This value is the same for all shared vertices. * @result The number of shared vertex attributes for every vertex. */ - uint32 GetNumSharedVertexAttributeLayers() const; + size_t GetNumSharedVertexAttributeLayers() const; /** * Find and return the shared vertex attribute layer of a given type. @@ -305,7 +306,7 @@ namespace EMotionFX * @result The vertex attribute layer index number that you can pass to GetSharedVertexAttributeLayer. A value of MCORE_INVALIDINDEX32 is returned * when no result could be found. */ - uint32 FindSharedVertexAttributeLayerNumber(uint32 layerTypeID, uint32 occurrence = 0) const; + size_t FindSharedVertexAttributeLayerNumber(uint32 layerTypeID, size_t occurrence = 0) const; /** * Find and return the shared vertex attribute layer of a given type. @@ -317,7 +318,7 @@ namespace EMotionFX * want the second layer of the given type, etc. * @result A pointer to the vertex attribute layer, or nullptr when none could be found. */ - VertexAttributeLayer* FindSharedVertexAttributeLayer(uint32 layerTypeID, uint32 occurence = 0) const; + VertexAttributeLayer* FindSharedVertexAttributeLayer(uint32 layerTypeID, size_t occurence = 0) const; /** * Removes all shared vertex attributes for all shared vertices. @@ -330,14 +331,14 @@ namespace EMotionFX * Automatically deletes the data from memory. * @param layerNr The layer number to remove, must be below the value returned by GetNumSharedVertexAttributeLayers(). */ - void RemoveSharedVertexAttributeLayer(uint32 layerNr); + void RemoveSharedVertexAttributeLayer(size_t layerNr); /** * Get the number of vertex attributes. * This value is the same for all vertices. * @result The number of vertex attributes for every vertex. */ - uint32 GetNumVertexAttributeLayers() const; + size_t GetNumVertexAttributeLayers() const; /** * Get the vertex attribute data of a given layer. @@ -345,7 +346,7 @@ namespace EMotionFX * @param layerNr The layer number to get the attributes from. Must be below the value returned by GetNumVertexAttributeLayers(). * @result A pointer to the array of vertex attributes. You can typecast this pointer if you know the type of the vertex attributes. */ - VertexAttributeLayer* GetVertexAttributeLayer(uint32 layerNr); + VertexAttributeLayer* GetVertexAttributeLayer(size_t layerNr); /** * Adds a new layer of vertex attributes. @@ -372,9 +373,9 @@ namespace EMotionFX * @result The vertex attribute layer index number that you can pass to GetSharedVertexAttributeLayer. A value of MCORE_INVALIDINDEX32 os returned * when no result could be found. */ - uint32 FindVertexAttributeLayerNumber(uint32 layerTypeID, uint32 occurrence = 0) const; + size_t FindVertexAttributeLayerNumber(uint32 layerTypeID, size_t occurrence = 0) const; - uint32 FindVertexAttributeLayerNumberByName(uint32 layerTypeID, const char* name) const; + size_t FindVertexAttributeLayerNumberByName(uint32 layerTypeID, const char* name) const; VertexAttributeLayer* FindVertexAttributeLayerByName(uint32 layerTypeID, const char* name) const; @@ -388,15 +389,15 @@ namespace EMotionFX * want the second layer of the given type, etc. * @result A pointer to the vertex attribute layer, or nullptr when none could be found. */ - VertexAttributeLayer* FindVertexAttributeLayer(uint32 layerTypeID, uint32 occurence = 0) const; + VertexAttributeLayer* FindVertexAttributeLayer(uint32 layerTypeID, size_t occurence = 0) const; - uint32 FindVertexAttributeLayerIndexByName(const char* name) const; - uint32 FindVertexAttributeLayerIndexByNameString(const AZStd::string& name) const; - uint32 FindVertexAttributeLayerIndexByNameID(uint32 nameID) const; + size_t FindVertexAttributeLayerIndexByName(const char* name) const; + size_t FindVertexAttributeLayerIndexByNameString(const AZStd::string& name) const; + size_t FindVertexAttributeLayerIndexByNameID(uint32 nameID) const; - uint32 FindSharedVertexAttributeLayerIndexByName(const char* name) const; - uint32 FindSharedVertexAttributeLayerIndexByNameString(const AZStd::string& name) const; - uint32 FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const; + size_t FindSharedVertexAttributeLayerIndexByName(const char* name) const; + size_t FindSharedVertexAttributeLayerIndexByNameString(const AZStd::string& name) const; + size_t FindSharedVertexAttributeLayerIndexByNameID(uint32 nameID) const; /** * Removes all vertex attributes for all vertices. @@ -409,7 +410,7 @@ namespace EMotionFX * Automatically deletes the data from memory. * @param layerNr The layer number to remove, must be below the value returned by GetNumVertexAttributeLayers(). */ - void RemoveVertexAttributeLayer(uint32 layerNr); + void RemoveVertexAttributeLayer(size_t layerNr); //--------------------------------------------------- @@ -446,7 +447,7 @@ namespace EMotionFX * @param outBones The array to store the pointers to the bones in. Any existing array contents will be cleared when it enters the method. * @param actor The actor to search the bones in. */ - void GatherBonesForFace(uint32 startIndexOfFace, MCore::Array& outBones, Actor* actor); + void GatherBonesForFace(uint32 startIndexOfFace, AZStd::vector& outBones, Actor* actor); /** * Calculates the maximum number of bone influences for a given face. @@ -461,7 +462,7 @@ namespace EMotionFX * This is calculated by for each vertex checking the number of bone influences, and take the maximum of that amount. * @result The maximum number of influences. This will be 0 for non-softskinned objects. */ - uint32 CalcMaxNumInfluences() const; + size_t CalcMaxNumInfluences() const; /** * Calculates the maximum number of bone influences. @@ -471,7 +472,7 @@ namespace EMotionFX * which are effected by 4 bones. * @result The maximum number of influences. This will be 0 for non-softskinned objects. */ - uint32 CalcMaxNumInfluences(AZStd::vector& outVertexCounts) const; + size_t CalcMaxNumInfluences(AZStd::vector& outVertexCounts) const; /** * Extract a list of positions of the original vertices. @@ -516,7 +517,7 @@ namespace EMotionFX * @param onlyRemoveOnZeroVertsAndTriangles Only remove when both the number of vertices and number of indices/triangles are zero. * @result Returns the number of removed submeshes. */ - uint32 RemoveEmptySubMeshes(bool onlyRemoveOnZeroVertsAndTriangles = true); + size_t RemoveEmptySubMeshes(bool onlyRemoveOnZeroVertsAndTriangles = true); /** * Find specific current vertex data in the mesh. This contains the vertex data after mesh deformers have been @@ -537,7 +538,7 @@ namespace EMotionFX * when there are multiple layers of the same type. An example is a mesh having multiple UV layers. * @result A void pointer to the layer data. You have to typecast yourself. */ - void* FindVertexData(uint32 layerID, uint32 occurrence = 0) const; + void* FindVertexData(uint32 layerID, size_t occurrence = 0) const; void* FindVertexDataByName(uint32 layerID, const char* name) const; @@ -560,7 +561,7 @@ namespace EMotionFX * when there are multiple layers of the same type. An example is a mesh having multiple UV layers. * @result A void pointer to the layer data. You have to typecast yourself. */ - void* FindOriginalVertexData(uint32 layerID, uint32 occurrence = 0) const; + void* FindOriginalVertexData(uint32 layerID, size_t occurrence = 0) const; void* FindOriginalVertexDataByName(uint32 layerID, const char* name) const; @@ -571,7 +572,7 @@ namespace EMotionFX * @param vertexFrequency This is the for loop increase counter value. A value of 1 means every vertex will be processed * while a value of 2 means every second vertex, etc. The value must be 1 or higher. */ - void CalcAABB(MCore::AABB* outBoundingBox, const Transform& transform, uint32 vertexFrequency = 1); + void CalcAabb(AZ::Aabb* outBoundingBox, const Transform& transform, uint32 vertexFrequency = 1); /** * The mesh type used to indicate if a mesh is either static, like a cube or building, cpu deformed, if it needs to be processed on the CPU, or GPU deformed if it can be processed fully on the GPU. @@ -595,7 +596,7 @@ namespace EMotionFX * @param maxBonesPerSubMesh The maximum number of bones per submesh can be processed on hardware. If there will be more bones per submesh the mesh will be processed in software which will be very slow. * @return The mesh type meaning if the given mesh is static like a cube or building or if is deformed by the GPU or CPU. */ - EMeshType ClassifyMeshType(uint32 lodLevel, Actor* actor, uint32 nodeIndex, bool forceCPUSkinning, uint32 maxInfluences, uint32 maxBonesPerSubMesh) const; + EMeshType ClassifyMeshType(size_t lodLevel, Actor* actor, size_t nodeIndex, bool forceCPUSkinning, uint32 maxInfluences, uint32 maxBonesPerSubMesh) const; /** * Debug log information. @@ -647,31 +648,31 @@ namespace EMotionFX void Scale(float scaleFactor); - MCORE_INLINE bool GetIsCollisionMesh() const { return mIsCollisionMesh; } - void SetIsCollisionMesh(bool isCollisionMesh) { mIsCollisionMesh = isCollisionMesh; } + MCORE_INLINE bool GetIsCollisionMesh() const { return m_isCollisionMesh; } + void SetIsCollisionMesh(bool isCollisionMesh) { m_isCollisionMesh = isCollisionMesh; } protected: - MCore::Array mSubMeshes; /**< The collection of sub meshes. */ - uint32* mIndices; /**< The array of indices, which define the faces. */ - uint8* mPolyVertexCounts; /**< The number of vertices for each polygon, where the length of this array equals the number of polygons. */ - uint32 mNumPolygons; /**< The number of polygons in this mesh. */ - uint32 mNumOrgVerts; /**< The number of original vertices. */ - uint32 mNumVertices; /**< Number of vertices. */ - uint32 mNumIndices; /**< Number of indices. */ - bool mIsCollisionMesh; /**< Is this mesh a collision mesh? */ + AZStd::vector m_subMeshes; /**< The collection of sub meshes. */ + uint32* m_indices; /**< The array of indices, which define the faces. */ + uint8* m_polyVertexCounts; /**< The number of vertices for each polygon, where the length of this array equals the number of polygons. */ + uint32 m_numPolygons; /**< The number of polygons in this mesh. */ + uint32 m_numOrgVerts; /**< The number of original vertices. */ + uint32 m_numVertices; /**< Number of vertices. */ + uint32 m_numIndices; /**< Number of indices. */ + bool m_isCollisionMesh; /**< Is this mesh a collision mesh? */ /** * The array of shared vertex attribute layers. * The number of attributes in each shared layer will be equal to the value returned by Mesh::GetNumOrgVertices(). */ - MCore::Array< VertexAttributeLayer* > mSharedVertexAttributes; + AZStd::vector< VertexAttributeLayer* > m_sharedVertexAttributes; /** * The array of non-shared vertex attribute layers. * The number of attributes in each shared layer will be equal to the value returned by Mesh::GetNumVertices(). */ - MCore::Array< VertexAttributeLayer* > mVertexAttributes; + AZStd::vector< VertexAttributeLayer* > m_vertexAttributes; /** * Default constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl index 850d9d1f17..1794303b76 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Mesh.inl @@ -8,65 +8,54 @@ MCORE_INLINE uint32 Mesh::GetNumVertices() const { - return mNumVertices; + return m_numVertices; } MCORE_INLINE uint32 Mesh::GetNumIndices() const { - return mNumIndices; + return m_numIndices; } MCORE_INLINE uint32 Mesh::GetNumPolygons() const { - return mNumPolygons; + return m_numPolygons; } -MCORE_INLINE uint32 Mesh::GetNumSubMeshes() const +MCORE_INLINE size_t Mesh::GetNumSubMeshes() const { - return mSubMeshes.GetLength(); + return m_subMeshes.size(); } -MCORE_INLINE SubMesh* Mesh::GetSubMesh(uint32 nr) const +MCORE_INLINE SubMesh* Mesh::GetSubMesh(size_t nr) const { - MCORE_ASSERT(nr < mSubMeshes.GetLength()); - return mSubMeshes[nr]; + MCORE_ASSERT(nr < m_subMeshes.size()); + return m_subMeshes[nr]; } MCORE_INLINE void Mesh::AddSubMesh(SubMesh* subMesh) { - mSubMeshes.Add(subMesh); + m_subMeshes.emplace_back(subMesh); } MCORE_INLINE uint32* Mesh::GetIndices() const { - return mIndices; + return m_indices; } MCORE_INLINE uint8* Mesh::GetPolygonVertexCounts() const { - return mPolyVertexCounts; + return m_polyVertexCounts; } -/* -MCORE_INLINE void Mesh::SetFace(const uint32 faceNr, const uint32 a, const uint32 b, const uint32 c) -{ - MCORE_ASSERT(faceNr < mNumIndices * 3); - - uint32 startIndex = faceNr * 3; - mIndices[startIndex++] = a; - mIndices[startIndex++] = b; - mIndices[startIndex] = c; -} -*/ MCORE_INLINE uint32 Mesh::GetNumOrgVertices() const { - return mNumOrgVerts; + return m_numOrgVerts; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp index a7d628b8c3..93a716571d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.cpp @@ -19,8 +19,8 @@ namespace EMotionFX MeshDeformer::MeshDeformer(Mesh* mesh) : BaseObject() { - mMesh = mesh; - mIsEnabled = true; + m_mesh = mesh; + m_isEnabled = true; } @@ -33,19 +33,19 @@ namespace EMotionFX // check if the deformer is enabled bool MeshDeformer::GetIsEnabled() const { - return mIsEnabled; + return m_isEnabled; } // enable or disable it void MeshDeformer::SetIsEnabled(bool enabled) { - mIsEnabled = enabled; + m_isEnabled = enabled; } // reinitialize the mesh deformer - void MeshDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) + void MeshDeformer::Reinitialize(Actor* actor, Node* node, size_t lodLevel) { MCORE_UNUSED(actor); MCORE_UNUSED(node); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h index 6b379eda1d..dcb95fcd82 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformer.h @@ -49,14 +49,14 @@ namespace EMotionFX * @param node The node where the mesh belongs to during this initialization. * @param lodLevel The LOD level of the mesh the mesh deformer works on. */ - virtual void Reinitialize(Actor* actor, Node* node, uint32 lodLevel); + virtual void Reinitialize(Actor* actor, Node* node, size_t lodLevel); /** * Creates an exact clone (copy) of this deformer, and returns a pointer to it. * @param mesh The mesh to apply the cloned deformer on. * @result A pointer to the newly created clone of this deformer. */ - virtual MeshDeformer* Clone(Mesh* mesh) = 0; + virtual MeshDeformer* Clone(Mesh* mesh) const = 0; /** * Returns the type identification number of the deformer class. @@ -86,8 +86,8 @@ namespace EMotionFX void SetIsEnabled(bool enabled); protected: - Mesh* mMesh; /**< Pointer to the mesh to which the deformer belongs to.*/ - bool mIsEnabled; /**< When set to true, this mesh deformer will be processed, otherwise it will be skipped during update. */ + Mesh* m_mesh; /**< Pointer to the mesh to which the deformer belongs to.*/ + bool m_isEnabled; /**< When set to true, this mesh deformer will be processed, otherwise it will be skipped during update. */ /** * Default constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp index c50aca4325..bf7fd657ec 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.cpp @@ -21,24 +21,22 @@ namespace EMotionFX MeshDeformerStack::MeshDeformerStack(Mesh* mesh) : BaseObject() { - mMesh = mesh; - mDeformers.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_DEFORMERS); + m_mesh = mesh; } // destructor MeshDeformerStack::~MeshDeformerStack() { - const uint32 numDeformers = mDeformers.GetLength(); - for (uint32 i = 0; i < numDeformers; ++i) + for (MeshDeformer* deformer : m_deformers) { - mDeformers[i]->Destroy(); + deformer->Destroy(); } - mDeformers.Clear(); + m_deformers.clear(); // reset - mMesh = nullptr; + m_mesh = nullptr; } @@ -52,37 +50,32 @@ namespace EMotionFX // returns the mesh Mesh* MeshDeformerStack::GetMesh() const { - return mMesh; + return m_mesh; } // update the mesh deformer stack void MeshDeformerStack::Update(ActorInstance* actorInstance, Node* node, float timeDelta, bool forceUpdateDisabledDeformers) { - // if we have deformers in the stack - const uint32 numDeformers = mDeformers.GetLength(); - if (numDeformers > 0) - { - bool firstEnabled = true; + bool firstEnabled = true; - // iterate through the deformers and update them - for (uint32 i = 0; i < numDeformers; ++i) + // iterate through the deformers and update them + for (MeshDeformer* deformer : m_deformers) + { + // if the deformer is enabled + if (deformer->GetIsEnabled() || forceUpdateDisabledDeformers) { - // if the deformer is enabled - if (mDeformers[i]->GetIsEnabled() || forceUpdateDisabledDeformers) + // if this is the first enabled deformer + if (firstEnabled) { - // if this is the first enabled deformer - if (firstEnabled) - { - firstEnabled = false; + firstEnabled = false; - // reset all output vertex data to the original vertex data - mMesh->ResetToOriginalData(); - } - - // update the mesh deformer - mDeformers[i]->Update(actorInstance, node, timeDelta); + // reset all output vertex data to the original vertex data + m_mesh->ResetToOriginalData(); } + + // update the mesh deformer + deformer->Update(actorInstance, node, timeDelta); } } } @@ -91,39 +84,36 @@ namespace EMotionFX void MeshDeformerStack::UpdateByModifierType(ActorInstance* actorInstance, Node* node, float timeDelta, uint32 typeID, bool resetMesh, bool forceUpdateDisabledDeformers) { bool resetDone = false; - // if we have deformers in the stack - const uint32 numDeformers = mDeformers.GetLength(); - // iterate through the deformers and update them - for (uint32 i = 0; i < numDeformers; ++i) + for (MeshDeformer* deformer : m_deformers) { // if the deformer of the correct type and is enabled - if (mDeformers[i]->GetType() == typeID && (mDeformers[i]->GetIsEnabled() || forceUpdateDisabledDeformers)) + if (deformer->GetType() == typeID && (deformer->GetIsEnabled() || forceUpdateDisabledDeformers)) { // if this is the first enabled deformer if (resetMesh && !resetDone) { // reset all output vertex data to the original vertex data - mMesh->ResetToOriginalData(); + m_mesh->ResetToOriginalData(); resetDone = true; } // update the mesh deformer - mDeformers[i]->Update(actorInstance, node, timeDelta); + deformer->Update(actorInstance, node, timeDelta); } } } // reinitialize mesh deformers - void MeshDeformerStack::ReinitializeDeformers(Actor* actor, Node* node, uint32 lodLevel) + void MeshDeformerStack::ReinitializeDeformers(Actor* actor, Node* node, size_t lodLevel) { // if we have deformers in the stack - const uint32 numDeformers = mDeformers.GetLength(); + const size_t numDeformers = m_deformers.size(); // iterate through the deformers and reinitialize them - for (uint32 i = 0; i < numDeformers; ++i) + for (size_t i = 0; i < numDeformers; ++i) { - mDeformers[i]->Reinitialize(actor, node, lodLevel); + m_deformers[i]->Reinitialize(actor, node, lodLevel); } } @@ -131,21 +121,26 @@ namespace EMotionFX void MeshDeformerStack::AddDeformer(MeshDeformer* meshDeformer) { // add the object into the stack - mDeformers.Add(meshDeformer); + m_deformers.emplace_back(meshDeformer); } - void MeshDeformerStack::InsertDeformer(uint32 pos, MeshDeformer* meshDeformer) + void MeshDeformerStack::InsertDeformer(size_t pos, MeshDeformer* meshDeformer) { // add the object into the stack - mDeformers.Insert(pos, meshDeformer); + m_deformers.emplace(AZStd::next(begin(m_deformers), pos), meshDeformer); } bool MeshDeformerStack::RemoveDeformer(MeshDeformer* meshDeformer) { // delete the object - return mDeformers.RemoveByValue(meshDeformer); + if (const auto it = AZStd::find(begin(m_deformers), end(m_deformers), meshDeformer); it != end(m_deformers)) + { + m_deformers.erase(it); + return true; + } + return false; } @@ -155,10 +150,9 @@ namespace EMotionFX MeshDeformerStack* newStack = aznew MeshDeformerStack(mesh); // clone all deformers - const uint32 numDeformers = mDeformers.GetLength(); - for (uint32 i = 0; i < numDeformers; ++i) + for (const MeshDeformer* deformer : m_deformers) { - newStack->AddDeformer(mDeformers[i]->Clone(mesh)); + newStack->AddDeformer(deformer->Clone(mesh)); } // return a pointer to the clone @@ -166,26 +160,26 @@ namespace EMotionFX } - uint32 MeshDeformerStack::GetNumDeformers() const + size_t MeshDeformerStack::GetNumDeformers() const { - return mDeformers.GetLength(); + return m_deformers.size(); } - MeshDeformer* MeshDeformerStack::GetDeformer(uint32 nr) const + MeshDeformer* MeshDeformerStack::GetDeformer(size_t nr) const { - MCORE_ASSERT(nr < mDeformers.GetLength()); - return mDeformers[nr]; + MCORE_ASSERT(nr < m_deformers.size()); + return m_deformers[nr]; } // remove all the deformers of a given type - uint32 MeshDeformerStack::RemoveAllDeformersByType(uint32 deformerTypeID) + size_t MeshDeformerStack::RemoveAllDeformersByType(uint32 deformerTypeID) { - uint32 numRemoved = 0; - for (uint32 a = 0; a < mDeformers.GetLength(); ) + size_t numRemoved = 0; + for (size_t a = 0; a < m_deformers.size(); ) { - MeshDeformer* deformer = mDeformers[a]; + MeshDeformer* deformer = m_deformers[a]; if (deformer->GetType() == deformerTypeID) { RemoveDeformer(deformer); @@ -205,12 +199,10 @@ namespace EMotionFX // remove all the deformers void MeshDeformerStack::RemoveAllDeformers() { - for (uint32 i = 0; i < mDeformers.GetLength(); ++i) + for (MeshDeformer* deformer : m_deformers) { // retrieve the current deformer - MeshDeformer* deformer = mDeformers[i]; - - // remove the deformer + // remove the deformer RemoveDeformer(deformer); deformer->Destroy(); } @@ -218,14 +210,12 @@ namespace EMotionFX // enabled or disable all controllers of a given type - uint32 MeshDeformerStack::EnableAllDeformersByType(uint32 deformerTypeID, bool enabled) + size_t MeshDeformerStack::EnableAllDeformersByType(uint32 deformerTypeID, bool enabled) { - uint32 numChanged = 0; - const uint32 numDeformers = mDeformers.GetLength(); - for (uint32 a = 0; a < numDeformers; ++a) + size_t numChanged = 0; + for (MeshDeformer* deformer : m_deformers) { - MeshDeformer* deformer = mDeformers[a]; - if (deformer->GetType() == deformerTypeID) + if (deformer->GetType() == deformerTypeID) { deformer->SetIsEnabled(enabled); numChanged++; @@ -239,44 +229,20 @@ namespace EMotionFX // check if the stack contains a deformer of a specified type bool MeshDeformerStack::CheckIfHasDeformerOfType(uint32 deformerTypeID) const { - const uint32 numDeformers = mDeformers.GetLength(); - for (uint32 a = 0; a < numDeformers; ++a) + return AZStd::any_of(begin(m_deformers), end(m_deformers), [deformerTypeID](const MeshDeformer* deformer) { - if (mDeformers[a]->GetType() == deformerTypeID) - { - return true; - } - } - - return false; + return deformer->GetType() == deformerTypeID; + }); } // find a deformer by type ID - MeshDeformer* MeshDeformerStack::FindDeformerByType(uint32 deformerTypeID, uint32 occurrence) const + MeshDeformer* MeshDeformerStack::FindDeformerByType(uint32 deformerTypeID, size_t occurrence) const { - uint32 count = 0; - - // for all deformers - const uint32 numDeformers = mDeformers.GetLength(); - for (uint32 a = 0; a < numDeformers; ++a) + const auto foundDeformer = AZStd::find_if(begin(m_deformers), end(m_deformers), [deformerTypeID, iter = occurrence](const MeshDeformer* deformer) mutable { - // if this is a deformer of the type we search for - if (mDeformers[a]->GetType() == deformerTypeID) - { - // if its the one we want - if (count == occurrence) - { - return mDeformers[a]; - } - else - { - count++; - } - } - } - - // none found - return nullptr; + return deformer->GetType() == deformerTypeID && iter-- == 0; + }); + return foundDeformer != end(m_deformers) ? *foundDeformer : nullptr; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h index 902eecf0d2..885bc06cab 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MeshDeformerStack.h @@ -12,7 +12,7 @@ #include "EMotionFXConfig.h" #include "MeshDeformer.h" #include "BaseObject.h" -#include +#include namespace EMotionFX @@ -74,7 +74,7 @@ namespace EMotionFX * @param node The node to use for the reinitialize, so the node where the mesh belongs to during this initialization. * @param lodLevel The LOD level the mesh deformers work on. */ - void ReinitializeDeformers(Actor* actor, Node* node, uint32 lodLevel); + void ReinitializeDeformers(Actor* actor, Node* node, size_t lodLevel); /** * Add a given deformer to the back of the stack. @@ -87,7 +87,7 @@ namespace EMotionFX * @param pos The position to insert the deformer. * @param meshDeformer The deformer to store at this position. */ - void InsertDeformer(uint32 pos, MeshDeformer* meshDeformer); + void InsertDeformer(size_t pos, MeshDeformer* meshDeformer); /** * Remove a given deformer. @@ -101,7 +101,7 @@ namespace EMotionFX * @param deformerTypeID The type ID of the deformer, which is returned by MeshDeformer::GetType(). * @result Returns the number of deformers that have been removed. */ - uint32 RemoveAllDeformersByType(uint32 deformerTypeID); + size_t RemoveAllDeformersByType(uint32 deformerTypeID); /** * Remove all deformers from this mesh deformer stack. @@ -115,7 +115,7 @@ namespace EMotionFX * @param enabled Set to true when you want to enable these deformers, or false if you want to disable them. * @result Returns the number of deformers that have been enabled or disabled. */ - uint32 EnableAllDeformersByType(uint32 deformerTypeID, bool enabled); + size_t EnableAllDeformersByType(uint32 deformerTypeID, bool enabled); /** * Creates an exact clone (copy) of this deformer stack, including all deformers (which will also be cloned). @@ -134,14 +134,14 @@ namespace EMotionFX * Get the number of deformers in the stack. * @result The number of deformers in the stack. */ - uint32 GetNumDeformers() const; + size_t GetNumDeformers() const; /** * Get a given deformer. * @param nr The deformer number to get. * @result A pointer to the deformer. */ - MeshDeformer* GetDeformer(uint32 nr) const; + MeshDeformer* GetDeformer(size_t nr) const; /** * Check if the stack contains a deformer of a given type. @@ -156,11 +156,11 @@ namespace EMotionFX * @param occurrence In case there are multiple controllers of the same type, 0 means it returns the first one, 1 means the second, etc. * @result A pointer to the mesh deformer of the given type, or nullptr when not found. */ - MeshDeformer* FindDeformerByType(uint32 deformerTypeID, uint32 occurrence = 0) const; + MeshDeformer* FindDeformerByType(uint32 deformerTypeID, size_t occurrence = 0) const; private: - MCore::Array mDeformers; /**< The stack of deformers. */ - Mesh* mMesh; /**< Pointer to the mesh to which the modifier stack belongs to.*/ + AZStd::vector m_deformers; /**< The stack of deformers. */ + Mesh* m_mesh; /**< Pointer to the mesh to which the modifier stack belongs to.*/ /** * Constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp index c609f908d1..8dd0c15d84 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.cpp @@ -26,7 +26,6 @@ namespace EMotionFX MorphMeshDeformer::MorphMeshDeformer(Mesh* mesh) : MeshDeformer(mesh) { - mDeformPasses.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_DEFORMERS); } @@ -58,19 +57,19 @@ namespace EMotionFX // clone this class - MeshDeformer* MorphMeshDeformer::Clone(Mesh* mesh) + MeshDeformer* MorphMeshDeformer::Clone(Mesh* mesh) const { // create the new cloned deformer MorphMeshDeformer* result = aznew MorphMeshDeformer(mesh); // copy the deform passes - result->mDeformPasses.Resize(mDeformPasses.GetLength()); - for (uint32 i = 0; i < mDeformPasses.GetLength(); ++i) + result->m_deformPasses.resize(m_deformPasses.size()); + for (size_t i = 0; i < m_deformPasses.size(); ++i) { - DeformPass& pass = result->mDeformPasses[i]; - pass.mDeformDataNr = mDeformPasses[i].mDeformDataNr; - pass.mMorphTarget = mDeformPasses[i].mMorphTarget; - pass.mLastNearZero = false; + DeformPass& pass = result->m_deformPasses[i]; + pass.m_deformDataNr = m_deformPasses[i].m_deformDataNr; + pass.m_morphTarget = m_deformPasses[i].m_morphTarget; + pass.m_lastNearZero = false; } // return the result @@ -86,27 +85,26 @@ namespace EMotionFX // get the actor instance and its LOD level Actor* actor = actorInstance->GetActor(); - const uint32 lodLevel = actorInstance->GetLODLevel(); + const size_t lodLevel = actorInstance->GetLODLevel(); // apply all deform passes - const uint32 numPasses = mDeformPasses.GetLength(); - for (uint32 i = 0; i < numPasses; ++i) + for (DeformPass& deformPass : m_deformPasses) { // find the morph target - MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(mDeformPasses[i].mMorphTarget->GetID()); + MorphTargetStandard* morphTarget = (MorphTargetStandard*)actor->GetMorphSetup(lodLevel)->FindMorphTargetByID(deformPass.m_morphTarget->GetID()); if (morphTarget == nullptr) { continue; } // get the deform data and number of vertices to deform - MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(mDeformPasses[i].mDeformDataNr); - const uint32 numDeformVerts = deformData->mNumVerts; + MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(deformPass.m_deformDataNr); + const uint32 numDeformVerts = deformData->m_numVerts; // this mesh deformer can't work on this mesh, because the deformdata number of vertices is bigger than the // number of vertices inside this mesh! // and that would make it crash, which isn't what we want - if (numDeformVerts > mMesh->GetNumVertices()) + if (numDeformVerts > m_mesh->GetNumVertices()) { continue; } @@ -122,7 +120,7 @@ namespace EMotionFX const bool nearZero = (MCore::Math::Abs(weight) < 0.0001f); // we are near zero, and the previous frame as well, so we can return - if (nearZero && mDeformPasses[i].mLastNearZero) + if (nearZero && deformPass.m_lastNearZero) { continue; } @@ -130,64 +128,61 @@ namespace EMotionFX // update the flag if (nearZero) { - mDeformPasses[i].mLastNearZero = true; + deformPass.m_lastNearZero = true; } else { - mDeformPasses[i].mLastNearZero = false; // we moved away from zero influence + deformPass.m_lastNearZero = false; // we moved away from zero influence } // output data - 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::Vector3* positions = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_POSITIONS)); + AZ::Vector3* normals = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_NORMALS)); + AZ::Vector4* tangents = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_TANGENTS)); + AZ::Vector3* bitangents = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_BITANGENTS)); // input data - const MorphTargetStandard::DeformData::VertexDelta* deltas = deformData->mDeltas; - const float minValue = deformData->mMinValue; - const float maxValue = deformData->mMaxValue; + const MorphTargetStandard::DeformData::VertexDelta* deltas = deformData->m_deltas; + const float minValue = deformData->m_minValue; + const float maxValue = deformData->m_maxValue; if (tangents && bitangents) { // process all vertices that we need to deform - uint32 vtxNr; for (uint32 v = 0; v < numDeformVerts; ++v) { - vtxNr = deltas[v].mVertexNr; + uint32 vtxNr = deltas[v].m_vertexNr; - positions [vtxNr] = positions[vtxNr] + deltas[v].mPosition.ToVector3(minValue, maxValue) * weight; - normals [vtxNr] = normals[vtxNr] + deltas[v].mNormal.ToVector3(-2.0f, 2.0f) * weight; - bitangents[vtxNr] = bitangents[vtxNr] + deltas[v].mBitangent.ToVector3(-2.0f, 2.0f) * weight; + positions [vtxNr] = positions[vtxNr] + deltas[v].m_position.ToVector3(minValue, maxValue) * weight; + normals [vtxNr] = normals[vtxNr] + deltas[v].m_normal.ToVector3(-2.0f, 2.0f) * weight; + bitangents[vtxNr] = bitangents[vtxNr] + deltas[v].m_bitangent.ToVector3(-2.0f, 2.0f) * weight; - const AZ::Vector3 tangentDirVector = deltas[v].mTangent.ToVector3(-2.0f, 2.0f); + const AZ::Vector3 tangentDirVector = deltas[v].m_tangent.ToVector3(-2.0f, 2.0f); tangents[vtxNr] += AZ::Vector4(tangentDirVector.GetX()*weight, tangentDirVector.GetY()*weight, tangentDirVector.GetZ()*weight, 0.0f); } } else if (tangents && !bitangents) // tangents but no bitangents { - uint32 vtxNr; for (uint32 v = 0; v < numDeformVerts; ++v) { - vtxNr = deltas[v].mVertexNr; + uint32 vtxNr = deltas[v].m_vertexNr; - positions[vtxNr] = positions[vtxNr] + deltas[v].mPosition.ToVector3(minValue, maxValue) * weight; - normals [vtxNr] = normals[vtxNr] + deltas[v].mNormal.ToVector3(-2.0f, 2.0f) * weight; + positions[vtxNr] = positions[vtxNr] + deltas[v].m_position.ToVector3(minValue, maxValue) * weight; + normals [vtxNr] = normals[vtxNr] + deltas[v].m_normal.ToVector3(-2.0f, 2.0f) * weight; - const AZ::Vector3 tangentDirVector = deltas[v].mTangent.ToVector3(-2.0f, 2.0f); + const AZ::Vector3 tangentDirVector = deltas[v].m_tangent.ToVector3(-2.0f, 2.0f); tangents[vtxNr] += AZ::Vector4(tangentDirVector.GetX()*weight, tangentDirVector.GetY()*weight, tangentDirVector.GetZ()*weight, 0.0f); } } else // no tangents { // process all vertices that we need to deform - uint32 vtxNr; for (uint32 v = 0; v < numDeformVerts; ++v) { - vtxNr = deltas[v].mVertexNr; + uint32 vtxNr = deltas[v].m_vertexNr; - positions[vtxNr] = positions[vtxNr] + deltas[v].mPosition.ToVector3(minValue, maxValue) * weight; - normals[vtxNr] = normals[vtxNr] + deltas[v].mNormal.ToVector3(-2.0f, 2.0f) * weight; + positions[vtxNr] = positions[vtxNr] + deltas[v].m_position.ToVector3(minValue, maxValue) * weight; + normals[vtxNr] = normals[vtxNr] + deltas[v].m_normal.ToVector3(-2.0f, 2.0f) * weight; } } } @@ -195,34 +190,34 @@ namespace EMotionFX // initialize the mesh deformer - void MorphMeshDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) + void MorphMeshDeformer::Reinitialize(Actor* actor, Node* node, size_t lodLevel) { // clear the deform passes, but don't free the currently allocated/reserved memory - mDeformPasses.Clear(false); + m_deformPasses.clear(); // get the morph setup MorphSetup* morphSetup = actor->GetMorphSetup(lodLevel); // get the number of morph targets and iterate through them - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (uint32 i = 0; i < numMorphTargets; ++i) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t i = 0; i < numMorphTargets; ++i) { // get the morph target MorphTargetStandard* morphTarget = static_cast(morphSetup->GetMorphTarget(i)); // get the number of deform datas and add one deform pass per deform data - const uint32 numDeformDatas = morphTarget->GetNumDeformDatas(); - for (uint32 j = 0; j < numDeformDatas; ++j) + const size_t numDeformDatas = morphTarget->GetNumDeformDatas(); + for (size_t j = 0; j < numDeformDatas; ++j) { // get the deform data and only add it to our deformer in case it belongs to our mesh MorphTargetStandard::DeformData* deformData = morphTarget->GetDeformData(j); - if (deformData->mNodeIndex == node->GetNodeIndex()) + if (deformData->m_nodeIndex == node->GetNodeIndex()) { // add an empty deform pass and fill it afterwards - mDeformPasses.AddEmpty(); - const uint32 deformPassIndex = mDeformPasses.GetLength() - 1; - mDeformPasses[deformPassIndex].mDeformDataNr = j; - mDeformPasses[deformPassIndex].mMorphTarget = morphTarget; + m_deformPasses.emplace_back(); + const size_t deformPassIndex = m_deformPasses.size() - 1; + m_deformPasses[deformPassIndex].m_deformDataNr = j; + m_deformPasses[deformPassIndex].m_morphTarget = morphTarget; } } } @@ -231,18 +226,18 @@ namespace EMotionFX void MorphMeshDeformer::AddDeformPass(const DeformPass& deformPass) { - mDeformPasses.Add(deformPass); + m_deformPasses.emplace_back(deformPass); } - uint32 MorphMeshDeformer::GetNumDeformPasses() const + size_t MorphMeshDeformer::GetNumDeformPasses() const { - return mDeformPasses.GetLength(); + return m_deformPasses.size(); } - void MorphMeshDeformer::ReserveDeformPasses(uint32 numPasses) + void MorphMeshDeformer::ReserveDeformPasses(size_t numPasses) { - mDeformPasses.Reserve(numPasses); + m_deformPasses.reserve(numPasses); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h index 6cbf4cae5b..fb4b2efa5c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphMeshDeformer.h @@ -54,18 +54,18 @@ namespace EMotionFX */ struct EMFX_API DeformPass { - MorphTargetStandard* mMorphTarget; /**< The morph target working on the mesh. */ - uint32 mDeformDataNr; /**< An index inside the deform datas of the standard morph target. */ - bool mLastNearZero; /**< Was the last frame's weight near zero? */ + MorphTargetStandard* m_morphTarget; /**< The morph target working on the mesh. */ + size_t m_deformDataNr; /**< An index inside the deform datas of the standard morph target. */ + bool m_lastNearZero; /**< Was the last frame's weight near zero? */ /** * Constructor. * Automatically initializes on defaults. */ DeformPass() - : mMorphTarget(nullptr) - , mDeformDataNr(MCORE_INVALIDINDEX32) - , mLastNearZero(false) {} + : m_morphTarget(nullptr) + , m_deformDataNr(InvalidIndex) + , m_lastNearZero(false) {} }; /** @@ -103,14 +103,14 @@ namespace EMotionFX * @param node The node where the mesh belongs to during this initialization. * @param lodLevel The LOD level of the mesh the mesh deformer works on. */ - void Reinitialize(Actor* actor, Node* node, uint32 lodLevel) override; + void Reinitialize(Actor* actor, Node* node, size_t lodLevel) override; /** * Creates an exact clone (copy) of this deformer, and returns a pointer to it. * @param mesh The mesh to apply the deformer on. * @result A pointer to the newly created clone of this deformer. */ - MeshDeformer* Clone(Mesh* mesh) override; + MeshDeformer* Clone(Mesh* mesh) const override; /** * Add a deform pass. @@ -122,17 +122,17 @@ namespace EMotionFX * Get the number of deform passes. * @result The number of deform passes. */ - uint32 GetNumDeformPasses() const; + size_t GetNumDeformPasses() const; /** * Pre-allocate space for the deform passes. * This does not influence the return value of GetNumDeformPasses(). * @param numPasses The number of passes to pre-allocate space for. */ - void ReserveDeformPasses(uint32 numPasses); + void ReserveDeformPasses(size_t numPasses); private: - MCore::Array mDeformPasses; /**< The deform passes. Each pass basically represents a morph target. */ + AZStd::vector m_deformPasses; /**< The deform passes. Each pass basically represents a morph target. */ /** * Default constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp index 0c9f4f8cd7..9836325ff2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.cpp @@ -10,6 +10,7 @@ #include "MorphSetup.h" #include "MorphTarget.h" #include +#include #include namespace EMotionFX @@ -17,14 +18,6 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(MorphSetup, DeformerAllocator, 0) - // constructor - MorphSetup::MorphSetup() - : BaseObject() - { - mMorphTargets.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_PMORPHTARGETS); - } - - // destructor MorphSetup::~MorphSetup() { @@ -42,26 +35,30 @@ namespace EMotionFX // add a morph target void MorphSetup::AddMorphTarget(MorphTarget* morphTarget) { - mMorphTargets.Add(morphTarget); + m_morphTargets.emplace_back(morphTarget); } // remove a morph target - void MorphSetup::RemoveMorphTarget(uint32 nr, bool delFromMem) + void MorphSetup::RemoveMorphTarget(size_t nr, bool delFromMem) { if (delFromMem) { - mMorphTargets[nr]->Destroy(); + m_morphTargets[nr]->Destroy(); } - mMorphTargets.Remove(nr); + m_morphTargets.erase(AZStd::next(begin(m_morphTargets), nr)); } // remove a morph target void MorphSetup::RemoveMorphTarget(MorphTarget* morphTarget, bool delFromMem) { - mMorphTargets.RemoveByValue(morphTarget); + const auto* foundMorphTarget = AZStd::find(begin(m_morphTargets), end(m_morphTargets), morphTarget); + if (foundMorphTarget != end(m_morphTargets)) + { + m_morphTargets.erase(foundMorphTarget); + } if (delFromMem) { @@ -73,111 +70,76 @@ namespace EMotionFX // remove all morph targets void MorphSetup::RemoveAllMorphTargets() { - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + for (MorphTarget*& morphTarget : m_morphTargets) { - mMorphTargets[i]->Destroy(); + morphTarget->Destroy(); } - mMorphTargets.Clear(); + m_morphTargets.clear(); } // get a morph target by ID MorphTarget* MorphSetup::FindMorphTargetByID(uint32 id) const { - // linear search, and check IDs - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [id](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetID() == id) - { - return mMorphTargets[i]; - } - } - - // nothing found - return nullptr; + return morphTarget->GetID() == id; + }); + return foundMorphTarget != end(m_morphTargets) ? *foundMorphTarget : nullptr; } // get a morph target number by ID - uint32 MorphSetup::FindMorphTargetNumberByID(uint32 id) const + size_t MorphSetup::FindMorphTargetNumberByID(uint32 id) const { - // linear search, and check IDs - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [id](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetID() == id) - { - return i; - } - } - - // nothing found - return MCORE_INVALIDINDEX32; + return morphTarget->GetID() == id; + }); + return foundMorphTarget != end(m_morphTargets) ? AZStd::distance(begin(m_morphTargets), foundMorphTarget) : InvalidIndex; } - uint32 MorphSetup::FindMorphTargetIndexByName(const char* name) const + size_t MorphSetup::FindMorphTargetIndexByName(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetNameString() == name) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return morphTarget->GetNameString() == name; + }); + return foundMorphTarget != end(m_morphTargets) ? AZStd::distance(begin(m_morphTargets), foundMorphTarget) : InvalidIndex; } - uint32 MorphSetup::FindMorphTargetIndexByNameNoCase(const char* name) const + size_t MorphSetup::FindMorphTargetIndexByNameNoCase(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { - if (AzFramework::StringFunc::Equal(mMorphTargets[i]->GetNameString().c_str(), name, false /* no case */)) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return AzFramework::StringFunc::Equal(morphTarget->GetNameString().c_str(), name, false /* no case */); + }); + return foundMorphTarget != end(m_morphTargets) ? AZStd::distance(begin(m_morphTargets), foundMorphTarget) : InvalidIndex; } // find a morph target by name (case sensitive) MorphTarget* MorphSetup::FindMorphTargetByName(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { - if (mMorphTargets[i]->GetNameString() == name) - { - return mMorphTargets[i]; - } - } - - return nullptr; + return morphTarget->GetNameString() == name; + }); + return foundMorphTarget != end(m_morphTargets) ? *foundMorphTarget : nullptr; } // find a morph target by name (not case sensitive) MorphTarget* MorphSetup::FindMorphTargetByNameNoCase(const char* name) const { - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundMorphTarget = AZStd::find_if(begin(m_morphTargets), end(m_morphTargets), [name](const MorphTarget* morphTarget) { - if (AzFramework::StringFunc::Equal(mMorphTargets[i]->GetNameString().c_str(), name, false /* no case */)) - { - return mMorphTargets[i]; - } - } - - return nullptr; + return AzFramework::StringFunc::Equal(morphTarget->GetNameString().c_str(), name, false /* no case */); + }); + return foundMorphTarget != end(m_morphTargets) ? *foundMorphTarget : nullptr; } @@ -188,10 +150,9 @@ namespace EMotionFX MorphSetup* clone = MorphSetup::Create(); // clone all morph targets - const uint32 numMorphTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numMorphTargets; ++i) + for (const MorphTarget* morphTarget : m_morphTargets) { - clone->AddMorphTarget(mMorphTargets[i]->Clone()); + clone->AddMorphTarget(morphTarget->Clone()); } // return the cloned morph setup @@ -199,9 +160,9 @@ namespace EMotionFX } - void MorphSetup::ReserveMorphTargets(uint32 numMorphTargets) + void MorphSetup::ReserveMorphTargets(size_t numMorphTargets) { - mMorphTargets.Reserve(numMorphTargets); + m_morphTargets.reserve(numMorphTargets); } @@ -215,10 +176,9 @@ namespace EMotionFX } // scale the morph targets - const uint32 numMorphTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numMorphTargets; ++i) + for (MorphTarget* morphTarget : m_morphTargets) { - mMorphTargets[i]->Scale(scaleFactor); + morphTarget->Scale(scaleFactor); } } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h index 6a19a0247c..12014dba8e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetup.h @@ -34,20 +34,20 @@ namespace EMotionFX * This does not influence the return value of GetNumMorphTargets(). * @param numMorphTargets The number of morph targets to pre-allocate space for. */ - void ReserveMorphTargets(uint32 numMorphTargets); + void ReserveMorphTargets(size_t numMorphTargets); /** * Get the number of morph targets inside this morph setup. * @result The number of morph targets. */ - MCORE_INLINE uint32 GetNumMorphTargets() const { return mMorphTargets.GetLength(); } + MCORE_INLINE size_t GetNumMorphTargets() const { return m_morphTargets.size(); } /** * Get a given morph target. * @param nr The morph target number, must be in range of [0..GetNumMorphTargets()-1]. * @result A pointer to the morph target. */ - MCORE_INLINE MorphTarget* GetMorphTarget(uint32 nr) const { return mMorphTargets[nr]; } + MCORE_INLINE MorphTarget* GetMorphTarget(size_t nr) const { return m_morphTargets[nr]; } /** * Add a morph target to this morph setup. @@ -61,7 +61,7 @@ namespace EMotionFX * @param delFromMem When set to true, the morph target will be deleted from memory as well. When false, it will * only be removed from the array of morph targets inside this class. */ - void RemoveMorphTarget(uint32 nr, bool delFromMem = true); + void RemoveMorphTarget(size_t nr, bool delFromMem = true); /** * Remove a given morph target. @@ -89,24 +89,24 @@ namespace EMotionFX * Find a morph target index by its unique ID, which has been calculated based on its name. * All morph targets with the same ID will also have the same name. * @param id The ID to search for. - * @result The morph target number, or MCORE_INVALIDINDEX32 when not found. You can use the returned number with the method + * @result The morph target number, or InvalidIndex when not found. You can use the returned number with the method * GetMorphTarget(nr) in order to convert it into a direct pointer to the morph target. */ - uint32 FindMorphTargetNumberByID(uint32 id) const; + size_t FindMorphTargetNumberByID(uint32 id) const; /** * Find a morph target index by its name. * Please remember that this is case sensitive. * @result The index of the morph target that you can pass to GetMorphTarget(index). */ - uint32 FindMorphTargetIndexByName(const char* name) const; + size_t FindMorphTargetIndexByName(const char* name) const; /** * Find a morph target index by its name. * Please remember that this is case insensitive. * @result The index of the morph target that you can pass to GetMorphTarget(index). */ - uint32 FindMorphTargetIndexByNameNoCase(const char* name) const; + size_t FindMorphTargetIndexByNameNoCase(const char* name) const; /** * Find a morph target by its name. @@ -137,12 +137,12 @@ namespace EMotionFX protected: - MCore::Array mMorphTargets; /**< The collection of morph targets. */ + AZStd::vector m_morphTargets; /**< The collection of morph targets. */ /** * The constructor. */ - MorphSetup(); + MorphSetup() = default; /** * The destructor. Automatically removes all morph targets from memory. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp index f27051d7e2..5b6e85d653 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.cpp @@ -20,7 +20,6 @@ namespace EMotionFX MorphSetupInstance::MorphSetupInstance() : BaseObject() { - mMorphTargets.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_PMORPHTARGETS); Init(nullptr); } @@ -62,41 +61,35 @@ namespace EMotionFX } // allocate the number of morph targets - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); - mMorphTargets.Resize(numMorphTargets); + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + m_morphTargets.resize(numMorphTargets); // update the ID values for (uint32 i = 0; i < numMorphTargets; ++i) { - mMorphTargets[i].SetID(morphSetup->GetMorphTarget(i)->GetID()); + m_morphTargets[i].SetID(morphSetup->GetMorphTarget(i)->GetID()); } } // try to locate the morph target by ID - uint32 MorphSetupInstance::FindMorphTargetIndexByID(uint32 id) const + size_t MorphSetupInstance::FindMorphTargetIndexByID(uint32 id) const { // try to locate the morph target with the given ID - const uint32 numTargets = mMorphTargets.GetLength(); - for (uint32 i = 0; i < numTargets; ++i) + const auto foundElement = AZStd::find_if(m_morphTargets.begin(), m_morphTargets.end(), [id](const MorphTarget& morphTarget) { - if (mMorphTargets[i].GetID() == id) - { - return i; - } - } - - // there is no such morph target with the given ID - return MCORE_INVALIDINDEX32; + return morphTarget.GetID() == id; + }); + return foundElement != m_morphTargets.end() ? AZStd::distance(m_morphTargets.begin(), foundElement) : InvalidIndex; } MorphSetupInstance::MorphTarget* MorphSetupInstance::FindMorphTargetByID(uint32 id) { - const uint32 index = FindMorphTargetIndexByID(id); - if (index != MCORE_INVALIDINDEX32) + const size_t index = FindMorphTargetIndexByID(id); + if (index != InvalidIndex) { - return &mMorphTargets[index]; + return &m_morphTargets[index]; } else { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h index 7cc0c0dbd0..d0c71f1f84 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphSetupInstance.h @@ -11,7 +11,7 @@ // include the required headers #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include namespace EMotionFX @@ -41,9 +41,9 @@ namespace EMotionFX * The constructor. */ MorphTarget() - : mID(MCORE_INVALIDINDEX32) - , mWeight(0.0f) - , mIsInManualMode(false) {} + : m_id(MCORE_INVALIDINDEX32) + , m_weight(0.0f) + , m_isInManualMode(false) {} /** * The destructor. @@ -55,13 +55,13 @@ namespace EMotionFX * This ID links the MorphTarget class with this local morph target class. * @result The ID of this morph target. */ - MCORE_INLINE uint32 GetID() const { return mID; } + MCORE_INLINE uint32 GetID() const { return m_id; } /** * Get the weight value of the morph target. * @result The weight value. */ - float GetWeight() const { return mWeight; } + float GetWeight() const { return m_weight; } /** * Check if we are in manual mode or not. @@ -69,20 +69,20 @@ namespace EMotionFX * then the motion system will overwrite the weight values. * @result Returns true when we are in manual mode, otherwise false is returned. */ - bool GetIsInManualMode() const { return mIsInManualMode; } + bool GetIsInManualMode() const { return m_isInManualMode; } /** * Set the ID of this morph target. * This ID links the MorphTarget class with this local morph target class. * @param id The ID to use. */ - void SetID(uint32 id) { mID = id; } + void SetID(uint32 id) { m_id = id; } /** * Set the weight value of the morph target. * @param weight The weight value. */ - void SetWeight(float weight) { mWeight = weight; } + void SetWeight(float weight) { m_weight = weight; } /** * Enable or disable manual mode. @@ -90,12 +90,12 @@ namespace EMotionFX * then the motion system will overwrite the weight values. * @param enabled Set to true if you wish to enable manual mode on this morph target. Otherwise set to false. */ - void SetManualMode(bool enabled) { mIsInManualMode = enabled; } + void SetManualMode(bool enabled) { m_isInManualMode = enabled; } private: - uint32 mID; /**< The ID, which is based on the weight. */ - float mWeight; /**< The weight for this morph target. */ - bool mIsInManualMode; /**< The flag if we are in manual weight update mode or not. */ + uint32 m_id; /**< The ID, which is based on the weight. */ + float m_weight; /**< The weight for this morph target. */ + bool m_isInManualMode; /**< The flag if we are in manual weight update mode or not. */ }; @@ -123,23 +123,23 @@ namespace EMotionFX * This should always be equal to the number of morph targets in the highest detail. * @result The number of morph targets. */ - MCORE_INLINE uint32 GetNumMorphTargets() const { return mMorphTargets.GetLength(); } + MCORE_INLINE size_t GetNumMorphTargets() const { return m_morphTargets.size(); } /** * Get a specific morph target. * @param nr The morph target number, which must be in range of [0..GetNumMorphTargets()-1]. * @result A pointer to the morph target inside this class. */ - MCORE_INLINE MorphTarget* GetMorphTarget(uint32 nr) { return &mMorphTargets[nr]; } + MCORE_INLINE MorphTarget* GetMorphTarget(size_t nr) { return &m_morphTargets[nr]; } - MCORE_INLINE const MorphTarget* GetMorphTarget(uint32 nr) const { return &mMorphTargets[nr]; } + MCORE_INLINE const MorphTarget* GetMorphTarget(size_t nr) const { return &m_morphTargets[nr]; } /** * Find a given morph target number by its ID. * @param id The ID value to search for. - * @result Returns the morph target number in range of [0..GetNumMorphTargets()-1], or MCORE_INVALIDINDEX32 when not found. + * @result Returns the morph target number in range of [0..GetNumMorphTargets()-1], or InvalidIndex when not found. */ - uint32 FindMorphTargetIndexByID(uint32 id) const; + size_t FindMorphTargetIndexByID(uint32 id) const; /** * Find the morph target by its ID. @@ -149,7 +149,7 @@ namespace EMotionFX MorphTarget* FindMorphTargetByID(uint32 id); private: - MCore::Array mMorphTargets; /**< The unique morph target information. */ + AZStd::vector m_morphTargets; /**< The unique morph target information. */ /** * The default constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp index 0a62253464..f2ff9eef5d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.cpp @@ -11,6 +11,7 @@ #include "Node.h" #include "MorphTarget.h" #include +#include #include namespace EMotionFX @@ -22,21 +23,15 @@ namespace EMotionFX MorphTarget::MorphTarget(const char* name) : BaseObject() { - mRangeMin = 0.0f; - mRangeMax = 1.0f; - mPhonemeSets = PHONEMESET_NONE; + m_rangeMin = 0.0f; + m_rangeMax = 1.0f; + m_phonemeSets = PHONEMESET_NONE; // set the name SetName(name); } - // destructor - MorphTarget::~MorphTarget() - { - } - - // convert the given phoneme name to a phoneme set MorphTarget::EPhonemeSet MorphTarget::FindPhonemeSet(const AZStd::string& phonemeName) { @@ -182,10 +177,10 @@ namespace EMotionFX // calculate the weight in range of 0..1 float MorphTarget::CalcNormalizedWeight(float rangedWeight) const { - const float range = mRangeMax - mRangeMin; + const float range = m_rangeMax - m_rangeMin; if (MCore::Math::Abs(range) > 0.0f) { - return (rangedWeight - mRangeMin) / range; + return (rangedWeight - m_rangeMin) / range; } else { @@ -206,99 +201,99 @@ namespace EMotionFX { if (enabled) { - mPhonemeSets = (EPhonemeSet)((uint32)mPhonemeSets | (uint32)set); + m_phonemeSets = (EPhonemeSet)((uint32)m_phonemeSets | (uint32)set); } else { - mPhonemeSets = (EPhonemeSet)((uint32)mPhonemeSets & (uint32) ~set); + m_phonemeSets = (EPhonemeSet)((uint32)m_phonemeSets & (uint32) ~set); } } // copy the base class members to the target class - void MorphTarget::CopyBaseClassMemberValues(MorphTarget* target) + void MorphTarget::CopyBaseClassMemberValues(MorphTarget* target) const { - target->mNameID = mNameID; - target->mRangeMin = mRangeMin; - target->mRangeMax = mRangeMax; - target->mPhonemeSets = mPhonemeSets; + target->m_nameId = m_nameId; + target->m_rangeMin = m_rangeMin; + target->m_rangeMax = m_rangeMax; + target->m_phonemeSets = m_phonemeSets; } const char* MorphTarget::GetName() const { - return MCore::GetStringIdPool().GetName(mNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } const AZStd::string& MorphTarget::GetNameString() const { - return MCore::GetStringIdPool().GetName(mNameID); + return MCore::GetStringIdPool().GetName(m_nameId); } void MorphTarget::SetRangeMin(float rangeMin) { - mRangeMin = rangeMin; + m_rangeMin = rangeMin; } void MorphTarget::SetRangeMax(float rangeMax) { - mRangeMax = rangeMax; + m_rangeMax = rangeMax; } float MorphTarget::GetRangeMin() const { - return mRangeMin; + return m_rangeMin; } float MorphTarget::GetRangeMax() const { - return mRangeMax; + return m_rangeMax; } void MorphTarget::SetName(const char* name) { - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } void MorphTarget::SetPhonemeSets(EPhonemeSet phonemeSets) { - mPhonemeSets = phonemeSets; + m_phonemeSets = phonemeSets; } MorphTarget::EPhonemeSet MorphTarget::GetPhonemeSets() const { - return mPhonemeSets; + return m_phonemeSets; } bool MorphTarget::GetIsPhonemeSetEnabled(EPhonemeSet set) const { - return (mPhonemeSets & set) != 0; + return (m_phonemeSets & set) != 0; } float MorphTarget::CalcRangedWeight(float weight) const { - return mRangeMin + (weight * (mRangeMax - mRangeMin)); + return m_rangeMin + (weight * (m_rangeMax - m_rangeMin)); } float MorphTarget::CalcZeroInfluenceWeight() const { - return MCore::Math::Abs(mRangeMin) / MCore::Math::Abs(mRangeMax - mRangeMin); + return MCore::Math::Abs(m_rangeMin) / MCore::Math::Abs(m_rangeMax - m_rangeMin); } bool MorphTarget::GetIsPhoneme() const { - return (mPhonemeSets != PHONEMESET_NONE); + return (m_phonemeSets != PHONEMESET_NONE); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h index 726f7d81bc..0cd85222d0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTarget.h @@ -68,7 +68,7 @@ namespace EMotionFX * @param scale This must contain the initial scale, and will be modified inside this method as well. * @param weight The absolute weight value. */ - virtual void ApplyTransformation(ActorInstance* actorInstance, uint32 nodeIndex, AZ::Vector3& position, AZ::Quaternion& rotation, AZ::Vector3& scale, float weight) = 0; + virtual void ApplyTransformation(ActorInstance* actorInstance, size_t nodeIndex, AZ::Vector3& position, AZ::Quaternion& rotation, AZ::Vector3& scale, float weight) = 0; /** * Get the unique ID of this morph target. @@ -77,7 +77,7 @@ namespace EMotionFX * name compares to simple integer compares. * @result The unique ID of the morph target. */ - MCORE_INLINE uint32 GetID() const { return mNameID; } + MCORE_INLINE uint32 GetID() const { return m_nameId; } /** * Get the unique name of the morph target. @@ -212,7 +212,7 @@ namespace EMotionFX * @param nodeIndex The node number to perform the check on. * @result Returns true if the given node will be modified by this morph target, otherwise false is returned. */ - virtual bool Influences(uint32 nodeIndex) const = 0; + virtual bool Influences(size_t nodeIndex) const = 0; /** * Calculate the range based weight value from a normalized weight value given by a facial animation key frame. @@ -259,14 +259,14 @@ namespace EMotionFX * Creates an exact clone of this morph target. * @result Returns a pointer to an exact clone of this morph target. */ - virtual MorphTarget* Clone() = 0; + virtual MorphTarget* Clone() const = 0; /** * Copy the morph target base class members over to another morph target. * This can be used when implementing your own Clone method for your own morph target. * @param target The morph target to copy the data from. */ - void CopyBaseClassMemberValues(MorphTarget* target); + void CopyBaseClassMemberValues(MorphTarget* target) const; /** * Scale all transform and positional data. @@ -276,20 +276,15 @@ namespace EMotionFX virtual void Scale(float scaleFactor) = 0; protected: - uint32 mNameID; /**< The unique ID of the morph target, calculated from the name. */ - float mRangeMin; /**< The minimum range of the weight. */ - float mRangeMax; /**< The maximum range of the weight. */ - EPhonemeSet mPhonemeSets; /**< The phoneme sets in case this morph target is used as a phoneme. */ + uint32 m_nameId; /**< The unique ID of the morph target, calculated from the name. */ + float m_rangeMin; /**< The minimum range of the weight. */ + float m_rangeMax; /**< The maximum range of the weight. */ + EPhonemeSet m_phonemeSets; /**< The phoneme sets in case this morph target is used as a phoneme. */ /** * The constructor. * @param name The unique name of the morph target. */ MorphTarget(const char* name); - - /** - * The destructor. - */ - virtual ~MorphTarget(); }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp index 6d2dc08d4b..ccb849a0d3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.cpp @@ -65,28 +65,18 @@ namespace EMotionFX if (captureTransforms) { - // get a bone list, if we also captured meshes, because in that case we want - // to disable capturing transforms for the bones since the deforms already have been captured - // by the mesh capture - //Array boneList; - //if (mCaptureMeshDeforms) - //pose->ExtractBoneList(0, &boneList); - Skeleton* targetSkeleton = targetPose->GetSkeleton(); Skeleton* neutralSkeleton = neutralPose->GetSkeleton(); const Pose& neutralBindPose = *neutralPose->GetBindPose(); const Pose& targetBindPose = *targetPose->GetBindPose(); - // Transform* neutralData = neutralPose->GetBindPoseLocalTransforms(); - // Transform* targetData = targetPose->GetBindPoseLocalTransforms(); - // check for transformation changes - const uint32 numPoseNodes = targetSkeleton->GetNumNodes(); - for (uint32 i = 0; i < numPoseNodes; ++i) + const size_t numPoseNodes = targetSkeleton->GetNumNodes(); + for (size_t i = 0; i < numPoseNodes; ++i) { // get a node id (both nodes will have the same id since they represent their names) - const uint32 nodeID = targetSkeleton->GetNode(i)->GetID(); + const size_t nodeID = targetSkeleton->GetNode(i)->GetID(); // try to find the node with the same name inside the neutral pose actor Node* neutralNode = neutralSkeleton->FindNodeByID(nodeID); @@ -96,28 +86,21 @@ namespace EMotionFX } // get the node indices of both nodes - const uint32 neutralNodeIndex = neutralNode->GetNodeIndex(); - const uint32 targetNodeIndex = targetSkeleton->GetNode(i)->GetNodeIndex(); - - // skip bones in the bone list - //if (mCaptureMeshDeforms) - //if (boneList.Contains( nodeA )) - //continue; + const size_t neutralNodeIndex = neutralNode->GetNodeIndex(); + const size_t targetNodeIndex = targetSkeleton->GetNode(i)->GetNodeIndex(); const Transform& neutralTransform = neutralBindPose.GetLocalSpaceTransform(neutralNodeIndex); const Transform& targetTransform = targetBindPose.GetLocalSpaceTransform(targetNodeIndex); - AZ::Vector3 neutralPos = neutralTransform.mPosition; - AZ::Vector3 targetPos = targetTransform.mPosition; - AZ::Quaternion neutralRot = neutralTransform.mRotation; - AZ::Quaternion targetRot = targetTransform.mRotation; + AZ::Vector3 neutralPos = neutralTransform.m_position; + AZ::Vector3 targetPos = targetTransform.m_position; + AZ::Quaternion neutralRot = neutralTransform.m_rotation; + AZ::Quaternion targetRot = targetTransform.m_rotation; EMFX_SCALECODE ( - AZ::Vector3 neutralScale = neutralTransform.mScale; - AZ::Vector3 targetScale = targetTransform.mScale; - //AZ::Quaternion neutralScaleRot = neutralTransform.mScaleRotation; - //AZ::Quaternion targetScaleRot = targetTransform.mScaleRotation; + AZ::Vector3 neutralScale = neutralTransform.m_scale; + AZ::Vector3 targetScale = targetTransform.m_scale; ) // check if the position changed @@ -137,9 +120,6 @@ namespace EMotionFX changed = (MCore::Compare::CheckIfIsClose(neutralScale, targetScale, MCore::Math::epsilon) == false); } - // check if the scale rotation changed - // if (changed == false) - // changed = (MCore::Compare::CheckIfIsClose(neutralScaleRot, targetScaleRot, MCore::Math::epsilon) == false); ) // if this node changed transformation @@ -147,51 +127,47 @@ namespace EMotionFX { // create a transform object form the node in the pose Transformation transform; - transform.mPosition = targetPos - neutralPos; - transform.mRotation = targetRot; + transform.m_position = targetPos - neutralPos; + transform.m_rotation = targetRot; EMFX_SCALECODE ( - //transform.mScaleRotation= targetScaleRot; - transform.mScale = targetScale - neutralScale; + transform.m_scale = targetScale - neutralScale; ) - transform.mNodeIndex = neutralNodeIndex; + transform.m_nodeIndex = neutralNodeIndex; // add the new transform AddTransformation(transform); } } - - //LogInfo("Num transforms = %d", mTransforms.GetLength()); } } // apply the relative transformation to the specified node // store the result in the position, rotation and scale parameters - void MorphTargetStandard::ApplyTransformation(ActorInstance* actorInstance, uint32 nodeIndex, AZ::Vector3& position, AZ::Quaternion& rotation, AZ::Vector3& scale, float weight) + void MorphTargetStandard::ApplyTransformation(ActorInstance* actorInstance, size_t nodeIndex, AZ::Vector3& position, AZ::Quaternion& rotation, AZ::Vector3& scale, float weight) { // calculate the normalized weight (in range of 0..1) - const float newWeight = MCore::Clamp(weight, mRangeMin, mRangeMax); // make sure its within the range + const float newWeight = MCore::Clamp(weight, m_rangeMin, m_rangeMax); // make sure its within the range const float normalizedWeight = CalcNormalizedWeight(newWeight); // convert in range of 0..1 // calculate the new transformations for all nodes of this morph target - const uint32 numTransforms = mTransforms.GetLength(); - for (uint32 i = 0; i < numTransforms; ++i) + for (const Transformation& transform : m_transforms) { // if this is the node that gets modified by this transform - if (mTransforms[i].mNodeIndex != nodeIndex) + if (transform.m_nodeIndex != nodeIndex) { continue; } - position += mTransforms[i].mPosition * newWeight; - scale += mTransforms[i].mScale * newWeight; + position += transform.m_position * newWeight; + scale += transform.m_scale * newWeight; // rotate additively - const AZ::Quaternion& orgRot = actorInstance->GetTransformData()->GetBindPose()->GetLocalSpaceTransform(nodeIndex).mRotation; - const AZ::Quaternion rot = orgRot.NLerp(mTransforms[i].mRotation, normalizedWeight); + const AZ::Quaternion& orgRot = actorInstance->GetTransformData()->GetBindPose()->GetLocalSpaceTransform(nodeIndex).m_rotation; + const AZ::Quaternion rot = orgRot.NLerp(transform.m_rotation, normalizedWeight); rotation = rotation * (orgRot.GetInverseFull() * rot); rotation.Normalize(); @@ -202,29 +178,18 @@ namespace EMotionFX // check if this morph target influences the specified node or not - bool MorphTargetStandard::Influences(uint32 nodeIndex) const + bool MorphTargetStandard::Influences(size_t nodeIndex) const { - // check if there is a deform data object, which works on the specified node - for (const DeformData* deformData : mDeformDatas) - { - if (deformData->mNodeIndex == nodeIndex) + return + AZStd::any_of(begin(m_deformDatas), end(m_deformDatas), [nodeIndex](const DeformData* deformData) { - return true; - } - } - - // check all transforms - const uint32 numTransforms = mTransforms.GetLength(); - for (uint32 i = 0; i < numTransforms; ++i) - { - if (mTransforms[i].mNodeIndex == nodeIndex) + return deformData->m_nodeIndex == nodeIndex; + }) + || + AZStd::any_of(begin(m_transforms), end(m_transforms), [nodeIndex](const Transformation& transform) { - return true; - } - } - - // this morph target doesn't influence the given node - return false; + return transform.m_nodeIndex == nodeIndex; + }); } @@ -232,84 +197,73 @@ namespace EMotionFX void MorphTargetStandard::Apply(ActorInstance* actorInstance, float weight) { // calculate the normalized weight (in range of 0..1) - const float newWeight = MCore::Clamp(weight, mRangeMin, mRangeMax); // make sure its within the range + const float newWeight = MCore::Clamp(weight, m_rangeMin, m_rangeMax); // make sure its within the range const float normalizedWeight = CalcNormalizedWeight(newWeight); // convert in range of 0..1 TransformData* transformData = actorInstance->GetTransformData(); Transform newTransform; // calculate the new transformations for all nodes of this morph target - const uint32 numTransforms = mTransforms.GetLength(); - for (uint32 i = 0; i < numTransforms; ++i) + for (const Transformation& transform : m_transforms) { // try to find the node - const uint32 nodeIndex = mTransforms[i].mNodeIndex; + const size_t nodeIndex = transform.m_nodeIndex; // init the transform data newTransform = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex); // calc new position and scale (delta based targetTransform) - newTransform.mPosition += mTransforms[i].mPosition * newWeight; + newTransform.m_position += transform.m_position * newWeight; EMFX_SCALECODE ( - newTransform.mScale += mTransforms[i].mScale * newWeight; - // newTransform.mScaleRotation.Identity(); + newTransform.m_scale += transform.m_scale * newWeight; ) // rotate additively - const AZ::Quaternion& orgRot = transformData->GetBindPose()->GetLocalSpaceTransform(nodeIndex).mRotation; - const AZ::Quaternion rot = orgRot.NLerp(mTransforms[i].mRotation, normalizedWeight); - newTransform.mRotation = newTransform.mRotation * (orgRot.GetInverseFull() * rot); - newTransform.mRotation.Normalize(); - /* - // scale rotate additively - orgRot = actorInstance->GetTransformData()->GetOrgScaleRot( nodeIndex ); - a = orgRot; - b = mTransforms[i].mScaleRotation; - rot = a.Lerp(b, normalizedWeight); - rot.Normalize(); - newTransform.mScaleRotation = newTransform.mScaleRotation * (orgRot.Inversed() * rot); - newTransform.mScaleRotation.Normalize(); - */ + const AZ::Quaternion& orgRot = transformData->GetBindPose()->GetLocalSpaceTransform(nodeIndex).m_rotation; + const AZ::Quaternion rot = orgRot.NLerp(transform.m_rotation, normalizedWeight); + newTransform.m_rotation = newTransform.m_rotation * (orgRot.GetInverseFull() * rot); + newTransform.m_rotation.Normalize(); // set the new transformation transformData->GetCurrentPose()->SetLocalSpaceTransform(nodeIndex, newTransform); } } - uint32 MorphTargetStandard::GetNumDeformDatas() const + size_t MorphTargetStandard::GetNumDeformDatas() const { - return static_cast(mDeformDatas.size()); + return m_deformDatas.size(); } - MorphTargetStandard::DeformData* MorphTargetStandard::GetDeformData(uint32 nr) const + MorphTargetStandard::DeformData* MorphTargetStandard::GetDeformData(size_t nr) const { - return mDeformDatas[nr]; + return m_deformDatas[nr]; } void MorphTargetStandard::AddDeformData(DeformData* data) { - mDeformDatas.emplace_back(data); + m_deformDatas.emplace_back(data); } void MorphTargetStandard::AddTransformation(const Transformation& transform) { - mTransforms.Add(transform); + m_transforms.emplace_back(transform); } - uint32 MorphTargetStandard::GetNumTransformations() const + // get the number of transformations in this morph target + size_t MorphTargetStandard::GetNumTransformations() const { - return mTransforms.GetLength(); + return m_transforms.size(); } - MorphTargetStandard::Transformation& MorphTargetStandard::GetTransformation(uint32 nr) + MorphTargetStandard::Transformation& MorphTargetStandard::GetTransformation(size_t nr) { - return mTransforms[nr]; + return m_transforms[nr]; } // clone this morph target - MorphTarget* MorphTargetStandard::Clone() + MorphTarget* MorphTargetStandard::Clone() const { // create the clone and copy its base class values MorphTargetStandard* clone = aznew MorphTargetStandard(""); // use an empty dummy name, as we will copy over the ID generated from it anyway @@ -317,13 +271,13 @@ namespace EMotionFX // now copy over the standard morph target related values // first start with the transforms - clone->mTransforms = mTransforms; + clone->m_transforms = m_transforms; // now clone the deform datas - clone->mDeformDatas.resize(mDeformDatas.size()); - for (size_t i = 0; i < mDeformDatas.size(); ++i) + clone->m_deformDatas.resize(m_deformDatas.size()); + for (uint32 i = 0; i < m_deformDatas.size(); ++i) { - clone->mDeformDatas[i] = mDeformDatas[i]->Clone(); + clone->m_deformDatas[i] = m_deformDatas[i]->Clone(); } // return the clone @@ -337,25 +291,25 @@ namespace EMotionFX //--------------------------------------------------- // constructor - MorphTargetStandard::DeformData::DeformData(uint32 nodeIndex, uint32 numVerts) + MorphTargetStandard::DeformData::DeformData(size_t nodeIndex, uint32 numVerts) { - mNodeIndex = nodeIndex; - mNumVerts = numVerts; - mDeltas = (VertexDelta*)MCore::Allocate(numVerts * sizeof(VertexDelta), EMFX_MEMCATEGORY_GEOMETRY_PMORPHTARGETS, MorphTargetStandard::MEMORYBLOCK_ID); - mMinValue = -10.0f; - mMaxValue = +10.0f; + m_nodeIndex = nodeIndex; + m_numVerts = numVerts; + m_deltas = (VertexDelta*)MCore::Allocate(numVerts * sizeof(VertexDelta), EMFX_MEMCATEGORY_GEOMETRY_PMORPHTARGETS, MorphTargetStandard::MEMORYBLOCK_ID); + m_minValue = -10.0f; + m_maxValue = +10.0f; } // destructor MorphTargetStandard::DeformData::~DeformData() { - MCore::Free(mDeltas); + MCore::Free(m_deltas); } // create - MorphTargetStandard::DeformData* MorphTargetStandard::DeformData::Create(uint32 nodeIndex, uint32 numVerts) + MorphTargetStandard::DeformData* MorphTargetStandard::DeformData::Create(size_t nodeIndex, uint32 numVerts) { return aznew MorphTargetStandard::DeformData(nodeIndex, numVerts); } @@ -364,62 +318,62 @@ namespace EMotionFX // clone a morph target MorphTargetStandard::DeformData* MorphTargetStandard::DeformData::Clone() { - MorphTargetStandard::DeformData* clone = aznew MorphTargetStandard::DeformData(mNodeIndex, mNumVerts); + MorphTargetStandard::DeformData* clone = aznew MorphTargetStandard::DeformData(m_nodeIndex, m_numVerts); // copy the data - clone->mMinValue = mMinValue; - clone->mMaxValue = mMaxValue; - MCore::MemCopy((uint8*)clone->mDeltas, (uint8*)mDeltas, mNumVerts * sizeof(VertexDelta)); + clone->m_minValue = m_minValue; + clone->m_maxValue = m_maxValue; + MCore::MemCopy((uint8*)clone->m_deltas, (uint8*)m_deltas, m_numVerts * sizeof(VertexDelta)); return clone; } void MorphTargetStandard::RemoveAllDeformDatas() { - for (DeformData* deformData : mDeformDatas) + for (DeformData* deformData : m_deformDatas) { deformData->Destroy(); } - mDeformDatas.clear(); + m_deformDatas.clear(); } void MorphTargetStandard::RemoveAllDeformDatasFor(Node* joint) { - mDeformDatas.erase( - AZStd::remove_if(mDeformDatas.begin(), mDeformDatas.end(), + m_deformDatas.erase( + AZStd::remove_if(m_deformDatas.begin(), m_deformDatas.end(), [=](const DeformData* deformData) { - return deformData->mNodeIndex == joint->GetNodeIndex(); + return deformData->m_nodeIndex == joint->GetNodeIndex(); }), - mDeformDatas.end()); + m_deformDatas.end()); } // pre-alloc memory for the deform datas - void MorphTargetStandard::ReserveDeformDatas(uint32 numDeformDatas) + void MorphTargetStandard::ReserveDeformDatas(size_t numDeformDatas) { - mDeformDatas.reserve(numDeformDatas); + m_deformDatas.reserve(numDeformDatas); } // pre-allocate memory for the transformations - void MorphTargetStandard::ReserveTransformations(uint32 numTransforms) + void MorphTargetStandard::ReserveTransformations(size_t numTransforms) { - mTransforms.Reserve(numTransforms); + m_transforms.reserve(numTransforms); } - void MorphTargetStandard::RemoveDeformData(uint32 index, bool delFromMem) + void MorphTargetStandard::RemoveDeformData(size_t index, bool delFromMem) { if (delFromMem) { - delete mDeformDatas[index]; + delete m_deformDatas[index]; } - mDeformDatas.erase(mDeformDatas.begin() + index); + m_deformDatas.erase(m_deformDatas.begin() + index); } - void MorphTargetStandard::RemoveTransformation(uint32 index) + void MorphTargetStandard::RemoveTransformation(size_t index) { - mTransforms.Remove(index); + m_transforms.erase(AZStd::next(begin(m_transforms), index)); } @@ -433,20 +387,18 @@ namespace EMotionFX } // scale the transformations - const uint32 numTransformations = mTransforms.GetLength(); - for (uint32 i = 0; i < numTransformations; ++i) + for (Transformation& transform : m_transforms) { - Transformation& transform = mTransforms[i]; - transform.mPosition *= scaleFactor; + transform.m_position *= scaleFactor; } // scale the deform datas (packed per vertex morph deltas) - for (DeformData* deformData : mDeformDatas) + for (DeformData* deformData : m_deformDatas) { - DeformData::VertexDelta* deltas = deformData->mDeltas; + DeformData::VertexDelta* deltas = deformData->m_deltas; - float newMinValue = deformData->mMinValue * scaleFactor; - float newMaxValue = deformData->mMaxValue * scaleFactor; + float newMinValue = deformData->m_minValue * scaleFactor; + float newMaxValue = deformData->m_maxValue * scaleFactor; // make sure the values won't be too small if (newMaxValue - newMinValue < 1.0f) @@ -464,21 +416,21 @@ namespace EMotionFX // iterate over the deltas (per vertex values) - const uint32 numVerts = deformData->mNumVerts; + const uint32 numVerts = deformData->m_numVerts; for (uint32 v = 0; v < numVerts; ++v) { // decompress - AZ::Vector3 decompressed = deltas[v].mPosition.ToVector3(deformData->mMinValue, deformData->mMaxValue); + AZ::Vector3 decompressed = deltas[v].m_position.ToVector3(deformData->m_minValue, deformData->m_maxValue); // scale decompressed *= scaleFactor; // compress again - deltas[v].mPosition.FromVector3(decompressed, newMinValue, newMaxValue); + deltas[v].m_position.FromVector3(decompressed, newMinValue, newMaxValue); } - deformData->mMinValue = newMinValue; - deformData->mMaxValue = newMaxValue; + deformData->m_minValue = newMinValue; + deformData->m_maxValue = newMaxValue; } } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h index 2d8a20ec11..c4187fd638 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MorphTargetStandard.h @@ -59,31 +59,31 @@ namespace EMotionFX */ struct EMFX_API VertexDelta { - MCore::Compressed16BitVector3 mPosition; /**< The position delta. */ - MCore::Compressed8BitVector3 mNormal; /**< The normal delta. */ - MCore::Compressed8BitVector3 mTangent; /**< The first tangent layer delta. */ - MCore::Compressed8BitVector3 mBitangent; /**< The first bitangent layer delta. */ - uint32 mVertexNr; /**< The vertex number inside the mesh to apply this to. */ + MCore::Compressed16BitVector3 m_position; /**< The position delta. */ + MCore::Compressed8BitVector3 m_normal; /**< The normal delta. */ + MCore::Compressed8BitVector3 m_tangent; /**< The first tangent layer delta. */ + MCore::Compressed8BitVector3 m_bitangent; /**< The first bitangent layer delta. */ + uint32 m_vertexNr; /**< The vertex number inside the mesh to apply this to. */ }; - static DeformData* Create(uint32 nodeIndex, uint32 numVerts); + static DeformData* Create(size_t nodeIndex, uint32 numVerts); // creates a clone DeformData* Clone(); public: - VertexDelta* mDeltas; /**< The delta values. */ - uint32 mNumVerts; /**< The number of vertices in the mDeltas and mVertexNumbers arrays. */ - uint32 mNodeIndex; /**< The node which this data works on. */ - float mMinValue; /**< The compression/decompression minimum value for the delta positions. */ - float mMaxValue; /**< The compression/decompression maximum value for the delta positions. */ + VertexDelta* m_deltas; /**< The delta values. */ + uint32 m_numVerts; /**< The number of vertices in the m_deltas and m_vertexNumbers arrays. */ + size_t m_nodeIndex; /**< The node which this data works on. */ + float m_minValue; /**< The compression/decompression minimum value for the delta positions. */ + float m_maxValue; /**< The compression/decompression maximum value for the delta positions. */ /** * The constructor. * @param nodeIndex The node number on which the deformations should work. * @param numVerts The number of vertices modified by this deform. */ - DeformData(uint32 nodeIndex, uint32 numVerts); + DeformData(size_t nodeIndex, uint32 numVerts); /** * The destructor. @@ -100,11 +100,11 @@ namespace EMotionFX */ struct EMFX_API MCORE_ALIGN_PRE(16) Transformation { - AZ::Quaternion mRotation; /**< The rotation as absolute value. So not a delta value, but a target (absolute) rotation. */ - AZ::Quaternion mScaleRotation; /**< The scale rotation, as absolute value. */ - AZ::Vector3 mPosition; /**< The position as a delta, so the difference between the original and target position. */ - AZ::Vector3 mScale; /**< The scale as a delta, so the difference between the original and target scale. */ - uint32 mNodeIndex; /**< The node number to apply this on. */ + AZ::Quaternion m_rotation; /**< The rotation as absolute value. So not a delta value, but a target (absolute) rotation. */ + AZ::Quaternion m_scaleRotation; /**< The scale rotation, as absolute value. */ + AZ::Vector3 m_position; /**< The position as a delta, so the difference between the original and target position. */ + AZ::Vector3 m_scale; /**< The scale as a delta, so the difference between the original and target scale. */ + size_t m_nodeIndex; /**< The node number to apply this on. */ } MCORE_ALIGN_POST(16); @@ -155,14 +155,14 @@ namespace EMotionFX * @param scale The input scale to which relative adjustments will be applied. * @param weight The absolute weight value. */ - void ApplyTransformation(ActorInstance* actorInstance, uint32 nodeIndex, AZ::Vector3& position, AZ::Quaternion& rotation, AZ::Vector3& scale, float weight) override; + void ApplyTransformation(ActorInstance* actorInstance, size_t nodeIndex, AZ::Vector3& position, AZ::Quaternion& rotation, AZ::Vector3& scale, float weight) override; /** * Checks if this morph target would influence the given node. * @param nodeIndex The node to perform the check with. * @result Returns true if the given node will be modified by this morph target, otherwise false is returned. */ - bool Influences(uint32 nodeIndex) const override; + bool Influences(size_t nodeIndex) const override; /** * Apply the relative deformations for this morph target to the given actor instance. @@ -175,14 +175,14 @@ namespace EMotionFX * Get the number of deform data objects. * @result The number of deform data objects. */ - uint32 GetNumDeformDatas() const; + size_t GetNumDeformDatas() const; /** * Get a given deform data object. * @param nr The deform data number, which must be in range of [0..GetNumDeformDatas()-1]. * @result A pointer to the deform data object. */ - DeformData* GetDeformData(uint32 nr) const; + DeformData* GetDeformData(size_t nr) const; /** * Add a given deform data to the array of deform data objects. @@ -200,20 +200,20 @@ namespace EMotionFX * Get the number of transformations which are part of this bones morph target. * @result The number of tranformations. */ - uint32 GetNumTransformations() const; + size_t GetNumTransformations() const; /** * Get a given transformation and it's corresponding node id to which the transformation belongs to. * @param nr The transformation number, must be in range of [0..GetNumTransformations()-1]. * @result A reference to the transformation. */ - Transformation& GetTransformation(uint32 nr); + Transformation& GetTransformation(size_t nr); /** * Creates an exact clone of this morph target. * @result Returns a pointer to an exact clone of this morph target. */ - MorphTarget* Clone() override; + MorphTarget* Clone() const override; /** * Remove all deform data objects from memory as well as from the class. @@ -230,27 +230,27 @@ namespace EMotionFX * @param index The deform data to remove. The index must be in range of [0, GetNumDeformDatas()]. * @param delFromMem Set to true (default) when you wish to also delete the specified deform data from memory. */ - void RemoveDeformData(uint32 index, bool delFromMem = true); + void RemoveDeformData(size_t index, bool delFromMem = true); /** * Remove the given transformation. * @param index The transformation to remove. The index must be in range of [0, GetNumTransformations()]. */ - void RemoveTransformation(uint32 index); + void RemoveTransformation(size_t index); /** * Reserve (pre-allocate) space in the array of deform datas. * This does NOT change the value returned by GetNumDeformDatas(). * @param numDeformDatas The absolute number of deform datas to pre-allocate space for. */ - void ReserveDeformDatas(uint32 numDeformDatas); + void ReserveDeformDatas(size_t numDeformDatas); /** * Reserve (pre-allocate) space in the array of transformations. * This does NOT change the value returned by GetNumTransformations(). * @param numTransforms The absolute number of transformations to pre-allocate space for. */ - void ReserveTransformations(uint32 numTransforms); + void ReserveTransformations(size_t numTransforms); /** * Scale all transform and positional data. @@ -260,8 +260,8 @@ namespace EMotionFX void Scale(float scaleFactor) override; private: - MCore::Array mTransforms; /**< The relative transformations for the given nodes, in local space. The rotation however is absolute. */ - AZStd::vector mDeformDatas; /**< The deformation data objects. */ + AZStd::vector m_transforms; /**< The relative transformations for the given nodes, in local space. The rotation however is absolute. */ + AZStd::vector m_deformDatas; /**< The deformation data objects. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp index c10740acb5..9ad55b1c40 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Motion.cpp @@ -30,11 +30,11 @@ namespace EMotionFX Motion::Motion(const char* name) : BaseObject() { - mID = MCore::GetIDGenerator().GenerateID(); + m_id = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); m_eventTable = AZStd::make_unique(); - mUnitType = GetEMotionFX().GetUnitType(); - mFileUnitType = mUnitType; - mExtractionFlags = static_cast(0); + m_unitType = GetEMotionFX().GetUnitType(); + m_fileUnitType = m_unitType; + m_extractionFlags = static_cast(0); if (name) { @@ -42,7 +42,7 @@ namespace EMotionFX } #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = false; + m_isOwnedByRuntime = false; #endif // EMFX_DEVELOPMENT_BUILD // automatically register the motion @@ -55,7 +55,7 @@ namespace EMotionFX GetEventManager().OnDeleteMotion(this); // automatically unregister the motion - if (mAutoUnregister) + if (m_autoUnregister) { GetMotionManager().RemoveMotion(this, false); } @@ -68,42 +68,42 @@ namespace EMotionFX void Motion::SetName(const char* name) { // calculate the ID - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } // set the filename of the motion void Motion::SetFileName(const char* filename) { - mFileName = filename; + m_fileName = filename; } // adjust the dirty flag void Motion::SetDirtyFlag(bool dirty) { - mDirtyFlag = dirty; + m_dirtyFlag = dirty; } // adjust the auto unregistering from the motion manager on delete void Motion::SetAutoUnregister(bool enabled) { - mAutoUnregister = enabled; + m_autoUnregister = enabled; } // do we auto unregister from the motion manager on delete? bool Motion::GetAutoUnregister() const { - return mAutoUnregister; + return m_autoUnregister; } void Motion::SetIsOwnedByRuntime(bool isOwnedByRuntime) { #if defined(EMFX_DEVELOPMENT_BUILD) - mIsOwnedByRuntime = isOwnedByRuntime; + m_isOwnedByRuntime = isOwnedByRuntime; #else AZ_UNUSED(isOwnedByRuntime); #endif @@ -113,7 +113,7 @@ namespace EMotionFX bool Motion::GetIsOwnedByRuntime() const { #if defined(EMFX_DEVELOPMENT_BUILD) - return mIsOwnedByRuntime; + return m_isOwnedByRuntime; #else return true; #endif @@ -122,25 +122,25 @@ namespace EMotionFX const char* Motion::GetName() const { - return MCore::GetStringIdPool().GetName(mNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } const AZStd::string& Motion::GetNameString() const { - return MCore::GetStringIdPool().GetName(mNameID); + return MCore::GetStringIdPool().GetName(m_nameId); } void Motion::SetMotionFPS(float motionFPS) { - mMotionFPS = motionFPS; + m_motionFps = motionFPS; } float Motion::GetMotionFPS() const { - return mMotionFPS; + return m_motionFps; } @@ -163,31 +163,31 @@ namespace EMotionFX bool Motion::GetDirtyFlag() const { - return mDirtyFlag; + return m_dirtyFlag; } void Motion::SetMotionExtractionFlags(EMotionExtractionFlags flags) { - mExtractionFlags = flags; + m_extractionFlags = flags; } EMotionExtractionFlags Motion::GetMotionExtractionFlags() const { - return mExtractionFlags; + return m_extractionFlags; } void Motion::SetCustomData(void* dataPointer) { - mCustomData = dataPointer; + m_customData = dataPointer; } void* Motion::GetCustomData() const { - return mCustomData; + return m_customData; } @@ -203,48 +203,48 @@ namespace EMotionFX void Motion::SetID(uint32 id) { - mID = id; + m_id = id; } const char* Motion::GetFileName() const { - return mFileName.c_str(); + return m_fileName.c_str(); } const AZStd::string& Motion::GetFileNameString() const { - return mFileName; + return m_fileName; } uint32 Motion::GetID() const { - return mID; + return m_id; } void Motion::SetUnitType(MCore::Distance::EUnitType unitType) { - mUnitType = unitType; + m_unitType = unitType; } MCore::Distance::EUnitType Motion::GetUnitType() const { - return mUnitType; + return m_unitType; } void Motion::SetFileUnitType(MCore::Distance::EUnitType unitType) { - mFileUnitType = unitType; + m_fileUnitType = unitType; } MCore::Distance::EUnitType Motion::GetFileUnitType() const { - return mFileUnitType; + return m_fileUnitType; } void Motion::Scale(float scaleFactor) @@ -257,17 +257,17 @@ namespace EMotionFX // scale everything to the given unit type void Motion::ScaleToUnitType(MCore::Distance::EUnitType targetUnitType) { - if (mUnitType == targetUnitType) + if (m_unitType == targetUnitType) { return; } // calculate the scale factor and scale - const float scaleFactor = static_cast(MCore::Distance::GetConversionFactor(mUnitType, targetUnitType)); + const float scaleFactor = static_cast(MCore::Distance::GetConversionFactor(m_unitType, targetUnitType)); Scale(scaleFactor); // update the unit type - mUnitType = targetUnitType; + m_unitType = targetUnitType; } void Motion::UpdateDuration() diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Motion.h b/Gems/EMotionFX/Code/EMotionFX/Source/Motion.h index eae1037ab3..e6ec99835b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Motion.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Motion.h @@ -251,21 +251,21 @@ namespace EMotionFX protected: MotionData* m_motionData = nullptr; /**< The motion data, which can in theory be any data representation/compression. */ - AZStd::string mFileName; /**< The filename of the motion. */ + AZStd::string m_fileName; /**< The filename of the motion. */ PlayBackInfo m_defaultPlayBackInfo; /**< The default/fallback motion playback info which will be used when no playback info is passed to the Play() function. */ AZStd::unique_ptr m_eventTable; /**< The event table, which contains all events, and will make sure events get executed. */ - MCore::Distance::EUnitType mUnitType; /**< The type of units used. */ - MCore::Distance::EUnitType mFileUnitType; /**< The type of units used, inside the file that got loaded. */ - void* mCustomData = nullptr; /**< A pointer to custom user data that is linked with this motion object. */ - float mMotionFPS = 30.0f; /**< The number of keyframes per second. */ - uint32 mNameID = MCORE_INVALIDINDEX32; /**< The ID represention the name or description of this motion. */ - uint32 mID = MCORE_INVALIDINDEX32; /**< The unique identification number for the motion. */ - EMotionExtractionFlags mExtractionFlags; /**< The motion extraction flags, which define behavior of the motion extraction system when applied to this motion. */ - bool mDirtyFlag = false; /**< The dirty flag which indicates whether the user has made changes to the motion since the last file save operation. */ - bool mAutoUnregister = true; /**< Automatically unregister the motion from the motion manager when this motion gets deleted? Default is true. */ + MCore::Distance::EUnitType m_unitType; /**< The type of units used. */ + MCore::Distance::EUnitType m_fileUnitType; /**< The type of units used, inside the file that got loaded. */ + void* m_customData = nullptr; /**< A pointer to custom user data that is linked with this motion object. */ + float m_motionFps = 30.0f; /**< The number of keyframes per second. */ + uint32 m_nameId = MCORE_INVALIDINDEX32; /**< The ID represention the name or description of this motion. */ + uint32 m_id = MCORE_INVALIDINDEX32; /**< The unique identification number for the motion. */ + EMotionExtractionFlags m_extractionFlags; /**< The motion extraction flags, which define behavior of the motion extraction system when applied to this motion. */ + bool m_dirtyFlag = false; /**< The dirty flag which indicates whether the user has made changes to the motion since the last file save operation. */ + bool m_autoUnregister = true; /**< Automatically unregister the motion from the motion manager when this motion gets deleted? Default is true. */ #if defined(EMFX_DEVELOPMENT_BUILD) - bool mIsOwnedByRuntime; + bool m_isOwnedByRuntime; #endif // EMFX_DEVELOPMENT_BUILD }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp index 5f394fb791..e3391ed44f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.cpp @@ -76,13 +76,13 @@ namespace EMotionFX { auto data = AZStd::make_unique(); const Skeleton* skeleton = actor->GetSkeleton(); - const AZ::u32 numJoints = skeleton->GetNumNodes(); - AZStd::vector& jointLinks = data->GetJointDataLinks(); + const size_t numJoints = skeleton->GetNumNodes(); + AZStd::vector& jointLinks = data->GetJointDataLinks(); jointLinks.resize(numJoints); - for (AZ::u32 i = 0; i < numJoints; ++i) + for (size_t i = 0; i < numJoints; ++i) { const AZ::Outcome findResult = FindJointIndexByNameId(skeleton->GetNode(i)->GetID()); - jointLinks[i] = findResult.IsSuccess() ? static_cast(findResult.GetValue()) : InvalidIndex32; + jointLinks[i] = findResult.IsSuccess() ? findResult.GetValue() : InvalidIndex; } return AZStd::move(data); } @@ -186,7 +186,7 @@ namespace EMotionFX return FindFloatIndexByNameId(MCore::GetStringIdPool().GenerateIdForString(name)); } - AZ::Outcome MotionData::FindJointIndexByNameId(AZ::u32 id) const + AZ::Outcome MotionData::FindJointIndexByNameId(size_t id) const { return FindIndexIf(m_staticJointData, [id](const StaticJointData& item) { return item.m_nameId == id; }); } @@ -218,18 +218,18 @@ namespace EMotionFX AZ::Vector3 MotionData::GetJointStaticPosition(size_t jointDataIndex) const { - return m_staticJointData[jointDataIndex].m_staticTransform.mPosition; + return m_staticJointData[jointDataIndex].m_staticTransform.m_position; } AZ::Quaternion MotionData::GetJointStaticRotation(size_t jointDataIndex) const { - return m_staticJointData[jointDataIndex].m_staticTransform.mRotation; + return m_staticJointData[jointDataIndex].m_staticTransform.m_rotation; } #ifndef EMFX_SCALE_DISABLED AZ::Vector3 MotionData::GetJointStaticScale(size_t jointDataIndex) const { - return m_staticJointData[jointDataIndex].m_staticTransform.mScale; + return m_staticJointData[jointDataIndex].m_staticTransform.m_scale; } #endif @@ -240,18 +240,18 @@ namespace EMotionFX AZ::Vector3 MotionData::GetJointBindPosePosition(size_t jointDataIndex) const { - return m_staticJointData[jointDataIndex].m_bindTransform.mPosition; + return m_staticJointData[jointDataIndex].m_bindTransform.m_position; } AZ::Quaternion MotionData::GetJointBindPoseRotation(size_t jointDataIndex) const { - return m_staticJointData[jointDataIndex].m_bindTransform.mRotation; + return m_staticJointData[jointDataIndex].m_bindTransform.m_rotation; } #ifndef EMFX_SCALE_DISABLED AZ::Vector3 MotionData::GetJointBindPoseScale(size_t jointDataIndex) const { - return m_staticJointData[jointDataIndex].m_bindTransform.mScale; + return m_staticJointData[jointDataIndex].m_bindTransform.m_scale; } #endif @@ -322,18 +322,18 @@ namespace EMotionFX void MotionData::SetJointStaticPosition(size_t jointDataIndex, const AZ::Vector3& position) { - m_staticJointData[jointDataIndex].m_staticTransform.mPosition = position; + m_staticJointData[jointDataIndex].m_staticTransform.m_position = position; } void MotionData::SetJointStaticRotation(size_t jointDataIndex, const AZ::Quaternion& rotation) { - m_staticJointData[jointDataIndex].m_staticTransform.mRotation = rotation; + m_staticJointData[jointDataIndex].m_staticTransform.m_rotation = rotation; } #ifndef EMFX_SCALE_DISABLED void MotionData::SetJointStaticScale(size_t jointDataIndex, const AZ::Vector3& scale) { - m_staticJointData[jointDataIndex].m_staticTransform.mScale = scale; + m_staticJointData[jointDataIndex].m_staticTransform.m_scale = scale; } #endif @@ -344,18 +344,18 @@ namespace EMotionFX void MotionData::SetJointBindPosePosition(size_t jointDataIndex, const AZ::Vector3& position) { - m_staticJointData[jointDataIndex].m_bindTransform.mPosition = position; + m_staticJointData[jointDataIndex].m_bindTransform.m_position = position; } void MotionData::SetJointBindPoseRotation(size_t jointDataIndex, const AZ::Quaternion& rotation) { - m_staticJointData[jointDataIndex].m_bindTransform.mRotation = rotation; + m_staticJointData[jointDataIndex].m_bindTransform.m_rotation = rotation; } #ifndef EMFX_SCALE_DISABLED void MotionData::SetJointBindPoseScale(size_t jointDataIndex, const AZ::Vector3& scale) { - m_staticJointData[jointDataIndex].m_bindTransform.mScale = scale; + m_staticJointData[jointDataIndex].m_bindTransform.m_scale = scale; } #endif @@ -453,12 +453,12 @@ namespace EMotionFX m_sampleRate = 30.0f; } - void MotionData::BasicRetarget(const ActorInstance* actorInstance, const MotionLinkData* motionLinkData, AZ::u32 jointIndex, Transform& inOutTransform) const + void MotionData::BasicRetarget(const ActorInstance* actorInstance, const MotionLinkData* motionLinkData, size_t jointIndex, Transform& inOutTransform) const { AZ_Assert(motionLinkData, "Expecting valid motionLinkData pointer."); const Pose* bindPose = actorInstance->GetTransformData()->GetBindPose(); - const AZStd::vector& jointLinks = motionLinkData->GetJointDataLinks(); + const AZStd::vector& jointLinks = motionLinkData->GetJointDataLinks(); // Special case handling on translation of root nodes. // Scale the translation amount based on the height difference between the bind pose height of the @@ -466,39 +466,39 @@ namespace EMotionFX // All other nodes get their translation data displaced based on the position difference between the // parent relative space positions in the actor instance's bind pose and the motion bind pose. const Actor* actor = actorInstance->GetActor(); - const AZ::u32 retargetRootIndex = actor->GetRetargetRootNodeIndex(); + const size_t retargetRootIndex = actor->GetRetargetRootNodeIndex(); const Node* joint = actor->GetSkeleton()->GetNode(jointIndex); bool needsDisplacement = true; - if ((retargetRootIndex == jointIndex || joint->GetIsRootNode()) && retargetRootIndex != InvalidIndex32) + if ((retargetRootIndex == jointIndex || joint->GetIsRootNode()) && retargetRootIndex != InvalidIndex) { - const AZ::u32 retargetRootDataIndex = jointLinks[actor->GetRetargetRootNodeIndex()]; - if (retargetRootDataIndex != InvalidIndex32) + const size_t retargetRootDataIndex = jointLinks[actor->GetRetargetRootNodeIndex()]; + if (retargetRootDataIndex != InvalidIndex) { - const float subMotionHeight = m_staticJointData[retargetRootDataIndex].m_bindTransform.mPosition.GetZ(); + const float subMotionHeight = m_staticJointData[retargetRootDataIndex].m_bindTransform.m_position.GetZ(); if (AZ::GetAbs(subMotionHeight) >= AZ::Constants::FloatEpsilon) { - const float heightFactor = bindPose->GetLocalSpaceTransform(retargetRootIndex).mPosition.GetZ() / subMotionHeight; - inOutTransform.mPosition *= heightFactor; + const float heightFactor = bindPose->GetLocalSpaceTransform(retargetRootIndex).m_position.GetZ() / subMotionHeight; + inOutTransform.m_position *= heightFactor; needsDisplacement = false; } } } - const AZ::u16 jointDataIndex = jointLinks[jointIndex]; - if (jointDataIndex != InvalidIndex16) + const size_t jointDataIndex = jointLinks[jointIndex]; + if (jointDataIndex != InvalidIndex) { const Transform& bindPoseTransform = bindPose->GetLocalSpaceTransform(jointIndex); const Transform& motionBindPose = m_staticJointData[jointDataIndex].m_bindTransform; if (needsDisplacement) { - const AZ::Vector3 displacement = bindPoseTransform.mPosition - motionBindPose.mPosition; - inOutTransform.mPosition += displacement; + const AZ::Vector3 displacement = bindPoseTransform.m_position - motionBindPose.m_position; + inOutTransform.m_position += displacement; } EMFX_SCALECODE ( - const AZ::Vector3 scaleOffset = bindPoseTransform.mScale - motionBindPose.mScale; - inOutTransform.mScale += scaleOffset; + const AZ::Vector3 scaleOffset = bindPoseTransform.m_scale - motionBindPose.m_scale; + inOutTransform.m_scale += scaleOffset; ) } } @@ -566,8 +566,8 @@ namespace EMotionFX // Scale the static data for (StaticJointData& jointData : m_staticJointData) { - jointData.m_staticTransform.mPosition *= scaleFactor; - jointData.m_bindTransform.mPosition *= scaleFactor; + jointData.m_staticTransform.m_position *= scaleFactor; + jointData.m_bindTransform.m_position *= scaleFactor; } // Scale all data stored by the inherited class. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.h index 54c618bb86..fe831f1df0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/MotionData.h @@ -48,13 +48,13 @@ namespace EMotionFX MotionLinkData& operator=(MotionLinkData&&) = default; virtual ~MotionLinkData() = default; - AZStd::vector& GetJointDataLinks() { return m_jointDataLinks; } - const AZStd::vector& GetJointDataLinks() const { return m_jointDataLinks; } - bool IsJointActive(size_t jointIndex) const { return (m_jointDataLinks[jointIndex] != InvalidIndex32); } - AZ::u32 GetJointDataLink(size_t jointIndex) const { return m_jointDataLinks[jointIndex]; } + AZStd::vector& GetJointDataLinks() { return m_jointDataLinks; } + const AZStd::vector& GetJointDataLinks() const { return m_jointDataLinks; } + bool IsJointActive(size_t jointIndex) const { return (m_jointDataLinks[jointIndex] != InvalidIndex); } + size_t GetJointDataLink(size_t jointIndex) const { return m_jointDataLinks[jointIndex]; } protected: - AZStd::vector m_jointDataLinks; + AZStd::vector m_jointDataLinks; }; class EMFX_API MotionLinkCache @@ -162,7 +162,7 @@ namespace EMotionFX virtual const char* GetSceneSettingsName() const = 0; // Sampling - virtual Transform SampleJointTransform(const SampleSettings& settings, AZ::u32 jointSkeletonIndex) const = 0; + virtual Transform SampleJointTransform(const SampleSettings& settings, size_t jointSkeletonIndex) const = 0; virtual void SamplePose(const SampleSettings& settings, Pose* outputPose) const = 0; virtual float SampleMorph(float sampleTime, size_t morphDataIndex) const = 0; virtual float SampleFloat(float sampleTime, size_t morphDataIndex) const = 0; @@ -211,7 +211,7 @@ namespace EMotionFX void SetDuration(float duration); virtual void SetSampleRate(float sampleRate); - AZ::Outcome FindJointIndexByNameId(AZ::u32 nameId) const; + AZ::Outcome FindJointIndexByNameId(size_t nameId) const; AZ::Outcome FindMorphIndexByNameId(AZ::u32 nameId) const; AZ::Outcome FindFloatIndexByNameId(AZ::u32 nameId) const; @@ -265,7 +265,7 @@ namespace EMotionFX static void CalculateInterpolationIndicesNonUniform(const AZStd::vector& timeValues, float sampleTime, size_t& indexA, size_t& indexB, float& t); static void CalculateInterpolationIndicesUniform(float sampleTime, float sampleSpacing, float duration, size_t numSamples, size_t& indexA, size_t& indexB, float& t); - void BasicRetarget(const ActorInstance* actorInstance, const MotionLinkData* motionLinkData, AZ::u32 jointIndex, Transform& inOutTransform) const; + void BasicRetarget(const ActorInstance* actorInstance, const MotionLinkData* motionLinkData, size_t jointIndex, Transform& inOutTransform) const; bool IsAdditive() const; void SetAdditive(bool isAdditive); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp index a2f224a752..6ced6152e1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.cpp @@ -74,14 +74,14 @@ namespace EMotionFX return values[indexA].ToQuaternion().NLerp(values[indexB].ToQuaternion(), t); } - Transform NonUniformMotionData::SampleJointTransform(const SampleSettings& settings, AZ::u32 jointSkeletonIndex) const + Transform NonUniformMotionData::SampleJointTransform(const SampleSettings& settings, size_t jointSkeletonIndex) const { const Actor* actor = settings.m_actorInstance->GetActor(); const MotionLinkData* motionLinkData = FindMotionLinkData(actor); const Skeleton* skeleton = actor->GetSkeleton(); - const AZ::u32 jointDataIndex = motionLinkData->GetJointDataLinks()[jointSkeletonIndex]; - if (m_additive && jointDataIndex == InvalidIndex32) + const size_t jointDataIndex = motionLinkData->GetJointDataLinks()[jointSkeletonIndex]; + if (m_additive && jointDataIndex == InvalidIndex) { return Transform::CreateIdentity(); } @@ -89,13 +89,13 @@ namespace EMotionFX // Sample the interpolated data. Transform result; const bool inPlace = (settings.m_inPlace && skeleton->GetNode(jointSkeletonIndex)->GetIsRootNode()); - if (jointDataIndex != InvalidIndex32 && !inPlace) + if (jointDataIndex != InvalidIndex && !inPlace) { const JointData& jointData = m_jointData[jointDataIndex]; - result.mPosition = (!jointData.m_positionTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_positionTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mPosition; - result.mRotation = (!jointData.m_rotationTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_rotationTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mRotation; + result.m_position = (!jointData.m_positionTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_positionTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_position; + result.m_rotation = (!jointData.m_rotationTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_rotationTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_rotation; #ifndef EMFX_SCALE_DISABLED - result.mScale = (!jointData.m_scaleTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_scaleTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mScale; + result.m_scale = (!jointData.m_scaleTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_scaleTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_scale; #endif } else @@ -123,9 +123,9 @@ namespace EMotionFX const Actor::NodeMirrorInfo& mirrorInfo = actor->GetNodeMirrorInfo(jointSkeletonIndex); Transform mirrored = bindPose->GetLocalSpaceTransform(jointSkeletonIndex); AZ::Vector3 mirrorAxis = AZ::Vector3::CreateZero(); - mirrorAxis.SetElement(mirrorInfo.mAxis, 1.0f); - const AZ::u16 motionSource = actor->GetNodeMirrorInfo(jointSkeletonIndex).mSourceNode; - mirrored.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(motionSource), result, mirrorAxis, mirrorInfo.mFlags); + mirrorAxis.SetElement(mirrorInfo.m_axis, 1.0f); + const AZ::u16 motionSource = actor->GetNodeMirrorInfo(jointSkeletonIndex).m_sourceNode; + mirrored.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(motionSource), result, mirrorAxis, mirrorInfo.m_flags); result = mirrored; } @@ -141,27 +141,27 @@ namespace EMotionFX const ActorInstance* actorInstance = settings.m_actorInstance; const Skeleton* skeleton = actor->GetSkeleton(); const Pose* bindPose = actorInstance->GetTransformData()->GetBindPose(); - const AZ::u32 numNodes = actorInstance->GetNumEnabledNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const AZ::u32 jointIndex = actorInstance->GetEnabledNode(i); - const AZ::u32 jointDataIndex = motionLinkData->GetJointDataLinks()[jointIndex]; + const uint16 jointIndex = actorInstance->GetEnabledNode(i); + const size_t jointDataIndex = motionLinkData->GetJointDataLinks()[jointIndex]; const bool inPlace = (settings.m_inPlace && skeleton->GetNode(jointIndex)->GetIsRootNode()); // Sample the interpolated data. Transform result; - if (jointDataIndex != InvalidIndex32 && !inPlace) + if (jointDataIndex != InvalidIndex && !inPlace) { const JointData& jointData = m_jointData[jointDataIndex]; - result.mPosition = (!jointData.m_positionTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_positionTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mPosition; - result.mRotation = (!jointData.m_rotationTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_rotationTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mRotation; + result.m_position = (!jointData.m_positionTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_positionTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_position; + result.m_rotation = (!jointData.m_rotationTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_rotationTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_rotation; #ifndef EMFX_SCALE_DISABLED - result.mScale = (!jointData.m_scaleTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_scaleTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mScale; + result.m_scale = (!jointData.m_scaleTrack.m_times.empty()) ? CalculateInterpolatedValue(jointData.m_scaleTrack, settings.m_sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_scale; #endif } else { - if (m_additive && jointDataIndex == InvalidIndex32) + if (m_additive && jointDataIndex == InvalidIndex) { result = Transform::CreateIdentity(); } @@ -195,8 +195,8 @@ namespace EMotionFX // Output morph target weights. const MorphSetupInstance* morphSetup = actorInstance->GetMorphSetupInstance(); - const AZ::u32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (AZ::u32 i = 0; i < numMorphTargets; ++i) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t i = 0; i < numMorphTargets; ++i) { const AZ::u32 morphTargetId = morphSetup->GetMorphTarget(i)->GetID(); const AZ::Outcome morphIndex = FindMorphIndexByNameId(morphTargetId); @@ -1018,11 +1018,11 @@ namespace EMotionFX maxScaleError = 0.00001f; } - ReduceTrackSamples(jointData.m_positionTrack, m_staticJointData[i].m_staticTransform.mPosition, maxPosError); - ReduceTrackSamples(jointData.m_rotationTrack, m_staticJointData[i].m_staticTransform.mRotation, maxRotError); + ReduceTrackSamples(jointData.m_positionTrack, m_staticJointData[i].m_staticTransform.m_position, maxPosError); + ReduceTrackSamples(jointData.m_rotationTrack, m_staticJointData[i].m_staticTransform.m_rotation, maxRotError); EMFX_SCALECODE ( - ReduceTrackSamples(jointData.m_scaleTrack, m_staticJointData[i].m_staticTransform.mScale, maxScaleError); + ReduceTrackSamples(jointData.m_scaleTrack, m_staticJointData[i].m_staticTransform.m_scale, maxScaleError); ) } @@ -1143,11 +1143,11 @@ namespace EMotionFX { const float keyTime = s * sampleSpacing; const Transform transform = motionData->SampleJointTransform(keyTime, i); - SetJointPositionSample(i, s, {keyTime, transform.mPosition}); - SetJointRotationSample(i, s, {keyTime, transform.mRotation}); + SetJointPositionSample(i, s, {keyTime, transform.m_position}); + SetJointRotationSample(i, s, {keyTime, transform.m_rotation}); EMFX_SCALECODE ( - SetJointScaleSample(i, s, {keyTime, transform.mScale}); + SetJointScaleSample(i, s, {keyTime, transform.m_scale}); ) } } @@ -1191,18 +1191,18 @@ namespace EMotionFX AZ::Vector3 NonUniformMotionData::SampleJointPosition(float sampleTime, size_t jointDataIndex) const { - return !m_jointData[jointDataIndex].m_positionTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_positionTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mPosition; + return !m_jointData[jointDataIndex].m_positionTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_positionTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_position; } AZ::Quaternion NonUniformMotionData::SampleJointRotation(float sampleTime, size_t jointDataIndex) const { - return !m_jointData[jointDataIndex].m_rotationTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_rotationTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mRotation; + return !m_jointData[jointDataIndex].m_rotationTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_rotationTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_rotation; } #ifndef EMFX_SCALE_DISABLED AZ::Vector3 NonUniformMotionData::SampleJointScale(float sampleTime, size_t jointDataIndex) const { - return !m_jointData[jointDataIndex].m_scaleTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_scaleTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mScale; + return !m_jointData[jointDataIndex].m_scaleTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_scaleTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_scale; } #endif @@ -1210,10 +1210,10 @@ namespace EMotionFX { return Transform ( - !m_jointData[jointDataIndex].m_positionTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_positionTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mPosition, - !m_jointData[jointDataIndex].m_rotationTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_rotationTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mRotation + !m_jointData[jointDataIndex].m_positionTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_positionTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_position, + !m_jointData[jointDataIndex].m_rotationTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_rotationTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_rotation #ifndef EMFX_SCALE_DISABLED - ,!m_jointData[jointDataIndex].m_scaleTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_scaleTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.mScale + ,!m_jointData[jointDataIndex].m_scaleTrack.m_times.empty() ? CalculateInterpolatedValue(m_jointData[jointDataIndex].m_scaleTrack, sampleTime) : m_staticJointData[jointDataIndex].m_staticTransform.m_scale #endif ); } @@ -1225,11 +1225,11 @@ namespace EMotionFX for (size_t i = 0; i < m_jointData.size(); ++i) { JointData& jointData = tempJointData[i]; - ReduceTrackSamples(jointData.m_positionTrack, m_staticJointData[i].m_staticTransform.mPosition, 0.0001f); - ReduceTrackSamples(jointData.m_rotationTrack, m_staticJointData[i].m_staticTransform.mRotation, 0.0001f); + ReduceTrackSamples(jointData.m_positionTrack, m_staticJointData[i].m_staticTransform.m_position, 0.0001f); + ReduceTrackSamples(jointData.m_rotationTrack, m_staticJointData[i].m_staticTransform.m_rotation, 0.0001f); EMFX_SCALECODE ( - ReduceTrackSamples(jointData.m_scaleTrack, m_staticJointData[i].m_staticTransform.mScale, 0.0001f); + ReduceTrackSamples(jointData.m_scaleTrack, m_staticJointData[i].m_staticTransform.m_scale, 0.0001f); if (jointData.m_scaleTrack.m_times.empty()) { ClearJointScaleSamples(i); @@ -1376,15 +1376,15 @@ namespace EMotionFX if (saveSettings.m_logDetails) { - const AZ::Quaternion uncompressedPoseRot = MCore::Compressed16BitQuaternion(jointInfo.m_staticRot.mX, jointInfo.m_staticRot.mY, jointInfo.m_staticRot.mZ, jointInfo.m_staticRot.mW).ToQuaternion().GetNormalized(); - const AZ::Quaternion uncompressedBindPoseRot = MCore::Compressed16BitQuaternion(jointInfo.m_bindPoseRot.mX, jointInfo.m_bindPoseRot.mY, jointInfo.m_bindPoseRot.mZ, jointInfo.m_bindPoseRot.mW).ToQuaternion().GetNormalized(); + const AZ::Quaternion uncompressedPoseRot = MCore::Compressed16BitQuaternion(jointInfo.m_staticRot.m_x, jointInfo.m_staticRot.m_y, jointInfo.m_staticRot.m_z, jointInfo.m_staticRot.m_w).ToQuaternion().GetNormalized(); + const AZ::Quaternion uncompressedBindPoseRot = MCore::Compressed16BitQuaternion(jointInfo.m_bindPoseRot.m_x, jointInfo.m_bindPoseRot.m_y, jointInfo.m_bindPoseRot.m_z, jointInfo.m_bindPoseRot.m_w).ToQuaternion().GetNormalized(); MCore::LogDetailedInfo("- Motion Joint: %s", motionData->GetJointName(jointDataIndex).c_str()); - MCore::LogDetailedInfo(" + Pose Translation: x=%f y=%f z=%f", jointInfo.m_staticPos.mX, jointInfo.m_staticPos.mY, jointInfo.m_staticPos.mZ); + MCore::LogDetailedInfo(" + Pose Translation: x=%f y=%f z=%f", jointInfo.m_staticPos.m_x, jointInfo.m_staticPos.m_y, jointInfo.m_staticPos.m_z); MCore::LogDetailedInfo(" + Pose Rotation: x=%f y=%f z=%f w=%f", static_cast(uncompressedPoseRot.GetX()), static_cast(uncompressedPoseRot.GetY()), static_cast(uncompressedPoseRot.GetZ()), static_cast(uncompressedPoseRot.GetW())); - MCore::LogDetailedInfo(" + Pose Scale: x=%f y=%f z=%f", jointInfo.m_staticScale.mX, jointInfo.m_staticScale.mY, jointInfo.m_staticScale.mZ); - MCore::LogDetailedInfo(" + Bind Pose Translation: x=%f y=%f z=%f", jointInfo.m_bindPosePos.mX, jointInfo.m_bindPosePos.mY, jointInfo.m_bindPosePos.mZ); + MCore::LogDetailedInfo(" + Pose Scale: x=%f y=%f z=%f", jointInfo.m_staticScale.m_x, jointInfo.m_staticScale.m_y, jointInfo.m_staticScale.m_z); + MCore::LogDetailedInfo(" + Bind Pose Translation: x=%f y=%f z=%f", jointInfo.m_bindPosePos.m_x, jointInfo.m_bindPosePos.m_y, jointInfo.m_bindPosePos.m_z); MCore::LogDetailedInfo(" + Bind Pose Rotation: x=%f y=%f z=%f w=%f", static_cast(uncompressedBindPoseRot.GetX()), static_cast(uncompressedBindPoseRot.GetY()), static_cast(uncompressedBindPoseRot.GetZ()), static_cast(uncompressedBindPoseRot.GetW())); - MCore::LogDetailedInfo(" + Bind Pose Scale: x=%f y=%f z=%f", jointInfo.m_bindPoseScale.mX, jointInfo.m_bindPoseScale.mY, jointInfo.m_bindPoseScale.mZ); + MCore::LogDetailedInfo(" + Bind Pose Scale: x=%f y=%f z=%f", jointInfo.m_bindPoseScale.m_x, jointInfo.m_bindPoseScale.m_y, jointInfo.m_bindPoseScale.m_z); MCore::LogDetailedInfo(" + Num Position Keys: %d", jointInfo.m_numPosKeys); MCore::LogDetailedInfo(" + Num Rotation Keys: %d", jointInfo.m_numRotKeys); MCore::LogDetailedInfo(" + Num Scale Keys: %d", jointInfo.m_numScaleKeys); @@ -1697,12 +1697,12 @@ namespace EMotionFX return false; } - AZ::Vector3 staticPos(jointInfo.m_staticPos.mX, jointInfo.m_staticPos.mY, jointInfo.m_staticPos.mZ); - AZ::Vector3 staticScale(jointInfo.m_staticScale.mX, jointInfo.m_staticScale.mY, jointInfo.m_staticScale.mZ); - MCore::Compressed16BitQuaternion staticRot(jointInfo.m_staticRot.mX, jointInfo.m_staticRot.mY, jointInfo.m_staticRot.mZ, jointInfo.m_staticRot.mW); - AZ::Vector3 bindPosePos(jointInfo.m_bindPosePos.mX, jointInfo.m_bindPosePos.mY, jointInfo.m_bindPosePos.mZ); - AZ::Vector3 bindPoseScale(jointInfo.m_bindPoseScale.mX, jointInfo.m_bindPoseScale.mY, jointInfo.m_bindPoseScale.mZ); - MCore::Compressed16BitQuaternion bindPoseRot(jointInfo.m_bindPoseRot.mX, jointInfo.m_bindPoseRot.mY, jointInfo.m_bindPoseRot.mZ, jointInfo.m_bindPoseRot.mW); + AZ::Vector3 staticPos(jointInfo.m_staticPos.m_x, jointInfo.m_staticPos.m_y, jointInfo.m_staticPos.m_z); + AZ::Vector3 staticScale(jointInfo.m_staticScale.m_x, jointInfo.m_staticScale.m_y, jointInfo.m_staticScale.m_z); + MCore::Compressed16BitQuaternion staticRot(jointInfo.m_staticRot.m_x, jointInfo.m_staticRot.m_y, jointInfo.m_staticRot.m_z, jointInfo.m_staticRot.m_w); + AZ::Vector3 bindPosePos(jointInfo.m_bindPosePos.m_x, jointInfo.m_bindPosePos.m_y, jointInfo.m_bindPosePos.m_z); + AZ::Vector3 bindPoseScale(jointInfo.m_bindPoseScale.m_x, jointInfo.m_bindPoseScale.m_y, jointInfo.m_bindPoseScale.m_z); + MCore::Compressed16BitQuaternion bindPoseRot(jointInfo.m_bindPoseRot.m_x, jointInfo.m_bindPoseRot.m_y, jointInfo.m_bindPoseRot.m_z, jointInfo.m_bindPoseRot.m_w); MCore::Endian::ConvertVector3(&staticPos, sourceEndianType); MCore::Endian::Convert16BitQuaternion(&staticRot, sourceEndianType); MCore::Endian::ConvertVector3(&staticScale, sourceEndianType); @@ -1747,8 +1747,8 @@ namespace EMotionFX return false; } MCore::Endian::ConvertFloat(&keyInfo.m_time, sourceEndianType); - MCore::Endian::ConvertFloat(&keyInfo.m_value.mX, sourceEndianType, /*numFloats=*/3); - motionData->SetJointPositionSample(i, s, {keyInfo.m_time, AZ::Vector3(keyInfo.m_value.mX, keyInfo.m_value.mY, keyInfo.m_value.mZ)}); + MCore::Endian::ConvertFloat(&keyInfo.m_value.m_x, sourceEndianType, /*numFloats=*/3); + motionData->SetJointPositionSample(i, s, {keyInfo.m_time, AZ::Vector3(keyInfo.m_value.m_x, keyInfo.m_value.m_y, keyInfo.m_value.m_z)}); } } @@ -1764,7 +1764,7 @@ namespace EMotionFX return false; } MCore::Endian::ConvertFloat(&keyInfo.m_time, sourceEndianType); - MCore::Compressed16BitQuaternion compressedQuat(keyInfo.m_value.mX, keyInfo.m_value.mY, keyInfo.m_value.mZ, keyInfo.m_value.mW); + MCore::Compressed16BitQuaternion compressedQuat(keyInfo.m_value.m_x, keyInfo.m_value.m_y, keyInfo.m_value.m_z, keyInfo.m_value.m_w); MCore::Endian::Convert16BitQuaternion(&compressedQuat, sourceEndianType); motionData->SetJointRotationSample(i, s, {keyInfo.m_time, compressedQuat.ToQuaternion().GetNormalized()}); } @@ -1784,8 +1784,8 @@ namespace EMotionFX return false; } MCore::Endian::ConvertFloat(&keyInfo.m_time, sourceEndianType); - MCore::Endian::ConvertFloat(&keyInfo.m_value.mX, sourceEndianType, /*numFloats=*/3); - motionData->SetJointScaleSample(i, s, {keyInfo.m_time, AZ::Vector3(keyInfo.m_value.mX, keyInfo.m_value.mY, keyInfo.m_value.mZ)}); + MCore::Endian::ConvertFloat(&keyInfo.m_value.m_x, sourceEndianType, /*numFloats=*/3); + motionData->SetJointScaleSample(i, s, {keyInfo.m_time, AZ::Vector3(keyInfo.m_value.m_x, keyInfo.m_value.m_y, keyInfo.m_value.m_z)}); } } ) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.h index 648693120e..b5d8a05c44 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/NonUniformMotionData.h @@ -55,7 +55,7 @@ namespace EMotionFX AZ::u32 GetStreamSaveVersion() const override; const char* GetSceneSettingsName() const override; - Transform SampleJointTransform(const SampleSettings& settings, AZ::u32 jointSkeletonIndex) const override; + Transform SampleJointTransform(const SampleSettings& settings, size_t jointSkeletonIndex) const override; void SamplePose(const SampleSettings& settings, Pose* outputPose) const override; Transform SampleJointTransform(float sampleTime, size_t jointDataIndex) const override; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp index d029a5de73..c4451ff902 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.cpp @@ -88,11 +88,11 @@ namespace EMotionFX { const float keyTime = s * sampleSpacing; const Transform transform = motionData->SampleJointTransform(keyTime, i); - if (posAnimated) m_jointData[i].m_positions[s] = transform.mPosition; - if (rotAnimated) m_jointData[i].m_rotations[s] = transform.mRotation.GetNormalized(); + if (posAnimated) m_jointData[i].m_positions[s] = transform.m_position; + if (rotAnimated) m_jointData[i].m_rotations[s] = transform.m_rotation.GetNormalized(); EMFX_SCALECODE ( - if (scaleAnimated) m_jointData[i].m_scales[s] = transform.mScale; + if (scaleAnimated) m_jointData[i].m_scales[s] = transform.m_scale; ) } } @@ -130,13 +130,13 @@ namespace EMotionFX } } - Transform UniformMotionData::SampleJointTransform(const SampleSettings& settings, AZ::u32 jointSkeletonIndex) const + Transform UniformMotionData::SampleJointTransform(const SampleSettings& settings, size_t jointSkeletonIndex) const { const Actor* actor = settings.m_actorInstance->GetActor(); const MotionLinkData* motionLinkData = FindMotionLinkData(actor); - const AZ::u32 transformDataIndex = motionLinkData->GetJointDataLinks()[jointSkeletonIndex]; - if (m_additive && transformDataIndex == InvalidIndex32) + const size_t transformDataIndex = motionLinkData->GetJointDataLinks()[jointSkeletonIndex]; + if (m_additive && transformDataIndex == InvalidIndex) { return Transform::CreateIdentity(); } @@ -152,14 +152,14 @@ namespace EMotionFX // Sample the interpolated data. Transform result; - if (transformDataIndex != InvalidIndex32 && !inPlace) + if (transformDataIndex != InvalidIndex && !inPlace) { const StaticJointData& staticJointData = m_staticJointData[transformDataIndex]; const JointData& jointData = m_jointData[transformDataIndex]; - result.mPosition = !jointData.m_positions.empty() ? jointData.m_positions[indexA].Lerp(jointData.m_positions[indexB], t) : staticJointData.m_staticTransform.mPosition; - result.mRotation = !jointData.m_rotations.empty() ? jointData.m_rotations[indexA].ToQuaternion().NLerp(jointData.m_rotations[indexB].ToQuaternion(), t) : staticJointData.m_staticTransform.mRotation; + result.m_position = !jointData.m_positions.empty() ? jointData.m_positions[indexA].Lerp(jointData.m_positions[indexB], t) : staticJointData.m_staticTransform.m_position; + result.m_rotation = !jointData.m_rotations.empty() ? jointData.m_rotations[indexA].ToQuaternion().NLerp(jointData.m_rotations[indexB].ToQuaternion(), t) : staticJointData.m_staticTransform.m_rotation; #ifndef EMFX_SCALE_DISABLED - result.mScale = !jointData.m_scales.empty() ? jointData.m_scales[indexA].Lerp(jointData.m_scales[indexB], t) : staticJointData.m_staticTransform.mScale; + result.m_scale = !jointData.m_scales.empty() ? jointData.m_scales[indexA].Lerp(jointData.m_scales[indexB], t) : staticJointData.m_staticTransform.m_scale; #endif } else @@ -187,9 +187,9 @@ namespace EMotionFX const Actor::NodeMirrorInfo& mirrorInfo = actor->GetNodeMirrorInfo(jointSkeletonIndex); Transform mirrored = bindPose->GetLocalSpaceTransform(jointSkeletonIndex); AZ::Vector3 mirrorAxis = AZ::Vector3::CreateZero(); - mirrorAxis.SetElement(mirrorInfo.mAxis, 1.0f); - const AZ::u16 motionSource = actor->GetNodeMirrorInfo(jointSkeletonIndex).mSourceNode; - mirrored.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(motionSource), result, mirrorAxis, mirrorInfo.mFlags); + mirrorAxis.SetElement(mirrorInfo.m_axis, 1.0f); + const AZ::u16 motionSource = actor->GetNodeMirrorInfo(jointSkeletonIndex).m_sourceNode; + mirrored.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(motionSource), result, mirrorAxis, mirrorInfo.m_flags); result = mirrored; } @@ -208,33 +208,33 @@ namespace EMotionFX size_t indexB; CalculateInterpolationIndicesUniform(settings.m_sampleTime, m_sampleSpacing, m_duration, m_numSamples, indexA, indexB, t); - const AZStd::vector& jointLinks = motionLinkData->GetJointDataLinks(); + const AZStd::vector& jointLinks = motionLinkData->GetJointDataLinks(); const ActorInstance* actorInstance = settings.m_actorInstance; const Skeleton* skeleton = actor->GetSkeleton(); const Pose* bindPose = actorInstance->GetTransformData()->GetBindPose(); - const AZ::u32 numNodes = actorInstance->GetNumEnabledNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const AZ::u32 skeletonJointIndex = actorInstance->GetEnabledNode(i); + const size_t skeletonJointIndex = actorInstance->GetEnabledNode(i); const bool inPlace = (settings.m_inPlace && skeleton->GetNode(skeletonJointIndex)->GetIsRootNode()); // Sample the interpolated data. Transform result; - const AZ::u32 jointDataIndex = jointLinks[skeletonJointIndex]; - if (jointDataIndex != InvalidIndex32 && !inPlace) + const size_t jointDataIndex = jointLinks[skeletonJointIndex]; + if (jointDataIndex != InvalidIndex && !inPlace) { const StaticJointData& staticJointData = m_staticJointData[jointDataIndex]; const JointData& jointData = m_jointData[jointDataIndex]; - result.mPosition = !jointData.m_positions.empty() ? jointData.m_positions[indexA].Lerp(jointData.m_positions[indexB], t) : staticJointData.m_staticTransform.mPosition; - result.mRotation = !jointData.m_rotations.empty() ? jointData.m_rotations[indexA].ToQuaternion().NLerp(jointData.m_rotations[indexB].ToQuaternion(), t) : staticJointData.m_staticTransform.mRotation; + result.m_position = !jointData.m_positions.empty() ? jointData.m_positions[indexA].Lerp(jointData.m_positions[indexB], t) : staticJointData.m_staticTransform.m_position; + result.m_rotation = !jointData.m_rotations.empty() ? jointData.m_rotations[indexA].ToQuaternion().NLerp(jointData.m_rotations[indexB].ToQuaternion(), t) : staticJointData.m_staticTransform.m_rotation; #ifndef EMFX_SCALE_DISABLED - result.mScale = !jointData.m_scales.empty() ? jointData.m_scales[indexA].Lerp(jointData.m_scales[indexB], t) : staticJointData.m_staticTransform.mScale; + result.m_scale = !jointData.m_scales.empty() ? jointData.m_scales[indexA].Lerp(jointData.m_scales[indexB], t) : staticJointData.m_staticTransform.m_scale; #endif } else { - if (m_additive && jointDataIndex == InvalidIndex32) + if (m_additive && jointDataIndex == InvalidIndex) { result = Transform::CreateIdentity(); } @@ -268,8 +268,8 @@ namespace EMotionFX // Output morph target weights. const MorphSetupInstance* morphSetup = actorInstance->GetMorphSetupInstance(); - const AZ::u32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (AZ::u32 i = 0; i < numMorphTargets; ++i) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t i = 0; i < numMorphTargets; ++i) { const AZ::u32 morphTargetId = morphSetup->GetMorphTarget(i)->GetID(); const AZ::Outcome morphIndex = FindMorphIndexByNameId(morphTargetId); @@ -663,7 +663,7 @@ namespace EMotionFX CalculateInterpolationIndicesUniform(sampleTime, m_sampleSpacing, m_duration, m_numSamples, indexA, indexB, t); const AZStd::vector& values = m_jointData[jointDataIndex].m_positions; - return !values.empty() ? values[indexA].Lerp(values[indexB], t) : m_staticJointData[jointDataIndex].m_staticTransform.mPosition; + return !values.empty() ? values[indexA].Lerp(values[indexB], t) : m_staticJointData[jointDataIndex].m_staticTransform.m_position; } AZ::Quaternion UniformMotionData::SampleJointRotation(float sampleTime, size_t jointDataIndex) const @@ -674,7 +674,7 @@ namespace EMotionFX CalculateInterpolationIndicesUniform(sampleTime, m_sampleSpacing, m_duration, m_numSamples, indexA, indexB, t); const AZStd::vector& values = m_jointData[jointDataIndex].m_rotations; - return !values.empty() ? values[indexA].ToQuaternion().NLerp(values[indexB].ToQuaternion(), t) : m_staticJointData[jointDataIndex].m_staticTransform.mRotation; + return !values.empty() ? values[indexA].ToQuaternion().NLerp(values[indexB].ToQuaternion(), t) : m_staticJointData[jointDataIndex].m_staticTransform.m_rotation; } #ifndef EMFX_SCALE_DISABLED @@ -686,7 +686,7 @@ namespace EMotionFX CalculateInterpolationIndicesUniform(sampleTime, m_sampleSpacing, m_duration, m_numSamples, indexA, indexB, t); const AZStd::vector& values = m_jointData[jointDataIndex].m_scales; - return !values.empty() ? values[indexA].Lerp(values[indexB], t) : m_staticJointData[jointDataIndex].m_staticTransform.mScale; + return !values.empty() ? values[indexA].Lerp(values[indexB], t) : m_staticJointData[jointDataIndex].m_staticTransform.m_scale; } #endif @@ -706,11 +706,11 @@ namespace EMotionFX return Transform ( - !posValues.empty() ? posValues[indexA].Lerp(posValues[indexB], t) : staticData.m_staticTransform.mScale, - !rotValues.empty() ? rotValues[indexA].ToQuaternion().NLerp(rotValues[indexB].ToQuaternion(), t) : staticData.m_staticTransform.mRotation + !posValues.empty() ? posValues[indexA].Lerp(posValues[indexB], t) : staticData.m_staticTransform.m_scale, + !rotValues.empty() ? rotValues[indexA].ToQuaternion().NLerp(rotValues[indexB].ToQuaternion(), t) : staticData.m_staticTransform.m_rotation #ifndef EMFX_SCALE_DISABLED - ,!scaleValues.empty() ? scaleValues[indexA].Lerp(scaleValues[indexB], t) : staticData.m_staticTransform.mScale + ,!scaleValues.empty() ? scaleValues[indexA].Lerp(scaleValues[indexB], t) : staticData.m_staticTransform.m_scale #endif ); } @@ -808,16 +808,16 @@ namespace EMotionFX if (saveSettings.m_logDetails) { // Create an uncompressed version of the quaternions, for logging. - const AZ::Quaternion uncompressedPoseRot = MCore::Compressed16BitQuaternion(jointChunk.m_staticRot.mX, jointChunk.m_staticRot.mY, jointChunk.m_staticRot.mZ, jointChunk.m_staticRot.mW).ToQuaternion().GetNormalized(); - const AZ::Quaternion uncompressedBindPoseRot = MCore::Compressed16BitQuaternion(jointChunk.m_bindPoseRot.mX, jointChunk.m_bindPoseRot.mY, jointChunk.m_bindPoseRot.mZ, jointChunk.m_bindPoseRot.mW).ToQuaternion().GetNormalized(); + const AZ::Quaternion uncompressedPoseRot = MCore::Compressed16BitQuaternion(jointChunk.m_staticRot.m_x, jointChunk.m_staticRot.m_y, jointChunk.m_staticRot.m_z, jointChunk.m_staticRot.m_w).ToQuaternion().GetNormalized(); + const AZ::Quaternion uncompressedBindPoseRot = MCore::Compressed16BitQuaternion(jointChunk.m_bindPoseRot.m_x, jointChunk.m_bindPoseRot.m_y, jointChunk.m_bindPoseRot.m_z, jointChunk.m_bindPoseRot.m_w).ToQuaternion().GetNormalized(); MCore::LogDetailedInfo("- Motion Joint: %s", motionData->GetJointName(jointDataIndex).c_str()); - MCore::LogDetailedInfo(" + Static Translation: x=%f y=%f z=%f", jointChunk.m_staticPos.mX, jointChunk.m_staticPos.mY, jointChunk.m_staticPos.mZ); + MCore::LogDetailedInfo(" + Static Translation: x=%f y=%f z=%f", jointChunk.m_staticPos.m_x, jointChunk.m_staticPos.m_y, jointChunk.m_staticPos.m_z); MCore::LogDetailedInfo(" + Static Rotation: x=%f y=%f z=%f w=%f", static_cast(uncompressedPoseRot.GetX()), static_cast(uncompressedPoseRot.GetY()), static_cast(uncompressedPoseRot.GetZ()), static_cast(uncompressedPoseRot.GetW())); - MCore::LogDetailedInfo(" + Static Scale: x=%f y=%f z=%f", jointChunk.m_staticScale.mX, jointChunk.m_staticScale.mY, jointChunk.m_staticScale.mZ); - MCore::LogDetailedInfo(" + Bind Pose Translation: x=%f y=%f z=%f", jointChunk.m_bindPosePos.mX, jointChunk.m_bindPosePos.mY, jointChunk.m_bindPosePos.mZ); + MCore::LogDetailedInfo(" + Static Scale: x=%f y=%f z=%f", jointChunk.m_staticScale.m_x, jointChunk.m_staticScale.m_y, jointChunk.m_staticScale.m_z); + MCore::LogDetailedInfo(" + Bind Pose Translation: x=%f y=%f z=%f", jointChunk.m_bindPosePos.m_x, jointChunk.m_bindPosePos.m_y, jointChunk.m_bindPosePos.m_z); MCore::LogDetailedInfo(" + Bind Pose Rotation: x=%f y=%f z=%f w=%f", static_cast(uncompressedBindPoseRot.GetX()), static_cast(uncompressedBindPoseRot.GetY()), static_cast(uncompressedBindPoseRot.GetZ()), static_cast(uncompressedBindPoseRot.GetW())); - MCore::LogDetailedInfo(" + Bind Pose Scale: x=%f y=%f z=%f", jointChunk.m_bindPoseScale.mX, jointChunk.m_bindPoseScale.mY, jointChunk.m_bindPoseScale.mZ); + MCore::LogDetailedInfo(" + Bind Pose Scale: x=%f y=%f z=%f", jointChunk.m_bindPoseScale.m_x, jointChunk.m_bindPoseScale.m_y, jointChunk.m_bindPoseScale.m_z); MCore::LogDetailedInfo(" + Position Animated: %s", (flags & File_UniformMotionData_Flags::IsPositionAnimated) ? "Yes" : "No"); MCore::LogDetailedInfo(" + Rotation Animated: %s", (flags & File_UniformMotionData_Flags::IsRotationAnimated) ? "Yes" : "No"); MCore::LogDetailedInfo(" + Scale Animated: %s", (flags & File_UniformMotionData_Flags::IsScaleAnimated) ? "Yes" : "No"); @@ -1122,12 +1122,12 @@ namespace EMotionFX } // Convert endian. - AZ::Vector3 staticPos(jointInfo.m_staticPos.mX, jointInfo.m_staticPos.mY, jointInfo.m_staticPos.mZ); - AZ::Vector3 staticScale(jointInfo.m_staticScale.mX, jointInfo.m_staticScale.mY, jointInfo.m_staticScale.mZ); - MCore::Compressed16BitQuaternion staticRot(jointInfo.m_staticRot.mX, jointInfo.m_staticRot.mY, jointInfo.m_staticRot.mZ, jointInfo.m_staticRot.mW); - AZ::Vector3 bindPosePos(jointInfo.m_bindPosePos.mX, jointInfo.m_bindPosePos.mY, jointInfo.m_bindPosePos.mZ); - AZ::Vector3 bindPoseScale(jointInfo.m_bindPoseScale.mX, jointInfo.m_bindPoseScale.mY, jointInfo.m_bindPoseScale.mZ); - MCore::Compressed16BitQuaternion bindPoseRot(jointInfo.m_bindPoseRot.mX, jointInfo.m_bindPoseRot.mY, jointInfo.m_bindPoseRot.mZ, jointInfo.m_bindPoseRot.mW); + AZ::Vector3 staticPos(jointInfo.m_staticPos.m_x, jointInfo.m_staticPos.m_y, jointInfo.m_staticPos.m_z); + AZ::Vector3 staticScale(jointInfo.m_staticScale.m_x, jointInfo.m_staticScale.m_y, jointInfo.m_staticScale.m_z); + MCore::Compressed16BitQuaternion staticRot(jointInfo.m_staticRot.m_x, jointInfo.m_staticRot.m_y, jointInfo.m_staticRot.m_z, jointInfo.m_staticRot.m_w); + AZ::Vector3 bindPosePos(jointInfo.m_bindPosePos.m_x, jointInfo.m_bindPosePos.m_y, jointInfo.m_bindPosePos.m_z); + AZ::Vector3 bindPoseScale(jointInfo.m_bindPoseScale.m_x, jointInfo.m_bindPoseScale.m_y, jointInfo.m_bindPoseScale.m_z); + MCore::Compressed16BitQuaternion bindPoseRot(jointInfo.m_bindPoseRot.m_x, jointInfo.m_bindPoseRot.m_y, jointInfo.m_bindPoseRot.m_z, jointInfo.m_bindPoseRot.m_w); MCore::Endian::ConvertVector3(&staticPos, sourceEndianType); MCore::Endian::Convert16BitQuaternion(&staticRot, sourceEndianType); MCore::Endian::ConvertVector3(&staticScale, sourceEndianType); @@ -1171,8 +1171,8 @@ namespace EMotionFX { return false; } - MCore::Endian::ConvertFloat(&fileVector.mX, sourceEndianType, /*numFloats=*/3); - motionData->SetJointPositionSample(i, s, AZ::Vector3(fileVector.mX, fileVector.mY, fileVector.mZ)); + MCore::Endian::ConvertFloat(&fileVector.m_x, sourceEndianType, /*numFloats=*/3); + motionData->SetJointPositionSample(i, s, AZ::Vector3(fileVector.m_x, fileVector.m_y, fileVector.m_z)); } } @@ -1188,7 +1188,7 @@ namespace EMotionFX { return false; } - MCore::Compressed16BitQuaternion compressedQuat(fileQuat.mX, fileQuat.mY, fileQuat.mZ, fileQuat.mW); + MCore::Compressed16BitQuaternion compressedQuat(fileQuat.m_x, fileQuat.m_y, fileQuat.m_z, fileQuat.m_w); MCore::Endian::Convert16BitQuaternion(&compressedQuat, sourceEndianType); motionData->SetJointRotationSample(i, s, compressedQuat.ToQuaternion().GetNormalized()); } @@ -1211,8 +1211,8 @@ namespace EMotionFX } EMFX_SCALECODE ( - MCore::Endian::ConvertFloat(&fileVector.mX, sourceEndianType, /*numFloats=*/3); - motionData->SetJointScaleSample(i, s, AZ::Vector3(fileVector.mX, fileVector.mY, fileVector.mZ)); + MCore::Endian::ConvertFloat(&fileVector.m_x, sourceEndianType, /*numFloats=*/3); + motionData->SetJointScaleSample(i, s, AZ::Vector3(fileVector.m_x, fileVector.m_y, fileVector.m_z)); ) } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.h index ada4b91d95..40674cf2d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionData/UniformMotionData.h @@ -53,7 +53,7 @@ namespace EMotionFX const char* GetSceneSettingsName() const override; // Overloaded. - Transform SampleJointTransform(const SampleSettings& settings, AZ::u32 jointSkeletonIndex) const override; + Transform SampleJointTransform(const SampleSettings& settings, size_t jointSkeletonIndex) const override; void SamplePose(const SampleSettings& settings, Pose* outputPose) const override; float SampleMorph(float sampleTime, size_t morphDataIndex) const override; float SampleFloat(float sampleTime, size_t floatDataIndex) const override; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.cpp index d288fa8b82..02b8c179b4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.cpp @@ -25,12 +25,12 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(MotionEventTrack, MotionEventAllocator, 0) MotionEventTrack::MotionEventTrack(Motion* motion) - : mMotion(motion) + : m_motion(motion) { } MotionEventTrack::MotionEventTrack(const char* name, Motion* motion) - : mMotion(motion) + : m_motion(motion) , m_name(name) { } @@ -47,7 +47,7 @@ namespace EMotionFX return *this; } m_events = other.m_events; - mMotion = other.mMotion; + m_motion = other.m_motion; m_name = other.m_name; return *this; } @@ -63,8 +63,8 @@ namespace EMotionFX serializeContext->Class() ->Version(2, VersionConverter) ->Field("name", &MotionEventTrack::m_name) - ->Field("enabled", &MotionEventTrack::mEnabled) - ->Field("deletable", &MotionEventTrack::mDeletable) + ->Field("enabled", &MotionEventTrack::m_enabled) + ->Field("deletable", &MotionEventTrack::m_deletable) ->Field("events", &MotionEventTrack::m_events) ; @@ -392,7 +392,7 @@ namespace EMotionFX { targetTrack->m_name = m_name; targetTrack->m_events = m_events; - targetTrack->mEnabled = mEnabled; + targetTrack->m_enabled = m_enabled; } // reserve memory for a given amount of events @@ -403,35 +403,35 @@ namespace EMotionFX void MotionEventTrack::SetIsEnabled(bool enabled) { - mEnabled = enabled; + m_enabled = enabled; } bool MotionEventTrack::GetIsEnabled() const { - return mEnabled; + return m_enabled; } bool MotionEventTrack::GetIsDeletable() const { - return mDeletable; + return m_deletable; } void MotionEventTrack::SetIsDeletable(bool isDeletable) { - mDeletable = isDeletable; + m_deletable = isDeletable; } Motion* MotionEventTrack::GetMotion() const { - return mMotion; + return m_motion; } void MotionEventTrack::SetMotion(Motion* newMotion) { - mMotion = newMotion; + m_motion = newMotion; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.h index 63f5abd0dd..fdf2e2bed7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionEventTrack.h @@ -182,11 +182,11 @@ namespace EMotionFX AZStd::string m_name; /// The motion where this track belongs to. - Motion* mMotion; + Motion* m_motion; /// Is this track enabled? - bool mEnabled = true; - bool mDeletable = true; + bool m_enabled = true; + bool m_deletable = true; private: void ProcessEventsImpl(float startTime, float endTime, ActorInstance* actorInstance, const MotionInstance* motionInstance, const AZStd::function& processFunc); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionGroup.cpp deleted file mode 100644 index 8b3a874c3b..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionGroup.cpp +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// include required headers -#include "MotionGroup.h" -#include "MotionInstance.h" -#include "ActorInstance.h" -#include "EMotionFXManager.h" -#include "MotionInstancePool.h" -#include "AnimGraphPose.h" -#include - - -namespace EMotionFX -{ - AZ_CLASS_ALLOCATOR_IMPL(MotionGroup, MotionAllocator, 0) - - - // default constructor - MotionGroup::MotionGroup() - : BaseObject() - { - mParentMotionInstance = nullptr; - } - - - // extended constructor - MotionGroup::MotionGroup(MotionInstance* parentMotionInstance) - : BaseObject() - { - LinkToMotionInstance(parentMotionInstance); - } - - - // destructor - MotionGroup::~MotionGroup() - { - RemoveAllMotionInstances(); - } - - - // creation - MotionGroup* MotionGroup::Create() - { - return aznew MotionGroup(); - } - - - // creation - MotionGroup* MotionGroup::Create(MotionInstance* parentMotionInstance) - { - return aznew MotionGroup(parentMotionInstance); - } - - - // link to a motion instance - void MotionGroup::LinkToMotionInstance(MotionInstance* parentMotionInstance) - { - mParentMotionInstance = parentMotionInstance; - } - - - // add a motion to the group - MotionInstance* MotionGroup::AddMotion(Motion* motion, PlayBackInfo* playInfo, uint32 startNodeIndex) - { - MCORE_ASSERT(mParentMotionInstance); // use LinkToMotionInstance before - - // create the new motion instance - MotionInstance* newInstance = GetMotionInstancePool().RequestNew(motion, mParentMotionInstance->GetActorInstance()); - - // initialize the motion instance settings - if (playInfo == nullptr) // if no playinfo specified, use default playback settings - { - PlayBackInfo info; - newInstance->InitFromPlayBackInfo(info); - } - else - { - newInstance->InitFromPlayBackInfo(*playInfo); - } - - // add it to the motion instance array - mMotionInstances.Add(newInstance); - - return newInstance; - } - - - // remove all motion instances from the group and from memory - void MotionGroup::RemoveAllMotionInstances() - { - // remove all motion instances from memory - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) - { - GetMotionInstancePool().Free(mMotionInstances[i]); - } - - mMotionInstances.Clear(); - } - - - // remove a given motion by its motion instance - void MotionGroup::RemoveMotionInstance(MotionInstance* instance) - { - if (mMotionInstances.RemoveByValue(instance)) - { - GetMotionInstancePool().Free(instance); - } - } - - - // remove all motion instances using a given motion - void MotionGroup::RemoveMotion(Motion* motion) - { - // for all the motion instances - for (uint32 i = 0; i < mMotionInstances.GetLength();) - { - // if this motion instance uses the given motion - if (mMotionInstances[i]->GetMotion() == motion) - { - // remove it from memory and from the array - GetMotionInstancePool().Free(mMotionInstances[i]); - mMotionInstances.Remove(i); - } - else - { - i++; - } - } - } - - - // remove a motion instance by its index - void MotionGroup::RemoveMotionInstance(uint32 index) - { - MCORE_ASSERT(index < mMotionInstances.GetLength()); - - // remove it from memory and from the array - GetMotionInstancePool().Free(mMotionInstances[index]); - mMotionInstances.Remove(index); - } - - - // update the motion instances - void MotionGroup::Update(float timePassed) - { - // update the motion instances - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) - { - mMotionInstances[i]->Update(timePassed); - } - } - - - // perform the blending and output it in the outPose buffer - void MotionGroup::Output(const Pose* inPose, Pose* outPose) - { - uint32 i; - - // calculate the total weight - float totalWeight = 0.0f; - const uint32 numInstances = mMotionInstances.GetLength(); - for (i = 0; i < numInstances; ++i) - { - totalWeight += mMotionInstances[i]->GetWeight(); - } - - // calculate the inverse of the total weight so that we can replace divides by multiplies, which is faster - float invTotalWeight; - if (totalWeight < 0.0001f) - { - invTotalWeight = 0.0f; - } - else - { - invTotalWeight = 1.0f / totalWeight; - } - - const ActorInstance* actorInstance = inPose->GetActorInstance(); - const uint32 threadIndex = actorInstance->GetThreadIndex(); - AnimGraphPosePool& posePool = GetEMotionFX().GetThreadData(threadIndex)->GetPosePool(); - AnimGraphPose* groupAnimGraphPose = posePool.RequestPose(actorInstance); - - // get the group blend pose and make sure it's big enough - Pose* groupBlendPose = &groupAnimGraphPose->GetPose();//mParentMotionInstance->GetActorInstance()->GetActor()->GetGroupBlendPose(); - MCORE_ASSERT(groupBlendPose->GetNumTransforms() == inPose->GetNumTransforms()); - - // blend using the normalized weights - for (i = 0; i < numInstances; ++i) - { - // calculate the normalized weight - const float normalizedWeight = mMotionInstances[i]->GetWeight() * invTotalWeight; - - // output the motion output into the group blend buffer - mMotionInstances[i]->GetMotion()->Update(inPose, groupBlendPose, mMotionInstances[i]); - - // if it's the first motion instance in the group - if (i == 0) - { - // blend all transforms - // TODO: use only enabled nodes - const uint32 numTransforms = outPose->GetNumTransforms(); - for (uint32 t = 0; t < numTransforms; ++t) - { - Transform& transform = groupBlendPose->GetLocalSpaceTransformDirect(t); - Transform& outTransform = outPose->GetLocalSpaceTransformDirect(t); - transform.mRotation.Normalize(); - - EMFX_SCALECODE - ( - //transform.mScaleRotation.Normalize(); - outTransform.mScale = transform.mScale * normalizedWeight; - //outTransform.mScaleRotation = transform.mScaleRotation * normalizedWeight; - ) - - outTransform.mPosition = transform.mPosition * normalizedWeight; - outTransform.mRotation = transform.mRotation * normalizedWeight; - } - } - else - { - // blend all transforms - // TODO: use only enabled nodes - const uint32 numTransforms = outPose->GetNumTransforms(); - for (uint32 t = 0; t < numTransforms; ++t) - { - Transform& transform = groupBlendPose->GetLocalSpaceTransformDirect(t); - Transform& outTransform = outPose->GetLocalSpaceTransformDirect(t); - - outTransform.mPosition += transform.mPosition * normalizedWeight; - - EMFX_SCALECODE - ( - outTransform.mScale += transform.mScale * normalizedWeight; - - // make sure we use the correct hemisphere - //if (outTransform.mScaleRotation.Dot( transform.mScaleRotation ) < 0.0f) - //transform.mScaleRotation = -transform.mScaleRotation; - - //outTransform.mScaleRotation += transform.mScaleRotation * normalizedWeight; - ) - - // make sure we use the correct hemisphere - if (outTransform.mRotation.Dot(transform.mRotation) < 0.0f) - { - transform.mRotation = -transform.mRotation; - } - - outTransform.mRotation += transform.mRotation * normalizedWeight; - } - } - } // for all motion instances in the group - - // normalize the quaternions - const uint32 numTransforms = outPose->GetNumTransforms(); - for (uint32 t = 0; t < numTransforms; ++t) - { - Transform& outTransform = outPose->GetLocalSpaceTransformDirect(t); - outTransform.mRotation.Normalize(); - - //EMFX_SCALECODE - //( - //outTransform.mScaleRotation.Normalize(); - //) - } - - // free the pose - posePool.FreePose(groupAnimGraphPose); - } -} // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp index bbadff74f2..696430271a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.cpp @@ -33,7 +33,7 @@ namespace EMotionFX m_motion = motion; m_actorInstance = actorInstance; - m_id = MCore::GetIDGenerator().GenerateID(); + m_id = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); SetDeleteOnZeroWeight(true); SetCanOverwrite(true); @@ -74,30 +74,30 @@ namespace EMotionFX void MotionInstance::InitFromPlayBackInfo(const PlayBackInfo& info, bool resetCurrentPlaytime) { - SetFadeTime (info.mBlendOutTime); - SetMixMode (info.mMix); - SetMaxLoops (info.mNumLoops); - SetBlendMode (info.mBlendMode); - SetPlaySpeed (info.mPlaySpeed); - SetWeight (info.mTargetWeight, info.mBlendInTime); - SetPriorityLevel (info.mPriorityLevel); - SetPlayMode (info.mPlayMode); - SetRetargetingEnabled (info.mRetarget); - SetMotionExtractionEnabled(info.mMotionExtractionEnabled); - SetFreezeAtLastFrame (info.mFreezeAtLastFrame); - SetMotionEventsEnabled (info.mEnableMotionEvents); - SetMaxPlayTime (info.mMaxPlayTime); - SetEventWeightThreshold (info.mEventWeightThreshold); - SetBlendOutBeforeEnded (info.mBlendOutBeforeEnded); - SetCanOverwrite (info.mCanOverwrite); - SetDeleteOnZeroWeight (info.mDeleteOnZeroWeight); - SetMirrorMotion (info.mMirrorMotion); - SetFreezeAtTime (info.mFreezeAtTime); - SetIsInPlace (info.mInPlace); + SetFadeTime (info.m_blendOutTime); + SetMixMode (info.m_mix); + SetMaxLoops (info.m_numLoops); + SetBlendMode (info.m_blendMode); + SetPlaySpeed (info.m_playSpeed); + SetWeight (info.m_targetWeight, info.m_blendInTime); + SetPriorityLevel (info.m_priorityLevel); + SetPlayMode (info.m_playMode); + SetRetargetingEnabled (info.m_retarget); + SetMotionExtractionEnabled(info.m_motionExtractionEnabled); + SetFreezeAtLastFrame (info.m_freezeAtLastFrame); + SetMotionEventsEnabled (info.m_enableMotionEvents); + SetMaxPlayTime (info.m_maxPlayTime); + SetEventWeightThreshold (info.m_eventWeightThreshold); + SetBlendOutBeforeEnded (info.m_blendOutBeforeEnded); + SetCanOverwrite (info.m_canOverwrite); + SetDeleteOnZeroWeight (info.m_deleteOnZeroWeight); + SetMirrorMotion (info.m_mirrorMotion); + SetFreezeAtTime (info.m_freezeAtTime); + SetIsInPlace (info.m_inPlace); if (resetCurrentPlaytime) { - m_currentTime = (info.mPlayMode == PLAYMODE_BACKWARD) ? GetDuration() : 0.0f; + m_currentTime = (info.m_playMode == PLAYMODE_BACKWARD) ? GetDuration() : 0.0f; m_lastCurTime = m_currentTime; m_timeDiffToEnd = GetDuration(); } @@ -363,14 +363,14 @@ namespace EMotionFX const float currentTimePreUpdate = m_currentTime; UpdateTime(timePassed); - // If UpdateTime() did not advance mCurrentTime we can skip over ProcessEvents(). + // If UpdateTime() did not advance m_currentTime we can skip over ProcessEvents(). if (!AZ::IsClose(m_lastCurTime, m_currentTime, AZ::Constants::FloatEpsilon)) { // if we are blending towards the destination motion or layer. - // Do this after UpdateTime(timePassed) and use (mCurrentTime - mLastCurTime) + // Do this after UpdateTime(timePassed) and use (m_currentTime - m_lastCurTime) // as the elapsed time. This will function for Updates that use SetCurrentTime(time, false) // like Simple Motion component does with Track View. This will also work for motions that - // have mPlaySpeed that is not 1.0f. + // have m_playSpeed that is not 1.0f. if (GetIsBlending()) { const float duration = GetDuration(); @@ -819,7 +819,7 @@ namespace EMotionFX } // calculate a world space transformation for a given node by sampling the motion at a given time - void MotionInstance::CalcGlobalTransform(const MCore::Array& hierarchyPath, float timeValue, Transform* outTransform) const + void MotionInstance::CalcGlobalTransform(const AZStd::vector& hierarchyPath, float timeValue, Transform* outTransform) const { Actor* actor = m_actorInstance->GetActor(); Skeleton* skeleton = actor->GetSkeleton(); @@ -829,10 +829,10 @@ namespace EMotionFX outTransform->Identity(); // iterate from root towards the node (so backwards in the array) - for (int32 i = hierarchyPath.GetLength() - 1; i >= 0; --i) + for (auto iter = rbegin(hierarchyPath); iter != rend(hierarchyPath); ++iter) { // get the current node index - const AZ::u32 nodeIndex = hierarchyPath[i]; + const size_t nodeIndex = *iter; m_motion->CalcNodeTransform(this, &subMotionTransform, actor, skeleton->GetNode(nodeIndex), timeValue, GetRetargetingEnabled()); // multiply parent transform with the current node's transform @@ -854,9 +854,9 @@ namespace EMotionFX m_motion->CalcNodeTransform(this, &oldNodeTransform, actor, rootNode, oldTime, GetRetargetingEnabled()); // calculate the relative transforms - outTransform->mPosition = curNodeTransform.mPosition - oldNodeTransform.mPosition; - outTransform->mRotation = curNodeTransform.mRotation * oldNodeTransform.mRotation.GetConjugate(); - outTransform->mRotation.Normalize(); + outTransform->m_position = curNodeTransform.m_position - oldNodeTransform.m_position; + outTransform->m_rotation = curNodeTransform.m_rotation * oldNodeTransform.m_rotation.GetConjugate(); + outTransform->m_rotation.Normalize(); } // extract the motion delta transform @@ -879,7 +879,7 @@ namespace EMotionFX } // get the motion extraction node index - const AZ::u32 motionExtractionNodeIndex = motionExtractNode->GetNodeIndex(); + const size_t motionExtractionNodeIndex = motionExtractNode->GetNodeIndex(); // get the current and previous time value from the motion instance float curTimeValue = GetCurrentTime(); @@ -916,8 +916,8 @@ namespace EMotionFX } // add the relative transform to the final values - trajectoryDelta.mPosition += relativeTrajectoryTransform.mPosition; - trajectoryDelta.mRotation = relativeTrajectoryTransform.mRotation * trajectoryDelta.mRotation; + trajectoryDelta.m_position += relativeTrajectoryTransform.m_position; + trajectoryDelta.m_rotation = relativeTrajectoryTransform.m_rotation * trajectoryDelta.m_rotation; } // calculate the relative movement @@ -925,8 +925,8 @@ namespace EMotionFX CalcRelativeTransform(motionExtractNode, curTimeValue, oldTimeValue, &relativeTrajectoryTransform); // add the relative transform to the final values - trajectoryDelta.mPosition += relativeTrajectoryTransform.mPosition; - trajectoryDelta.mRotation = relativeTrajectoryTransform.mRotation * trajectoryDelta.mRotation; + trajectoryDelta.m_position += relativeTrajectoryTransform.m_position; + trajectoryDelta.m_rotation = relativeTrajectoryTransform.m_rotation * trajectoryDelta.m_rotation; } // if not paused @@ -941,8 +941,8 @@ namespace EMotionFX // Calculate the difference between the first frame of the motion and the bind pose transform. TransformData* transformData = m_actorInstance->GetTransformData(); const Pose* bindPose = transformData->GetBindPose(); - AZ::Quaternion permBindPoseRotDiff = firstFrameTransform.mRotation * bindPose->GetLocalSpaceTransform(motionExtractionNodeIndex).mRotation.GetConjugate(); - AZ::Vector3 permBindPosePosDiff = bindPose->GetLocalSpaceTransform(motionExtractionNodeIndex).mPosition - firstFrameTransform.mPosition; + AZ::Quaternion permBindPoseRotDiff = firstFrameTransform.m_rotation * bindPose->GetLocalSpaceTransform(motionExtractionNodeIndex).m_rotation.GetConjugate(); + AZ::Vector3 permBindPosePosDiff = bindPose->GetLocalSpaceTransform(motionExtractionNodeIndex).m_position - firstFrameTransform.m_position; permBindPoseRotDiff.SetX(0.0f); permBindPoseRotDiff.SetY(0.0f); permBindPoseRotDiff.Normalize(); @@ -964,22 +964,22 @@ namespace EMotionFX // Capture rotation around the up axis only. trajectoryDelta.ApplyMotionExtractionFlags(m_motion->GetMotionExtractionFlags()); - AZ::Quaternion removeRot = currentFrameTransform.mRotation * firstFrameTransform.mRotation.GetConjugate(); + AZ::Quaternion removeRot = currentFrameTransform.m_rotation * firstFrameTransform.m_rotation.GetConjugate(); removeRot.SetX(0.0f); removeRot.SetY(0.0f); removeRot.Normalize(); - AZ::Quaternion rotation = removeRot.GetConjugate() * trajectoryDelta.mRotation * permBindPoseRotDiff.GetConjugate(); + AZ::Quaternion rotation = removeRot.GetConjugate() * trajectoryDelta.m_rotation * permBindPoseRotDiff.GetConjugate(); rotation.SetX(0.0f); rotation.SetY(0.0f); rotation.Normalize(); - AZ::Vector3 rotatedPos = rotation.TransformVector(trajectoryDelta.mPosition - bindPosePosDiff); + AZ::Vector3 rotatedPos = rotation.TransformVector(trajectoryDelta.m_position - bindPosePosDiff); // Calculate the real trajectory delta, taking into account the actor instance rotation. - outTrajectoryDelta.mPosition = m_actorInstance->GetLocalSpaceTransform().mRotation.TransformVector(rotatedPos); - outTrajectoryDelta.mRotation = trajectoryDelta.mRotation * bindPoseRotDiff; - outTrajectoryDelta.mRotation.Normalize(); + outTrajectoryDelta.m_position = m_actorInstance->GetLocalSpaceTransform().m_rotation.TransformVector(rotatedPos); + outTrajectoryDelta.m_rotation = trajectoryDelta.m_rotation * bindPoseRotDiff; + outTrajectoryDelta.m_rotation.Normalize(); if (m_boolFlags & MotionInstance::BOOL_ISFIRSTREPOSUPDATE) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h index 5c7ed822e3..f41cf29c79 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstance.h @@ -120,7 +120,7 @@ namespace EMotionFX * Get the blend in time. * This is the time passed to the SetWeight(...) method where when the target weight is bigger than the current. * So only blend ins are counted and not blending out towards for example a weight of 0. - * When you never call SetWeight(...) yourself, this means that this will contain the value specificied to PlayBackInfo::mBlendInTime + * When you never call SetWeight(...) yourself, this means that this will contain the value specificied to PlayBackInfo::m_blendInTime * at the time of MotionSystem::PlayMotion(...). * @result The blend-in time, in seconds. */ @@ -696,13 +696,13 @@ namespace EMotionFX * Get the event handler at the given index. * @result A pointer to the event handler at the given index. */ - MotionInstanceEventHandler* GetEventHandler(AZ::u32 index) const; + MotionInstanceEventHandler* GetEventHandler(size_t index) const; /** * Get the number of event handlers. * @result The number of event handlers assigned to the motion instance. */ - AZ::u32 GetNumEventHandlers() const; + size_t GetNumEventHandlers() const; //-------------------------------- @@ -803,7 +803,7 @@ namespace EMotionFX /** * This event gets triggered once the given motion instance gets added to the motion queue. - * This happens when you set the PlayBackInfo::mPlayNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) + * This happens when you set the PlayBackInfo::m_playNow member to false. In that case the MotionSystem::PlayMotion() method (OnPlayMotion) * will not directly start playing the motion (OnStartMotionInstance), but will add it to the motion queue instead. * The motion queue will then start playing the motion instance once it should. * @param info The playback information used to play this motion instance. @@ -821,7 +821,7 @@ namespace EMotionFX void CalcRelativeTransform(Node* rootNode, float curTime, float oldTime, Transform* outTransform) const; bool ExtractMotion(Transform& outTrajectoryDelta); - void CalcGlobalTransform(const MCore::Array& hierarchyPath, float timeValue, Transform* outTransform) const; + void CalcGlobalTransform(const AZStd::vector& hierarchyPath, float timeValue, Transform* outTransform) const; void ResetTimes(); AZ_DEPRECATED(void CalcNewTimeAfterUpdate(float timePassed, float* outNewTime) const, "MotionInstance::CalcNewTimeAfterUpdate has been deprecated, please use MotionInstance::CalcPlayStateAfterUpdate(timeDelta).m_currentTime instead."); @@ -885,17 +885,17 @@ namespace EMotionFX AZStd::vector m_eventHandlersByEventType; /**< The event handler to use to process events organized by EventTypes. */ float m_currentTime = 0.0f; /**< The current playtime. */ float m_timeDiffToEnd = 0.0f; /**< The time it takes until we reach the loop point in the motion. This also takes the playback direction into account (backward or forward play). */ - float m_freezeAtTime = -1.0f; /**< Freeze at a given time offset in seconds. The current play time would continue running though, and a blend out would be triggered, unlike the mFreezeAtLastFrame. Set to negative value to disable. Default=-1.*/ + float m_freezeAtTime = -1.0f; /**< Freeze at a given time offset in seconds. The current play time would continue running though, and a blend out would be triggered, unlike the m_freezeAtLastFrame. Set to negative value to disable. Default=-1.*/ float m_playSpeed = 1.0f; /**< The playspeed (1.0=normal speed). */ float m_lastCurTime = 0.0f; /**< The last current time, so the current time in the previous update. */ float m_totalPlayTime = 0.0f; /**< The current total play time that this motion is already playing. */ - float m_maxPlayTime = 0.0f; /**< The maximum play time of the motion. If the mTotalPlayTime is higher than this, the motion will be stopped, unless the max play time is zero or negative. */ + float m_maxPlayTime = 0.0f; /**< The maximum play time of the motion. If the m_totalPlayTime is higher than this, the motion will be stopped, unless the max play time is zero or negative. */ float m_eventWeightThreshold = 0.0f; /**< If the weight of the motion instance is below this value, the events won't get processed (default = 0.0f). */ float m_weight = 0.0f; /**< The current weight value, in range of [0..1]. */ float m_weightDelta = 0.0f; /**< The precalculated weight delta value, used during blending between weights. */ float m_targetWeight = 1.0f; /**< The target weight of the layer, when activating the motion. */ float m_blendInTime = 0.0f; /**< The blend in time. */ - float m_fadeTime = 0.3f; /**< Fadeout speed, when playing the animation once. So when it is done playing once, it will fade out in 'mFadeTime' seconds. */ + float m_fadeTime = 0.3f; /**< Fadeout speed, when playing the animation once. So when it is done playing once, it will fade out in 'm_fadeTime' seconds. */ AZ::u32 m_curLoops = 0; /**< Number of loops it currently has made (so the number of times the motion played already). */ AZ::u32 m_maxLoops = EMFX_LOOPFOREVER; /**< The maximum number of loops, before it has to stop. */ AZ::u32 m_lastLoops = 0; /**< The current number of loops in the previous update. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp index 0277843cf9..3a9d7b94b9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp @@ -20,9 +20,9 @@ namespace EMotionFX // constructor MotionInstancePool::SubPool::SubPool() - : mData(nullptr) - , mNumInstances(0) - , mNumInUse(0) + : m_data(nullptr) + , m_numInstances(0) + , m_numInUse(0) { } @@ -30,8 +30,8 @@ namespace EMotionFX // destructor MotionInstancePool::SubPool::~SubPool() { - MCore::Free(mData); - mData = nullptr; + MCore::Free(m_data); + m_data = nullptr; } @@ -42,39 +42,36 @@ namespace EMotionFX // constructor MotionInstancePool::Pool::Pool() { - mFreeList.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL); - mSubPools.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL); - mPoolType = POOLTYPE_DYNAMIC; - mData = nullptr; - mNumInstances = 0; - mNumUsedInstances = 0; - mSubPoolSize = 0; + m_poolType = POOLTYPE_DYNAMIC; + m_data = nullptr; + m_numInstances = 0; + m_numUsedInstances = 0; + m_subPoolSize = 0; } // destructor MotionInstancePool::Pool::~Pool() { - if (mPoolType == POOLTYPE_STATIC) + if (m_poolType == POOLTYPE_STATIC) { - MCore::Free(mData); - mData = nullptr; - mFreeList.Clear(); + MCore::Free(m_data); + m_data = nullptr; + m_freeList.clear(); } else - if (mPoolType == POOLTYPE_DYNAMIC) + if (m_poolType == POOLTYPE_DYNAMIC) { - MCORE_ASSERT(mData == nullptr); + MCORE_ASSERT(m_data == nullptr); // delete all subpools - const uint32 numSubPools = mSubPools.GetLength(); - for (uint32 s = 0; s < numSubPools; ++s) + for (SubPool* subPool : m_subPools) { - delete mSubPools[s]; + delete subPool; } - mSubPools.Clear(); + m_subPools.clear(); - mFreeList.Clear(); + m_freeList.clear(); } else { @@ -92,19 +89,19 @@ namespace EMotionFX MotionInstancePool::MotionInstancePool() : BaseObject() { - mPool = nullptr; + m_pool = nullptr; } // destructor MotionInstancePool::~MotionInstancePool() { - if (mPool->mNumUsedInstances > 0) + if (m_pool->m_numUsedInstances > 0) { - MCore::LogError("EMotionFX::~MotionInstancePool() - There are still %d unfreed motion instances, please use the Free function in the MotionInstancePool to free them, just like you would delete the object.", mPool->mNumUsedInstances); + MCore::LogError("EMotionFX::~MotionInstancePool() - There are still %d unfreed motion instances, please use the Free function in the MotionInstancePool to free them, just like you would delete the object.", m_pool->m_numUsedInstances); } - delete mPool; + delete m_pool; } @@ -116,9 +113,9 @@ namespace EMotionFX // init the motion instance pool - void MotionInstancePool::Init(uint32 numInitialInstances, EPoolType poolType, uint32 subPoolSize) + void MotionInstancePool::Init(size_t numInitialInstances, EPoolType poolType, size_t subPoolSize) { - if (mPool) + if (m_pool) { MCore::LogError("EMotionFX::MotionInstancePool::Init() - We have already initialized the pool, ignoring new init call."); return; @@ -133,40 +130,40 @@ namespace EMotionFX } // create the subpool - mPool = new Pool(); - mPool->mNumInstances = numInitialInstances; - mPool->mPoolType = poolType; - mPool->mSubPoolSize = subPoolSize; + m_pool = new Pool(); + m_pool->m_numInstances = numInitialInstances; + m_pool->m_poolType = poolType; + m_pool->m_subPoolSize = subPoolSize; // if we have a static pool if (poolType == POOLTYPE_STATIC) { - mPool->mData = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space - mPool->mFreeList.ResizeFast(numInitialInstances); - for (uint32 i = 0; i < numInitialInstances; ++i) + m_pool->m_data = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space + m_pool->m_freeList.resize_no_construct(numInitialInstances); + for (size_t i = 0; i < numInitialInstances; ++i) { - void* memLocation = (void*)(mPool->mData + i * sizeof(MotionInstance)); - mPool->mFreeList[i].mAddress = memLocation; - mPool->mFreeList[i].mSubPool = nullptr; + void* memLocation = (void*)(m_pool->m_data + i * sizeof(MotionInstance)); + m_pool->m_freeList[i].m_address = memLocation; + m_pool->m_freeList[i].m_subPool = nullptr; } } else // if we have a dynamic pool if (poolType == POOLTYPE_DYNAMIC) { - mPool->mSubPools.Reserve(32); + m_pool->m_subPools.reserve(32); SubPool* subPool = new SubPool(); - subPool->mData = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space - subPool->mNumInstances = numInitialInstances; + subPool->m_data = (uint8*)MCore::Allocate(numInitialInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space + subPool->m_numInstances = numInitialInstances; - mPool->mFreeList.ResizeFast(numInitialInstances); - for (uint32 i = 0; i < numInitialInstances; ++i) + m_pool->m_freeList.resize_no_construct(numInitialInstances); + for (size_t i = 0; i < numInitialInstances; ++i) { - mPool->mFreeList[i].mAddress = (void*)(subPool->mData + i * sizeof(MotionInstance)); - mPool->mFreeList[i].mSubPool = subPool; + m_pool->m_freeList[i].m_address = (void*)(subPool->m_data + i * sizeof(MotionInstance)); + m_pool->m_freeList[i].m_subPool = subPool; } - mPool->mSubPools.Add(subPool); + m_pool->m_subPools.emplace_back(subPool); } else { @@ -179,69 +176,68 @@ namespace EMotionFX MotionInstance* MotionInstancePool::RequestNewWithoutLock(Motion* motion, ActorInstance* actorInstance) { // check if we already initialized - if (mPool == nullptr) + if (m_pool == nullptr) { MCore::LogWarning("EMotionFX::MotionInstancePool::RequestNew() - We have not yet initialized the pool, initializing it to a dynamic pool"); Init(); } // if there is are free items left - if (mPool->mFreeList.GetLength() > 0) + if (m_pool->m_freeList.size() > 0) { - const MemLocation& location = mPool->mFreeList.GetLast(); - MotionInstance* result = MotionInstance::Create(location.mAddress, motion, actorInstance); + const MemLocation& location = m_pool->m_freeList.back(); + MotionInstance* result = MotionInstance::Create(location.m_address, motion, actorInstance); - if (location.mSubPool) + if (location.m_subPool) { - location.mSubPool->mNumInUse++; + location.m_subPool->m_numInUse++; } - result->SetSubPool(location.mSubPool); + result->SetSubPool(location.m_subPool); - mPool->mFreeList.RemoveLast(); // remove it from the free list - mPool->mNumUsedInstances++; + m_pool->m_freeList.pop_back(); // remove it from the free list + m_pool->m_numUsedInstances++; return result; } // we have no more free attributes left - if (mPool->mPoolType == POOLTYPE_DYNAMIC) // we're dynamic, so we can just create new ones + if (m_pool->m_poolType == POOLTYPE_DYNAMIC) // we're dynamic, so we can just create new ones { - const uint32 numInstances = mPool->mSubPoolSize; - mPool->mNumInstances += numInstances; + const size_t numInstances = m_pool->m_subPoolSize; + m_pool->m_numInstances += numInstances; SubPool* subPool = new SubPool(); - subPool->mData = (uint8*)MCore::Allocate(numInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space - subPool->mNumInstances = numInstances; + subPool->m_data = (uint8*)MCore::Allocate(numInstances * sizeof(MotionInstance), EMFX_MEMCATEGORY_MOTIONINSTANCEPOOL);// alloc space + subPool->m_numInstances = numInstances; - const uint32 startIndex = mPool->mFreeList.GetLength(); - //mPool->mFreeList.Reserve( numInstances * 2 ); - if (mPool->mFreeList.GetMaxLength() < mPool->mNumInstances) + const size_t startIndex = m_pool->m_freeList.size(); + if (m_pool->m_freeList.capacity() < m_pool->m_numInstances) { - mPool->mFreeList.Reserve(mPool->mNumInstances + mPool->mFreeList.GetMaxLength() / 2); + m_pool->m_freeList.reserve(m_pool->m_numInstances + m_pool->m_freeList.capacity() / 2); } - mPool->mFreeList.ResizeFast(startIndex + numInstances); - for (uint32 i = 0; i < numInstances; ++i) + m_pool->m_freeList.resize_no_construct(startIndex + numInstances); + for (size_t i = 0; i < numInstances; ++i) { - void* memAddress = (void*)(subPool->mData + i * sizeof(MotionInstance)); - mPool->mFreeList[i + startIndex].mAddress = memAddress; - mPool->mFreeList[i + startIndex].mSubPool = subPool; + void* memAddress = (void*)(subPool->m_data + i * sizeof(MotionInstance)); + m_pool->m_freeList[i + startIndex].m_address = memAddress; + m_pool->m_freeList[i + startIndex].m_subPool = subPool; } - mPool->mSubPools.Add(subPool); + m_pool->m_subPools.emplace_back(subPool); - const MemLocation& location = mPool->mFreeList.GetLast(); - MotionInstance* result = MotionInstance::Create(location.mAddress, motion, actorInstance); - if (location.mSubPool) + const MemLocation& location = m_pool->m_freeList.back(); + MotionInstance* result = MotionInstance::Create(location.m_address, motion, actorInstance); + if (location.m_subPool) { - location.mSubPool->mNumInUse++; + location.m_subPool->m_numInUse++; } - result->SetSubPool(location.mSubPool); - mPool->mFreeList.RemoveLast(); // remove it from the free list - mPool->mNumUsedInstances++; + result->SetSubPool(location.m_subPool); + m_pool->m_freeList.pop_back(); // remove it from the free list + m_pool->m_numUsedInstances++; return result; } else // we are static and ran out of free attributes - if (mPool->mPoolType == POOLTYPE_STATIC) + if (m_pool->m_poolType == POOLTYPE_STATIC) { MCore::LogError("EMotionFX::MotionInstancePool::RequestNew() - There are no free motion instance in the static pool. Please increase the size of the pool or make it dynamic when calling Init."); MCORE_ASSERT(false); // we ran out of free motion instances @@ -263,7 +259,7 @@ namespace EMotionFX return; } - if (mPool == nullptr) + if (m_pool == nullptr) { MCore::LogWarning("EMotionFX::MotionInstancePool::Free() - The pool has not yet been initialized, please call Init first."); MCORE_ASSERT(false); @@ -273,13 +269,13 @@ namespace EMotionFX // add it back to the free list if (motionInstance->GetSubPool()) { - motionInstance->GetSubPool()->mNumInUse--; + motionInstance->GetSubPool()->m_numInUse--; } - mPool->mFreeList.AddEmpty(); - mPool->mFreeList.GetLast().mAddress = motionInstance; - mPool->mFreeList.GetLast().mSubPool = motionInstance->GetSubPool(); - mPool->mNumUsedInstances--; + m_pool->m_freeList.emplace_back(); + m_pool->m_freeList.back().m_address = motionInstance; + m_pool->m_freeList.back().m_subPool = motionInstance->GetSubPool(); + m_pool->m_numUsedInstances--; motionInstance->DecreaseReferenceCount(); motionInstance->~MotionInstance(); // call the destructor @@ -292,27 +288,27 @@ namespace EMotionFX Lock(); MCore::LogInfo("EMotionFX::MotionInstancePool::LogMemoryStats() - Logging motion instance pool info"); - const uint32 numFree = mPool->mFreeList.GetLength(); - uint32 numUsed = mPool->mNumUsedInstances; - uint32 memUsage = 0; - uint32 usedMemUsage = 0; - uint32 totalMemUsage = 0; - uint32 totalUsedInstancesMemUsage = 0; + const size_t numFree = m_pool->m_freeList.size(); + size_t numUsed = m_pool->m_numUsedInstances; + size_t memUsage = 0; + size_t usedMemUsage = 0; + size_t totalMemUsage = 0; + size_t totalUsedInstancesMemUsage = 0; - if (mPool->mPoolType == POOLTYPE_STATIC) + if (m_pool->m_poolType == POOLTYPE_STATIC) { - if (mPool->mNumInstances > 0) + if (m_pool->m_numInstances > 0) { - memUsage = mPool->mNumInstances * sizeof(MotionInstance); + memUsage = m_pool->m_numInstances * sizeof(MotionInstance); usedMemUsage = numUsed * sizeof(MotionInstance); } } else - if (mPool->mPoolType == POOLTYPE_DYNAMIC) + if (m_pool->m_poolType == POOLTYPE_DYNAMIC) { - if (mPool->mNumInstances > 0) + if (m_pool->m_numInstances > 0) { - memUsage = mPool->mNumInstances * sizeof(MotionInstance); + memUsage = m_pool->m_numInstances * sizeof(MotionInstance); usedMemUsage = numUsed * sizeof(MotionInstance); } } @@ -320,17 +316,17 @@ namespace EMotionFX totalUsedInstancesMemUsage += usedMemUsage; totalMemUsage += memUsage; totalMemUsage += sizeof(Pool); - totalMemUsage += mPool->mFreeList.CalcMemoryUsage(false); + totalMemUsage += m_pool->m_freeList.capacity() * sizeof(decltype(m_pool->m_freeList)::value_type); MCore::LogInfo("Pool:"); - if (mPool->mPoolType == POOLTYPE_DYNAMIC) + if (m_pool->m_poolType == POOLTYPE_DYNAMIC) { - MCore::LogInfo(" - Num SubPools: %d", mPool->mSubPools.GetLength()); + MCore::LogInfo(" - Num SubPools: %d", m_pool->m_subPools.size()); } - MCore::LogInfo(" - Num Instances: %d", mPool->mNumInstances); + MCore::LogInfo(" - Num Instances: %d", m_pool->m_numInstances); MCore::LogInfo(" - Num Free: %d", numFree); MCore::LogInfo(" - Num Used: %d", numUsed); - MCore::LogInfo(" - PoolType: %s", (mPool->mPoolType == POOLTYPE_STATIC) ? "Static" : "Dynamic"); + MCore::LogInfo(" - PoolType: %s", (m_pool->m_poolType == POOLTYPE_STATIC) ? "Static" : "Dynamic"); MCore::LogInfo(" - Total Instances Mem: %d bytes (%d k)", memUsage, memUsage / 1000); MCore::LogInfo(" - Used Instances Mem: %d (%d k)", totalUsedInstancesMemUsage, totalUsedInstancesMemUsage / 1000); MCore::LogInfo(" - Total Mem Usage: %d (%d k)", totalMemUsage, totalMemUsage / 1000); @@ -361,14 +357,14 @@ namespace EMotionFX // wait with execution until we can set the lock void MotionInstancePool::Lock() { - mLock.Lock(); + m_lock.Lock(); } // release the lock again void MotionInstancePool::Unlock() { - mLock.Unlock(); + m_lock.Unlock(); } @@ -377,26 +373,26 @@ namespace EMotionFX { Lock(); - for (uint32 i = 0; i < mPool->mSubPools.GetLength(); ) + for (size_t i = 0; i < m_pool->m_subPools.size(); ) { - SubPool* subPool = mPool->mSubPools[i]; - if (subPool->mNumInUse == 0) + SubPool* subPool = m_pool->m_subPools[i]; + if (subPool->m_numInUse == 0) { // remove all free allocations - for (uint32 a = 0; a < mPool->mFreeList.GetLength(); ) + for (size_t a = 0; a < m_pool->m_freeList.size(); ) { - if (mPool->mFreeList[a].mSubPool == subPool) + if (m_pool->m_freeList[a].m_subPool == subPool) { - mPool->mFreeList.Remove(a); + m_pool->m_freeList.erase(AZStd::next(begin(m_pool->m_freeList), a)); } else { ++a; } } - mPool->mNumInstances -= subPool->mNumInstances; + m_pool->m_numInstances -= subPool->m_numInstances; - mPool->mSubPools.Remove(i); + m_pool->m_subPools.erase(AZStd::next(begin(m_pool->m_subPools), i)); delete subPool; } else @@ -405,11 +401,10 @@ namespace EMotionFX } } - mPool->mSubPools.Shrink(); - //mPool->mFreeList.Shrink(); - if ((mPool->mFreeList.GetMaxLength() - mPool->mFreeList.GetLength()) > 4096) + m_pool->m_subPools.shrink_to_fit(); + if ((m_pool->m_freeList.capacity() - m_pool->m_freeList.size()) > 4096) { - mPool->mFreeList.ReserveExact(mPool->mFreeList.GetLength() + 4096); + m_pool->m_freeList.reserve(m_pool->m_freeList.size() + 4096); } Unlock(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h index 0fd658915e..54837a1113 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.h @@ -11,7 +11,7 @@ // include the required headers #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include #include @@ -41,7 +41,7 @@ namespace EMotionFX static MotionInstancePool* Create(); - void Init(uint32 numInitialInstances = 256, EPoolType poolType = POOLTYPE_DYNAMIC, uint32 subPoolSize = 512); // auto called on EMotion FX init + void Init(size_t numInitialInstances = 256, EPoolType poolType = POOLTYPE_DYNAMIC, size_t subPoolSize = 512); // auto called on EMotion FX init // with lock MotionInstance* RequestNew(Motion* motion, ActorInstance* actorInstance); @@ -68,15 +68,15 @@ namespace EMotionFX SubPool(); ~SubPool(); - uint8* mData; - uint32 mNumInstances; - uint32 mNumInUse; + uint8* m_data; + size_t m_numInstances; + size_t m_numInUse; }; struct EMFX_API MemLocation { - void* mAddress; - SubPool* mSubPool; + void* m_address; + SubPool* m_subPool; }; class EMFX_API Pool @@ -87,17 +87,17 @@ namespace EMotionFX Pool(); ~Pool(); - uint8* mData; - uint32 mNumInstances; - uint32 mNumUsedInstances; - uint32 mSubPoolSize; - MCore::Array mFreeList; - MCore::Array mSubPools; - EPoolType mPoolType; + uint8* m_data; + size_t m_numInstances; + size_t m_numUsedInstances; + size_t m_subPoolSize; + AZStd::vector m_freeList; + AZStd::vector m_subPools; + EPoolType m_poolType; }; - Pool* mPool; - MCore::Mutex mLock; + Pool* m_pool; + MCore::Mutex m_lock; MotionInstancePool(); ~MotionInstancePool(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp index 14e6b582b4..dddfd1eba8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -22,10 +23,8 @@ namespace EMotionFX MotionLayerSystem::MotionLayerSystem(ActorInstance* actorInstance) : MotionSystem(actorInstance) { - mLayerPasses.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONSYSTEMS); - // set the motion based actor repositioning layer pass - mRepositioningPass = RepositioningLayerPass::Create(this); + m_repositioningPass = RepositioningLayerPass::Create(this); } @@ -35,7 +34,7 @@ namespace EMotionFX RemoveAllLayerPasses(); // get rid of the repositioning layer pass - mRepositioningPass->Destroy(); + m_repositioningPass->Destroy(); } @@ -50,16 +49,15 @@ namespace EMotionFX void MotionLayerSystem::RemoveAllLayerPasses(bool delFromMem) { // delete all layer passes - const uint32 numLayerPasses = mLayerPasses.GetLength(); - for (uint32 i = 0; i < numLayerPasses; ++i) + for (LayerPass* layerPass : m_layerPasses) { if (delFromMem) { - mLayerPasses[i]->Destroy(); + layerPass->Destroy(); } } - mLayerPasses.Clear(); + m_layerPasses.clear(); } @@ -67,23 +65,23 @@ namespace EMotionFX void MotionLayerSystem::StartMotion(MotionInstance* motion, PlayBackInfo* info) { // check if we have any motions playing already - const uint32 numMotionInstances = mMotionInstances.GetLength(); + const size_t numMotionInstances = m_motionInstances.size(); if (numMotionInstances > 0) { // find the right location in the motion instance array to insert this motion instance - uint32 insertPos = FindInsertPos(motion->GetPriorityLevel()); - if (insertPos != MCORE_INVALIDINDEX32) + size_t insertPos = FindInsertPos(motion->GetPriorityLevel()); + if (insertPos != InvalidIndex) { - mMotionInstances.Insert(insertPos, motion); + m_motionInstances.emplace(AZStd::next(begin(m_motionInstances), insertPos), motion); } else { - mMotionInstances.Add(motion); + m_motionInstances.emplace_back(motion); } } else // no motions are playing, so just add it { - mMotionInstances.Add(motion); + m_motionInstances.emplace_back(motion); } // trigger an event @@ -94,23 +92,18 @@ namespace EMotionFX motion->SetIsActive(true); // start the blend - motion->SetWeight(info->mTargetWeight, info->mBlendInTime); + motion->SetWeight(info->m_targetWeight, info->m_blendInTime); } // find the location where to insert a new motion with a given priority - uint32 MotionLayerSystem::FindInsertPos(uint32 priorityLevel) const + size_t MotionLayerSystem::FindInsertPos(size_t priorityLevel) const { - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) + const auto* foundInsertPosition = AZStd::lower_bound(begin(m_motionInstances), end(m_motionInstances), priorityLevel, [](const MotionInstance* motionInstance, size_t level) { - if (mMotionInstances[i]->GetPriorityLevel() <= priorityLevel) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motionInstance->GetPriorityLevel() < level; + }); + return foundInsertPosition != end(m_motionInstances) ? AZStd::distance(begin(m_motionInstances), foundInsertPosition) : InvalidIndex; } @@ -124,23 +117,22 @@ namespace EMotionFX UpdateMotionTree(); // update the motion queue - mMotionQueue->Update(); + m_motionQueue->Update(); // process all layer passes - const uint32 numPasses = mLayerPasses.GetLength(); - for (uint32 i = 0; i < numPasses; ++i) + for (LayerPass* layerPass : m_layerPasses) { - mLayerPasses[i]->Process(); + layerPass->Process(); } // process the repositioning as last - if (mRepositioningPass) + if (m_repositioningPass) { - mRepositioningPass->Process(); + m_repositioningPass->Process(); } // update the global transform now that we have an updated local transform of the actor instance itself (modified by motion extraction for example) - mActorInstance->UpdateWorldTransform(); + m_actorInstance->UpdateWorldTransform(); // if we need to update the node transforms because the character is visible if (updateNodes) @@ -153,9 +145,9 @@ namespace EMotionFX // update the motion tree void MotionLayerSystem::UpdateMotionTree() { - for (uint32 i = 0; i < mMotionInstances.GetLength(); ++i) + for (size_t i = 0; i < m_motionInstances.size(); ++i) { - MotionInstance* source = mMotionInstances[i]; + MotionInstance* source = m_motionInstances[i]; // if we aren't stopping this motion yet if (!source->GetIsStopping()) @@ -235,10 +227,10 @@ namespace EMotionFX if (source->GetCanOverwrite()) { // remove all motions that got overwritten by the current one - const uint32 numToRemove = mMotionInstances.GetLength() - (i + 1); - for (uint32 a = 0; a < numToRemove; ++a) + const size_t numToRemove = m_motionInstances.size() - (i + 1); + for (size_t a = 0; a < numToRemove; ++a) { - RemoveMotionInstance(mMotionInstances[i + 1]); + RemoveMotionInstance(m_motionInstances[i + 1]); } } } @@ -248,14 +240,14 @@ namespace EMotionFX // remove all layers below a given layer - uint32 MotionLayerSystem::RemoveLayersBelow(MotionInstance* source) + size_t MotionLayerSystem::RemoveLayersBelow(MotionInstance* source) { - uint32 numRemoved = 0; + size_t numRemoved = 0; // start from the bottom up - for (uint32 i = mMotionInstances.GetLength() - 1; i != MCORE_INVALIDINDEX32;) + for (auto iter = rbegin(m_motionInstances); iter != rend(m_motionInstances); ++iter) { - MotionInstance* curInstance = mMotionInstances[i]; + MotionInstance* curInstance = *iter; // if we reached the current motion instance we are done if (curInstance == source) @@ -265,7 +257,6 @@ namespace EMotionFX numRemoved++; RemoveMotionInstance(curInstance); - i--; } return numRemoved; @@ -276,21 +267,11 @@ namespace EMotionFX MotionInstance* MotionLayerSystem::FindFirstNonMixingMotionInstance() const { // if there aren't any motion instances, return nullptr - const uint32 numInstances = mMotionInstances.GetLength(); - if (numInstances == 0) - { - return nullptr; - } - - for (uint32 i = 0; i < numInstances; ++i) + const auto foundMotionInstance = AZStd::find_if(begin(m_motionInstances), end(m_motionInstances), [](const MotionInstance* motionInstance) { - if (mMotionInstances[i]->GetIsMixing() == false) - { - return mMotionInstances[i]; - } - } - - return nullptr; + return !motionInstance->GetIsMixing(); + }); + return foundMotionInstance != end(m_motionInstances) ? *foundMotionInstance : nullptr; } @@ -298,28 +279,28 @@ namespace EMotionFX void MotionLayerSystem::UpdateNodes() { // get the two pose buffers we need - const uint32 threadIndex = mActorInstance->GetThreadIndex(); + const uint32 threadIndex = m_actorInstance->GetThreadIndex(); AnimGraphPosePool& posePool = GetEMotionFX().GetThreadData(threadIndex)->GetPosePool(); - AnimGraphPose* tempAnimGraphPose = posePool.RequestPose(mActorInstance); + AnimGraphPose* tempAnimGraphPose = posePool.RequestPose(m_actorInstance); - const bool motionExtractionEnabled = mActorInstance->GetMotionExtractionEnabled(); + const bool motionExtractionEnabled = m_actorInstance->GetMotionExtractionEnabled(); Pose* tempActorPose = &tempAnimGraphPose->GetPose(); - const uint32 numMotionInstances = mMotionInstances.GetLength(); + const size_t numMotionInstances = m_motionInstances.size(); if (numMotionInstances > 0) { if (numMotionInstances > 1) { - TransformData* transformData = mActorInstance->GetTransformData(); + TransformData* transformData = m_actorInstance->GetTransformData(); Pose* finalPose = transformData->GetCurrentPose(); - finalPose->InitFromBindPose(mActorInstance); + finalPose->InitFromBindPose(m_actorInstance); // blend the layers - for (uint32 i = numMotionInstances - 1; i != MCORE_INVALIDINDEX32; --i) + for (auto iter = rbegin(m_motionInstances); iter != rend(m_motionInstances); ++iter) { // skip inactive motion instances - MotionInstance* instance = mMotionInstances[i]; // the motion to be blended + MotionInstance* instance = *iter; // the motion to be blended if (instance->GetIsActive() == false || instance->GetWeight() < 0.0001f) { continue; @@ -341,12 +322,12 @@ namespace EMotionFX else // there is just one motion playing { // skip inactive motion instances - MotionInstance* instance = mMotionInstances[0]; // the motion to be blended + MotionInstance* instance = m_motionInstances[0]; // the motion to be blended if (instance->GetIsActive() && instance->GetWeight() >= 0.9999f) { - TransformData* transformData = mActorInstance->GetTransformData(); + TransformData* transformData = m_actorInstance->GetTransformData(); Pose* finalPose = transformData->GetCurrentPose(); - finalPose->InitFromBindPose(mActorInstance); + finalPose->InitFromBindPose(m_actorInstance); instance->GetMotion()->Update(finalPose, finalPose, instance); // output the results of the single motion @@ -359,15 +340,15 @@ namespace EMotionFX else if (instance->GetIsActive() && instance->GetWeight() < 0.0001f) // almost not active { - TransformData* transformData = mActorInstance->GetTransformData(); - transformData->GetCurrentPose()->InitFromBindPose(mActorInstance); + TransformData* transformData = m_actorInstance->GetTransformData(); + transformData->GetCurrentPose()->InitFromBindPose(m_actorInstance); } else // semi active { - TransformData* transformData = mActorInstance->GetTransformData(); + TransformData* transformData = m_actorInstance->GetTransformData(); Pose* finalPose = transformData->GetCurrentPose(); - finalPose->InitFromBindPose(mActorInstance); + finalPose->InitFromBindPose(m_actorInstance); instance->GetMotion()->Update(finalPose, tempActorPose, instance); // output the results of the single motion // compensate for motion extraction @@ -384,8 +365,8 @@ namespace EMotionFX else // no motion playing { // update all node transforms - TransformData* transformData = mActorInstance->GetTransformData(); - transformData->GetCurrentPose()->InitFromBindPose(mActorInstance); + TransformData* transformData = m_actorInstance->GetTransformData(); + transformData->GetCurrentPose()->InitFromBindPose(m_actorInstance); } // free the poses back to the pool @@ -396,33 +377,36 @@ namespace EMotionFX // add a new pass void MotionLayerSystem::AddLayerPass(LayerPass* newPass) { - mLayerPasses.Add(newPass); + m_layerPasses.emplace_back(newPass); } // get the number of layer passes - uint32 MotionLayerSystem::GetNumLayerPasses() const + size_t MotionLayerSystem::GetNumLayerPasses() const { - return mLayerPasses.GetLength(); + return m_layerPasses.size(); } // remove a given pass - void MotionLayerSystem::RemoveLayerPass(uint32 nr, bool delFromMem) + void MotionLayerSystem::RemoveLayerPass(size_t nr, bool delFromMem) { if (delFromMem) { - mLayerPasses[nr]->Destroy(); + m_layerPasses[nr]->Destroy(); } - mLayerPasses.Remove(nr); + m_layerPasses.erase(AZStd::next(begin(m_layerPasses), nr)); } // remove a given pass void MotionLayerSystem::RemoveLayerPass(LayerPass* pass, bool delFromMem) { - mLayerPasses.RemoveByValue(pass); + if (const auto it = AZStd::find(begin(m_layerPasses), end(m_layerPasses), pass); it != end(m_layerPasses)) + { + m_layerPasses.erase(it); + } if (delFromMem) { @@ -432,9 +416,9 @@ namespace EMotionFX // insert a layer pass at a given position - void MotionLayerSystem::InsertLayerPass(uint32 insertPos, LayerPass* pass) + void MotionLayerSystem::InsertLayerPass(size_t insertPos, LayerPass* pass) { - mLayerPasses.Insert(insertPos, pass); + m_layerPasses.emplace(AZStd::next(begin(m_layerPasses), insertPos), pass); } @@ -455,17 +439,17 @@ namespace EMotionFX // remove the repositioning pass void MotionLayerSystem::RemoveRepositioningLayerPass() { - if (mRepositioningPass) + if (m_repositioningPass) { - mRepositioningPass->Destroy(); + m_repositioningPass->Destroy(); } - mRepositioningPass = nullptr; + m_repositioningPass = nullptr; } - LayerPass* MotionLayerSystem::GetLayerPass(uint32 index) const + LayerPass* MotionLayerSystem::GetLayerPass(size_t index) const { - return mLayerPasses[index]; + return m_layerPasses[index]; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h index ff4761d49c..81119977dd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionLayerSystem.h @@ -95,7 +95,7 @@ namespace EMotionFX * @param source The layer to remove all layers below from. So this does not remove the source layer itself. * @result Returns the number of removed layers. */ - uint32 RemoveLayersBelow(MotionInstance* source); + size_t RemoveLayersBelow(MotionInstance* source); /** * Update the motion tree. @@ -118,11 +118,11 @@ namespace EMotionFX /** * Find the location where to insert a motion layer with a given priority level. - * When MCORE_INVALIDINDEX32 is returned, it needs to be inserted at the bottom of the motion tree. + * When InvalidIndex is returned, it needs to be inserted at the bottom of the motion tree. * @param priorityLevel The priority level of the motion instance you want to insert. - * @result The insert pos in the list of motion instances, or MCORE_INVALIDINDEX32 when the new layer has to be inserted at the bottom of the tree. + * @result The insert pos in the list of motion instances, or InvalidIndex when the new layer has to be inserted at the bottom of the tree. */ - uint32 FindInsertPos(uint32 priorityLevel) const; + size_t FindInsertPos(size_t priorityLevel) const; /** * Remove all layer passes. @@ -140,14 +140,14 @@ namespace EMotionFX * Get the number of layer passes currently added to this motion layer system. * @result The number of layer passes. */ - uint32 GetNumLayerPasses() const; + size_t GetNumLayerPasses() const; /** * Remove a given layer pass by index. * @param nr The layer pass number to remove. * @param delFromMem When set to true, the layer passes will also be deleted from memory. */ - void RemoveLayerPass(uint32 nr, bool delFromMem = true); + void RemoveLayerPass(size_t nr, bool delFromMem = true); /** * Remove a given layer pass by pointer. @@ -161,7 +161,7 @@ namespace EMotionFX * @param insertPos The index position to insert the layer pass. * @param pass The layer pass to insert. */ - void InsertLayerPass(uint32 insertPos, LayerPass* pass); + void InsertLayerPass(size_t insertPos, LayerPass* pass); /** * Deletes the motion based actor repositioning layer pass, which is always there on default. @@ -175,12 +175,12 @@ namespace EMotionFX * @param index The layer pass number, which must be in range of [0..GetNumLayerPasses()-1]. * @result A pointer to the layer pass object. */ - LayerPass* GetLayerPass(uint32 index) const; + LayerPass* GetLayerPass(size_t index) const; private: - MCore::Array mLayerPasses; /**< The layer passes. */ - RepositioningLayerPass* mRepositioningPass; /**< The motion based actor repositioning layer pass. */ + AZStd::vector m_layerPasses; /**< The layer passes. */ + RepositioningLayerPass* m_repositioningPass; /**< The motion based actor repositioning layer pass. */ /** * Constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp index 13ac1956fa..5ed15fe896 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.cpp @@ -29,7 +29,7 @@ #include #include #include -#include +#include #include @@ -42,11 +42,8 @@ namespace EMotionFX MotionManager::MotionManager() : BaseObject() { - mMotions.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONMANAGER); - mMotionSets.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONMANAGER); - // reserve space for 400 motions - mMotions.Reserve(400); + m_motions.reserve(400); m_motionDataFactory = aznew MotionDataFactory(); } @@ -69,28 +66,28 @@ namespace EMotionFX if (delFromMemory) { // destroy all motion sets, they will internally call RemoveMotionSetWithoutLock(this) in their destructor - while (mMotionSets.GetLength() > 0) + while (m_motionSets.size() > 0) { - delete mMotionSets[0]; + delete m_motionSets[0]; } // destroy all motions, they will internally call RemoveMotionWithoutLock(this) in their destructor - while (mMotions.GetLength() > 0) + while (m_motions.size() > 0) { - mMotions[0]->Destroy(); + m_motions[0]->Destroy(); } } else { // wait with execution until we can set the lock - mSetLock.Lock(); - mMotionSets.Clear(); - mSetLock.Unlock(); + m_setLock.Lock(); + m_motionSets.clear(); + m_setLock.Unlock(); // clear the arrays without destroying the memory of the entries - mLock.Lock(); - mMotions.Clear(); - mLock.Unlock(); + m_lock.Lock(); + m_motions.clear(); + m_lock.Unlock(); } } @@ -98,245 +95,137 @@ namespace EMotionFX // find the motion and return a pointer, nullptr if the motion is not in Motion* MotionManager::FindMotionByName(const char* motionName, bool isTool) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [motionName, isTool](const auto& motion) { - if (mMotions[i]->GetIsOwnedByRuntime() == isTool) - { - continue; - } - - // compare the motion names - if (mMotions[i]->GetNameString() == motionName) - { - return mMotions[i]; - } - } - - return nullptr; + return motion->GetIsOwnedByRuntime() != isTool && motion->GetNameString() == motionName; + }); + return foundMotion != end(m_motions) ? *foundMotion : nullptr; } // find the motion and return a pointer, nullptr if the motion is not in Motion* MotionManager::FindMotionByFileName(const char* fileName, bool isTool) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [fileName, isTool](const auto& motion) { - if (mMotions[i]->GetIsOwnedByRuntime() == isTool) - { - continue; - } - - // compare the motion names - if (AzFramework::StringFunc::Equal(mMotions[i]->GetFileNameString().c_str(), fileName, false /* no case */)) - { - return mMotions[i]; - } - } - - return nullptr; + return motion->GetIsOwnedByRuntime() != isTool && + AzFramework::StringFunc::Equal(motion->GetFileNameString().c_str(), fileName, false /* no case */); + }); + return foundMotion != end(m_motions) ? *foundMotion : nullptr; } // find the motion set by filename and return a pointer, nullptr if the motion set is not in yet MotionSet* MotionManager::FindMotionSetByFileName(const char* fileName, bool isTool) const { - // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [fileName, isTool](const auto& motionSet) { - MotionSet* motionSet = mMotionSets[i]; - if (motionSet->GetIsOwnedByRuntime() == isTool) - { - continue; - } - - // compare the motion set filenames - if (AzFramework::StringFunc::Equal(motionSet->GetFilename(), fileName)) - { - return motionSet; - } - } - - return nullptr; + return motionSet->GetIsOwnedByRuntime() != isTool && + AzFramework::StringFunc::Equal(motionSet->GetFilename(), fileName); + }); + return foundMotionSet != end(m_motionSets) ? *foundMotionSet : nullptr; } // find the motion set and return a pointer, nullptr if the motion set has not been found MotionSet* MotionManager::FindMotionSetByName(const char* name, bool isOwnedByRuntime) const { - // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [name, isOwnedByRuntime](const auto& motionSet) { - MotionSet* motionSet = mMotionSets[i]; - - if (motionSet->GetIsOwnedByRuntime() == isOwnedByRuntime) - { - // compare the motion set names - if (AzFramework::StringFunc::Equal(motionSet->GetName(), name)) - { - return motionSet; - } - } - } - - return nullptr; + return motionSet->GetIsOwnedByRuntime() == isOwnedByRuntime && + AzFramework::StringFunc::Equal(motionSet->GetName(), name); + }); + return foundMotionSet != end(m_motionSets) ? *foundMotionSet : nullptr; } // find the motion index for the given motion - uint32 MotionManager::FindMotionIndexByName(const char* motionName, bool isTool) const + size_t MotionManager::FindMotionIndexByName(const char* motionName, bool isTool) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [motionName, isTool](const auto& motion) { - if (mMotions[i]->GetIsOwnedByRuntime() == isTool) - { - continue; - } - - // compare the motion names - if (mMotions[i]->GetNameString() == motionName) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motion->GetIsOwnedByRuntime() != isTool && motion->GetNameString() == motionName; + }); + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; } // find the motion set index for the given motion - uint32 MotionManager::FindMotionSetIndexByName(const char* name, bool isTool) const + size_t MotionManager::FindMotionSetIndexByName(const char* name, bool isTool) const { - // get the number of motions and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [name, isTool](const MotionSet* motionSet) { - MotionSet* motionSet = mMotionSets[i]; - - if (motionSet->GetIsOwnedByRuntime() == isTool) - { - continue; - } - - // compare the motion set names - if (AzFramework::StringFunc::Equal(motionSet->GetName(), name)) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motionSet->GetIsOwnedByRuntime() != isTool && + AzFramework::StringFunc::Equal(motionSet->GetName(), name); + }); + return foundMotionSet != end(m_motionSets) ? AZStd::distance(begin(m_motionSets), foundMotionSet) : InvalidIndex; } // find the motion index for the given motion - uint32 MotionManager::FindMotionIndexByID(uint32 id) const + size_t MotionManager::FindMotionIndexByID(uint32 id) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [id](const Motion* motion) { - if (mMotions[i]->GetID() == id) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motion->GetID() == id; + }); + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; + // get the number of motions and iterate through them } // find the motion set index - uint32 MotionManager::FindMotionSetIndexByID(uint32 id) const + size_t MotionManager::FindMotionSetIndexByID(uint32 id) const { - // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [id](const MotionSet* motionSet) { - // compare the motion names - if (mMotionSets[i]->GetID() == id) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motionSet->GetID() == id; + }); + return foundMotionSet != end(m_motionSets) ? AZStd::distance(begin(m_motionSets), foundMotionSet) : InvalidIndex; } // find the motion and return a pointer, nullptr if the motion is not in Motion* MotionManager::FindMotionByID(uint32 id) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [id](const Motion* motion) { - if (mMotions[i]->GetID() == id) - { - return mMotions[i]; - } - } - - return nullptr; + return motion->GetID() == id; + }); + return foundMotion != end(m_motions) ? *foundMotion : nullptr; } // find the motion set with the given and return it, nullptr if the motion set won't be found MotionSet* MotionManager::FindMotionSetByID(uint32 id) const { - // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [id](const MotionSet* motionSet) { - if (mMotionSets[i]->GetID() == id) - { - return mMotionSets[i]; - } - } - - return nullptr; + return motionSet->GetID() == id; + }); + return foundMotionSet != end(m_motionSets) ? *foundMotionSet : nullptr; } // find the motion set index and return it - uint32 MotionManager::FindMotionSetIndex(MotionSet* motionSet) const + size_t MotionManager::FindMotionSetIndex(MotionSet* motionSet) const { - // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + const auto foundMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [motionSet](const MotionSet* ms) { - if (mMotionSets[i] == motionSet) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return ms == motionSet; + }); + return foundMotionSet != end(m_motionSets) ? AZStd::distance(begin(m_motionSets), foundMotionSet) : InvalidIndex; } // find the motion index for the given motion - uint32 MotionManager::FindMotionIndex(Motion* motion) const + size_t MotionManager::FindMotionIndex(Motion* motion) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [motion](const Motion* m) { - // compare the motions - if (motion == mMotions[i]) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return m == motion; + }); + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; } @@ -344,16 +233,16 @@ namespace EMotionFX void MotionManager::AddMotion(Motion* motion) { // wait with execution until we can set the lock - mLock.Lock(); - mMotions.Add(motion); - mLock.Unlock(); + m_lock.Lock(); + m_motions.emplace_back(motion); + m_lock.Unlock(); } // find the motion based on the name and remove it bool MotionManager::RemoveMotionByName(const char* motionName, bool delFromMemory, bool isTool) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); return RemoveMotionWithoutLock(FindMotionIndexByName(motionName, isTool), delFromMemory); } @@ -361,7 +250,7 @@ namespace EMotionFX // find the motion set based on the name and remove it bool MotionManager::RemoveMotionSetByName(const char* motionName, bool delFromMemory, bool isTool) { - MCore::LockGuard lock(mSetLock); + MCore::LockGuard lock(m_setLock); return RemoveMotionSetWithoutLock(FindMotionSetIndexByName(motionName, isTool), delFromMemory); } @@ -369,7 +258,7 @@ namespace EMotionFX // find the motion based on the id and remove it bool MotionManager::RemoveMotionByID(uint32 id, bool delFromMemory) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); return RemoveMotionWithoutLock(FindMotionIndexByID(id), delFromMemory); } @@ -377,38 +266,26 @@ namespace EMotionFX // find the motion set based on the id and remove it bool MotionManager::RemoveMotionSetByID(uint32 id, bool delFromMemory) { - MCore::LockGuard lock(mSetLock); + MCore::LockGuard lock(m_setLock); return RemoveMotionSetWithoutLock(FindMotionSetIndexByID(id), delFromMemory); } // find the index by filename - uint32 MotionManager::FindMotionIndexByFileName(const char* fileName, bool isTool) const + size_t MotionManager::FindMotionIndexByFileName(const char* fileName, bool isTool) const { - // get the number of motions and iterate through them - const uint32 numMotions = mMotions.GetLength(); - for (uint32 i = 0; i < numMotions; ++i) + const auto foundMotion = AZStd::find_if(begin(m_motions), end(m_motions), [fileName, isTool](const Motion* motion) { - if (mMotions[i]->GetIsOwnedByRuntime() == isTool) - { - continue; - } - - // compare the motions - if (mMotions[i]->GetFileNameString() == fileName) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return motion->GetIsOwnedByRuntime() != isTool && motion->GetFileNameString() == fileName; + }); + return foundMotion != end(m_motions) ? AZStd::distance(begin(m_motions), foundMotion) : InvalidIndex; } // remove the motion by a given filename bool MotionManager::RemoveMotionByFileName(const char* fileName, bool delFromMemory, bool isTool) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); return RemoveMotionWithoutLock(FindMotionIndexByFileName(fileName, isTool), delFromMemory); } @@ -422,8 +299,8 @@ namespace EMotionFX AnimGraphInstance* animGraphInstance = animGraph->GetAnimGraphInstance(b); // reset all motion nodes that use this motion - const uint32 numNodes = animGraph->GetNumNodes(); - for (uint32 m = 0; m < numNodes; ++m) + const size_t numNodes = animGraph->GetNumNodes(); + for (size_t m = 0; m < numNodes; ++m) { AnimGraphNode* node = animGraph->GetNode(m); AnimGraphNodeData* uniqueData = static_cast(animGraphInstance->GetUniqueObjectData(node->GetObjectIndex())); @@ -437,7 +314,7 @@ namespace EMotionFX if (azrtti_istypeof(node)) { AnimGraphMotionNode::UniqueData* motionNodeData = static_cast(uniqueData); - const MotionInstance* motionInstance = motionNodeData->mMotionInstance; + const MotionInstance* motionInstance = motionNodeData->m_motionInstance; if (motionInstance && motionInstance->GetMotion() == motion) { motionNodeData->Reset(); @@ -456,26 +333,25 @@ namespace EMotionFX // remove the motion with the given index from the motion manager - bool MotionManager::RemoveMotionWithoutLock(uint32 index, bool delFromMemory) + bool MotionManager::RemoveMotionWithoutLock(size_t index, bool delFromMemory) { - if (index == MCORE_INVALIDINDEX32) + if (index == InvalidIndex) { return false; } - uint32 i; - Motion* motion = mMotions[index]; + Motion* motion = m_motions[index]; // stop all motion instances of the motion to delete - const uint32 numActorInstances = GetActorManager().GetNumActorInstances(); - for (i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { ActorInstance* actorInstance = GetActorManager().GetActorInstance(i); MotionSystem* motionSystem = actorInstance->GetMotionSystem(); MCORE_ASSERT(actorInstance->GetMotionSystem()); // instances and iterate through the motion instances - for (uint32 j = 0; j < motionSystem->GetNumMotionInstances(); ) + for (size_t j = 0; j < motionSystem->GetNumMotionInstances(); ) { MotionInstance* motionInstance = motionSystem->GetMotionInstance(j); @@ -494,11 +370,8 @@ namespace EMotionFX } // Reset all motion entries in the motion sets of the current motion. - const uint32 numMotionSets = mMotionSets.GetLength(); - for (i = 0; i < numMotionSets; ++i) + for (const MotionSet* motionSet : m_motionSets) { - MotionSet* motionSet = mMotionSets[i]; - const EMotionFX::MotionSet::MotionEntries& motionEntries = motionSet->GetMotionEntries(); for (const auto& item : motionEntries) { @@ -512,8 +385,8 @@ namespace EMotionFX } // stop all motion instances of the motion to delete inside the motion nodes and reset their unique data - const uint32 numAnimGraphs = GetAnimGraphManager().GetNumAnimGraphs(); - for (i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { AnimGraph* animGraph = GetAnimGraphManager().GetAnimGraph(i); ResetMotionNodes(animGraph, motion); @@ -525,11 +398,11 @@ namespace EMotionFX // which unregisters the motion from the motion manager motion->SetAutoUnregister(false); motion->Destroy(); - mMotions.Remove(index); // only remove the motion from the motion manager without destroying its memory + m_motions.erase(AZStd::next(begin(m_motions), index)); // only remove the motion from the motion manager without destroying its memory } else { - mMotions.Remove(index); // only remove the motion from the motion manager without destroying its memory + m_motions.erase(AZStd::next(begin(m_motions), index)); // only remove the motion from the motion manager without destroying its memory } return true; @@ -539,20 +412,20 @@ namespace EMotionFX // add a new motion set void MotionManager::AddMotionSet(MotionSet* motionSet) { - MCore::LockGuard lock(mLock); - mMotionSets.Add(motionSet); + MCore::LockGuard lock(m_lock); + m_motionSets.emplace_back(motionSet); } // remove the motion set with the given index from the motion manager - bool MotionManager::RemoveMotionSetWithoutLock(uint32 index, bool delFromMemory) + bool MotionManager::RemoveMotionSetWithoutLock(size_t index, bool delFromMemory) { - if (index == MCORE_INVALIDINDEX32) + if (index == InvalidIndex) { return false; } - MotionSet* motionSet = mMotionSets[index]; + MotionSet* motionSet = m_motionSets[index]; // remove from the parent MotionSet* parentSet = motionSet->GetParentSet(); @@ -578,7 +451,7 @@ namespace EMotionFX delete motionSet; } - mMotionSets.Remove(index); + m_motionSets.erase(AZStd::next(begin(m_motionSets), index)); return true; } @@ -587,7 +460,7 @@ namespace EMotionFX // remove the motion from the motion manager bool MotionManager::RemoveMotion(Motion* motion, bool delFromMemory) { - MCore::LockGuard lock(mLock); + MCore::LockGuard lock(m_lock); return RemoveMotionWithoutLock(FindMotionIndex(motion), delFromMemory); } @@ -595,22 +468,21 @@ namespace EMotionFX // remove the motion set from the motion manager bool MotionManager::RemoveMotionSet(MotionSet* motionSet, bool delFromMemory) { - MCore::LockGuard lock(mSetLock); + MCore::LockGuard lock(m_setLock); return RemoveMotionSetWithoutLock(FindMotionSetIndex(motionSet), delFromMemory); } // calculate the number of root motion sets - uint32 MotionManager::CalcNumRootMotionSets() const + size_t MotionManager::CalcNumRootMotionSets() const { - uint32 result = 0; + size_t result = 0; // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + for (const MotionSet* motionSet : m_motionSets) { // sum up the root motion sets - if (mMotionSets[i]->GetParentSet() == nullptr) + if (motionSet->GetParentSet() == nullptr) { result++; } @@ -621,46 +493,27 @@ namespace EMotionFX // find the given root motion set - MotionSet* MotionManager::FindRootMotionSet(uint32 index) + MotionSet* MotionManager::FindRootMotionSet(size_t index) { - uint32 currentIndex = 0; - - // get the number of motion sets and iterate through them - const uint32 numMotionSets = mMotionSets.GetLength(); - for (uint32 i = 0; i < numMotionSets; ++i) + auto foundRootMotionSet = AZStd::find_if(begin(m_motionSets), end(m_motionSets), [iter = index](const MotionSet* motionSet) mutable { - // get the current motion set - MotionSet* motionSet = mMotionSets[i]; - - // check if we are dealing with a root motion set and skip all others - if (mMotionSets[i]->GetParentSet()) - { - continue; - } - - // compare the indices and return in case we reached it, if not increase the counter - if (currentIndex == index) - { - return motionSet; - } - currentIndex++; - } - - return nullptr; + return motionSet->GetParentSet() == nullptr && iter-- == 0; + }); + return foundRootMotionSet != end(m_motionSets) ? *foundRootMotionSet : nullptr; } // wait with execution until we can set the lock void MotionManager::Lock() { - mLock.Lock(); + m_lock.Lock(); } // release the lock again void MotionManager::Unlock() { - mLock.Unlock(); + m_lock.Unlock(); } MotionDataFactory& MotionManager::GetMotionDataFactory() diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h index 78d8b0eaa7..24c8c784f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionManager.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include #include #include @@ -44,13 +44,13 @@ namespace EMotionFX * @param[in] index The index of the motion. The index must be in range [0, GetNumMotions()-1]. * @return A pointer to the given motion set. */ - MCORE_INLINE Motion* GetMotion(uint32 index) const { return mMotions[index]; } + MCORE_INLINE Motion* GetMotion(size_t index) const { return m_motions[index]; } /** * Get the number of motions in the motion manager. * @return The number of registered motions. */ - MCORE_INLINE uint32 GetNumMotions() const { return mMotions.GetLength(); } + MCORE_INLINE size_t GetNumMotions() const { return m_motions.size(); } /** * Remove the motion with the given name from the motion manager. @@ -119,7 +119,7 @@ namespace EMotionFX * @param[in] isTool Set when calling this function from the tools environment (default). * @return The index of the motion with the given name. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionIndexByName(const char* motionName, bool isTool = true) const; + size_t FindMotionIndexByName(const char* motionName, bool isTool = true) const; /** * Find the motion index by file name. @@ -127,21 +127,21 @@ namespace EMotionFX * @param[in] isTool Set when calling this function from the tools environment (default). * @return The index of the motion with the given name. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionIndexByFileName(const char* fileName, bool isTool = true) const; + size_t FindMotionIndexByFileName(const char* fileName, bool isTool = true) const; /** * Find the motion index by id. * @param[in] id The id of the motion. * @return The index of the motion with the given id. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionIndexByID(uint32 id) const; + size_t FindMotionIndexByID(uint32 id) const; /** * Find the index for the given motion. * @param[in] motion A pointer to the motion to search. * @return The index of the motion. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionIndex(Motion* motion) const; + size_t FindMotionIndex(Motion* motion) const; /** * Add a motion set to the motion manager. @@ -154,27 +154,27 @@ namespace EMotionFX * @param[in] index The index of the motion set. The index must be in range [0, GetNumMotionSets()-1]. * @return A pointer to the given motion set. */ - MCORE_INLINE MotionSet* GetMotionSet(uint32 index) const { return mMotionSets[index]; } + MCORE_INLINE MotionSet* GetMotionSet(size_t index) const { return m_motionSets[index]; } /** * Get the number of motion sets in the motion manager. * @return The number of registered motion sets. */ - MCORE_INLINE uint32 GetNumMotionSets() const { return mMotionSets.GetLength(); } + MCORE_INLINE size_t GetNumMotionSets() const { return m_motionSets.size(); } /** * Calculate the number of root motion sets. * This will iterate over all motion sets, check if they have a parent and sum all the root ones. * @return The number of root motion sets. */ - uint32 CalcNumRootMotionSets() const; + size_t CalcNumRootMotionSets() const; /** * Find the root motion set with the given index. * @param[in] index The index of the root motion set. The index must be in range [0, CalcNumRootMotionSets()-1]. * @return A pointer to the given motion set. */ - MotionSet* FindRootMotionSet(uint32 index); + MotionSet* FindRootMotionSet(size_t index); /** * Find motion set by name. @@ -205,21 +205,21 @@ namespace EMotionFX * @param[in] isTool Set when calling this function from the tools environment (default). * @return The index of the motion set with the given name. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionSetIndexByName(const char* name, bool isTool = true) const; + size_t FindMotionSetIndexByName(const char* name, bool isTool = true) const; /** * Find motion set index by id. * @param[in] id The id of the motion set. * @return The index of the motion set with the given id. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionSetIndexByID(uint32 id) const; + size_t FindMotionSetIndexByID(uint32 id) const; /** * Find motion set index for the given motion set. * @param[in] motionSet A pointer to the motion set to search. * @return The index for the given motion set. MCORE_INVALIDINDEX32 in case the motion has not been found. */ - uint32 FindMotionSetIndex(MotionSet* motionSet) const; + size_t FindMotionSetIndex(MotionSet* motionSet) const; bool RemoveMotionSetByName(const char* motionName, bool delFromMemory = true, bool isTool = true); bool RemoveMotionSetByID(uint32 id, bool delFromMemory = true); @@ -233,10 +233,10 @@ namespace EMotionFX const MotionDataFactory& GetMotionDataFactory() const; private: - MCore::Array mMotions; /**< The array of motions. */ - MCore::Array mMotionSets; /**< The array of motion sets. */ - MCore::Mutex mLock; /**< Motion lock. */ - MCore::Mutex mSetLock; /**< The motion set multithread lock. */ + AZStd::vector m_motions; /**< The array of motions. */ + AZStd::vector m_motionSets; /**< The array of motion sets. */ + MCore::Mutex m_lock; /**< Motion lock. */ + MCore::Mutex m_setLock; /**< The motion set multithread lock. */ MotionDataFactory* m_motionDataFactory = nullptr; /**< The motion data factory. */ //void RecursiveResetMotionNodes(AnimGraphNode* animGraphNode, Motion* motion); @@ -249,9 +249,9 @@ namespace EMotionFX * When set to false, it will not be deleted from memory, but only removed from the array of motions. * @return True in case the motion has been removed successfully. False in case the motion has not been found or the removal failed. */ - bool RemoveMotionWithoutLock(uint32 index, bool delFromMemory = true); + bool RemoveMotionWithoutLock(size_t index, bool delFromMemory = true); - bool RemoveMotionSetWithoutLock(uint32 index, bool delFromMemory = true); + bool RemoveMotionSetWithoutLock(size_t index, bool delFromMemory = true); MotionManager(); ~MotionManager() override; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp index d3a76f7967..e523572689 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.cpp @@ -26,9 +26,8 @@ namespace EMotionFX { MCORE_ASSERT(actorInstance && motionSystem); - mEntries.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MISC); - mActorInstance = actorInstance; - mMotionSystem = motionSystem; + m_actorInstance = actorInstance; + m_motionSystem = motionSystem; } @@ -47,14 +46,14 @@ namespace EMotionFX // remove a given entry from the queue - void MotionQueue::RemoveEntry(uint32 nr) + void MotionQueue::RemoveEntry(size_t nr) { - if (mMotionSystem->RemoveMotionInstance(mEntries[nr].mMotion) == false) + if (m_motionSystem->RemoveMotionInstance(m_entries[nr].m_motion) == false) { - GetMotionInstancePool().Free(mEntries[nr].mMotion); + GetMotionInstancePool().Free(m_entries[nr].m_motion); } - mEntries.Remove(nr); + m_entries.erase(AZStd::next(begin(m_entries), nr)); } @@ -62,7 +61,7 @@ namespace EMotionFX void MotionQueue::Update() { // get the number of entries - uint32 numEntries = GetNumEntries(); + size_t numEntries = GetNumEntries(); // if there are entries in the queue if (numEntries == 0) @@ -71,7 +70,7 @@ namespace EMotionFX } // if there is only one entry in the queue, we can start playing it immediately - if (mMotionSystem->GetIsPlaying() == false) + if (m_motionSystem->GetIsPlaying() == false) { // get the entry from the queue to play next MotionQueue::QueueEntry queueEntry = GetFirstEntry(); @@ -80,7 +79,7 @@ namespace EMotionFX RemoveFirstEntry(); // start the motion on the queue - mMotionSystem->StartMotion(queueEntry.mMotion, &queueEntry.mPlayInfo); + m_motionSystem->StartMotion(queueEntry.m_motion, &queueEntry.m_playInfo); // get out of this method, nothing more to do :) return; @@ -110,7 +109,7 @@ namespace EMotionFX RemoveFirstEntry(); // start the motion - mMotionSystem->StartMotion(queueEntry.mMotion, &queueEntry.mPlayInfo); + m_motionSystem->StartMotion(queueEntry.m_motion, &queueEntry.m_playInfo); } @@ -118,7 +117,7 @@ namespace EMotionFX bool MotionQueue::ShouldPlayNextMotion() { // find the first non mixing motion - MotionInstance* motionInst = mMotionSystem->FindFirstNonMixingMotionInstance(); + MotionInstance* motionInst = m_motionSystem->FindFirstNonMixingMotionInstance(); // if there isn't a non mixing motion if (motionInst == nullptr) @@ -127,7 +126,7 @@ namespace EMotionFX } // the total amount of blending time - const float timeToRemoveFromMaxTime = GetFirstEntry().mPlayInfo.mBlendInTime + motionInst->GetFadeTime(); + const float timeToRemoveFromMaxTime = GetFirstEntry().m_playInfo.m_blendInTime + motionInst->GetFadeTime(); // if the motion has ended or is stopping, then we should start the next motion if (motionInst->GetIsStopping() || motionInst->GetHasEnded()) @@ -168,7 +167,7 @@ namespace EMotionFX void MotionQueue::ClearAllEntries() { - while (mEntries.GetLength()) + while (m_entries.size()) { RemoveEntry(0); } @@ -177,31 +176,31 @@ namespace EMotionFX void MotionQueue::AddEntry(const MotionQueue::QueueEntry& motion) { - mEntries.Add(motion); + m_entries.emplace_back(motion); } - uint32 MotionQueue::GetNumEntries() const + size_t MotionQueue::GetNumEntries() const { - return mEntries.GetLength(); + return m_entries.size(); } MotionQueue::QueueEntry& MotionQueue::GetFirstEntry() { - MCORE_ASSERT(mEntries.GetLength() > 0); - return mEntries[0]; + MCORE_ASSERT(m_entries.size() > 0); + return m_entries[0]; } void MotionQueue::RemoveFirstEntry() { - mEntries.RemoveFirst(); + m_entries.erase(m_entries.begin()); } - MotionQueue::QueueEntry& MotionQueue::GetEntry(uint32 nr) + MotionQueue::QueueEntry& MotionQueue::GetEntry(size_t nr) { - return mEntries[nr]; + return m_entries[nr]; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h index 5480f5c40d..8584d43be2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionQueue.h @@ -12,7 +12,7 @@ #include "EMotionFXConfig.h" #include "BaseObject.h" #include "PlayBackInfo.h" -#include +#include namespace EMotionFX @@ -43,17 +43,17 @@ namespace EMotionFX class QueueEntry { public: - MotionInstance* mMotion; /**< The motion instance we want to play. */ - PlayBackInfo mPlayInfo; /**< The motion playback settings. */ + MotionInstance* m_motion; /**< The motion instance we want to play. */ + PlayBackInfo m_playInfo; /**< The motion playback settings. */ /// The default constructor QueueEntry() - : mMotion(nullptr) {} + : m_motion(nullptr) {} /// The extended constructor. QueueEntry(MotionInstance* motion, class PlayBackInfo* info) - : mMotion(motion) - , mPlayInfo(*info) {} + : m_motion(motion) + , m_playInfo(*info) {} }; /** @@ -79,7 +79,7 @@ namespace EMotionFX * Get the number of entries currently in the queue. * @result The number of entries currently scheduled in the queue. */ - uint32 GetNumEntries() const; + size_t GetNumEntries() const; /** * Get the first entry. @@ -99,13 +99,13 @@ namespace EMotionFX * @param nr The queue entry number to get. * @result A reference to the queue entry, with write access. */ - QueueEntry& GetEntry(uint32 nr); + QueueEntry& GetEntry(size_t nr); /** * Remove a given entry from the queue. * @param nr The entry number to remove from the queue. */ - void RemoveEntry(uint32 nr); + void RemoveEntry(size_t nr); /** * Updates the motion queue. @@ -133,9 +133,9 @@ namespace EMotionFX void PlayNextMotion(); private: - MCore::Array mEntries; /**< The motion queue entries. */ - MotionSystem* mMotionSystem; /**< Motion system access pointer. */ - ActorInstance* mActorInstance; /**< The actor instance where this queue works on. */ + AZStd::vector m_entries; /**< The motion queue entries. */ + MotionSystem* m_motionSystem; /**< Motion system access pointer. */ + ActorInstance* m_actorInstance; /**< The actor instance where this queue works on. */ /** * Constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.cpp index fe086b1c25..d8880f6fcc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.cpp @@ -6,6 +6,8 @@ * */ +#include +#include #include #include #include @@ -151,7 +153,7 @@ namespace EMotionFX , m_autoUnregister(true) , m_dirtyFlag(false) { - m_id = MCore::GetIDGenerator().GenerateID(); + m_id = aznumeric_caster(MCore::GetIDGenerator().GenerateID()); m_callback = aznew MotionSetCallback(this); #if defined(EMFX_DEVELOPMENT_BUILD) @@ -320,18 +322,16 @@ namespace EMotionFX } } - void MotionSet::ReserveMotionEntries(uint32 numMotionEntries) + void MotionSet::ReserveMotionEntries(size_t numMotionEntries) { MCore::LockGuardRecursive lock(m_mutex); - // Not supported yet by the AZStd::unordered_map. - //m_motionEntries.reserve(numMotionEntries); - MCORE_UNUSED(numMotionEntries); + m_motionEntries.reserve(numMotionEntries); } // Find the motion entry for a given motion. - MotionSet::MotionEntry* MotionSet::FindMotionEntry(Motion* motion) const + MotionSet::MotionEntry* MotionSet::FindMotionEntry(const Motion* motion) const { MCore::LockGuardRecursive lock(m_mutex); @@ -642,23 +642,10 @@ namespace EMotionFX { MCore::LockGuardRecursive lock(m_mutex); - // Is the given motion set dirty? - if (m_dirtyFlag) + return m_dirtyFlag || AZStd::any_of(begin(m_childSets), end(m_childSets), [](const MotionSet* childSet) { - return true; - } - - // Is any of the child motion sets dirty? - for (MotionSet* childSet : m_childSets) - { - if (childSet->GetDirtyFlag()) - { - return true; - } - } - - // Neither the given set nor any of the child sets is dirty. - return false; + return childSet->GetDirtyFlag(); + }); } @@ -735,38 +722,25 @@ namespace EMotionFX } - uint32 MotionSet::GetNumChildSets() const + size_t MotionSet::GetNumChildSets() const { MCore::LockGuardRecursive lock(m_mutex); - uint32 childSetSize = 0; - for (const MotionSet* motionSet : m_childSets) + return AZStd::accumulate(begin(m_childSets), end(m_childSets), size_t{0}, [](size_t total, const MotionSet* motionSet) { - if (!motionSet->GetIsOwnedByRuntime()) - { - ++childSetSize; - } - } - return childSetSize; + return total + motionSet->GetIsOwnedByRuntime(); + }); } - MotionSet* MotionSet::GetChildSet(uint32 index) const + MotionSet* MotionSet::GetChildSet(size_t index) const { MCore::LockGuardRecursive lock(m_mutex); - uint32 currentIndex = 0; - for (MotionSet* motionSet : m_childSets) + const auto foundChildSet = AZStd::find_if(begin(m_childSets), end(m_childSets), [iter = index](const MotionSet* motionSet) mutable { - if (!motionSet->GetIsOwnedByRuntime()) - { - if (currentIndex == index) - { - return motionSet; - } - ++currentIndex; - } - } - return nullptr; + return !motionSet->GetIsOwnedByRuntime() && iter-- == 0; + }); + return foundChildSet != end(m_childSets) ? *foundChildSet : nullptr; } void MotionSet::RecursiveGetMotionSets(AZStd::vector& childMotionSets, bool isOwnedByRuntime) const @@ -903,8 +877,8 @@ namespace EMotionFX void MotionSet::RecursiveRewireParentSets(MotionSet* motionSet) { - const AZ::u32 numChildSets = motionSet->GetNumChildSets(); - for (AZ::u32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { MotionSet* childSet = motionSet->GetChildSet(i); childSet->m_parentSet = motionSet; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.h index c7402df130..c49dd444f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSet.h @@ -231,7 +231,7 @@ namespace EMotionFX * This will NOT grow the motion entries array as reported by GetNumMotionEntries(). However, it internally pre-allocates memory to make the AddMotionEntry() calls faster. * @param[in] numMotionEntries The number of motion entries to peallocate */ - void ReserveMotionEntries(uint32 numMotionEntries); + void ReserveMotionEntries(size_t numMotionEntries); /** * Remove all motion entries from the motion set. @@ -249,7 +249,7 @@ namespace EMotionFX * @param[in] motion A pointer to the motion. * @result A pointer to the motion entry for the given motion. nullptr in case no motion entry has been found. */ - MotionEntry* FindMotionEntry(Motion* motion) const; + MotionEntry* FindMotionEntry(const Motion* motion) const; MotionEntry* FindMotionEntryById(const AZStd::string& motionId) const; @@ -293,14 +293,14 @@ namespace EMotionFX * Get the number of child motion sets. * @result The number of child sets. */ - uint32 GetNumChildSets() const; + size_t GetNumChildSets() const; /** * Get the given child motion set. * @param[in] index The index of the child set to get. The index must be in range [0, GetNumChildSets()]. * @result A pointer to the child set at the given index. */ - MotionSet* GetChildSet(uint32 index) const; + MotionSet* GetChildSet(size_t index) const; /** * Gets child motion sets recursively. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp index 364ad28d3d..a6ddb776c2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.cpp @@ -29,12 +29,11 @@ namespace EMotionFX { MCORE_ASSERT(actorInstance); - mMotionInstances.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONSYSTEMS); - mActorInstance = actorInstance; - mMotionQueue = nullptr; + m_actorInstance = actorInstance; + m_motionQueue = nullptr; // create the motion queue - mMotionQueue = MotionQueue::Create(actorInstance, this); + m_motionQueue = MotionQueue::Create(actorInstance, this); GetEventManager().OnCreateMotionSystem(this); } @@ -46,17 +45,16 @@ namespace EMotionFX GetEventManager().OnDeleteMotionSystem(this); // delete the motion infos - while (mMotionInstances.GetLength()) + while (!m_motionInstances.empty()) { - //delete mMotionInstances.GetLast(); - GetMotionInstancePool().Free(mMotionInstances.GetLast()); - mMotionInstances.RemoveLast(); + GetMotionInstancePool().Free(m_motionInstances.back()); + m_motionInstances.pop_back(); } // get rid of the motion queue - if (mMotionQueue) + if (m_motionQueue) { - mMotionQueue->Destroy(); + m_motionQueue->Destroy(); } } @@ -76,33 +74,21 @@ namespace EMotionFX info = &tempInfo; } - /* - // if we want to play a motion which will loop forever (so never ends) and we want to put it on the queue - if (info->mNumLoops==FOREVER && info->mPlayNow==false) - { - // if there is already a motion on the queue, this means the queue would end up in some kind of deadlock - // because it has to wait until the current motion is finished with playing, before it would start this motion - // and since that will never happen, the queue won't be processed anymore... - // so we may simply not allow this to happen. - if (mMotionQueue->GetNumEntries() > 0) - throw Exception("Cannot schedule this LOOPING motion to be played later, because there are already motions queued. If we would put this motion on the queue, all motions added later on to the queue will never be processed because this motion is a looping (so never ending) one.", MCORE_HERE); - }*/ - // trigger the OnPlayMotion event GetEventManager().OnPlayMotion(motion, info); // make sure we always mix when using additive blending - if (info->mBlendMode == BLENDMODE_ADDITIVE && info->mMix == false) + if (info->m_blendMode == BLENDMODE_ADDITIVE && info->m_mix == false) { MCORE_ASSERT(false); // this shouldn't happen actually, please make sure you always mix additive motions - info->mMix = true; + info->m_mix = true; } // create the motion instance and add the motion info the this actor MotionInstance* motionInst = CreateMotionInstance(motion, info); // if we want to play it immediately (so if we do NOT want to schedule it for later on) - if (info->mPlayNow) + if (info->m_playNow) { // start the motion for real StartMotion(motionInst, info); @@ -110,7 +96,7 @@ namespace EMotionFX else { // schedule the motion, by adding it to the back of the motion queue - mMotionQueue->AddEntry(MotionQueue::QueueEntry(motionInst, info)); + m_motionQueue->AddEntry(MotionQueue::QueueEntry(motionInst, info)); motionInst->Pause(); motionInst->SetIsActive(false); GetEventManager().OnQueueMotionInstance(motionInst, info); @@ -125,7 +111,7 @@ namespace EMotionFX MotionInstance* MotionSystem::CreateMotionInstance(Motion* motion, PlayBackInfo* info) { // create the motion instance - MotionInstance* motionInst = GetMotionInstancePool().RequestNew(motion, mActorInstance); + MotionInstance* motionInst = GetMotionInstancePool().RequestNew(motion, m_actorInstance); // initialize the motion instance from the playback info settings motionInst->InitFromPlayBackInfo(*info); @@ -138,7 +124,14 @@ namespace EMotionFX bool MotionSystem::RemoveMotionInstance(MotionInstance* instance) { // remove the motion instance from the actor - const bool isSuccess = mMotionInstances.RemoveByValue(instance); + const bool isSuccess = [this, instance] { + if(const auto it = AZStd::find(begin(m_motionInstances), end(m_motionInstances), instance); it != end(m_motionInstances)) + { + m_motionInstances.erase(it); + return true; + } + return false; + }(); // delete the motion instance from memory if (isSuccess) @@ -157,7 +150,7 @@ namespace EMotionFX MCORE_UNUSED(updateNodes); // update the motion queue - mMotionQueue->Update(); + m_motionQueue->Update(); // update the motions UpdateMotionInstances(timePassed); @@ -167,10 +160,9 @@ namespace EMotionFX // stop all the motions that are currently playing void MotionSystem::StopAllMotions() { - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) + for (MotionInstance* motionInstance : m_motionInstances) { - mMotionInstances[i]->Stop(); + motionInstance->Stop(); } } @@ -178,28 +170,27 @@ namespace EMotionFX // stop all motion instances of a given motion void MotionSystem::StopAllMotions(Motion* motion) { - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) + for (MotionInstance* motionInstance : m_motionInstances) { - if (mMotionInstances[i]->GetMotion()->GetID() == motion->GetID()) + if (motionInstance->GetMotion()->GetID() == motion->GetID()) { - mMotionInstances[i]->Stop(); + motionInstance->Stop(); } } } // remove the given motion - void MotionSystem::RemoveMotion(uint32 nr, bool deleteMem) + void MotionSystem::RemoveMotion(size_t nr, bool deleteMem) { - MCORE_ASSERT(nr < mMotionInstances.GetLength()); + MCORE_ASSERT(nr < m_motionInstances.size()); if (deleteMem) { - GetEMotionFX().GetMotionInstancePool()->Free(mMotionInstances[nr]); + GetEMotionFX().GetMotionInstancePool()->Free(m_motionInstances[nr]); } - mMotionInstances.Remove(nr); + m_motionInstances.erase(AZStd::next(begin(m_motionInstances), nr)); } @@ -208,15 +199,15 @@ namespace EMotionFX { MCORE_ASSERT(motion); - uint32 nr = mMotionInstances.Find(motion); - MCORE_ASSERT(nr != MCORE_INVALIDINDEX32); + const auto it = AZStd::find(begin(m_motionInstances), end(m_motionInstances), motion); + MCORE_ASSERT(it != end(m_motionInstances)); - if (nr == MCORE_INVALIDINDEX32) + if (it == end(m_motionInstances)) { return; } - RemoveMotion(nr, delMem); + RemoveMotion(AZStd::distance(begin(m_motionInstances), it), delMem); } @@ -224,10 +215,9 @@ namespace EMotionFX void MotionSystem::UpdateMotionInstances(float timePassed) { // update all the motion infos - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) + for (MotionInstance* motionInstance : m_motionInstances) { - mMotionInstances[i]->Update(timePassed); + motionInstance->Update(timePassed); } } @@ -235,86 +225,48 @@ namespace EMotionFX // check if the given motion instance still exists within the actor, so if it hasn't been deleted from memory yet bool MotionSystem::CheckIfIsValidMotionInstance(MotionInstance* instance) const { - // if it's a null pointer, just return - if (instance == nullptr) + return instance && AZStd::any_of(begin(m_motionInstances), end(m_motionInstances), [instance](const MotionInstance* motionInstance) { - return false; - } - - // for all motion instances currently playing in this actor - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) - { - // check if this one is the one we are searching for, if so, return that it is still valid - if (mMotionInstances[i] == instance) // if the memory object appears to be valid - { - if (mMotionInstances[i]->GetID() == instance->GetID()) // check if the id is the same, as a new motion theoretically could have received the same memory address - { - return true; - } - } - } - - // it's not found, this means it has already been deleted from memory and is not valid anymore - return false; + return motionInstance->GetID() == instance->GetID(); + }); } // check if there is a motion instance playing, which is an instance of a specified motion bool MotionSystem::CheckIfIsPlayingMotion(Motion* motion, bool ignorePausedMotions) const { - if (!motion) + return motion && AZStd::any_of(begin(m_motionInstances), end(m_motionInstances), [motion, ignorePausedMotions](const MotionInstance* motionInstance) { - return false; - } - - // for all motion instances currently playing in this actor - const uint32 numInstances = mMotionInstances.GetLength(); - for (uint32 i = 0; i < numInstances; ++i) - { - const MotionInstance* motionInstance = mMotionInstances[i]; - - if (ignorePausedMotions && motionInstance->GetIsPaused()) - { - continue; - } - - // check if the motion instance is an instance of the motion we are searching for - if (motionInstance->GetMotion()->GetID() == motion->GetID()) - { - return true; - } - } - - // it's not found, this means it has already been deleted from memory and is not valid anymore - return false; + return !(ignorePausedMotions && motionInstance->GetIsPaused()) && + motionInstance->GetMotion()->GetID() == motion->GetID(); + }); } // return given motion instance - MotionInstance* MotionSystem::GetMotionInstance(uint32 nr) const + MotionInstance* MotionSystem::GetMotionInstance(size_t nr) const { - MCORE_ASSERT(nr < mMotionInstances.GetLength()); - return mMotionInstances[nr]; + MCORE_ASSERT(nr < m_motionInstances.size()); + return m_motionInstances[nr]; } // return number of motion instances - uint32 MotionSystem::GetNumMotionInstances() const + size_t MotionSystem::GetNumMotionInstances() const { - return mMotionInstances.GetLength(); + return m_motionInstances.size(); } // set a new motion queue void MotionSystem::SetMotionQueue(MotionQueue* motionQueue) { - if (mMotionQueue) + if (m_motionQueue) { - mMotionQueue->Destroy(); + m_motionQueue->Destroy(); } - mMotionQueue = motionQueue; + m_motionQueue = motionQueue; } @@ -324,9 +276,9 @@ namespace EMotionFX MCORE_ASSERT(motionQueue); // copy entries from the given queue to the motion system's one - for (uint32 i = 0; i < motionQueue->GetNumEntries(); ++i) + for (size_t i = 0; i < motionQueue->GetNumEntries(); ++i) { - mMotionQueue->AddEntry(motionQueue->GetEntry(i)); + m_motionQueue->AddEntry(motionQueue->GetEntry(i)); } // get rid of the given motion queue @@ -337,25 +289,25 @@ namespace EMotionFX // return motion queue pointer MotionQueue* MotionSystem::GetMotionQueue() const { - return mMotionQueue; + return m_motionQueue; } // return the actor to which this motion system belongs to ActorInstance* MotionSystem::GetActorInstance() const { - return mActorInstance; + return m_actorInstance; } void MotionSystem::AddMotionInstance(MotionInstance* instance) { - mMotionInstances.Add(instance); + m_motionInstances.emplace_back(instance); } bool MotionSystem::GetIsPlaying() const { - return (mMotionInstances.GetLength() > 0); + return !m_motionInstances.empty(); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h index c0cbb779df..611ccd731a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionSystem.h @@ -11,7 +11,7 @@ // include the required headers #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include namespace EMotionFX @@ -76,7 +76,7 @@ namespace EMotionFX * @param nr The motion to remove. * @param deleteMem If true the allocated memory of the motion will be deleted. */ - void RemoveMotion(uint32 nr, bool deleteMem = true); + void RemoveMotion(size_t nr, bool deleteMem = true); /** * Remove a given motion. @@ -104,7 +104,7 @@ namespace EMotionFX * @result A pointer to the motion instance. * @see IsValidMotionInstance */ - MotionInstance* GetMotionInstance(uint32 nr) const; + MotionInstance* GetMotionInstance(size_t nr) const; /** * Recursively search for the first non mixing motion and return the motion instance. @@ -122,7 +122,7 @@ namespace EMotionFX * @result The number of active motion instances inside this actor. * @see IsValidMotionInstance */ - uint32 GetNumMotionInstances() const; + size_t GetNumMotionInstances() const; /** * Checks if a given motion instance is still valid. @@ -215,9 +215,9 @@ namespace EMotionFX protected: - MCore::Array mMotionInstances; /**< The collection of motion instances. */ - ActorInstance* mActorInstance; /**< The actor instance where this motion system belongs to. */ - MotionQueue* mMotionQueue; /**< The motion queue. */ + AZStd::vector m_motionInstances; /**< The collection of motion instances. */ + ActorInstance* m_actorInstance; /**< The actor instance where this motion system belongs to. */ + MotionQueue* m_motionQueue; /**< The motion queue. */ /** * Constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp index 9af9ddf71f..6f07936fe7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.cpp @@ -30,9 +30,8 @@ namespace EMotionFX MultiThreadScheduler::MultiThreadScheduler() : ActorUpdateScheduler() { - mSteps.SetMemoryCategory(EMFX_MEMCATEGORY_UPDATESCHEDULERS); - mCleanTimer = 0.0f; // time passed since last schedule cleanup, in seconds - mSteps.Reserve(1000); + m_cleanTimer = 0.0f; // time passed since last schedule cleanup, in seconds + m_steps.reserve(1000); } @@ -53,7 +52,7 @@ namespace EMotionFX void MultiThreadScheduler::Clear() { Lock(); - mSteps.Clear(); + m_steps.clear(); Unlock(); } @@ -79,10 +78,10 @@ namespace EMotionFX void MultiThreadScheduler::Print() { // for all steps - const uint32 numSteps = mSteps.GetLength(); - for (uint32 i = 0; i < numSteps; ++i) + const size_t numSteps = m_steps.size(); + for (size_t i = 0; i < numSteps; ++i) { - AZ_Printf("EMotionFX", "STEP %.3d - %d", i, mSteps[i].mActorInstances.size()); + AZ_Printf("EMotionFX", "STEP %.3zu - %zu", i, m_steps[i].m_actorInstances.size()); } AZ_Printf("EMotionFX", "---------"); @@ -92,16 +91,15 @@ namespace EMotionFX void MultiThreadScheduler::RemoveEmptySteps() { // process all steps - for (uint32 s = 0; s < mSteps.GetLength(); ) + for (size_t s = 0; s < m_steps.size(); ) { - // if the step isn't empty - if (mSteps[s].mActorInstances.size() > 0) + if (!m_steps[s].m_actorInstances.empty()) { s++; } - else // otherwise remove it + else { - mSteps.Remove(s); + m_steps.erase(AZStd::next(begin(m_steps), s)); } } } @@ -110,29 +108,29 @@ namespace EMotionFX // execute the schedule void MultiThreadScheduler::Execute(float timePassedInSeconds) { - MCore::LockGuardRecursive guard(mMutex); + MCore::LockGuardRecursive guard(m_mutex); - uint32 numSteps = mSteps.GetLength(); + size_t numSteps = m_steps.size(); if (numSteps == 0) { return; } // check if we need to cleanup the schedule - mCleanTimer += timePassedInSeconds; - if (mCleanTimer >= 1.0f) + m_cleanTimer += timePassedInSeconds; + if (m_cleanTimer >= 1.0f) { - mCleanTimer = 0.0f; + m_cleanTimer = 0.0f; RemoveEmptySteps(); - numSteps = mSteps.GetLength(); + numSteps = m_steps.size(); } //----------------------------------------------------------- // propagate root actor instance visibility to their attachments const ActorManager& actorManager = GetActorManager(); - const uint32 numRootActorInstances = actorManager.GetNumRootActorInstances(); - for (uint32 i = 0; i < numRootActorInstances; ++i) + const size_t numRootActorInstances = actorManager.GetNumRootActorInstances(); + for (size_t i = 0; i < numRootActorInstances; ++i) { ActorInstance* rootInstance = actorManager.GetRootActorInstance(i); if (rootInstance->GetIsEnabled() == false) @@ -144,26 +142,21 @@ namespace EMotionFX } // reset stats - mNumUpdated.SetValue(0); - mNumVisible.SetValue(0); - mNumSampled.SetValue(0); + m_numUpdated.SetValue(0); + m_numVisible.SetValue(0); + m_numSampled.SetValue(0); - for (uint32 s = 0; s < numSteps; ++s) + for (const ScheduleStep& currentStep : m_steps) { - const ScheduleStep& currentStep = mSteps[s]; - - // skip empty steps - const size_t numStepEntries = currentStep.mActorInstances.size(); - if (numStepEntries == 0) + if (currentStep.m_actorInstances.empty()) { continue; } // process the actor instances in the current step in parallel - AZ::JobCompletion jobCompletion; - for (uint32 c = 0; c < numStepEntries; ++c) + AZ::JobCompletion jobCompletion; + for (ActorInstance* actorInstance : currentStep.m_actorInstances) { - ActorInstance* actorInstance = currentStep.mActorInstances[c]; if (actorInstance->GetIsEnabled() == false) { continue; @@ -180,7 +173,7 @@ namespace EMotionFX const bool isVisible = actorInstance->GetIsVisible(); if (isVisible) { - mNumVisible.Increment(); + m_numVisible.Increment(); } // check if we want to sample motions @@ -193,7 +186,7 @@ namespace EMotionFX if (isVisible) { - mNumSampled.Increment(); + m_numSampled.Increment(); } } @@ -204,7 +197,7 @@ namespace EMotionFX job->SetDependent(&jobCompletion); job->Start(); - mNumUpdated.Increment(); + m_numUpdated.Increment(); } jobCompletion.StartAndWaitForCompletion(); @@ -213,14 +206,14 @@ namespace EMotionFX // find the next free spot in the schedule - bool MultiThreadScheduler::FindNextFreeItem(ActorInstance* actorInstance, uint32 startStep, uint32* outStepNr) + bool MultiThreadScheduler::FindNextFreeItem(ActorInstance* actorInstance, size_t startStep, size_t* outStepNr) { // try out all steps - const uint32 numSteps = mSteps.GetLength(); - for (uint32 s = startStep; s < numSteps; ++s) + const size_t numSteps = m_steps.size(); + for (size_t s = startStep; s < numSteps; ++s) { // if there is a conflicting dependency, skip this step - if (CheckIfHasMatchingDependency(actorInstance, &mSteps[s])) + if (CheckIfHasMatchingDependency(actorInstance, &m_steps[s])) { continue; } @@ -236,11 +229,11 @@ namespace EMotionFX bool MultiThreadScheduler::HasActorInstanceInSteps(const ActorInstance* actorInstance) const { - const uint32 numSteps = mSteps.GetLength(); - for (uint32 s = 0; s < numSteps; ++s) + const size_t numSteps = m_steps.size(); + for (size_t s = 0; s < numSteps; ++s) { - const ScheduleStep& step = mSteps[s]; - if (AZStd::find(step.mActorInstances.begin(), step.mActorInstances.end(), actorInstance) != step.mActorInstances.end()) + const ScheduleStep& step = m_steps[s]; + if (AZStd::find(step.m_actorInstances.begin(), step.m_actorInstances.end(), actorInstance) != step.m_actorInstances.end()) { return true; } @@ -249,39 +242,39 @@ namespace EMotionFX return false; } - void MultiThreadScheduler::RecursiveInsertActorInstance(ActorInstance* instance, uint32 startStep) + void MultiThreadScheduler::RecursiveInsertActorInstance(ActorInstance* instance, size_t startStep) { - MCore::LockGuardRecursive guard(mMutex); + MCore::LockGuardRecursive guard(m_mutex); AZ_Assert(!HasActorInstanceInSteps(instance), "Expected the actor instance not being part of another step already."); // find the first free location that doesn't conflict - uint32 outStep = startStep; + size_t outStep = startStep; if (!FindNextFreeItem(instance, startStep, &outStep)) { - mSteps.Reserve(10); - mSteps.AddEmpty(); - outStep = mSteps.GetLength() - 1; + m_steps.reserve(10); + m_steps.emplace_back(); + outStep = m_steps.size() - 1; } // pre-allocate step size - if (mSteps[outStep].mActorInstances.size() % 10 == 0) + if (m_steps[outStep].m_actorInstances.size() % 10 == 0) { - mSteps[outStep].mActorInstances.reserve(mSteps[outStep].mActorInstances.size() + 10); + m_steps[outStep].m_actorInstances.reserve(m_steps[outStep].m_actorInstances.size() + 10); } - if (mSteps[outStep].mDependencies.GetLength() % 5 == 0) + if (m_steps[outStep].m_dependencies.size() % 5 == 0) { - mSteps[outStep].mDependencies.Reserve(mSteps[outStep].mDependencies.GetLength() + 5); + m_steps[outStep].m_dependencies.reserve(m_steps[outStep].m_dependencies.size() + 5); } // add the actor instance and its dependencies - mSteps[ outStep ].mActorInstances.reserve(GetEMotionFX().GetNumThreads()); - mSteps[ outStep ].mActorInstances.emplace_back(instance); - AddDependenciesToStep(instance, &mSteps[outStep]); + m_steps[ outStep ].m_actorInstances.reserve(GetEMotionFX().GetNumThreads()); + m_steps[ outStep ].m_actorInstances.emplace_back(instance); + AddDependenciesToStep(instance, &m_steps[outStep]); // recursively add all attachments too - const uint32 numAttachments = instance->GetNumAttachments(); - for (uint32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = instance->GetNumAttachments(); + for (size_t i = 0; i < numAttachments; ++i) { ActorInstance* attachment = instance->GetAttachment(i)->GetAttachmentActorInstance(); if (attachment) @@ -293,29 +286,29 @@ namespace EMotionFX // remove the actor instance from the schedule (excluding attachments) - uint32 MultiThreadScheduler::RemoveActorInstance(ActorInstance* actorInstance, uint32 startStep) + size_t MultiThreadScheduler::RemoveActorInstance(ActorInstance* actorInstance, size_t startStep) { - MCore::LockGuardRecursive guard(mMutex); + MCore::LockGuardRecursive guard(m_mutex); // for all scheduler steps, starting from the specified start step number - const uint32 numSteps = mSteps.GetLength(); - for (uint32 s = startStep; s < numSteps; ++s) + const size_t numSteps = m_steps.size(); + for (size_t s = startStep; s < numSteps; ++s) { - ScheduleStep& step = mSteps[s]; + ScheduleStep& step = m_steps[s]; // Remove all occurrences of the actor instance. - const size_t numActorInstancesPreRemove = step.mActorInstances.size(); - step.mActorInstances.erase(AZStd::remove(step.mActorInstances.begin(), step.mActorInstances.end(), actorInstance), step.mActorInstances.end()); + const size_t numActorInstancesPreRemove = step.m_actorInstances.size(); + step.m_actorInstances.erase(AZStd::remove(step.m_actorInstances.begin(), step.m_actorInstances.end(), actorInstance), step.m_actorInstances.end()); // try to see if there is anything to remove in this step // and if so, reconstruct the dependencies of this step - if (step.mActorInstances.size() < numActorInstancesPreRemove) + if (step.m_actorInstances.size() < numActorInstancesPreRemove) { // clear the dependencies (but don't delete the memory) - step.mDependencies.Clear(false); + step.m_dependencies.clear(); // calculate the new dependencies for this step - for (ActorInstance* stepActorInstance : step.mActorInstances) + for (ActorInstance* stepActorInstance : step.m_actorInstances) { AddDependenciesToStep(stepActorInstance, &step); } @@ -331,16 +324,16 @@ namespace EMotionFX // remove the actor instance (including all of its attachments) - void MultiThreadScheduler::RecursiveRemoveActorInstance(ActorInstance* actorInstance, uint32 startStep) + void MultiThreadScheduler::RecursiveRemoveActorInstance(ActorInstance* actorInstance, size_t startStep) { - MCore::LockGuardRecursive guard(mMutex); + MCore::LockGuardRecursive guard(m_mutex); // remove the actual actor instance - const uint32 step = RemoveActorInstance(actorInstance, startStep); + const size_t step = RemoveActorInstance(actorInstance, startStep); // recursively remove all attachments as well - const uint32 numAttachments = actorInstance->GetNumAttachments(); - for (uint32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = actorInstance->GetNumAttachments(); + for (size_t i = 0; i < numAttachments; ++i) { ActorInstance* attachment = actorInstance->GetAttachment(i)->GetAttachmentActorInstance(); if (attachment) @@ -353,12 +346,12 @@ namespace EMotionFX void MultiThreadScheduler::Lock() { - mMutex.Lock(); + m_mutex.Lock(); } void MultiThreadScheduler::Unlock() { - mMutex.Unlock(); + m_mutex.Unlock(); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h index 75a5a6519a..cf22875d97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MultiThreadScheduler.h @@ -50,16 +50,8 @@ namespace EMotionFX */ struct EMFX_API ScheduleStep { - MCore::Array mDependencies; /**< The dependencies of this scheduler step. No actor instances with the same dependencies are allowed to be added to this step. */ - AZStd::vector mActorInstances; /**< The actor instances used inside this step. Each array entry will execute in another thread. */ - - /** - * The constructor. - */ - ScheduleStep() - { - mDependencies.SetMemoryCategory(EMFX_MEMCATEGORY_UPDATESCHEDULERS); - } + AZStd::vector m_dependencies; /**< The dependencies of this scheduler step. No actor instances with the same dependencies are allowed to be added to this step. */ + AZStd::vector m_actorInstances; /**< The actor instances used inside this step. Each array entry will execute in another thread. */ }; /** @@ -107,14 +99,14 @@ namespace EMotionFX * @param actorInstance The actor instance to insert. * @param startStep An offset in the schedule where to start trying to insert the actor instances. */ - void RecursiveInsertActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) override; + void RecursiveInsertActorInstance(ActorInstance* actorInstance, size_t startStep = 0) override; /** * Recursively remove an actor instance and its attachments from the schedule. * @param actorInstance The actor instance to remove. * @param startStep An offset in the schedule where to start trying to remove from. */ - void RecursiveRemoveActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) override; + void RecursiveRemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) override; /** * Remove a single actor instance from the schedule. This will not remove its attachments. @@ -122,18 +114,18 @@ namespace EMotionFX * @param startStep An offset in the schedule where to start trying to remove from. * @result Returns the offset in the schedule where the actor instance was removed. */ - uint32 RemoveActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) override; + size_t RemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) override; void Lock(); void Unlock(); - const ScheduleStep& GetScheduleStep(uint32 index) const { return mSteps[index]; } - uint32 GetNumScheduleSteps() const { return mSteps.GetLength(); } + const ScheduleStep& GetScheduleStep(size_t index) const { return m_steps[index]; } + size_t GetNumScheduleSteps() const { return m_steps.size(); } protected: - MCore::Array< ScheduleStep > mSteps; /**< An array of update steps, that together form the schedule. */ - float mCleanTimer; /**< The time passed since the last automatic call to the Optimize method. */ - MCore::MutexRecursive mMutex; + AZStd::vector< ScheduleStep > m_steps; /**< An array of update steps, that together form the schedule. */ + float m_cleanTimer; /**< The time passed since the last automatic call to the Optimize method. */ + MCore::MutexRecursive m_mutex; bool HasActorInstanceInSteps(const ActorInstance* actorInstance) const; @@ -164,7 +156,7 @@ namespace EMotionFX * @param outStepNr This will contain the step number in which we can insert the actor instance. * @result Returns false when there is no step where we can insert in. A new step will have to be added. */ - bool FindNextFreeItem(ActorInstance* actorInstance, uint32 startStep, uint32* outStepNr); + bool FindNextFreeItem(ActorInstance* actorInstance, size_t startStep, size_t* outStepNr); /** * Add the dependencies of a given actor instance to a specified scheduler step. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp index 2aa6b796ab..1217c928bc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.cpp @@ -20,24 +20,20 @@ namespace EMotionFX Node::Node(const char* name, Skeleton* skeleton) : BaseObject() { - // set the array memory categories - mAttributes.SetMemoryCategory(EMFX_MEMCATEGORY_NODES); - mChildIndices.SetMemoryCategory(EMFX_MEMCATEGORY_NODES); - - mParentIndex = MCORE_INVALIDINDEX32; - mNodeIndex = MCORE_INVALIDINDEX32; // hasn't been set yet - mSkeletalLODs = 0xFFFFFFFF; // set all bits of the integer to 1, which enables this node in all LOD levels on default - mSkeleton = skeleton; - mSemanticNameID = MCORE_INVALIDINDEX32; - mNodeFlags = FLAG_INCLUDEINBOUNDSCALC; + m_parentIndex = InvalidIndex; + m_nodeIndex = InvalidIndex; // hasn't been set yet + m_skeletalLoDs = 0xFFFFFFFF; // set all bits of the integer to 1, which enables this node in all LOD levels on default + m_skeleton = skeleton; + m_semanticNameId = InvalidIndex32; + m_nodeFlags = FLAG_INCLUDEINBOUNDSCALC; if (name) { - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } else { - mNameID = MCORE_INVALIDINDEX32; + m_nameId = InvalidIndex32; } } @@ -45,17 +41,13 @@ namespace EMotionFX Node::Node(uint32 nameID, Skeleton* skeleton) : BaseObject() { - // set the array memory categories - mAttributes.SetMemoryCategory(EMFX_MEMCATEGORY_NODES); - mChildIndices.SetMemoryCategory(EMFX_MEMCATEGORY_NODES); - - mParentIndex = MCORE_INVALIDINDEX32; - mNodeIndex = MCORE_INVALIDINDEX32; // hasn't been set yet - mSkeletalLODs = 0xFFFFFFFF;// set all bits of the integer to 1, which enables this node in all LOD levels on default - mSkeleton = skeleton; - mNameID = nameID; - mSemanticNameID = MCORE_INVALIDINDEX32; - mNodeFlags = FLAG_INCLUDEINBOUNDSCALC; + m_parentIndex = InvalidIndex; + m_nodeIndex = InvalidIndex; // hasn't been set yet + m_skeletalLoDs = 0xFFFFFFFF;// set all bits of the integer to 1, which enables this node in all LOD levels on default + m_skeleton = skeleton; + m_nameId = nameID; + m_semanticNameId = InvalidIndex32; + m_nodeFlags = FLAG_INCLUDEINBOUNDSCALC; } @@ -83,95 +75,24 @@ namespace EMotionFX } - /* - // create a clone of this node - Node* Node::Clone(Actor* actor) const - { - Node* result = Node::Create(GetName(), actor); - - // copy attributes - result->mParentIndex = mParentIndex; - result->mNodeIndex = mNodeIndex; - result->mNameID = mNameID; - result->mSkeletalLODs = mSkeletalLODs; - //result->mMotionLODs = mMotionLODs; - result->mChildIndices = mChildIndices; - //result->mImportanceFactor = mImportanceFactor; - result->mNodeFlags = mNodeFlags; - result->mOBB = mOBB; - result->mSemanticNameID = mSemanticNameID; - - // copy the node attributes - for (uint32 i=0; iAddAttribute( mAttributes[i]->Clone() ); - - // copy the meshes - const uint32 numLODs = mLODs.GetLength(); - if (result->mLODs.GetLength() < numLODs) - result->mLODs.Resize( numLODs ); - - for (uint32 i=0; imLODs[i].mMesh = realMesh->Clone(actor, result); - else - result->mLODs[i].mMesh = nullptr; - } - - // copy the collision meshes - for (uint32 i=0; imLODs[i].mColMesh = realMesh->Clone(actor, result); - else - result->mLODs[i].mColMesh = nullptr; - } - - // clone node stacks - for (uint32 i=0; imLODs[i].mStack = realStack->Clone(result->mLODs[i].mMesh, actor); - else - result->mLODs[i].mStack = nullptr; - } - - // clone node collision stacks if desired - for (uint32 i=0; imLODs[i].mColStack = realStack->Clone(result->mLODs[i].mColMesh, actor); - else - result->mLODs[i].mColStack = nullptr; - } - - // return the resulting clone - return result; - } - */ - // create a clone of this node Node* Node::Clone(Skeleton* skeleton) const { - Node* result = Node::Create(mNameID, skeleton); + Node* result = Node::Create(m_nameId, skeleton); // copy attributes - result->mParentIndex = mParentIndex; - result->mNodeIndex = mNodeIndex; - result->mSkeletalLODs = mSkeletalLODs; - result->mChildIndices = mChildIndices; - result->mNodeFlags = mNodeFlags; - result->mSemanticNameID = mSemanticNameID; + result->m_parentIndex = m_parentIndex; + result->m_nodeIndex = m_nodeIndex; + result->m_skeletalLoDs = m_skeletalLoDs; + result->m_childIndices = m_childIndices; + result->m_nodeFlags = m_nodeFlags; + result->m_semanticNameId = m_semanticNameId; // copy the node attributes - result->mAttributes.Reserve(mAttributes.GetLength()); - for (uint32 i = 0; i < mAttributes.GetLength(); i++) + result->m_attributes.reserve(m_attributes.size()); + for (const NodeAttribute* attribute : m_attributes) { - result->AddAttribute(mAttributes[i]->Clone()); + result->AddAttribute(attribute->Clone()); } // return the resulting clone @@ -182,25 +103,24 @@ namespace EMotionFX // removes all attributes void Node::RemoveAllAttributes() { - while (mAttributes.GetLength()) + while (!m_attributes.empty()) { - mAttributes.GetLast()->Destroy(); - mAttributes.RemoveLast(); + m_attributes.back()->Destroy(); + m_attributes.pop_back(); } } // get the total number of children - uint32 Node::GetNumChildNodesRecursive() const + size_t Node::GetNumChildNodesRecursive() const { // the number of total child nodes which include the childs of the childs, too - uint32 result = 0; + size_t result = 0; // retrieve the number of child nodes of the actual node - const uint32 numChildNodes = GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + for (size_t childIndex : m_childIndices) { - mSkeleton->GetNode(mChildIndices[i])->RecursiveCountChildNodes(result); + m_skeleton->GetNode(childIndex)->RecursiveCountChildNodes(result); } return result; @@ -208,22 +128,21 @@ namespace EMotionFX // recursively count the number of nodes down the hierarchy - void Node::RecursiveCountChildNodes(uint32& numNodes) + void Node::RecursiveCountChildNodes(size_t& numNodes) { // increase the counter numNodes++; // recurse down the hierarchy - const uint32 numChildNodes = mChildIndices.GetLength(); - for (uint32 i = 0; i < numChildNodes; ++i) + for (size_t childIndex : m_childIndices) { - mSkeleton->GetNode(mChildIndices[i])->RecursiveCountChildNodes(numNodes); + m_skeleton->GetNode(childIndex)->RecursiveCountChildNodes(numNodes); } } // recursively go through the parents until a root node is reached and store all parents inside an array - void Node::RecursiveCollectParents(AZStd::vector& parents, bool clearParentsArray) const + void Node::RecursiveCollectParents(AZStd::vector& parents, bool clearParentsArray) const { if (clearParentsArray) { @@ -231,12 +150,12 @@ namespace EMotionFX } // loop until we reached a root node - Node* node = const_cast(this); + const Node* node = this; while (node) { // get the parent index and add it to the list of parents if the current node is not a root node - const uint32 parentIndex = node->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + const size_t parentIndex = node->GetParentIndex(); + if (parentIndex != InvalidIndex) { // check if the parent is already in our array, if not add it so that we only store each node once if (AZStd::find(begin(parents), end(parents), parentIndex) == end(parents)) @@ -252,55 +171,29 @@ namespace EMotionFX // remove the given attribute of the given type from the node - void Node::RemoveAttributeByType(uint32 attributeTypeID, uint32 occurrence) + void Node::RemoveAttributeByType(uint32 attributeTypeID, size_t occurrence) { - // retrieve the number of attributes inside this node - const uint32 numAttributes = GetNumAttributes(); - - // counts the number of occurrences of the attribute to search for - uint32 numOccurredAttibutes = 0; - - // iterate through all node attributes - for (uint32 i = 0; i < numAttributes; ++i) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [attributeTypeID, occurrence, currentOccurrence = size_t{0}] (const NodeAttribute* attribute) mutable { - // get the current node attribute - NodeAttribute* nodeAttribute = GetAttribute(i); - - // check the type of the current node attribute and compare the two - if (nodeAttribute->GetType() == attributeTypeID) + if (attribute->GetType() == attributeTypeID) { - // increase the occurrence counter - numOccurredAttibutes++; - - // check if the found attribute is the one we searched - if (occurrence < numOccurredAttibutes) - { - // remove the attribute and return - RemoveAttribute(i); - return; - } + ++currentOccurrence; + return occurrence < currentOccurrence; } - } + return false; + }); + + m_attributes.erase(foundAttribute); } // remove all attributes of the given type from the node - uint32 Node::RemoveAllAttributesByType(uint32 attributeTypeID) + size_t Node::RemoveAllAttributesByType(uint32 attributeTypeID) { - uint32 attributeNumber = MCORE_INVALIDINDEX32; - uint32 numAttributesRemoved = 0; - - // try to find a node of the given attribute type - while ((attributeNumber = FindAttributeNumber(attributeTypeID)) != MCORE_INVALIDINDEX32) + return AZStd::erase_if(m_attributes, [attributeTypeID](const NodeAttribute* attribute) { - // remove the attribute we found and go again - RemoveAttribute(attributeNumber); - - // increase the number of removed attributes - numAttributesRemoved++; - } - - return numAttributesRemoved; + return attribute->GetType() == attributeTypeID; + }); } @@ -308,25 +201,25 @@ namespace EMotionFX // recursively find the root node (expensive call) Node* Node::FindRoot() const { - uint32 parentIndex = mParentIndex; - Node* curNode = const_cast(this); + size_t parentIndex = m_parentIndex; + const Node* curNode = this; - while (parentIndex != MCORE_INVALIDINDEX32) + while (parentIndex != InvalidIndex) { - curNode = mSkeleton->GetNode(parentIndex); + curNode = m_skeleton->GetNode(parentIndex); parentIndex = curNode->GetParentIndex(); } - return curNode; + return const_cast(curNode); } // get the parent node, or nullptr when it doesn't exist Node* Node::GetParentNode() const { - if (mParentIndex != MCORE_INVALIDINDEX32) + if (m_parentIndex != InvalidIndex) { - return mSkeleton->GetNode(mParentIndex); + return m_skeleton->GetNode(m_parentIndex); } return nullptr; @@ -338,11 +231,11 @@ namespace EMotionFX { if (name) { - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } else { - mNameID = MCORE_INVALIDINDEX32; + m_nameId = InvalidIndex32; } } @@ -352,53 +245,53 @@ namespace EMotionFX { if (name) { - mSemanticNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_semanticNameId = MCore::GetStringIdPool().GenerateIdForString(name); } else { - mSemanticNameID = MCORE_INVALIDINDEX32; + m_semanticNameId = InvalidIndex32; } } - void Node::SetParentIndex(uint32 parentNodeIndex) + void Node::SetParentIndex(size_t parentNodeIndex) { - mParentIndex = parentNodeIndex; + m_parentIndex = parentNodeIndex; } // get the name const char* Node::GetName() const { - return MCore::GetStringIdPool().GetName(mNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } // get the name of the node as pointer to chars const AZStd::string& Node::GetNameString() const { - return MCore::GetStringIdPool().GetName(mNameID); + return MCore::GetStringIdPool().GetName(m_nameId); } // get the semantic name const char* Node::GetSemanticName() const { - return MCore::GetStringIdPool().GetName(mSemanticNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_semanticNameId).c_str(); } // get the semantic name of the node as pointer to chars const AZStd::string& Node::GetSemanticNameString() const { - return MCore::GetStringIdPool().GetName(mSemanticNameID); + return MCore::GetStringIdPool().GetName(m_semanticNameId); } // returns true if this is a root node, so if it has no parents bool Node::GetIsRootNode() const { - return (mParentIndex == MCORE_INVALIDINDEX32); + return (m_parentIndex == InvalidIndex); } @@ -406,132 +299,123 @@ namespace EMotionFX void Node::AddAttribute(NodeAttribute* attribute) { - mAttributes.Add(attribute); + m_attributes.emplace_back(attribute); } - uint32 Node::GetNumAttributes() const + size_t Node::GetNumAttributes() const { - return mAttributes.GetLength(); + return m_attributes.size(); } - NodeAttribute* Node::GetAttribute(uint32 attributeNr) + NodeAttribute* Node::GetAttribute(size_t attributeNr) { // make sure we are in range - MCORE_ASSERT(attributeNr < mAttributes.GetLength()); + MCORE_ASSERT(attributeNr < m_attributes.size()); // return the attribute - return mAttributes[attributeNr]; + return m_attributes[attributeNr]; } - uint32 Node::FindAttributeNumber(uint32 attributeTypeID) const + size_t Node::FindAttributeNumber(uint32 attributeTypeID) const { // check all attributes, and find where the specific attribute is - const uint32 numAttributes = mAttributes.GetLength(); - for (uint32 i = 0; i < numAttributes; ++i) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [attributeTypeID](const NodeAttribute* attribute) { - if (mAttributes[i]->GetType() == attributeTypeID) - { - return i; - } - } - - // not found - return MCORE_INVALIDINDEX32; + return attribute->GetType() == attributeTypeID; + }); + return foundAttribute != end(m_attributes) ? AZStd::distance(begin(m_attributes), foundAttribute) : InvalidIndex; } NodeAttribute* Node::GetAttributeByType(uint32 attributeType) { // check all attributes - const uint32 numAttributes = mAttributes.GetLength(); - for (uint32 i = 0; i < numAttributes; ++i) + const auto foundAttribute = AZStd::find_if(begin(m_attributes), end(m_attributes), [attributeType](const NodeAttribute* attribute) { - if (mAttributes[i]->GetType() == attributeType) - { - return mAttributes[i]; - } - } - - // not found - return nullptr; + return attribute->GetType() == attributeType; + }); + return foundAttribute != end(m_attributes) ? *foundAttribute : nullptr; } // remove the given attribute - void Node::RemoveAttribute(uint32 index) + void Node::RemoveAttribute(size_t index) { - mAttributes.Remove(index); + m_attributes.erase(AZStd::next(begin(m_attributes), index)); } - void Node::AddChild(uint32 nodeIndex) + void Node::AddChild(size_t nodeIndex) { - mChildIndices.AddExact(nodeIndex); + m_childIndices.emplace_back(nodeIndex); } - void Node::SetChild(uint32 childNr, uint32 childNodeIndex) + void Node::SetChild(size_t childNr, size_t childNodeIndex) { - mChildIndices[childNr] = childNodeIndex; + m_childIndices[childNr] = childNodeIndex; } - void Node::SetNumChildNodes(uint32 numChildNodes) + void Node::SetNumChildNodes(size_t numChildNodes) { - mChildIndices.Resize(numChildNodes); + m_childIndices.resize(numChildNodes); } - void Node::PreAllocNumChildNodes(uint32 numChildNodes) + void Node::PreAllocNumChildNodes(size_t numChildNodes) { - mChildIndices.Reserve(numChildNodes); + m_childIndices.reserve(numChildNodes); } - void Node::RemoveChild(uint32 nodeIndex) + void Node::RemoveChild(size_t nodeIndex) { - mChildIndices.RemoveByValue(nodeIndex); + if (const auto it = AZStd::find(begin(m_childIndices), end(m_childIndices), nodeIndex); it != end(m_childIndices)) + { + m_childIndices.erase(it); + } } void Node::RemoveAllChildNodes() { - mChildIndices.Clear(); + m_childIndices.clear(); } bool Node::GetHasChildNodes() const { - return (mChildIndices.GetLength() > 0); + return !m_childIndices.empty(); } - void Node::SetNodeIndex(uint32 index) + void Node::SetNodeIndex(size_t index) { - mNodeIndex = index; + m_nodeIndex = index; } - void Node::SetSkeletalLODLevelBits(uint32 bitValues) + void Node::SetSkeletalLODLevelBits(size_t bitValues) { - mSkeletalLODs = bitValues; + m_skeletalLoDs = bitValues; } - void Node::SetSkeletalLODStatus(uint32 lodLevel, bool enabled) + void Node::SetSkeletalLODStatus(size_t lodLevel, bool enabled) { - MCORE_ASSERT(lodLevel <= 31); + MCORE_ASSERT(lodLevel <= 63); if (enabled) { - mSkeletalLODs |= (1 << lodLevel); + m_skeletalLoDs |= (1ull << lodLevel); } else { - mSkeletalLODs &= ~(1 << lodLevel); + m_skeletalLoDs &= ~(1ull << lodLevel); } } @@ -540,11 +424,11 @@ namespace EMotionFX { if (includeThisNode) { - mNodeFlags |= FLAG_INCLUDEINBOUNDSCALC; + m_nodeFlags |= FLAG_INCLUDEINBOUNDSCALC; } else { - mNodeFlags &= ~FLAG_INCLUDEINBOUNDSCALC; + m_nodeFlags &= ~FLAG_INCLUDEINBOUNDSCALC; } } @@ -552,18 +436,18 @@ namespace EMotionFX { if (isCritical) { - mNodeFlags |= FLAG_CRITICAL; + m_nodeFlags |= FLAG_CRITICAL; } else { - mNodeFlags &= ~FLAG_CRITICAL; + m_nodeFlags &= ~FLAG_CRITICAL; } } bool Node::GetIsAttachmentNode() const { - return (mNodeFlags & FLAG_ATTACHMENT) != 0; + return (m_nodeFlags & FLAG_ATTACHMENT) != 0; } @@ -571,11 +455,11 @@ namespace EMotionFX { if (isAttachmentNode) { - mNodeFlags |= FLAG_ATTACHMENT; + m_nodeFlags |= FLAG_ATTACHMENT; } else { - mNodeFlags &= ~FLAG_ATTACHMENT; + m_nodeFlags &= ~FLAG_ATTACHMENT; } } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h index b8618018d2..01dfacc28c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Node.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Node.h @@ -12,7 +12,7 @@ #include #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include #include namespace EMotionFX @@ -85,14 +85,14 @@ namespace EMotionFX * In that case this node is a root node. * @param parentNodeIndex The node index of the node where to link this node to. */ - void SetParentIndex(uint32 parentNodeIndex); + void SetParentIndex(size_t parentNodeIndex); /** * Get the parent node's index. * This is either a valid index, or MCORE_INVALIDINDEX32 in case there is no parent node. * @result The index of the parent node, or MCORE_INVALIDINDEX32 in case this node has no parent. */ - MCORE_INLINE uint32 GetParentIndex() const { return mParentIndex; } + MCORE_INLINE size_t GetParentIndex() const { return m_parentIndex; } /** * Get the parent node as node pointer. @@ -105,7 +105,7 @@ namespace EMotionFX * @param parents The array to which parent and the parents of the parents of the node will be added. * @param clearParentsArray When true the given parents array will be cleared before filling it. */ - void RecursiveCollectParents(AZStd::vector& parents, bool clearParentsArray = true) const; + void RecursiveCollectParents(AZStd::vector& parents, bool clearParentsArray = true) const; /** * Set the node name. @@ -155,68 +155,68 @@ namespace EMotionFX * same ID number. * @result The node ID number, which can be used for fast compares between nodes. */ - MCORE_INLINE uint32 GetID() const { return mNameID; } + MCORE_INLINE uint32 GetID() const { return m_nameId; } /** * Get the semantic name ID. * To get the name you can also use GetSemanticName() and GetSemanticNameString(). * @result The semantic name ID. */ - MCORE_INLINE uint32 GetSemanticID() const { return mSemanticNameID; } + MCORE_INLINE uint32 GetSemanticID() const { return m_semanticNameId; } /** * Get the number of child nodes attached to this node. * @result The number of child nodes. */ - MCORE_INLINE uint32 GetNumChildNodes() const { return mChildIndices.GetLength(); } + MCORE_INLINE size_t GetNumChildNodes() const { return m_childIndices.size(); } /** * Get the number of child nodes down the hierarchy of this node. * The current node is not included in the count. * @return The total number of nodes down the hierarchy of this node. */ - uint32 GetNumChildNodesRecursive() const; + size_t GetNumChildNodesRecursive() const; /** * Get a given child's node index. * @param nr The child number. * @result The index of the child node, which is a node number inside the actor. */ - MCORE_INLINE uint32 GetChildIndex(uint32 nr) const { return mChildIndices[nr]; } + MCORE_INLINE size_t GetChildIndex(size_t nr) const { return m_childIndices[nr]; } /** * Checks if the given node is a child of this node. * @param nodeIndex The node to check whether it is a child or not. * @result True if the given node is a child, false if not. */ - MCORE_INLINE bool CheckIfIsChildNode(uint32 nodeIndex) const { return (mChildIndices.Find(nodeIndex) != MCORE_INVALIDINDEX32); } + MCORE_INLINE bool CheckIfIsChildNode(size_t nodeIndex) const { return (AZStd::find(begin(m_childIndices), end(m_childIndices), nodeIndex) != end(m_childIndices)); } /** * Add a child to this node. * @param nodeIndex The index of the child node to add. */ - void AddChild(uint32 nodeIndex); + void AddChild(size_t nodeIndex); /** * Set the value for a given child node. * @param childNr The child number, which must be in range of [0..GetNumChildNodes()-1]. * @param childNodeIndex The node index for this child. */ - void SetChild(uint32 childNr, uint32 childNodeIndex); + void SetChild(size_t childNr, size_t childNodeIndex); /** * Resize the array of child nodes. * This will grow the child node array so that the value returned by GetNumChildNodes() will return the same value as you specify as parameter here. * @param numChildNodes The number of child nodes to create. Be sure to initialize all of the child nodes using SetChild() though! */ - void SetNumChildNodes(uint32 numChildNodes); + void SetNumChildNodes(size_t numChildNodes); /** * Preallocate the array of child nodes. * Unlike SetNumChildNodes, this will NOT grow the child node array as reported by GetNumChildNodes(). However, it internally pre-allocates memory to make the AddChild() calls faster. * @param numChildNodes The number of child nodes to pre-allocate space for. */ - void PreAllocNumChildNodes(uint32 numChildNodes); + void PreAllocNumChildNodes(size_t numChildNodes); /** * Removes a given child (does not delete it from memory though). @@ -224,7 +224,7 @@ namespace EMotionFX * So you have to adjust the parent pointer of the child node manually. * @param nodeIndex The index of the child to remove. */ - void RemoveChild(uint32 nodeIndex); + void RemoveChild(size_t nodeIndex); /** * Removes all child nodes (not from memory though but just clears the childs pointers in this node). @@ -262,7 +262,7 @@ namespace EMotionFX * Get the number of node attributes. * @result The number of node attributes for this node. */ - uint32 GetNumAttributes() const; + size_t GetNumAttributes() const; /** * Get a given node attribute. @@ -273,7 +273,7 @@ namespace EMotionFX * @result A pointer to the node attribute. * @see FindNodeAttributeNumber */ - NodeAttribute* GetAttribute(uint32 attributeNr); + NodeAttribute* GetAttribute(size_t attributeNr); /** * Get a given node attribute of a given type. @@ -289,7 +289,7 @@ namespace EMotionFX * @param attributeTypeID The attribute type ID (returned by NodeAttribute::GetType()). * @result The first located attribute number which is of the given type, or MCORE_INVALIDINDEX32 when the attribute of this type could not be located. */ - uint32 FindAttributeNumber(uint32 attributeTypeID) const; + size_t FindAttributeNumber(uint32 attributeTypeID) const; /** * Removes all node attributes from this node. @@ -301,7 +301,7 @@ namespace EMotionFX * Remove the given node attribute from this node. * @param index The index of the node attribute to remove. */ - void RemoveAttribute(uint32 index); + void RemoveAttribute(size_t index); /** * Remove the given node attribute from this node which occurs at the given position. @@ -311,14 +311,14 @@ namespace EMotionFX * @param occurrence The number of node attributes which will be skipped until we reached the * node to remove. */ - void RemoveAttributeByType(uint32 attributeTypeID, uint32 occurrence = 0); + void RemoveAttributeByType(uint32 attributeTypeID, size_t occurrence = 0); /** * Removes all node attributes from this node of the given type. * @param attributeTypeID The attribute type ID (returned by NodeAttribute::GetType()). * @result The number of attributes that have been removed. */ - uint32 RemoveAllAttributesByType(uint32 attributeTypeID); + size_t RemoveAllAttributesByType(uint32 attributeTypeID); //-------------------------------------------- @@ -328,7 +328,7 @@ namespace EMotionFX * So Actor::GetNode( nodeIndex ) will return this node. * @param index The index to use. */ - void SetNodeIndex(uint32 index); + void SetNodeIndex(size_t index); /** * Get the node index value. @@ -336,7 +336,7 @@ namespace EMotionFX * So Actor::GetNode( nodeIndex ) will return this node. * @result The index of the node. */ - MCORE_INLINE uint32 GetNodeIndex() const { return mNodeIndex; } + MCORE_INLINE size_t GetNodeIndex() const { return m_nodeIndex; } //------------------------------ @@ -346,7 +346,7 @@ namespace EMotionFX * Bit 0 represents LOD 0, bit 1 represents LOD 1, etc. * @param bitValues The unsigned 32-bits integer that contains the settings for each LOD. */ - void SetSkeletalLODLevelBits(uint32 bitValues); + void SetSkeletalLODLevelBits(size_t bitValues); /** * Set the skeletal LOD status for a given LOD level. @@ -357,14 +357,14 @@ namespace EMotionFX * @param lodLevel The skeletal LOD level to change the settings for. This must be in range of [0..31]. * @param enabled Set to true when you wish the node to be enabled in the given LOD, or false when you wish to disable it in the given LOD. */ - void SetSkeletalLODStatus(uint32 lodLevel, bool enabled); + void SetSkeletalLODStatus(size_t lodLevel, bool enabled); /** * Get the skeletal LOD status for this node at a given skeletal LOD. * @param lodLevel The skeletal LOD level to check. * @result Returns true when this node is enabled in the specified LOD level. Otherwise false is returned. */ - MCORE_INLINE bool GetSkeletalLODStatus(uint32 lodLevel) const { return (mSkeletalLODs & (1 << lodLevel)) != 0; } + MCORE_INLINE bool GetSkeletalLODStatus(size_t lodLevel) const { return (m_skeletalLoDs & (1ull << lodLevel)) != 0; } //-------------------------------------------- @@ -376,7 +376,7 @@ namespace EMotionFX * On default all nodes are included inside the bounding volume calculations. * @result Returns true when this node will be included in the bounds calculation, or false when it won't. */ - MCORE_INLINE bool GetIncludeInBoundsCalc() const { return mNodeFlags & FLAG_INCLUDEINBOUNDSCALC; } + MCORE_INLINE bool GetIncludeInBoundsCalc() const { return m_nodeFlags & FLAG_INCLUDEINBOUNDSCALC; } /** * Specify whether this node should be included inside the bounding volume calculations or not. @@ -394,7 +394,7 @@ namespace EMotionFX * Sometimes we perform optimization process on the node. This flag make sure that critical node will always be included in the actor heirarchy. * @result Returns true when this node is critical, or false when it won't. */ - MCORE_INLINE bool GetIsCritical() const { return mNodeFlags & FLAG_CRITICAL; } + MCORE_INLINE bool GetIsCritical() const { return m_nodeFlags & FLAG_CRITICAL; } /** * Specify whether this node is critcal and should not be optimized out in any situations. @@ -415,15 +415,15 @@ namespace EMotionFX void SetIsAttachmentNode(bool isAttachmentNode); private: - uint32 mNodeIndex; /**< The node index, which is the index into the array of nodes inside the Skeleton class. */ - uint32 mParentIndex; /**< The parent node index, or MCORE_INVALIDINDEX32 when there is no parent. */ - uint32 mSkeletalLODs; /**< The skeletal LOD status values. Each bit represents if this node is enabled or disabled in the given LOD. */ - uint32 mNameID; /**< The ID, which is generated from the name. You can use this for fast compares between nodes. */ - uint32 mSemanticNameID; /**< The semantic name ID, for example "LeftHand" or "RightFoot" or so, this can be used for retargeting. */ - Skeleton* mSkeleton; /**< The skeleton where this node belongs to. */ - MCore::Array mChildIndices; /**< The indices that point to the child nodes. */ - MCore::Array mAttributes; /**< The node attributes. */ - uint8 mNodeFlags; /**< The node flags are used to store boolean attributes of the node as single bits. */ + size_t m_nodeIndex; /**< The node index, which is the index into the array of nodes inside the Skeleton class. */ + size_t m_parentIndex; /**< The parent node index, or MCORE_INVALIDINDEX32 when there is no parent. */ + size_t m_skeletalLoDs; /**< The skeletal LOD status values. Each bit represents if this node is enabled or disabled in the given LOD. */ + uint32 m_nameId; /**< The ID, which is generated from the name. You can use this for fast compares between nodes. */ + uint32 m_semanticNameId; /**< The semantic name ID, for example "LeftHand" or "RightFoot" or so, this can be used for retargeting. */ + Skeleton* m_skeleton; /**< The skeleton where this node belongs to. */ + AZStd::vector m_childIndices; /**< The indices that point to the child nodes. */ + AZStd::vector m_attributes; /**< The node attributes. */ + uint8 m_nodeFlags; /**< The node flags are used to store boolean attributes of the node as single bits. */ /** * Constructor. @@ -450,6 +450,6 @@ namespace EMotionFX * Recursively count the number of nodes down the hierarchy of this node. * @param numNodes The integer containing the current node count. This counter will be increased during recursion. */ - void RecursiveCountChildNodes(uint32& numNodes); + void RecursiveCountChildNodes(size_t& numNodes); }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeAttribute.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeAttribute.h index 30bfbe280c..6fb310d15d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeAttribute.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeAttribute.h @@ -42,7 +42,7 @@ namespace EMotionFX * Clone the node attribute. * @result Returns a pointer to a newly created exact copy of the node attribute. */ - virtual NodeAttribute* Clone() = 0; + virtual NodeAttribute* Clone() const = 0; protected: /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp index e22ad5f064..293d64775d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp @@ -18,9 +18,9 @@ namespace EMotionFX NodeGroup::NodeGroup(const AZStd::string& groupName, uint16 numNodes, bool enabledOnDefault) - : mName(groupName) - , mNodes(numNodes) - , mEnabledOnDefault(enabledOnDefault) + : m_name(groupName) + , m_nodes(numNodes) + , m_enabledOnDefault(enabledOnDefault) { } @@ -28,59 +28,59 @@ namespace EMotionFX // set the name of the group void NodeGroup::SetName(const AZStd::string& groupName) { - mName = groupName; + m_name = groupName; } // get the name of the group as character buffer const char* NodeGroup::GetName() const { - return mName.c_str(); + return m_name.c_str(); } // get the name of the string as mcore string object const AZStd::string& NodeGroup::GetNameString() const { - return mName; + return m_name; } // set the number of nodes void NodeGroup::SetNumNodes(const uint16 numNodes) { - mNodes.Resize(numNodes); + m_nodes.Resize(numNodes); } // get the number of nodes uint16 NodeGroup::GetNumNodes() const { - return static_cast(mNodes.GetLength()); + return static_cast(m_nodes.GetLength()); } // set a given node to a given node number void NodeGroup::SetNode(uint16 index, uint16 nodeIndex) { - mNodes[index] = nodeIndex; + m_nodes[index] = nodeIndex; } // get the node number of a given index - uint16 NodeGroup::GetNode(uint16 index) + uint16 NodeGroup::GetNode(uint16 index) const { - return mNodes[index]; + return m_nodes[index]; } // enable all nodes in the group inside a given actor instance void NodeGroup::EnableNodes(ActorInstance* targetActorInstance) { - const uint16 numNodes = static_cast(mNodes.GetLength()); + const uint16 numNodes = static_cast(m_nodes.GetLength()); for (uint16 i = 0; i < numNodes; ++i) { - targetActorInstance->EnableNode(mNodes[i]); + targetActorInstance->EnableNode(m_nodes[i]); } } @@ -88,10 +88,10 @@ namespace EMotionFX // disable all nodes in the group inside a given actor instance void NodeGroup::DisableNodes(ActorInstance* targetActorInstance) { - const uint16 numNodes = static_cast(mNodes.GetLength()); + const uint16 numNodes = static_cast(m_nodes.GetLength()); for (uint16 i = 0; i < numNodes; ++i) { - targetActorInstance->DisableNode(mNodes[i]); + targetActorInstance->DisableNode(m_nodes[i]); } } @@ -99,42 +99,42 @@ namespace EMotionFX // add a given node to the group (performs a realloc internally) void NodeGroup::AddNode(uint16 nodeIndex) { - mNodes.Add(nodeIndex); + m_nodes.Add(nodeIndex); } // remove a given node by its node number void NodeGroup::RemoveNodeByNodeIndex(uint16 nodeIndex) { - mNodes.RemoveByValue(nodeIndex); + m_nodes.RemoveByValue(nodeIndex); } // remove a given array element from the list of nodes void NodeGroup::RemoveNodeByGroupIndex(uint16 index) { - mNodes.Remove(index); + m_nodes.Remove(index); } // get the node array directly MCore::SmallArray& NodeGroup::GetNodeArray() { - return mNodes; + return m_nodes; } // is this group enabled on default? bool NodeGroup::GetIsEnabledOnDefault() const { - return mEnabledOnDefault; + return m_enabledOnDefault; } // set the default enabled state void NodeGroup::SetIsEnabledOnDefault(bool enabledOnDefault) { - mEnabledOnDefault = enabledOnDefault; + m_enabledOnDefault = enabledOnDefault; } NodeGroup::NodeGroup(const NodeGroup& aOther) @@ -144,9 +144,9 @@ namespace EMotionFX NodeGroup& NodeGroup::operator=(const NodeGroup& aOther) { - mName = aOther.mName; - mNodes = aOther.mNodes; - mEnabledOnDefault = aOther.mEnabledOnDefault; + m_name = aOther.m_name; + m_nodes = aOther.m_nodes; + m_enabledOnDefault = aOther.m_enabledOnDefault; return *this; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h index dfe876c86a..7ee74415c0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h @@ -82,7 +82,7 @@ namespace EMotionFX * @param index The node number inside this group, which must be in range of [0..GetNumNodes()-1]. * @result The node number, which points inside the Actor object. Use Actor::GetNode( returnValue ) to get access to the node information. */ - uint16 GetNode(uint16 index); + uint16 GetNode(uint16 index) const; /** * Enable all nodes that remain inside this group, for a given actor instance. @@ -154,8 +154,8 @@ namespace EMotionFX void SetIsEnabledOnDefault(bool enabledOnDefault); private: - AZStd::string mName; /**< The name of the group. */ - MCore::SmallArray mNodes; /**< The node index numbers that are inside this group. */ - bool mEnabledOnDefault; /**< Specifies whether this group is enabled on default (true) or disabled (false). With on default we mean after directly after the actor instance using this group has been created. */ + AZStd::string m_name; /**< The name of the group. */ + MCore::SmallArray m_nodes; /**< The node index numbers that are inside this group. */ + bool m_enabledOnDefault; /**< Specifies whether this group is enabled on default (true) or disabled (false). With on default we mean after directly after the actor instance using this group has been created. */ }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp index 8f2e752917..f9774751ba 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.cpp @@ -27,7 +27,7 @@ namespace EMotionFX NodeMap::NodeMap() : BaseObject() { - mSourceActor = nullptr; + m_sourceActor = nullptr; } @@ -39,38 +39,38 @@ namespace EMotionFX // preallocate space - void NodeMap::Reserve(uint32 numEntries) + void NodeMap::Reserve(size_t numEntries) { - mEntries.Reserve(numEntries); + m_entries.reserve(numEntries); } // resize the entries array - void NodeMap::Resize(uint32 numEntries) + void NodeMap::Resize(size_t numEntries) { - mEntries.Resize(numEntries); + m_entries.resize(numEntries); } // modify the first name of a given entry - void NodeMap::SetFirstName(uint32 entryIndex, const char* name) + void NodeMap::SetFirstName(size_t entryIndex, const char* name) { - mEntries[entryIndex].mFirstNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_entries[entryIndex].m_firstNameId = MCore::GetStringIdPool().GenerateIdForString(name); } // modify the second name - void NodeMap::SetSecondName(uint32 entryIndex, const char* name) + void NodeMap::SetSecondName(size_t entryIndex, const char* name) { - mEntries[entryIndex].mSecondNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_entries[entryIndex].m_secondNameId = MCore::GetStringIdPool().GenerateIdForString(name); } // modify a given entry - void NodeMap::SetEntry(uint32 entryIndex, const char* firstName, const char* secondName) + void NodeMap::SetEntry(size_t entryIndex, const char* firstName, const char* secondName) { - mEntries[entryIndex].mFirstNameID = MCore::GetStringIdPool().GenerateIdForString(firstName); - mEntries[entryIndex].mSecondNameID = MCore::GetStringIdPool().GenerateIdForString(secondName); + m_entries[entryIndex].m_firstNameId = MCore::GetStringIdPool().GenerateIdForString(firstName); + m_entries[entryIndex].m_secondNameId = MCore::GetStringIdPool().GenerateIdForString(secondName); } @@ -78,8 +78,8 @@ namespace EMotionFX void NodeMap::SetEntry(const char* firstName, const char* secondName, bool addIfNotExists) { // check if there is already an entry for this name - const uint32 entryIndex = FindEntryIndexByName(firstName); - if (entryIndex == MCORE_INVALIDINDEX32) + const size_t entryIndex = FindEntryIndexByName(firstName); + if (entryIndex == InvalidIndex) { // if there is no such entry yet, and we also don't want to add a new one, then there is nothing to do if (addIfNotExists == false) @@ -101,62 +101,62 @@ namespace EMotionFX void NodeMap::AddEntry(const char* firstName, const char* secondName) { MCORE_ASSERT(GetHasEntry(firstName) == false); // prevent duplicates - mEntries.AddEmpty(); - SetEntry(mEntries.GetLength() - 1, firstName, secondName); + m_entries.emplace_back(); + SetEntry(m_entries.size() - 1, firstName, secondName); } // remove a given entry by its index - void NodeMap::RemoveEntryByIndex(uint32 entryIndex) + void NodeMap::RemoveEntryByIndex(size_t entryIndex) { - mEntries.Remove(entryIndex); + m_entries.erase(AZStd::next(begin(m_entries), entryIndex)); } // remove a given entry by its name void NodeMap::RemoveEntryByName(const char* firstName) { - const uint32 entryIndex = FindEntryIndexByName(firstName); - if (entryIndex == MCORE_INVALIDINDEX32) + const size_t entryIndex = FindEntryIndexByName(firstName); + if (entryIndex == InvalidIndex) { return; } - mEntries.Remove(entryIndex); + m_entries.erase(AZStd::next(begin(m_entries), entryIndex)); } // remove a given entry by its name ID void NodeMap::RemoveEntryByNameID(uint32 firstNameID) { - const uint32 entryIndex = FindEntryIndexByNameID(firstNameID); - if (entryIndex == MCORE_INVALIDINDEX32) + const size_t entryIndex = FindEntryIndexByNameID(firstNameID); + if (entryIndex == InvalidIndex) { return; } - mEntries.Remove(entryIndex); + m_entries.erase(AZStd::next(begin(m_entries), entryIndex)); } // set the filename void NodeMap::SetFileName(const char* fileName) { - mFileName = fileName; + m_fileName = fileName; } // get the filename const char* NodeMap::GetFileName() const { - return mFileName.c_str(); + return m_fileName.c_str(); } // get the filename const AZStd::string& NodeMap::GetFileNameString() const { - return mFileName; + return m_fileName; } @@ -208,18 +208,18 @@ namespace EMotionFX uint32 NodeMap::CalcFileChunkSize() const { // add the node map info header - uint32 numBytes = sizeof(FileFormat::NodeMapChunk); + size_t numBytes = sizeof(FileFormat::NodeMapChunk); // for all entries - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + const size_t numEntries = m_entries.size(); + for (size_t i = 0; i < numEntries; ++i) { numBytes += CalcFileStringSize(GetFirstNameString(i)); numBytes += CalcFileStringSize(GetSecondNameString(i)); } // return the number of bytes - return numBytes; + return aznumeric_caster(numBytes); } @@ -236,13 +236,13 @@ namespace EMotionFX // try to write the file header FileFormat::NodeMap_Header header{}; - header.mFourCC[0] = 'N'; - header.mFourCC[1] = 'O'; - header.mFourCC[2] = 'M'; - header.mFourCC[3] = 'P'; - header.mHiVersion = 1; - header.mLoVersion = 0; - header.mEndianType = (uint8)targetEndianType; + header.m_fourCc[0] = 'N'; + header.m_fourCc[1] = 'O'; + header.m_fourCc[2] = 'M'; + header.m_fourCc[3] = 'P'; + header.m_hiVersion = 1; + header.m_loVersion = 0; + header.m_endianType = (uint8)targetEndianType; if (f.Write(&header, sizeof(FileFormat::NodeMap_Header)) == 0) { MCore::LogError("NodeMap::Save() - Cannot write the header to file '%s', is the file maybe in use by another application?", fileName); @@ -251,12 +251,12 @@ namespace EMotionFX // write the chunk header FileFormat::FileChunk chunkHeader{}; - chunkHeader.mChunkID = FileFormat::CHUNK_NODEMAP; - chunkHeader.mVersion = 1; - chunkHeader.mSizeInBytes = CalcFileChunkSize();// calculate the chunk size - MCore::Endian::ConvertUnsignedInt32To(&chunkHeader.mChunkID, targetEndianType); - MCore::Endian::ConvertUnsignedInt32To(&chunkHeader.mSizeInBytes, targetEndianType); - MCore::Endian::ConvertUnsignedInt32To(&chunkHeader.mVersion, targetEndianType); + chunkHeader.m_chunkId = FileFormat::CHUNK_NODEMAP; + chunkHeader.m_version = 1; + chunkHeader.m_sizeInBytes = CalcFileChunkSize();// calculate the chunk size + MCore::Endian::ConvertUnsignedInt32To(&chunkHeader.m_chunkId, targetEndianType); + MCore::Endian::ConvertUnsignedInt32To(&chunkHeader.m_sizeInBytes, targetEndianType); + MCore::Endian::ConvertUnsignedInt32To(&chunkHeader.m_version, targetEndianType); if (f.Write(&chunkHeader, sizeof(FileFormat::FileChunk)) == 0) { MCore::LogError("NodeMap::Save() - Cannot write the chunk header to file '%s', is the file maybe in use by another application?", fileName); @@ -265,8 +265,8 @@ namespace EMotionFX // the main info FileFormat::NodeMapChunk nodeMapChunk{}; - nodeMapChunk.mNumEntries = mEntries.GetLength(); - MCore::Endian::ConvertUnsignedInt32To(&nodeMapChunk.mNumEntries, targetEndianType); + nodeMapChunk.m_numEntries = aznumeric_caster(m_entries.size()); + MCore::Endian::ConvertUnsignedInt32To(&nodeMapChunk.m_numEntries, targetEndianType); if (f.Write(&nodeMapChunk, sizeof(FileFormat::NodeMapChunk)) == 0) { MCore::LogError("NodeMap::Save() - Cannot write the node map chunk to file '%s', is the file maybe in use by another application?", fileName); @@ -282,7 +282,7 @@ namespace EMotionFX } // for all entries - const uint32 numEntries = mEntries.GetLength(); + const uint32 numEntries = aznumeric_caster(m_entries.size()); for (uint32 i = 0; i < numEntries; ++i) { if (WriteFileString(&f, GetFirstNameString(i), targetEndianType) == false) @@ -308,97 +308,86 @@ namespace EMotionFX // update the source actor pointer void NodeMap::SetSourceActor(Actor* actor) { - mSourceActor = actor; + m_sourceActor = actor; } // get the source actor pointer Actor* NodeMap::GetSourceActor() const { - return mSourceActor; + return m_sourceActor; } // get the number of entries - uint32 NodeMap::GetNumEntries() const + size_t NodeMap::GetNumEntries() const { - return mEntries.GetLength(); + return m_entries.size(); } // get the first name as char pointer - const char* NodeMap::GetFirstName(uint32 entryIndex) const + const char* NodeMap::GetFirstName(size_t entryIndex) const { - return MCore::GetStringIdPool().GetName(mEntries[entryIndex].mFirstNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_entries[entryIndex].m_firstNameId).c_str(); } // get the second node name as char pointer - const char* NodeMap::GetSecondName(uint32 entryIndex) const + const char* NodeMap::GetSecondName(size_t entryIndex) const { - return MCore::GetStringIdPool().GetName(mEntries[entryIndex].mSecondNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_entries[entryIndex].m_secondNameId).c_str(); } // get the first node name as string - const AZStd::string& NodeMap::GetFirstNameString(uint32 entryIndex) const + const AZStd::string& NodeMap::GetFirstNameString(size_t entryIndex) const { - return MCore::GetStringIdPool().GetName(mEntries[entryIndex].mFirstNameID); + return MCore::GetStringIdPool().GetName(m_entries[entryIndex].m_firstNameId); } // get the second node name as string - const AZStd::string& NodeMap::GetSecondNameString(uint32 entryIndex) const + const AZStd::string& NodeMap::GetSecondNameString(size_t entryIndex) const { - return MCore::GetStringIdPool().GetName(mEntries[entryIndex].mSecondNameID); + return MCore::GetStringIdPool().GetName(m_entries[entryIndex].m_secondNameId); } // check if we already have an entry for this name bool NodeMap::GetHasEntry(const char* firstName) const { - return (FindEntryIndexByName(firstName) != MCORE_INVALIDINDEX32); + return (FindEntryIndexByName(firstName) != InvalidIndex); } // find an entry index by its name - uint32 NodeMap::FindEntryIndexByName(const char* firstName) const + size_t NodeMap::FindEntryIndexByName(const char* firstName) const { - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [firstName](const MapEntry& entry) { - const AZStd::string& firstNameEntry = GetFirstName(i); - if (firstNameEntry == firstName) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return MCore::GetStringIdPool().GetName(entry.m_firstNameId) == firstName; + }); + return foundEntry != end(m_entries) ? AZStd::distance(begin(m_entries), foundEntry) : InvalidIndex; } // find an entry index by its name ID - uint32 NodeMap::FindEntryIndexByNameID(uint32 firstNameID) const + size_t NodeMap::FindEntryIndexByNameID(uint32 firstNameID) const { - const uint32 numEntries = mEntries.GetLength(); - for (uint32 i = 0; i < numEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(m_entries), end(m_entries), [firstNameID](const MapEntry& entry) { - if (mEntries[i].mFirstNameID == firstNameID) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return entry.m_firstNameId == firstNameID; + }); + return foundEntry != end(m_entries) ? AZStd::distance(begin(m_entries), foundEntry) : InvalidIndex; } // find the second name for a given first name const char* NodeMap::FindSecondName(const char* firstName) const { - const uint32 entryIndex = FindEntryIndexByName(firstName); - if (entryIndex == MCORE_INVALIDINDEX32) + const size_t entryIndex = FindEntryIndexByName(firstName); + if (entryIndex == InvalidIndex) { return nullptr; } @@ -410,8 +399,8 @@ namespace EMotionFX // find the second name based on a first given name void NodeMap::FindSecondName(const char* firstName, AZStd::string* outString) { - const uint32 entryIndex = FindEntryIndexByName(firstName); - if (entryIndex == MCORE_INVALIDINDEX32) + const size_t entryIndex = FindEntryIndexByName(firstName); + if (entryIndex == InvalidIndex) { outString->clear(); return; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h index d033d0a36f..c0744323af 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeMap.h @@ -11,7 +11,7 @@ // include required files #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include #include #include @@ -39,39 +39,35 @@ namespace EMotionFX public: struct MapEntry { - uint32 mFirstNameID; /**< The first name ID, which is the primary key in the map. */ - uint32 mSecondNameID; /**< The second name ID. */ - - MapEntry() - : mFirstNameID(MCORE_INVALIDINDEX32) - , mSecondNameID(MCORE_INVALIDINDEX32) {} + uint32 m_firstNameId = InvalidIndex32; /**< The first name ID, which is the primary key in the map. */ + uint32 m_secondNameId = InvalidIndex32; /**< The second name ID. */ }; static NodeMap* Create(); // prealloc space in the map - void Reserve(uint32 numEntries); - void Resize(uint32 numEntries); + void Reserve(size_t numEntries); + void Resize(size_t numEntries); // get data - uint32 GetNumEntries() const; - const char* GetFirstName(uint32 entryIndex) const; - const char* GetSecondName(uint32 entryIndex) const; - const AZStd::string& GetFirstNameString(uint32 entryIndex) const; - const AZStd::string& GetSecondNameString(uint32 entryIndex) const; + size_t GetNumEntries() const; + const char* GetFirstName(size_t entryIndex) const; + const char* GetSecondName(size_t entryIndex) const; + const AZStd::string& GetFirstNameString(size_t entryIndex) const; + const AZStd::string& GetSecondNameString(size_t entryIndex) const; bool GetHasEntry(const char* firstName) const; - uint32 FindEntryIndexByName(const char* firstName) const; - uint32 FindEntryIndexByNameID(uint32 firstNameID) const; + size_t FindEntryIndexByName(const char* firstName) const; + size_t FindEntryIndexByNameID(uint32 firstNameID) const; const char* FindSecondName(const char* firstName) const; void FindSecondName(const char* firstName, AZStd::string* outString); // set/modify - void SetFirstName(uint32 entryIndex, const char* name); - void SetSecondName(uint32 entryIndex, const char* name); - void SetEntry(uint32 entryIndex, const char* firstName, const char* secondName); + void SetFirstName(size_t entryIndex, const char* name); + void SetSecondName(size_t entryIndex, const char* name); + void SetEntry(size_t entryIndex, const char* firstName, const char* secondName); void AddEntry(const char* firstName, const char* secondName); void SetEntry(const char* firstName, const char* secondName, bool addIfNotExists); - void RemoveEntryByIndex(uint32 entryIndex); + void RemoveEntryByIndex(size_t entryIndex); void RemoveEntryByName(const char* firstName); void RemoveEntryByNameID(uint32 firstNameID); @@ -88,9 +84,9 @@ namespace EMotionFX bool Save(const char* fileName, MCore::Endian::EEndianType targetEndianType) const; private: - MCore::Array mEntries; /**< The array of entries. */ - AZStd::string mFileName; /**< The filename. */ - Actor* mSourceActor; /**< The source actor. */ + AZStd::vector m_entries; /**< The array of entries. */ + AZStd::string m_fileName; /**< The filename. */ + Actor* m_sourceActor; /**< The source actor. */ // constructor and destructor NodeMap(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp index 0b799bcb1b..02b3fd7649 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/PhysicsSetup.cpp @@ -496,7 +496,7 @@ namespace EMotionFX : Transform::CreateIdentity(); // if there are child nodes, point the bone direction to the average of their positions - const uint32 numChildNodes = node->GetNumChildNodes(); + const size_t numChildNodes = node->GetNumChildNodes(); if (numChildNodes > 0) { AZ::Vector3 meanChildPosition = AZ::Vector3::CreateZero(); @@ -504,21 +504,21 @@ namespace EMotionFX // weight by the number of descendants of each child node, so that things like jiggle bones and twist bones // have little influence on the bone direction. float totalSubChildren = 0.0f; - for (uint32 childNumber = 0; childNumber < numChildNodes; childNumber++) + for (size_t childNumber = 0; childNumber < numChildNodes; childNumber++) { - const uint32 childIndex = node->GetChildIndex(childNumber); + const size_t childIndex = node->GetChildIndex(childNumber); const Node* childNode = skeleton->GetNode(childIndex); const float numSubChildren = static_cast(1 + childNode->GetNumChildNodesRecursive()); totalSubChildren += numSubChildren; - meanChildPosition += numSubChildren * (bindPose->GetModelSpaceTransform(childIndex).mPosition); + meanChildPosition += numSubChildren * (bindPose->GetModelSpaceTransform(childIndex).m_position); } - boneDirection = meanChildPosition / totalSubChildren - nodeBindTransform.mPosition; + boneDirection = meanChildPosition / totalSubChildren - nodeBindTransform.m_position; } // otherwise, point the bone direction away from the parent else { - boneDirection = nodeBindTransform.mPosition - parentBindTransform.mPosition; + boneDirection = nodeBindTransform.m_position - parentBindTransform.m_position; } return boneDirection; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/PlayBackInfo.h b/Gems/EMotionFX/Code/EMotionFX/Source/PlayBackInfo.h index 6ae2b0d809..de84a97da8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/PlayBackInfo.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/PlayBackInfo.h @@ -65,29 +65,29 @@ namespace EMotionFX *
          * Member Name           - Default Value
          * ---------------------------------
-         * mBlendInTime          - 0.3 (seconds)
-         * mBlendOutTime         - 0.3 (seconds)
-         * mPlaySpeed            - 1.0 (original speed)
-         * mTargetWeight         - 1.0 (fully blend in)
-         * mEventWeightThreshold - 0.0 (allow all events even with low motion instance weight values)
-         * mMaxPlayTime          - 0.0 (disabled when zero or negative)
-         * mClipStartTime        - 0.0 (start and loop from the beginning of the motion)
-         * mClipEndTime          - 0.0 (set to negative or zero to play the full range of the motion)
-         * mNumLoops             - EMFX_LOOPFOREVER
-         * mBlendMode            - BLENDMODE_OVERWRITE (overwrites motions)
-         * mPlayMode             - PLAYMODE_FORWARD (regular forward playing motion)
-         * mMirrorMotion         - false (disable motion mirroring)
-         * mPlayNow              - true (start playing immediately)
-         * mMix                  - false (non mixing motion)
-         * mPriorityLevel        - 0 (no priority)
-         * mMotionExtractionEnabled - true
-         * mRetarget             - false (no motion retargeting allowed)
-         * mFreezeAtLastFrame    - true (motion freezes in last frame when not looping forever)
-         * mEnableMotionEvents   - true (all motion events will be processed for this motion instance
-         * mBlendOutBeforeEnded  - true (blend out so that it faded out at the end of the motion).
-         * mCanOverwrite         - true (can overwrite other motion instances when reaching a weight of 1.0)
-         * mDeleteOnZeroWeight   - true (delete this motion instance when it reaches a weight of 0.0)
-         * mFreezeAtTime;        - -1.0 (Freeze at a given time offset in seconds. The current play time would continue running though, and a blend out would be triggered, unlike the mFreezeAtLastFrame. Set to negative value to disable.
+         * m_blendInTime          - 0.3 (seconds)
+         * m_blendOutTime         - 0.3 (seconds)
+         * m_playSpeed            - 1.0 (original speed)
+         * m_targetWeight         - 1.0 (fully blend in)
+         * m_eventWeightThreshold - 0.0 (allow all events even with low motion instance weight values)
+         * m_maxPlayTime          - 0.0 (disabled when zero or negative)
+         * m_clipStartTime        - 0.0 (start and loop from the beginning of the motion)
+         * m_clipEndTime          - 0.0 (set to negative or zero to play the full range of the motion)
+         * m_numLoops             - EMFX_LOOPFOREVER
+         * m_blendMode            - BLENDMODE_OVERWRITE (overwrites motions)
+         * m_playMode             - PLAYMODE_FORWARD (regular forward playing motion)
+         * m_mirrorMotion         - false (disable motion mirroring)
+         * m_playNow              - true (start playing immediately)
+         * m_mix                  - false (non mixing motion)
+         * m_priorityLevel        - 0 (no priority)
+         * m_motionExtractionEnabled - true
+         * m_retarget             - false (no motion retargeting allowed)
+         * m_freezeAtLastFrame    - true (motion freezes in last frame when not looping forever)
+         * m_enableMotionEvents   - true (all motion events will be processed for this motion instance
+         * m_blendOutBeforeEnded  - true (blend out so that it faded out at the end of the motion).
+         * m_canOverwrite         - true (can overwrite other motion instances when reaching a weight of 1.0)
+         * m_deleteOnZeroWeight   - true (delete this motion instance when it reaches a weight of 0.0)
+         * m_freezeAtTime;        - -1.0 (Freeze at a given time offset in seconds. The current play time would continue running though, and a blend out would be triggered, unlike the m_freezeAtLastFrame. Set to negative value to disable.
          *
          * 
* @@ -95,30 +95,30 @@ namespace EMotionFX */ PlayBackInfo() { - mBlendInTime = 0.3f; - mBlendOutTime = 0.3f; - mPlaySpeed = 1.0f; - mTargetWeight = 1.0f; - mEventWeightThreshold = 0.0f; - mMaxPlayTime = 0.0f; - mClipStartTime = 0.0f; - mClipEndTime = 0.0f; - mFreezeAtTime = -1.0f; - mNumLoops = EMFX_LOOPFOREVER; - mBlendMode = BLENDMODE_OVERWRITE; - mPlayMode = PLAYMODE_FORWARD; - mMirrorMotion = false; - mPlayNow = true; - mMix = false; - mMotionExtractionEnabled = true; - mRetarget = false; - mFreezeAtLastFrame = true; - mEnableMotionEvents = true; - mBlendOutBeforeEnded = true; - mCanOverwrite = true; - mDeleteOnZeroWeight = true; - mInPlace = false; - mPriorityLevel = 0; + m_blendInTime = 0.3f; + m_blendOutTime = 0.3f; + m_playSpeed = 1.0f; + m_targetWeight = 1.0f; + m_eventWeightThreshold = 0.0f; + m_maxPlayTime = 0.0f; + m_clipStartTime = 0.0f; + m_clipEndTime = 0.0f; + m_freezeAtTime = -1.0f; + m_numLoops = EMFX_LOOPFOREVER; + m_blendMode = BLENDMODE_OVERWRITE; + m_playMode = PLAYMODE_FORWARD; + m_mirrorMotion = false; + m_playNow = true; + m_mix = false; + m_motionExtractionEnabled = true; + m_retarget = false; + m_freezeAtLastFrame = true; + m_enableMotionEvents = true; + m_blendOutBeforeEnded = true; + m_canOverwrite = true; + m_deleteOnZeroWeight = true; + m_inPlace = false; + m_priorityLevel = 0; } /** @@ -128,29 +128,29 @@ namespace EMotionFX public: - float mBlendInTime; /**< The time, in seconds, which it will take to fully have blended to the target weight. */ - float mBlendOutTime; /**< The time, in seconds, which it takes to smoothly fadeout the motion, after it has been stopped playing. */ - float mPlaySpeed; /**< The playback speed factor. A value of 1 stands for the original speed, while for example 2 means twice the original speed. */ - float mTargetWeight; /**< The target weight, where 1 means fully active, and 0 means not active at all. */ - float mEventWeightThreshold; /**< The motion event weight threshold. If the motion instance weight is lower than this value, no motion events will be executed for this motion instance. */ - float mMaxPlayTime; /**< The maximum play time, in seconds. Set to zero or a negative value to disable it. */ - float mClipStartTime; /**< The start playback time in seconds. Also in case of looping it will jump to this position on a loop. */ - float mClipEndTime; /**< The end playback time in seconds. It will jump back to the clip start time after reaching this playback time. */ - float mFreezeAtTime; /**< Freeze at a given time offset in seconds. The current play time would continue running though, and a blend out would be triggered, unlike the mFreezeAtLastFrame. Set to negative value to disable. Default=-1.*/ - uint32 mNumLoops; /**< The number of times you want to play this motion. A value of EMFX_LOOPFOREVER means it will loop forever. */ - uint32 mPriorityLevel; /**< The priority level, the higher this value, the higher priority it has on overwriting other motions. */ - EMotionBlendMode mBlendMode; /**< The motion blend mode. Please read the MotionInstance::SetBlendMode(...) method for more information. */ - EPlayMode mPlayMode; /**< The motion playback mode. This means forward or backward playback. */ - bool mMirrorMotion; /**< Is motion mirroring enabled or not? When set to true, the mMirrorPlaneNormal is used as mirroring axis. */ - bool mMix; /**< Set to true if you want this motion to mix or not. */ - bool mPlayNow; /**< Set to true if you want to start playing the motion right away. If set to false it will be scheduled for later by inserting it into the motion queue. */ - bool mMotionExtractionEnabled; /**< Set to true if you want this motion to move and rotate the actor instance, otherwise set to false. */ - bool mRetarget; /**< Set to true if you want to enable motion retargeting. Read the manual for more information. */ - bool mFreezeAtLastFrame; /**< Set to true if you like the motion to freeze at the last frame, for example in case of a death motion. */ - bool mEnableMotionEvents; /**< Set to true to enable motion events, or false to disable processing of motion events for this motion instance. */ - bool mBlendOutBeforeEnded; /**< Set to true if you want the motion to be stopped so that it exactly faded out when the motion/loop fully finished. If set to false it will fade out after the loop has completed (and starts repeating). The default is true. */ - bool mCanOverwrite; /**< Set to true if you want this motion to be able to delete other underlaying motion instances when this motion instance reaches a weight of 1.0.*/ - bool mDeleteOnZeroWeight; /**< Set to true if you wish to delete this motion instance once it reaches a weight of 0.0. */ - bool mInPlace; /**< Set to true if you want the motion to play in place. This means the root of the motion will not move. */ + float m_blendInTime; /**< The time, in seconds, which it will take to fully have blended to the target weight. */ + float m_blendOutTime; /**< The time, in seconds, which it takes to smoothly fadeout the motion, after it has been stopped playing. */ + float m_playSpeed; /**< The playback speed factor. A value of 1 stands for the original speed, while for example 2 means twice the original speed. */ + float m_targetWeight; /**< The target weight, where 1 means fully active, and 0 means not active at all. */ + float m_eventWeightThreshold; /**< The motion event weight threshold. If the motion instance weight is lower than this value, no motion events will be executed for this motion instance. */ + float m_maxPlayTime; /**< The maximum play time, in seconds. Set to zero or a negative value to disable it. */ + float m_clipStartTime; /**< The start playback time in seconds. Also in case of looping it will jump to this position on a loop. */ + float m_clipEndTime; /**< The end playback time in seconds. It will jump back to the clip start time after reaching this playback time. */ + float m_freezeAtTime; /**< Freeze at a given time offset in seconds. The current play time would continue running though, and a blend out would be triggered, unlike the m_freezeAtLastFrame. Set to negative value to disable. Default=-1.*/ + uint32 m_numLoops; /**< The number of times you want to play this motion. A value of EMFX_LOOPFOREVER means it will loop forever. */ + uint32 m_priorityLevel; /**< The priority level, the higher this value, the higher priority it has on overwriting other motions. */ + EMotionBlendMode m_blendMode; /**< The motion blend mode. Please read the MotionInstance::SetBlendMode(...) method for more information. */ + EPlayMode m_playMode; /**< The motion playback mode. This means forward or backward playback. */ + bool m_mirrorMotion; /**< Is motion mirroring enabled or not? When set to true, the m_mirrorPlaneNormal is used as mirroring axis. */ + bool m_mix; /**< Set to true if you want this motion to mix or not. */ + bool m_playNow; /**< Set to true if you want to start playing the motion right away. If set to false it will be scheduled for later by inserting it into the motion queue. */ + bool m_motionExtractionEnabled; /**< Set to true if you want this motion to move and rotate the actor instance, otherwise set to false. */ + bool m_retarget; /**< Set to true if you want to enable motion retargeting. Read the manual for more information. */ + bool m_freezeAtLastFrame; /**< Set to true if you like the motion to freeze at the last frame, for example in case of a death motion. */ + bool m_enableMotionEvents; /**< Set to true to enable motion events, or false to disable processing of motion events for this motion instance. */ + bool m_blendOutBeforeEnded; /**< Set to true if you want the motion to be stopped so that it exactly faded out when the motion/loop fully finished. If set to false it will fade out after the loop has completed (and starts repeating). The default is true. */ + bool m_canOverwrite; /**< Set to true if you want this motion to be able to delete other underlaying motion instances when this motion instance reaches a weight of 1.0.*/ + bool m_deleteOnZeroWeight; /**< Set to true if you wish to delete this motion instance once it reaches a weight of 0.0. */ + bool m_inPlace; /**< Set to true if you want the motion to play in place. This means the root of the motion will not move. */ }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp index e42393212d..23390bf69b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.cpp @@ -21,19 +21,13 @@ namespace EMotionFX // default constructor Pose::Pose() { - mActorInstance = nullptr; - mActor = nullptr; - mSkeleton = nullptr; - mLocalSpaceTransforms.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); - mModelSpaceTransforms.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); - mFlags.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); - mMorphWeights.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); - - // reset morph weights - //mMorphWeights.Reserve(32); - //mLocalSpaceTransforms.Reserve(128); - //mModelSpaceTransforms.Reserve(128); - //mFlags.Reserve(128); + m_actorInstance = nullptr; + m_actor = nullptr; + m_skeleton = nullptr; + m_localSpaceTransforms.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); + m_modelSpaceTransforms.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); + m_flags.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); + m_morphWeights.SetMemoryCategory(EMFX_MEMCATEGORY_ANIMGRAPH_POSE); } @@ -55,16 +49,16 @@ namespace EMotionFX void Pose::LinkToActorInstance(const ActorInstance* actorInstance, uint8 initialFlags) { // store the pointer to the actor instance etc - mActorInstance = actorInstance; - mActor = actorInstance->GetActor(); - mSkeleton = mActor->GetSkeleton(); + m_actorInstance = actorInstance; + m_actor = actorInstance->GetActor(); + m_skeleton = m_actor->GetSkeleton(); // resize the buffers - const uint32 numTransforms = mActor->GetSkeleton()->GetNumNodes(); - mLocalSpaceTransforms.ResizeFast(numTransforms); - mModelSpaceTransforms.ResizeFast(numTransforms); - mFlags.ResizeFast(numTransforms); - mMorphWeights.ResizeFast(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets()); + const size_t numTransforms = m_actor->GetSkeleton()->GetNumNodes(); + m_localSpaceTransforms.ResizeFast(numTransforms); + m_modelSpaceTransforms.ResizeFast(numTransforms); + m_flags.ResizeFast(numTransforms); + m_morphWeights.ResizeFast(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets()); for (const auto& poseDataItem : m_poseDatas) { @@ -79,27 +73,27 @@ namespace EMotionFX // link the pose to a given actor void Pose::LinkToActor(const Actor* actor, uint8 initialFlags, bool clearAllFlags) { - mActorInstance = nullptr; - mActor = actor; - mSkeleton = actor->GetSkeleton(); + m_actorInstance = nullptr; + m_actor = actor; + m_skeleton = actor->GetSkeleton(); // resize the buffers - const uint32 numTransforms = mActor->GetSkeleton()->GetNumNodes(); - mLocalSpaceTransforms.ResizeFast(numTransforms); - mModelSpaceTransforms.ResizeFast(numTransforms); + const size_t numTransforms = m_actor->GetSkeleton()->GetNumNodes(); + m_localSpaceTransforms.ResizeFast(numTransforms); + m_modelSpaceTransforms.ResizeFast(numTransforms); - const uint32 oldSize = mFlags.GetLength(); - mFlags.ResizeFast(numTransforms); + const size_t oldSize = m_flags.GetLength(); + m_flags.ResizeFast(numTransforms); if (oldSize < numTransforms && clearAllFlags == false) { - for (uint32 i = oldSize; i < numTransforms; ++i) + for (size_t i = oldSize; i < numTransforms; ++i) { - mFlags[i] = initialFlags; + m_flags[i] = initialFlags; } } - MorphSetup* morphSetup = mActor->GetMorphSetup(0); - mMorphWeights.ResizeFast((morphSetup) ? morphSetup->GetNumMorphTargets() : 0); + MorphSetup* morphSetup = m_actor->GetMorphSetup(0); + m_morphWeights.ResizeFast((morphSetup) ? morphSetup->GetNumMorphTargets() : 0); for (const auto& poseDataItem : m_poseDatas) { @@ -114,18 +108,18 @@ namespace EMotionFX } // - void Pose::SetNumTransforms(uint32 numTransforms) + void Pose::SetNumTransforms(size_t numTransforms) { // resize the buffers - mLocalSpaceTransforms.ResizeFast(numTransforms); - mModelSpaceTransforms.ResizeFast(numTransforms); + m_localSpaceTransforms.ResizeFast(numTransforms); + m_modelSpaceTransforms.ResizeFast(numTransforms); - const uint32 oldSize = mFlags.GetLength(); - mFlags.ResizeFast(numTransforms); + const size_t oldSize = m_flags.GetLength(); + m_flags.ResizeFast(numTransforms); - for (uint32 i = oldSize; i < numTransforms; ++i) + for (size_t i = oldSize; i < numTransforms; ++i) { - mFlags[i] = 0; + m_flags[i] = 0; SetLocalSpaceTransform(i, Transform::CreateIdentity()); } } @@ -133,10 +127,10 @@ namespace EMotionFX void Pose::Clear(bool clearMem) { - mLocalSpaceTransforms.Clear(clearMem); - mModelSpaceTransforms.Clear(clearMem); - mFlags.Clear(clearMem); - mMorphWeights.Clear(clearMem); + m_localSpaceTransforms.Clear(clearMem); + m_modelSpaceTransforms.Clear(clearMem); + m_flags.Clear(clearMem); + m_morphWeights.Clear(clearMem); ClearPoseDatas(); } @@ -145,25 +139,10 @@ namespace EMotionFX // clear the pose flags void Pose::ClearFlags(uint8 newFlags) { - MCore::MemSet((uint8*)mFlags.GetPtr(), newFlags, sizeof(uint8) * mFlags.GetLength()); + MCore::MemSet((uint8*)m_flags.GetPtr(), newFlags, sizeof(uint8) * m_flags.GetLength()); } - /* - // init from a set of local space transformations - void Pose::InitFromLocalTransforms(ActorInstance* actorInstance, const Transform* localTransforms) - { - // link to an actor instance - LinkToActorInstance( actorInstance, FLAG_LOCALTRANSFORMREADY ); - - // reset all flags - //MCore::MemSet( (uint8*)mFlags.GetPtr(), FLAG_LOCALTRANSFORMREADY, sizeof(uint8)*mFlags.GetLength() ); - - // copy over the local transforms - MCore::MemCopy((uint8*)mLocalTransforms.GetPtr(), (uint8*)localTransforms, sizeof(Transform)*mLocalTransforms.GetLength()); - } - */ - // initialize this pose to the bind pose void Pose::InitFromBindPose(const ActorInstance* actorInstance) { @@ -189,46 +168,26 @@ namespace EMotionFX } - /* - // initialize this pose from some given set of local space transformations - void Pose::InitFromLocalBindSpaceTransforms(Actor* actor) - { - // link to an actor - LinkToActor(actor); - - // reset all flags - MCore::MemSet( (uint8*)mFlags.GetPtr(), FLAG_LOCALTRANSFORMREADY, sizeof(uint8)*mFlags.GetLength() ); - - // copy over the local transforms - MCore::MemCopy((uint8*)mLocalTransforms.GetPtr(), (uint8*)actor->GetBindPose().GetLocalTransforms(), sizeof(Transform)*mLocalTransforms.GetLength()); - - // reset the morph targets - const uint32 numMorphWeights = mMorphWeights.GetLength(); - for (uint32 i=0; iGetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const uint32 parentIndex = skeleton->GetNode(i)->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + const size_t parentIndex = skeleton->GetNode(i)->GetParentIndex(); + if (parentIndex != InvalidIndex) { - GetModelSpaceTransform(parentIndex, &mLocalSpaceTransforms[i]); - mLocalSpaceTransforms[i].Inverse(); - mLocalSpaceTransforms[i].PreMultiply(mModelSpaceTransforms[i]); + GetModelSpaceTransform(parentIndex, &m_localSpaceTransforms[i]); + m_localSpaceTransforms[i].Inverse(); + m_localSpaceTransforms[i].PreMultiply(m_modelSpaceTransforms[i]); } else { - mLocalSpaceTransforms[i] = mModelSpaceTransforms[i]; + m_localSpaceTransforms[i] = m_modelSpaceTransforms[i]; } - mFlags[i] |= FLAG_LOCALTRANSFORMREADY; + m_flags[i] |= FLAG_LOCALTRANSFORMREADY; } } @@ -237,203 +196,201 @@ namespace EMotionFX void Pose::ForceUpdateFullModelSpacePose() { // iterate from root towards child nodes recursively, updating all model space transforms on the way - Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const uint32 parentIndex = skeleton->GetNode(i)->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + const size_t parentIndex = skeleton->GetNode(i)->GetParentIndex(); + if (parentIndex != InvalidIndex) { - mModelSpaceTransforms[parentIndex].PreMultiply(mLocalSpaceTransforms[i], &mModelSpaceTransforms[i]); + m_modelSpaceTransforms[parentIndex].PreMultiply(m_localSpaceTransforms[i], &m_modelSpaceTransforms[i]); } else { - mModelSpaceTransforms[i] = mLocalSpaceTransforms[i]; + m_modelSpaceTransforms[i] = m_localSpaceTransforms[i]; } - mFlags[i] |= FLAG_MODELTRANSFORMREADY; + m_flags[i] |= FLAG_MODELTRANSFORMREADY; } } // recursively update - void Pose::UpdateModelSpaceTransform(uint32 nodeIndex) const + void Pose::UpdateModelSpaceTransform(size_t nodeIndex) const { - Skeleton* skeleton = mActor->GetSkeleton(); + Skeleton* skeleton = m_actor->GetSkeleton(); - const uint32 parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32 && !(mFlags[parentIndex] & FLAG_MODELTRANSFORMREADY)) + const size_t parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); + if (parentIndex != InvalidIndex && !(m_flags[parentIndex] & FLAG_MODELTRANSFORMREADY)) { UpdateModelSpaceTransform(parentIndex); } // update the model space transform if needed - if ((mFlags[nodeIndex] & FLAG_MODELTRANSFORMREADY) == false) + if ((m_flags[nodeIndex] & FLAG_MODELTRANSFORMREADY) == false) { const Transform& localTransform = GetLocalSpaceTransform(nodeIndex); - if (parentIndex != MCORE_INVALIDINDEX32) + if (parentIndex != InvalidIndex) { - mModelSpaceTransforms[parentIndex].PreMultiply(localTransform, &mModelSpaceTransforms[nodeIndex]); + m_modelSpaceTransforms[parentIndex].PreMultiply(localTransform, &m_modelSpaceTransforms[nodeIndex]); } else { - mModelSpaceTransforms[nodeIndex] = mLocalSpaceTransforms[nodeIndex]; + m_modelSpaceTransforms[nodeIndex] = m_localSpaceTransforms[nodeIndex]; } - mFlags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; + m_flags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; } } // update the local transform - void Pose::UpdateLocalSpaceTransform(uint32 nodeIndex) const + void Pose::UpdateLocalSpaceTransform(size_t nodeIndex) const { - const uint32 flags = mFlags[nodeIndex]; + const uint8 flags = m_flags[nodeIndex]; if (flags & FLAG_LOCALTRANSFORMREADY) { return; } MCORE_ASSERT(flags & FLAG_MODELTRANSFORMREADY); // the model space transform has to be updated already, otherwise we cannot possibly calculate the local space one - //if ((flags & FLAG_GLOBALTRANSFORMREADY) == false) - // DebugBreak(); - Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); - if (parentIndex != MCORE_INVALIDINDEX32) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t parentIndex = skeleton->GetNode(nodeIndex)->GetParentIndex(); + if (parentIndex != InvalidIndex) { - GetModelSpaceTransform(parentIndex, &mLocalSpaceTransforms[nodeIndex]); - mLocalSpaceTransforms[nodeIndex].Inverse(); - mLocalSpaceTransforms[nodeIndex].PreMultiply(mModelSpaceTransforms[nodeIndex]); + GetModelSpaceTransform(parentIndex, &m_localSpaceTransforms[nodeIndex]); + m_localSpaceTransforms[nodeIndex].Inverse(); + m_localSpaceTransforms[nodeIndex].PreMultiply(m_modelSpaceTransforms[nodeIndex]); } else { - mLocalSpaceTransforms[nodeIndex] = mModelSpaceTransforms[nodeIndex]; + m_localSpaceTransforms[nodeIndex] = m_modelSpaceTransforms[nodeIndex]; } - mFlags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; + m_flags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; } // get the local transform - const Transform& Pose::GetLocalSpaceTransform(uint32 nodeIndex) const + const Transform& Pose::GetLocalSpaceTransform(size_t nodeIndex) const { UpdateLocalSpaceTransform(nodeIndex); - return mLocalSpaceTransforms[nodeIndex]; + return m_localSpaceTransforms[nodeIndex]; } - const Transform& Pose::GetModelSpaceTransform(uint32 nodeIndex) const + const Transform& Pose::GetModelSpaceTransform(size_t nodeIndex) const { UpdateModelSpaceTransform(nodeIndex); - return mModelSpaceTransforms[nodeIndex]; + return m_modelSpaceTransforms[nodeIndex]; } - Transform Pose::GetWorldSpaceTransform(uint32 nodeIndex) const + Transform Pose::GetWorldSpaceTransform(size_t nodeIndex) const { UpdateModelSpaceTransform(nodeIndex); - return mModelSpaceTransforms[nodeIndex].Multiplied(mActorInstance->GetWorldSpaceTransform()); + return m_modelSpaceTransforms[nodeIndex].Multiplied(m_actorInstance->GetWorldSpaceTransform()); } - void Pose::GetWorldSpaceTransform(uint32 nodeIndex, Transform* outResult) const + void Pose::GetWorldSpaceTransform(size_t nodeIndex, Transform* outResult) const { UpdateModelSpaceTransform(nodeIndex); - *outResult = mModelSpaceTransforms[nodeIndex]; - outResult->Multiply(mActorInstance->GetWorldSpaceTransform()); + *outResult = m_modelSpaceTransforms[nodeIndex]; + outResult->Multiply(m_actorInstance->GetWorldSpaceTransform()); } // calculate a local transform - void Pose::GetLocalSpaceTransform(uint32 nodeIndex, Transform* outResult) const + void Pose::GetLocalSpaceTransform(size_t nodeIndex, Transform* outResult) const { - if ((mFlags[nodeIndex] & FLAG_LOCALTRANSFORMREADY) == false) + if ((m_flags[nodeIndex] & FLAG_LOCALTRANSFORMREADY) == false) { UpdateLocalSpaceTransform(nodeIndex); } - *outResult = mLocalSpaceTransforms[nodeIndex]; + *outResult = m_localSpaceTransforms[nodeIndex]; } - void Pose::GetModelSpaceTransform(uint32 nodeIndex, Transform* outResult) const + void Pose::GetModelSpaceTransform(size_t nodeIndex, Transform* outResult) const { UpdateModelSpaceTransform(nodeIndex); - *outResult = mModelSpaceTransforms[nodeIndex]; + *outResult = m_modelSpaceTransforms[nodeIndex]; } // set the local transform - void Pose::SetLocalSpaceTransform(uint32 nodeIndex, const Transform& newTransform, bool invalidateGlobalTransforms) + void Pose::SetLocalSpaceTransform(size_t nodeIndex, const Transform& newTransform, bool invalidateGlobalTransforms) { - mLocalSpaceTransforms[nodeIndex] = newTransform; - mFlags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; + m_localSpaceTransforms[nodeIndex] = newTransform; + m_flags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; // mark all child node model space transforms as dirty (recursively) if (invalidateGlobalTransforms) { - if (mFlags[nodeIndex] & FLAG_MODELTRANSFORMREADY) + if (m_flags[nodeIndex] & FLAG_MODELTRANSFORMREADY) { - RecursiveInvalidateModelSpaceTransforms(mActor, nodeIndex); + RecursiveInvalidateModelSpaceTransforms(m_actor, nodeIndex); } } } // mark all child nodes recursively as dirty - void Pose::RecursiveInvalidateModelSpaceTransforms(const Actor* actor, uint32 nodeIndex) + void Pose::RecursiveInvalidateModelSpaceTransforms(const Actor* actor, size_t nodeIndex) { // if this model space transform ain't ready yet assume all child nodes are also not - if ((mFlags[nodeIndex] & FLAG_MODELTRANSFORMREADY) == false) + if ((m_flags[nodeIndex] & FLAG_MODELTRANSFORMREADY) == false) { return; } // mark the global transform as invalid - mFlags[nodeIndex] &= ~FLAG_MODELTRANSFORMREADY; + m_flags[nodeIndex] &= ~FLAG_MODELTRANSFORMREADY; // recurse through all child nodes Skeleton* skeleton = actor->GetSkeleton(); Node* node = skeleton->GetNode(nodeIndex); - const uint32 numChildNodes = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildNodes; ++i) + const size_t numChildNodes = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildNodes; ++i) { RecursiveInvalidateModelSpaceTransforms(actor, node->GetChildIndex(i)); } } - void Pose::SetModelSpaceTransform(uint32 nodeIndex, const Transform& newTransform, bool invalidateChildGlobalTransforms) + void Pose::SetModelSpaceTransform(size_t nodeIndex, const Transform& newTransform, bool invalidateChildGlobalTransforms) { - mModelSpaceTransforms[nodeIndex] = newTransform; + m_modelSpaceTransforms[nodeIndex] = newTransform; // invalidate the local transform - mFlags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; + m_flags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; // recursively invalidate all model space transforms of all child nodes if (invalidateChildGlobalTransforms) { - RecursiveInvalidateModelSpaceTransforms(mActor, nodeIndex); + RecursiveInvalidateModelSpaceTransforms(m_actor, nodeIndex); } // mark this model space transform as ready - mFlags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; + m_flags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; UpdateLocalSpaceTransform(nodeIndex); } - void Pose::SetWorldSpaceTransform(uint32 nodeIndex, const Transform& newTransform, bool invalidateChildGlobalTransforms) + void Pose::SetWorldSpaceTransform(size_t nodeIndex, const Transform& newTransform, bool invalidateChildGlobalTransforms) { - mModelSpaceTransforms[nodeIndex] = newTransform.Multiplied(mActorInstance->GetWorldSpaceTransformInversed()); - mFlags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; + m_modelSpaceTransforms[nodeIndex] = newTransform.Multiplied(m_actorInstance->GetWorldSpaceTransformInversed()); + m_flags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; if (invalidateChildGlobalTransforms) { - RecursiveInvalidateModelSpaceTransforms(mActor, nodeIndex); + RecursiveInvalidateModelSpaceTransforms(m_actor, nodeIndex); } - mFlags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; + m_flags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; UpdateLocalSpaceTransform(nodeIndex); } @@ -441,39 +398,39 @@ namespace EMotionFX // invalidate all local transforms void Pose::InvalidateAllLocalSpaceTransforms() { - const uint32 numFlags = mFlags.GetLength(); - for (uint32 i = 0; i < numFlags; ++i) + const size_t numFlags = m_flags.GetLength(); + for (size_t i = 0; i < numFlags; ++i) { - mFlags[i] &= ~FLAG_LOCALTRANSFORMREADY; + m_flags[i] &= ~FLAG_LOCALTRANSFORMREADY; } } void Pose::InvalidateAllModelSpaceTransforms() { - const uint32 numFlags = mFlags.GetLength(); - for (uint32 i = 0; i < numFlags; ++i) + const size_t numFlags = m_flags.GetLength(); + for (size_t i = 0; i < numFlags; ++i) { - mFlags[i] &= ~FLAG_MODELTRANSFORMREADY; + m_flags[i] &= ~FLAG_MODELTRANSFORMREADY; } } void Pose::InvalidateAllLocalAndModelSpaceTransforms() { - const uint32 numFlags = mFlags.GetLength(); - for (uint32 i = 0; i < numFlags; ++i) + const size_t numFlags = m_flags.GetLength(); + for (size_t i = 0; i < numFlags; ++i) { - mFlags[i] &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY); + m_flags[i] &= ~(FLAG_LOCALTRANSFORMREADY | FLAG_MODELTRANSFORMREADY); } } Transform Pose::CalcTrajectoryTransform() const { - MCORE_ASSERT(mActor); - const uint32 motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); - if (motionExtractionNodeIndex == MCORE_INVALIDINDEX32) + MCORE_ASSERT(m_actor); + const size_t motionExtractionNodeIndex = m_actor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex == InvalidIndex) { return Transform::CreateIdentity(); } @@ -484,9 +441,9 @@ namespace EMotionFX void Pose::UpdateAllLocalSpaceTranforms() { - Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { UpdateLocalSpaceTransform(i); } @@ -495,9 +452,9 @@ namespace EMotionFX void Pose::UpdateAllModelSpaceTranforms() { - Skeleton* skeleton = mActor->GetSkeleton(); - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + Skeleton* skeleton = m_actor->GetSkeleton(); + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { UpdateModelSpaceTransform(i); } @@ -512,8 +469,8 @@ namespace EMotionFX // make sure the number of transforms are equal MCORE_ASSERT(destPose); MCORE_ASSERT(outPose); - MCORE_ASSERT(mLocalSpaceTransforms.GetLength() == destPose->mLocalSpaceTransforms.GetLength()); - MCORE_ASSERT(mLocalSpaceTransforms.GetLength() == outPose->mLocalSpaceTransforms.GetLength()); + MCORE_ASSERT(m_localSpaceTransforms.GetLength() == destPose->m_localSpaceTransforms.GetLength()); + MCORE_ASSERT(m_localSpaceTransforms.GetLength() == outPose->m_localSpaceTransforms.GetLength()); MCORE_ASSERT(instance->GetIsMixing() == false); // get some motion instance properties which we use to decide the optimized blending routine @@ -532,11 +489,10 @@ namespace EMotionFX { if (weight > 0.0f) { - uint32 nodeNr; - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = actorInstance->GetEnabledNode(i); + const uint16 nodeNr = actorInstance->GetEnabledNode(i); Transform transform = GetLocalSpaceTransform(nodeNr); transform.Blend(destPose->GetLocalSpaceTransform(nodeNr), weight); outPose->SetLocalSpaceTransform(nodeNr, transform, false); @@ -553,24 +509,23 @@ namespace EMotionFX } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = MCore::LinearInterpolate(mMorphWeights[i], destPose->mMorphWeights[i], weight); + m_morphWeights[i] = MCore::LinearInterpolate(m_morphWeights[i], destPose->m_morphWeights[i], weight); } } else { TransformData* transformData = instance->GetActorInstance()->GetTransformData(); const Pose* bindPose = transformData->GetBindPose(); - uint32 nodeNr; Transform result; - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = actorInstance->GetEnabledNode(i); + const uint16 nodeNr = actorInstance->GetEnabledNode(i); const Transform& base = bindPose->GetLocalSpaceTransform(nodeNr); BlendTransformAdditiveUsingBindPose(base, GetLocalSpaceTransform(nodeNr), destPose->GetLocalSpaceTransform(nodeNr), weight, &result); outPose->SetLocalSpaceTransform(nodeNr, result, false); @@ -578,12 +533,12 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } } @@ -595,8 +550,8 @@ namespace EMotionFX // make sure the number of transforms are equal MCORE_ASSERT(destPose); MCORE_ASSERT(outPose); - MCORE_ASSERT(mLocalSpaceTransforms.GetLength() == destPose->mLocalSpaceTransforms.GetLength()); - MCORE_ASSERT(mLocalSpaceTransforms.GetLength() == outPose->mLocalSpaceTransforms.GetLength()); + MCORE_ASSERT(m_localSpaceTransforms.GetLength() == destPose->m_localSpaceTransforms.GetLength()); + MCORE_ASSERT(m_localSpaceTransforms.GetLength() == outPose->m_localSpaceTransforms.GetLength()); MCORE_ASSERT(instance->GetIsMixing()); const bool additive = (instance->GetBlendMode() == BLENDMODE_ADDITIVE); @@ -609,16 +564,15 @@ namespace EMotionFX Transform result; const MotionLinkData* motionLinkData = instance->GetMotion()->GetMotionData()->FindMotionLinkData(actorInstance->GetActor()); - AZ_Assert(motionLinkData->GetJointDataLinks().size() == mLocalSpaceTransforms.GetLength(), "Expecting there to be the same amount of motion links as pose transforms."); + AZ_Assert(motionLinkData->GetJointDataLinks().size() == m_localSpaceTransforms.GetLength(), "Expecting there to be the same amount of motion links as pose transforms."); // blend all transforms if (!additive) { - uint32 nodeNr; - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = actorInstance->GetEnabledNode(i); + const uint16 nodeNr = actorInstance->GetEnabledNode(i); // try to find the motion link // if we cannot find it, this node/transform is not influenced by the motion, so we skip it @@ -635,22 +589,21 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = MCore::LinearInterpolate(mMorphWeights[i], destPose->mMorphWeights[i], weight); + m_morphWeights[i] = MCore::LinearInterpolate(m_morphWeights[i], destPose->m_morphWeights[i], weight); } } else { Pose* bindPose = transformData->GetBindPose(); - uint32 nodeNr; - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = actorInstance->GetEnabledNode(i); + const uint16 nodeNr = actorInstance->GetEnabledNode(i); // try to find the motion link // if we cannot find it, this node/transform is not influenced by the motion, so we skip it @@ -666,12 +619,12 @@ namespace EMotionFX outPose->InvalidateAllModelSpaceTransforms(); // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); MCORE_ASSERT(actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } } @@ -682,22 +635,22 @@ namespace EMotionFX { if (!sourcePose) { - if (mActorInstance) + if (m_actorInstance) { - InitFromBindPose(mActorInstance); + InitFromBindPose(m_actorInstance); } else { - InitFromBindPose(mActor); + InitFromBindPose(m_actor); } return; } - mModelSpaceTransforms.MemCopyContentsFrom(sourcePose->mModelSpaceTransforms); - mLocalSpaceTransforms.MemCopyContentsFrom(sourcePose->mLocalSpaceTransforms); - mFlags.MemCopyContentsFrom(sourcePose->mFlags); - mMorphWeights.MemCopyContentsFrom(sourcePose->mMorphWeights); + m_modelSpaceTransforms.MemCopyContentsFrom(sourcePose->m_modelSpaceTransforms); + m_localSpaceTransforms.MemCopyContentsFrom(sourcePose->m_localSpaceTransforms); + m_flags.MemCopyContentsFrom(sourcePose->m_flags); + m_morphWeights.MemCopyContentsFrom(sourcePose->m_morphWeights); // Deactivate pose datas from the current pose that are not in the source that we copy from. // This is needed in order to prevent leftover pose datas and to avoid de-/allocations. @@ -765,36 +718,35 @@ namespace EMotionFX // reset all transforms to zero void Pose::Zero() { - if (mActorInstance) + if (m_actorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); - mLocalSpaceTransforms[nodeNr].Zero(); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); + m_localSpaceTransforms[nodeNr].Zero(); } - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); - for (uint32 i = 0; i < numMorphs; ++i) + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = 0.0f; + m_morphWeights[i] = 0.0f; } } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - mLocalSpaceTransforms[i].Zero(); + m_localSpaceTransforms[i].Zero(); } - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); - for (uint32 i = 0; i < numMorphs; ++i) + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = 0.0f; + m_morphWeights[i] = 0.0f; } } @@ -805,24 +757,23 @@ namespace EMotionFX // normalize all quaternions void Pose::NormalizeQuaternions() { - if (mActorInstance) + if (m_actorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); UpdateLocalSpaceTransform(nodeNr); - mLocalSpaceTransforms[nodeNr].mRotation.Normalize(); + m_localSpaceTransforms[nodeNr].m_rotation.Normalize(); } } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { UpdateLocalSpaceTransform(i); - mLocalSpaceTransforms[i].mRotation.Normalize(); + m_localSpaceTransforms[i].m_rotation.Normalize(); } } } @@ -831,13 +782,12 @@ namespace EMotionFX // add the transforms of another pose to this one void Pose::Sum(const Pose* other, float weight) { - if (mActorInstance) + if (m_actorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); const Transform& otherTransform = other->GetLocalSpaceTransform(nodeNr); @@ -845,18 +795,18 @@ namespace EMotionFX } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == other->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += other->mMorphWeights[i] * weight; + m_morphWeights[i] += other->m_morphWeights[i] * weight; } } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& otherTransform = other->GetLocalSpaceTransform(i); @@ -864,12 +814,12 @@ namespace EMotionFX } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == other->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += other->mMorphWeights[i] * weight; + m_morphWeights[i] += other->m_morphWeights[i] * weight; } } @@ -880,24 +830,23 @@ namespace EMotionFX // blend, without motion instance void Pose::Blend(const Pose* destPose, float weight) { - if (mActorInstance) + if (m_actorInstance) { - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& curTransform = const_cast(GetLocalSpaceTransform(nodeNr)); curTransform.Blend(destPose->GetLocalSpaceTransform(nodeNr), weight); } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = MCore::LinearInterpolate(mMorphWeights[i], destPose->mMorphWeights[i], weight); + m_morphWeights[i] = MCore::LinearInterpolate(m_morphWeights[i], destPose->m_morphWeights[i], weight); } for (const auto& poseDataItem : m_poseDatas) @@ -908,20 +857,20 @@ namespace EMotionFX } else { - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { Transform& curTransform = const_cast(GetLocalSpaceTransform(i)); curTransform.Blend(destPose->GetLocalSpaceTransform(i), weight); } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] = MCore::LinearInterpolate(mMorphWeights[i], destPose->mMorphWeights[i], weight); + m_morphWeights[i] = MCore::LinearInterpolate(m_morphWeights[i], destPose->m_morphWeights[i], weight); } for (const auto& poseDataItem : m_poseDatas) @@ -937,32 +886,32 @@ namespace EMotionFX Pose& Pose::MakeRelativeTo(const Pose& other) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); transform = transform.CalcRelativeTo(other.GetLocalSpaceTransform(nodeNr)); } } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); transform = transform.CalcRelativeTo(other.GetLocalSpaceTransform(i)); } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); AZ_Assert(numMorphs == other.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] -= other.mMorphWeights[i]; + m_morphWeights[i] -= other.m_morphWeights[i]; } InvalidateAllModelSpaceTransforms(); @@ -972,8 +921,8 @@ namespace EMotionFX Pose& Pose::ApplyAdditive(const Pose& additivePose, float weight) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == additivePose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { AZ_Assert(weight > -MCore::Math::epsilon && weight < (1 + MCore::Math::epsilon), "Expected weight to be between 0..1"); } @@ -990,46 +939,46 @@ namespace EMotionFX } else { - AZ_Assert(mLocalSpaceTransforms.GetLength() == additivePose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); const Transform& additiveTransform = additivePose.GetLocalSpaceTransform(nodeNr); - transform.mPosition += additiveTransform.mPosition * weight; - transform.mRotation = transform.mRotation.NLerp(additiveTransform.mRotation * transform.mRotation, weight); + transform.m_position += additiveTransform.m_position * weight; + transform.m_rotation = transform.m_rotation.NLerp(additiveTransform.m_rotation * transform.m_rotation, weight); EMFX_SCALECODE ( - transform.mScale *= AZ::Vector3::CreateOne().Lerp(additiveTransform.mScale, weight); + transform.m_scale *= AZ::Vector3::CreateOne().Lerp(additiveTransform.m_scale, weight); ) - transform.mRotation.Normalize(); + transform.m_rotation.Normalize(); } } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& additiveTransform = additivePose.GetLocalSpaceTransform(i); - transform.mPosition += additiveTransform.mPosition * weight; - transform.mRotation = transform.mRotation.NLerp(additiveTransform.mRotation * transform.mRotation, weight); + transform.m_position += additiveTransform.m_position * weight; + transform.m_rotation = transform.m_rotation.NLerp(additiveTransform.m_rotation * transform.m_rotation, weight); EMFX_SCALECODE ( - transform.mScale *= AZ::Vector3::CreateOne().Lerp(additiveTransform.mScale, weight); + transform.m_scale *= AZ::Vector3::CreateOne().Lerp(additiveTransform.m_scale, weight); ) - transform.mRotation.Normalize(); + transform.m_rotation.Normalize(); } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); AZ_Assert(numMorphs == additivePose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += additivePose.mMorphWeights[i] * weight; + m_morphWeights[i] += additivePose.m_morphWeights[i] * weight; } InvalidateAllModelSpaceTransforms(); @@ -1040,46 +989,46 @@ namespace EMotionFX Pose& Pose::ApplyAdditive(const Pose& additivePose) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == additivePose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == additivePose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); const Transform& additiveTransform = additivePose.GetLocalSpaceTransform(nodeNr); - transform.mPosition += additiveTransform.mPosition; - transform.mRotation = transform.mRotation * additiveTransform.mRotation; + transform.m_position += additiveTransform.m_position; + transform.m_rotation = transform.m_rotation * additiveTransform.m_rotation; EMFX_SCALECODE ( - transform.mScale *= additiveTransform.mScale; + transform.m_scale *= additiveTransform.m_scale; ) - transform.mRotation.Normalize(); + transform.m_rotation.Normalize(); } } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& additiveTransform = additivePose.GetLocalSpaceTransform(i); - transform.mPosition += additiveTransform.mPosition; - transform.mRotation = transform.mRotation * additiveTransform.mRotation; + transform.m_position += additiveTransform.m_position; + transform.m_rotation = transform.m_rotation * additiveTransform.m_rotation; EMFX_SCALECODE ( - transform.mScale *= additiveTransform.mScale; + transform.m_scale *= additiveTransform.m_scale; ) - transform.mRotation.Normalize(); + transform.m_rotation.Normalize(); } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); AZ_Assert(numMorphs == additivePose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += additivePose.mMorphWeights[i]; + m_morphWeights[i] += additivePose.m_morphWeights[i]; } InvalidateAllModelSpaceTransforms(); @@ -1089,44 +1038,44 @@ namespace EMotionFX Pose& Pose::MakeAdditive(const Pose& refPose) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == refPose.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == refPose.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); const Transform& refTransform = refPose.GetLocalSpaceTransform(nodeNr); - transform.mPosition = transform.mPosition - refTransform.mPosition; - transform.mRotation = refTransform.mRotation.GetConjugate() * transform.mRotation; + transform.m_position = transform.m_position - refTransform.m_position; + transform.m_rotation = refTransform.m_rotation.GetConjugate() * transform.m_rotation; EMFX_SCALECODE ( - transform.mScale *= refTransform.mScale; + transform.m_scale *= refTransform.m_scale; ) } } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); const Transform& refTransform = refPose.GetLocalSpaceTransform(i); - transform.mPosition = transform.mPosition - refTransform.mPosition; - transform.mRotation = refTransform.mRotation.GetConjugate() * transform.mRotation; + transform.m_position = transform.m_position - refTransform.m_position; + transform.m_rotation = refTransform.m_rotation.GetConjugate() * transform.m_rotation; EMFX_SCALECODE ( - transform.mScale *= refTransform.mScale; + transform.m_scale *= refTransform.m_scale; ) } } - const uint32 numMorphs = mMorphWeights.GetLength(); + const size_t numMorphs = m_morphWeights.GetLength(); AZ_Assert(numMorphs == refPose.GetNumMorphWeights(), "Number of morphs in the pose doesn't match the number of morphs inside the provided input pose."); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] -= refPose.mMorphWeights[i]; + m_morphWeights[i] -= refPose.m_morphWeights[i]; } InvalidateAllModelSpaceTransforms(); @@ -1137,50 +1086,49 @@ namespace EMotionFX // additive blend void Pose::BlendAdditiveUsingBindPose(const Pose* destPose, float weight) { - if (mActorInstance) + if (m_actorInstance) { - const TransformData* transformData = mActorInstance->GetTransformData(); + const TransformData* transformData = m_actorInstance->GetTransformData(); Pose* bindPose = transformData->GetBindPose(); Transform result; - uint32 nodeNr; - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); BlendTransformAdditiveUsingBindPose(bindPose->GetLocalSpaceTransform(nodeNr), GetLocalSpaceTransform(nodeNr), destPose->GetLocalSpaceTransform(nodeNr), weight, &result); SetLocalSpaceTransform(nodeNr, result, false); } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actorInstance->GetMorphSetupInstance()->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } else { - const TransformData* transformData = mActorInstance->GetTransformData(); + const TransformData* transformData = m_actorInstance->GetTransformData(); Pose* bindPose = transformData->GetBindPose(); Transform result; - const uint32 numNodes = mActor->GetSkeleton()->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetSkeleton()->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { BlendTransformAdditiveUsingBindPose(bindPose->GetLocalSpaceTransform(i), GetLocalSpaceTransform(i), destPose->GetLocalSpaceTransform(i), weight, &result); SetLocalSpaceTransform(i, result, false); } // blend the morph weights - const uint32 numMorphs = mMorphWeights.GetLength(); - MCORE_ASSERT(mActor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); + const size_t numMorphs = m_morphWeights.GetLength(); + MCORE_ASSERT(m_actor->GetMorphSetup(0)->GetNumMorphTargets() == numMorphs); MCORE_ASSERT(numMorphs == destPose->GetNumMorphWeights()); - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - mMorphWeights[i] += destPose->mMorphWeights[i] * weight; + m_morphWeights[i] += destPose->m_morphWeights[i] * weight; } } @@ -1284,11 +1232,11 @@ namespace EMotionFX // compensate for motion extraction, basically making it in-place void Pose::CompensateForMotionExtractionDirect(EMotionExtractionFlags motionExtractionFlags) { - const uint32 motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); - if (motionExtractionNodeIndex != MCORE_INVALIDINDEX32) + const size_t motionExtractionNodeIndex = m_actor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex != InvalidIndex) { Transform motionExtractionNodeTransform = GetLocalSpaceTransformDirect(motionExtractionNodeIndex); - mActorInstance->MotionExtractionCompensate(motionExtractionNodeTransform, motionExtractionFlags); + m_actorInstance->MotionExtractionCompensate(motionExtractionNodeTransform, motionExtractionFlags); SetLocalSpaceTransformDirect(motionExtractionNodeIndex, motionExtractionNodeTransform); } } @@ -1297,11 +1245,11 @@ namespace EMotionFX // compensate for motion extraction, basically making it in-place void Pose::CompensateForMotionExtraction(EMotionExtractionFlags motionExtractionFlags) { - const uint32 motionExtractionNodeIndex = mActor->GetMotionExtractionNodeIndex(); - if (motionExtractionNodeIndex != MCORE_INVALIDINDEX32) + const size_t motionExtractionNodeIndex = m_actor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex != InvalidIndex) { Transform motionExtractionNodeTransform = GetLocalSpaceTransform(motionExtractionNodeIndex); - mActorInstance->MotionExtractionCompensate(motionExtractionNodeTransform, motionExtractionFlags); + m_actorInstance->MotionExtractionCompensate(motionExtractionNodeTransform, motionExtractionFlags); SetLocalSpaceTransform(motionExtractionNodeIndex, motionExtractionNodeTransform); } } @@ -1310,14 +1258,14 @@ namespace EMotionFX // apply the morph target weights to the morph setup instance of the given actor instance void Pose::ApplyMorphWeightsToActorInstance() { - MorphSetupInstance* morphSetupInstance = mActorInstance->GetMorphSetupInstance(); - const uint32 numMorphs = morphSetupInstance->GetNumMorphTargets(); - for (uint32 m = 0; m < numMorphs; ++m) + MorphSetupInstance* morphSetupInstance = m_actorInstance->GetMorphSetupInstance(); + const size_t numMorphs = morphSetupInstance->GetNumMorphTargets(); + for (size_t m = 0; m < numMorphs; ++m) { MorphSetupInstance::MorphTarget* morphTarget = morphSetupInstance->GetMorphTarget(m); if (morphTarget->GetIsInManualMode() == false) { - morphTarget->SetWeight(mMorphWeights[m]); + morphTarget->SetWeight(m_morphWeights[m]); } } } @@ -1326,29 +1274,29 @@ namespace EMotionFX // zero all morph weights void Pose::ZeroMorphWeights() { - const uint32 numMorphs = mMorphWeights.GetLength(); - for (uint32 m = 0; m < numMorphs; ++m) + const size_t numMorphs = m_morphWeights.GetLength(); + for (size_t m = 0; m < numMorphs; ++m) { - mMorphWeights[m] = 0.0f; + m_morphWeights[m] = 0.0f; } } - void Pose::ResizeNumMorphs(uint32 numMorphTargets) + void Pose::ResizeNumMorphs(size_t numMorphTargets) { - mMorphWeights.Resize(numMorphTargets); + m_morphWeights.Resize(numMorphTargets); } Pose& Pose::PreMultiply(const Pose& other) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + const uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); Transform otherTransform = other.GetLocalSpaceTransform(nodeNr); transform = otherTransform * transform; @@ -1356,8 +1304,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); Transform otherTransform = other.GetLocalSpaceTransform(i); @@ -1372,21 +1320,21 @@ namespace EMotionFX Pose& Pose::Multiply(const Pose& other) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); transform.Multiply(other.GetLocalSpaceTransform(nodeNr)); } } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); transform.Multiply(other.GetLocalSpaceTransform(i)); @@ -1400,13 +1348,13 @@ namespace EMotionFX Pose& Pose::MultiplyInverse(const Pose& other) { - AZ_Assert(mLocalSpaceTransforms.GetLength() == other.mLocalSpaceTransforms.GetLength(), "Poses must be of the same size"); - if (mActorInstance) + AZ_Assert(m_localSpaceTransforms.GetLength() == other.m_localSpaceTransforms.GetLength(), "Poses must be of the same size"); + if (m_actorInstance) { - const uint32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - uint16 nodeNr = mActorInstance->GetEnabledNode(i); + uint16 nodeNr = m_actorInstance->GetEnabledNode(i); Transform& transform = const_cast(GetLocalSpaceTransform(nodeNr)); Transform otherTransform = other.GetLocalSpaceTransform(nodeNr); otherTransform.Inverse(); @@ -1415,8 +1363,8 @@ namespace EMotionFX } else { - const uint32 numNodes = mLocalSpaceTransforms.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_localSpaceTransforms.GetLength(); + for (size_t i = 0; i < numNodes; ++i) { Transform& transform = const_cast(GetLocalSpaceTransform(i)); Transform otherTransform = other.GetLocalSpaceTransform(i); @@ -1430,17 +1378,17 @@ namespace EMotionFX } - Transform Pose::GetMeshNodeWorldSpaceTransform(AZ::u32 lodLevel, AZ::u32 nodeIndex) const + Transform Pose::GetMeshNodeWorldSpaceTransform(size_t lodLevel, size_t nodeIndex) const { - if (!mActorInstance) + if (!m_actorInstance) { return Transform::CreateIdentity(); } - Actor* actor = mActorInstance->GetActor(); + Actor* actor = m_actorInstance->GetActor(); if (actor->CheckIfHasSkinningDeformer(lodLevel, nodeIndex)) { - return mActorInstance->GetWorldSpaceTransform(); + return m_actorInstance->GetWorldSpaceTransform(); } return GetWorldSpaceTransform(nodeIndex); @@ -1450,23 +1398,23 @@ namespace EMotionFX void Pose::Mirror(const MotionLinkData* motionLinkData) { AZ_Assert(motionLinkData, "Expecting valid motionLinkData pointer."); - AZ_Assert(mActorInstance, "Mirroring is only possible in combination with an actor instance."); + AZ_Assert(m_actorInstance, "Mirroring is only possible in combination with an actor instance."); - const Actor* actor = mActorInstance->GetActor(); - const TransformData* transformData = mActorInstance->GetTransformData(); + const Actor* actor = m_actorInstance->GetActor(); + const TransformData* transformData = m_actorInstance->GetTransformData(); const Pose* bindPose = transformData->GetBindPose(); - const AZStd::vector& jointLinks = motionLinkData->GetJointDataLinks(); + const AZStd::vector& jointLinks = motionLinkData->GetJointDataLinks(); - AnimGraphPose* tempPose = GetEMotionFX().GetThreadData(mActorInstance->GetThreadIndex())->GetPosePool().RequestPose(mActorInstance); + AnimGraphPose* tempPose = GetEMotionFX().GetThreadData(m_actorInstance->GetThreadIndex())->GetPosePool().RequestPose(m_actorInstance); Pose& unmirroredPose = tempPose->GetPose(); unmirroredPose = *this; - const AZ::u32 numNodes = mActorInstance->GetNumEnabledNodes(); - for (AZ::u32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numNodes; ++i) { - const AZ::u32 nodeNumber = mActorInstance->GetEnabledNode(i); - const AZ::u32 jointDataIndex = jointLinks[nodeNumber]; - if (jointDataIndex == InvalidIndex32) + const size_t nodeNumber = m_actorInstance->GetEnabledNode(i); + const size_t jointDataIndex = jointLinks[nodeNumber]; + if (jointDataIndex == InvalidIndex) { continue; } @@ -1475,12 +1423,12 @@ namespace EMotionFX Transform mirrored = bindPose->GetLocalSpaceTransform(nodeNumber); AZ::Vector3 mirrorAxis = AZ::Vector3::CreateZero(); - mirrorAxis.SetElement(mirrorInfo.mAxis, 1.0f); - mirrored.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(mirrorInfo.mSourceNode), unmirroredPose.GetLocalSpaceTransform(mirrorInfo.mSourceNode), mirrorAxis, mirrorInfo.mFlags); + mirrorAxis.SetElement(mirrorInfo.m_axis, 1.0f); + mirrored.ApplyDeltaMirrored(bindPose->GetLocalSpaceTransform(mirrorInfo.m_sourceNode), unmirroredPose.GetLocalSpaceTransform(mirrorInfo.m_sourceNode), mirrorAxis, mirrorInfo.m_flags); SetLocalSpaceTransformDirect(nodeNumber, mirrored); } - GetEMotionFX().GetThreadData(mActorInstance->GetThreadIndex())->GetPosePool().FreePose(tempPose); + GetEMotionFX().GetThreadData(m_actorInstance->GetThreadIndex())->GetPosePool().FreePose(tempPose); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h index ae3cfc7031..32c7a33bd2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Pose.h @@ -53,7 +53,7 @@ namespace EMotionFX void LinkToActorInstance(const ActorInstance* actorInstance, uint8 initialFlags = 0); void LinkToActor(const Actor* actor, uint8 initialFlags = 0, bool clearAllFlags = true); - void SetNumTransforms(uint32 numTransforms); + void SetNumTransforms(size_t numTransforms); void ApplyMorphWeightsToActorInstance(); void ZeroMorphWeights(); @@ -63,20 +63,20 @@ namespace EMotionFX void ForceUpdateFullLocalSpacePose(); void ForceUpdateFullModelSpacePose(); - const Transform& GetLocalSpaceTransform(uint32 nodeIndex) const; - const Transform& GetModelSpaceTransform(uint32 nodeIndex) const; - Transform GetWorldSpaceTransform(uint32 nodeIndex) const; + const Transform& GetLocalSpaceTransform(size_t nodeIndex) const; + const Transform& GetModelSpaceTransform(size_t nodeIndex) const; + Transform GetWorldSpaceTransform(size_t nodeIndex) const; - void GetLocalSpaceTransform(uint32 nodeIndex, Transform* outResult) const; - void GetModelSpaceTransform(uint32 nodeIndex, Transform* outResult) const; - void GetWorldSpaceTransform(uint32 nodeIndex, Transform* outResult) const; + void GetLocalSpaceTransform(size_t nodeIndex, Transform* outResult) const; + void GetModelSpaceTransform(size_t nodeIndex, Transform* outResult) const; + void GetWorldSpaceTransform(size_t nodeIndex, Transform* outResult) const; - void SetLocalSpaceTransform(uint32 nodeIndex, const Transform& newTransform, bool invalidateModelSpaceTransforms = true); - void SetModelSpaceTransform(uint32 nodeIndex, const Transform& newTransform, bool invalidateChildModelSpaceTransforms = true); - void SetWorldSpaceTransform(uint32 nodeIndex, const Transform& newTransform, bool invalidateChildModelSpaceTransforms = true); + void SetLocalSpaceTransform(size_t nodeIndex, const Transform& newTransform, bool invalidateModelSpaceTransforms = true); + void SetModelSpaceTransform(size_t nodeIndex, const Transform& newTransform, bool invalidateChildModelSpaceTransforms = true); + void SetWorldSpaceTransform(size_t nodeIndex, const Transform& newTransform, bool invalidateChildModelSpaceTransforms = true); - void UpdateModelSpaceTransform(uint32 nodeIndex) const; - void UpdateLocalSpaceTransform(uint32 nodeIndex) const; + void UpdateModelSpaceTransform(size_t nodeIndex) const; + void UpdateLocalSpaceTransform(size_t nodeIndex) const; void CompensateForMotionExtraction(EMotionExtractionFlags motionExtractionFlags = (EMotionExtractionFlags)0); void CompensateForMotionExtractionDirect(EMotionExtractionFlags motionExtractionFlags = (EMotionExtractionFlags)0); @@ -87,10 +87,10 @@ namespace EMotionFX * The difference between using GetWorldSpaceTransform directly from the current pose is that this looks whether the mesh is skinned or not. * Right now we handle skinned meshes differently. This will change in the future. Skinned meshes will always return an identity transform and therefore act like they cannot be animated. * This requires the pose to be linked to an actor instance. If this is not the case, identity transform is returned. - * @param The LOD level, which must be in range of 0..mActor->GetNumLODLevels(). + * @param The LOD level, which must be in range of 0..m_actor->GetNumLODLevels(). * @param nodeIndex The index of the node. If this node happens to have no mesh the regular current world space transform is returned. */ - Transform GetMeshNodeWorldSpaceTransform(AZ::u32 lodLevel, AZ::u32 nodeIndex) const; + Transform GetMeshNodeWorldSpaceTransform(size_t lodLevel, size_t nodeIndex) const; void InvalidateAllLocalSpaceTransforms(); void InvalidateAllModelSpaceTransforms(); @@ -98,26 +98,26 @@ namespace EMotionFX Transform CalcTrajectoryTransform() const; - MCORE_INLINE const Transform* GetLocalSpaceTransforms() const { return mLocalSpaceTransforms.GetReadPtr(); } - MCORE_INLINE const Transform* GetModelSpaceTransforms() const { return mModelSpaceTransforms.GetReadPtr(); } - MCORE_INLINE uint32 GetNumTransforms() const { return mLocalSpaceTransforms.GetLength(); } - MCORE_INLINE const ActorInstance* GetActorInstance() const { return mActorInstance; } - MCORE_INLINE const Actor* GetActor() const { return mActor; } - MCORE_INLINE const Skeleton* GetSkeleton() const { return mSkeleton; } - - MCORE_INLINE Transform& GetLocalSpaceTransformDirect(uint32 nodeIndex) { return mLocalSpaceTransforms[nodeIndex]; } - MCORE_INLINE Transform& GetModelSpaceTransformDirect(uint32 nodeIndex) { return mModelSpaceTransforms[nodeIndex]; } - MCORE_INLINE const Transform& GetLocalSpaceTransformDirect(uint32 nodeIndex) const { return mLocalSpaceTransforms[nodeIndex]; } - MCORE_INLINE const Transform& GetModelSpaceTransformDirect(uint32 nodeIndex) const { return mModelSpaceTransforms[nodeIndex]; } - MCORE_INLINE void SetLocalSpaceTransformDirect(uint32 nodeIndex, const Transform& transform){ mLocalSpaceTransforms[nodeIndex] = transform; mFlags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; } - MCORE_INLINE void SetModelSpaceTransformDirect(uint32 nodeIndex, const Transform& transform){ mModelSpaceTransforms[nodeIndex] = transform; mFlags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; } - MCORE_INLINE void InvalidateLocalSpaceTransform(uint32 nodeIndex) { mFlags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; } - MCORE_INLINE void InvalidateModelSpaceTransform(uint32 nodeIndex) { mFlags[nodeIndex] &= ~FLAG_MODELTRANSFORMREADY; } - - MCORE_INLINE void SetMorphWeight(uint32 index, float weight) { mMorphWeights[index] = weight; } - MCORE_INLINE float GetMorphWeight(uint32 index) const { return mMorphWeights[index]; } - MCORE_INLINE uint32 GetNumMorphWeights() const { return mMorphWeights.GetLength(); } - void ResizeNumMorphs(uint32 numMorphTargets); + MCORE_INLINE const Transform* GetLocalSpaceTransforms() const { return m_localSpaceTransforms.GetReadPtr(); } + MCORE_INLINE const Transform* GetModelSpaceTransforms() const { return m_modelSpaceTransforms.GetReadPtr(); } + MCORE_INLINE size_t GetNumTransforms() const { return m_localSpaceTransforms.GetLength(); } + MCORE_INLINE const ActorInstance* GetActorInstance() const { return m_actorInstance; } + MCORE_INLINE const Actor* GetActor() const { return m_actor; } + MCORE_INLINE const Skeleton* GetSkeleton() const { return m_skeleton; } + + MCORE_INLINE Transform& GetLocalSpaceTransformDirect(size_t nodeIndex) { return m_localSpaceTransforms[nodeIndex]; } + MCORE_INLINE Transform& GetModelSpaceTransformDirect(size_t nodeIndex) { return m_modelSpaceTransforms[nodeIndex]; } + MCORE_INLINE const Transform& GetLocalSpaceTransformDirect(size_t nodeIndex) const { return m_localSpaceTransforms[nodeIndex]; } + MCORE_INLINE const Transform& GetModelSpaceTransformDirect(size_t nodeIndex) const { return m_modelSpaceTransforms[nodeIndex]; } + MCORE_INLINE void SetLocalSpaceTransformDirect(size_t nodeIndex, const Transform& transform){ m_localSpaceTransforms[nodeIndex] = transform; m_flags[nodeIndex] |= FLAG_LOCALTRANSFORMREADY; } + MCORE_INLINE void SetModelSpaceTransformDirect(size_t nodeIndex, const Transform& transform){ m_modelSpaceTransforms[nodeIndex] = transform; m_flags[nodeIndex] |= FLAG_MODELTRANSFORMREADY; } + MCORE_INLINE void InvalidateLocalSpaceTransform(size_t nodeIndex) { m_flags[nodeIndex] &= ~FLAG_LOCALTRANSFORMREADY; } + MCORE_INLINE void InvalidateModelSpaceTransform(size_t nodeIndex) { m_flags[nodeIndex] &= ~FLAG_MODELTRANSFORMREADY; } + + MCORE_INLINE void SetMorphWeight(size_t index, float weight) { m_morphWeights[index] = weight; } + MCORE_INLINE float GetMorphWeight(size_t index) const { return m_morphWeights[index]; } + MCORE_INLINE size_t GetNumMorphWeights() const { return m_morphWeights.GetLength(); } + void ResizeNumMorphs(size_t numMorphTargets); /** * Blend this pose into a specified destination pose. @@ -168,8 +168,8 @@ namespace EMotionFX Pose& operator=(const Pose& other); - MCORE_INLINE uint8 GetFlags(uint32 nodeIndex) const { return mFlags[nodeIndex]; } - MCORE_INLINE void SetFlags(uint32 nodeIndex, uint8 flags) { mFlags[nodeIndex] = flags; } + MCORE_INLINE uint8 GetFlags(size_t nodeIndex) const { return m_flags[nodeIndex]; } + MCORE_INLINE void SetFlags(size_t nodeIndex, uint8 flags) { m_flags[nodeIndex] = flags; } bool HasPoseData(const AZ::TypeId& typeId) const; PoseData* GetPoseDataByType(const AZ::TypeId& typeId) const; @@ -193,16 +193,16 @@ namespace EMotionFX T* GetAndPreparePoseData(ActorInstance* linkToActorInstance) { return azdynamic_cast(GetAndPreparePoseData(azrtti_typeid(), linkToActorInstance)); } private: - mutable MCore::AlignedArray mLocalSpaceTransforms; - mutable MCore::AlignedArray mModelSpaceTransforms; - mutable MCore::AlignedArray mFlags; + mutable MCore::AlignedArray m_localSpaceTransforms; + mutable MCore::AlignedArray m_modelSpaceTransforms; + mutable MCore::AlignedArray m_flags; AZStd::unordered_map > m_poseDatas; - MCore::AlignedArray mMorphWeights; /**< The morph target weights. */ - const ActorInstance* mActorInstance; - const Actor* mActor; - const Skeleton* mSkeleton; + MCore::AlignedArray m_morphWeights; /**< The morph target weights. */ + const ActorInstance* m_actorInstance; + const Actor* m_actor; + const Skeleton* m_skeleton; - void RecursiveInvalidateModelSpaceTransforms(const Actor* actor, uint32 nodeIndex); + void RecursiveInvalidateModelSpaceTransforms(const Actor* actor, size_t nodeIndex); /** * Perform a non-mixed blend into the specified destination pose. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp index 5ef490cd2c..1d53b4961d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/PoseDataRagdoll.cpp @@ -94,8 +94,8 @@ namespace EMotionFX if (nodeState.m_simulationType == Physics::SimulationType::Kinematic && destNodeState.m_simulationType == Physics::SimulationType::Dynamic) { - nodeState.m_position = jointTransform.mPosition.Lerp(destNodeState.m_position, weight); - nodeState.m_orientation = jointTransform.mRotation.NLerp(destNodeState.m_orientation, weight); + nodeState.m_position = jointTransform.m_position.Lerp(destNodeState.m_position, weight); + nodeState.m_orientation = jointTransform.m_rotation.NLerp(destNodeState.m_orientation, weight); // We're blending from a kinematic to a dynamic joint, which means when starting the blend we know that the animation pose matches the ragdoll pose. // The closest a powered ragdoll joint can be to its target pose and thus matching the kinematic one is by using its maximum strength. @@ -114,8 +114,8 @@ namespace EMotionFX else if (nodeState.m_simulationType == Physics::SimulationType::Dynamic && destNodeState.m_simulationType == Physics::SimulationType::Kinematic) { - nodeState.m_position = nodeState.m_position.Lerp(destJointTransform.mPosition, weight); - nodeState.m_orientation = nodeState.m_orientation.NLerp(destJointTransform.mRotation, weight); + nodeState.m_position = nodeState.m_position.Lerp(destJointTransform.m_position, weight); + nodeState.m_orientation = nodeState.m_orientation.NLerp(destJointTransform.m_rotation, weight); // Inverse way here. Blending towards the maximum strength possible to make sure we're as close as possible to the target pose when switching simulation // state to kinematic. @@ -158,7 +158,7 @@ namespace EMotionFX // Blend node states. Both, the destination pose as well as the current pose hold used ragdoll pose datas. for (size_t i = 0; i < nodeStateCount; ++i) { - const AZ::u32 jointIndex = ragdollInstance->GetJointIndex(i); + const size_t jointIndex = ragdollInstance->GetJointIndex(i); const Transform& localTransform = m_pose->GetLocalSpaceTransform(jointIndex); const Transform& destLocalTransform = destPose->GetLocalSpaceTransform(jointIndex); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp index 98b4275791..c7da3430b1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.cpp @@ -45,14 +45,14 @@ namespace EMotionFX const Actor* actor = m_actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); const AZStd::shared_ptr& physicsSetup = actor->GetPhysicsSetup(); - const AZ::u32 jointCount = skeleton->GetNumNodes(); + const size_t jointCount = skeleton->GetNumNodes(); const Physics::RagdollConfiguration& ragdollConfig = physicsSetup->GetRagdollConfig(); const size_t ragdollNodeCount = ragdollConfig.m_nodes.size(); m_ragdollNodeIndices.resize(jointCount); m_jointIndicesByRagdollNodeIndices.resize(ragdollNodeCount); - for (AZ::u32 jointIndex = 0; jointIndex < jointCount; ++jointIndex) + for (size_t jointIndex = 0; jointIndex < jointCount; ++jointIndex) { const Node* joint = skeleton->GetNode(jointIndex); @@ -67,12 +67,12 @@ namespace EMotionFX } else { - m_ragdollNodeIndices[jointIndex] = MCORE_INVALIDINDEX32; + m_ragdollNodeIndices[jointIndex] = InvalidIndex; } } // Find and store the ragdoll root joint by iterating the skeleton top-down until we find the first node which is part of the ragdoll. - for (AZ::u32 jointIndex = 0; jointIndex < jointCount; ++jointIndex) + for (size_t jointIndex = 0; jointIndex < jointCount; ++jointIndex) { Node* joint = skeleton->GetNode(jointIndex); const AZ::Outcome ragdollNodeIndex = GetRagdollNodeIndex(jointIndex); @@ -162,7 +162,7 @@ namespace EMotionFX AZ_Assert(ragdollNodeCount == m_ragdoll->GetNumNodes(), "Ragdoll node index to animation skeleton joint index mapping not up to date. Expected the same number of joint indices than ragdoll nodes."); for (size_t ragdollNodeIndex = 0; ragdollNodeIndex < ragdollNodeCount; ++ragdollNodeIndex) { - const AZ::u32 jointIndex = GetJointIndex(ragdollNodeIndex); + const size_t jointIndex = GetJointIndex(ragdollNodeIndex); Physics::RagdollNodeState& ragdollNodeState = m_targetState[ragdollNodeIndex]; if (ragdollNodeState.m_simulationType == Physics::SimulationType::Kinematic) @@ -256,7 +256,7 @@ namespace EMotionFX const AZ::Outcome RagdollInstance::GetRagdollNodeIndex(size_t jointIndex) const { const size_t ragdollNodeIndex = m_ragdollNodeIndices[jointIndex]; - if (ragdollNodeIndex == MCORE_INVALIDINDEX32) + if (ragdollNodeIndex == InvalidIndex) { return AZ::Failure(); } @@ -264,7 +264,7 @@ namespace EMotionFX return AZ::Success(ragdollNodeIndex); } - AZ::u32 RagdollInstance::GetJointIndex(size_t ragdollNodeIndex) const + size_t RagdollInstance::GetJointIndex(size_t ragdollNodeIndex) const { return m_jointIndicesByRagdollNodeIndices[ragdollNodeIndex]; } @@ -330,15 +330,15 @@ namespace EMotionFX return m_velocityEvaluator.get(); } - void RagdollInstance::GetWorldSpaceTransform(const Pose* pose, AZ::u32 jointIndex, AZ::Vector3& outPosition, AZ::Quaternion& outRotation) + void RagdollInstance::GetWorldSpaceTransform(const Pose* pose, size_t jointIndex, AZ::Vector3& outPosition, AZ::Quaternion& outRotation) { const Transform& globalTransform = pose->GetModelSpaceTransform(jointIndex); - const AZ::Quaternion actorInstanceRotation = m_actorInstance->GetLocalSpaceTransform().mRotation; - const AZ::Vector3& actorInstanceTranslation = m_actorInstance->GetLocalSpaceTransform().mPosition; + const AZ::Quaternion actorInstanceRotation = m_actorInstance->GetLocalSpaceTransform().m_rotation; + const AZ::Vector3& actorInstanceTranslation = m_actorInstance->GetLocalSpaceTransform().m_position; // Calculate the world space position and rotation (The actor instance position and rotation equal the entity transform). - outPosition = actorInstanceRotation.TransformVector(globalTransform.mPosition) + actorInstanceTranslation; - outRotation = actorInstanceRotation * globalTransform.mRotation; + outPosition = actorInstanceRotation.TransformVector(globalTransform.m_position) + actorInstanceTranslation; + outRotation = actorInstanceRotation * globalTransform.m_rotation; } void RagdollInstance::ReadRagdollStateFromActorInstance(Physics::RagdollState& outRagdollState, AZ::Vector3& outRagdollPos, AZ::Quaternion& outRagdollRot) @@ -349,15 +349,15 @@ namespace EMotionFX const Skeleton* skeleton = actor->GetSkeleton(); const Pose* currentPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - const AZ::Quaternion& actorInstanceRotation = m_actorInstance->GetLocalSpaceTransform().mRotation; - const AZ::Vector3& actorInstanceTranslation = m_actorInstance->GetLocalSpaceTransform().mPosition; + const AZ::Quaternion& actorInstanceRotation = m_actorInstance->GetLocalSpaceTransform().m_rotation; + const AZ::Vector3& actorInstanceTranslation = m_actorInstance->GetLocalSpaceTransform().m_position; const size_t ragdollNodeCount = m_ragdoll->GetNumNodes(); outRagdollState.resize(ragdollNodeCount); for (size_t ragdollNodeIndex = 0; ragdollNodeIndex < ragdollNodeCount; ++ragdollNodeIndex) { - const AZ::u32 jointIndex = m_jointIndicesByRagdollNodeIndices[ragdollNodeIndex]; + const size_t jointIndex = m_jointIndicesByRagdollNodeIndices[ragdollNodeIndex]; const Node* joint = skeleton->GetNode(jointIndex); Physics::RagdollNodeState& ragdollNodeState = outRagdollState[ragdollNodeIndex]; @@ -371,14 +371,14 @@ namespace EMotionFX { // Calculate the ragdoll world space position and rotation from the ragdoll root node representative in the animation skeleton (e.g. the Pelvis). const Transform& globalTransform = currentPose->GetModelSpaceTransform(m_ragdollRootJoint->GetNodeIndex()); - outRagdollPos = actorInstanceRotation.TransformVector(globalTransform.mPosition) + actorInstanceTranslation; - outRagdollRot = actorInstanceRotation * globalTransform.mRotation; + outRagdollPos = actorInstanceRotation.TransformVector(globalTransform.m_position) + actorInstanceTranslation; + outRagdollRot = actorInstanceRotation * globalTransform.m_rotation; } else { AZ_Assert(false, "Expected valid ragdoll root node. Either the ragdoll root node does not exist in the animation skeleton or the ragdoll is empty."); - outRagdollPos = m_actorInstance->GetLocalSpaceTransform().mPosition; - outRagdollRot = m_actorInstance->GetLocalSpaceTransform().mRotation; + outRagdollPos = m_actorInstance->GetLocalSpaceTransform().m_position; + outRagdollRot = m_actorInstance->GetLocalSpaceTransform().m_rotation; } } @@ -433,9 +433,9 @@ namespace EMotionFX } const EMotionFX::TransformData* transformData = m_actorInstance->GetTransformData(); - const AZ::u32 transformCount = transformData->GetNumTransforms(); + const size_t transformCount = transformData->GetNumTransforms(); const EMotionFX::Skeleton* skeleton = m_actorInstance->GetActor()->GetSkeleton(); - const AZ::u32 jointCount = skeleton->GetNumNodes(); + const size_t jointCount = skeleton->GetNumNodes(); const RagdollInstance* ragdollInstance = m_actorInstance->GetRagdollInstance(); const Physics::Ragdoll* ragdoll = ragdollInstance->GetRagdoll(); @@ -459,7 +459,7 @@ namespace EMotionFX const size_t ragdollNodeCount = ragdoll->GetNumNodes(); for (size_t i = 0; i < ragdollNodeCount; ++i) { - const AZ::u32 jointIndex = ragdollInstance->GetJointIndex(i); + const size_t jointIndex = ragdollInstance->GetJointIndex(i); const Physics::RagdollNodeState& targetJointPose = ragdollTargetPose[i]; if (targetJointPose.m_simulationType == Physics::SimulationType::Dynamic) @@ -468,7 +468,7 @@ namespace EMotionFX } } - for (AZ::u32 jointIndex = 0; jointIndex < jointCount; ++jointIndex) + for (size_t jointIndex = 0; jointIndex < jointCount; ++jointIndex) { const Node* joint = skeleton->GetNode(jointIndex); const AZ::Outcome ragdollJointIndex = ragdollInstance->GetRagdollNodeIndex(jointIndex); @@ -512,8 +512,8 @@ namespace EMotionFX drawLine(currentParentPos, simulatedColor, currentPos, simulatedColor, defaultLineThickness); // Render target pose - const AZ::Vector3& targetPos = targetPose.GetWorldSpaceTransform(jointIndex).mPosition; - const AZ::Vector3& targetParentPos = targetPose.GetWorldSpaceTransform(ragdollParentJoint->GetNodeIndex()).mPosition; + const AZ::Vector3& targetPos = targetPose.GetWorldSpaceTransform(jointIndex).m_position; + const AZ::Vector3& targetParentPos = targetPose.GetWorldSpaceTransform(ragdollParentJoint->GetNodeIndex()).m_position; drawLine(targetParentPos, simulatedTargetColor, targetPos, simulatedTargetColor, targetLineThickness); } else diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.h b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.h index 0f249bd1b8..a78ec08da7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RagdollInstance.h @@ -60,7 +60,7 @@ namespace EMotionFX * @param[in] ragdollNodeIndex The index of the ragdoll node [0, Physics::Ragdoll::GetNumNodes()-1]. * @result The index of the joint in the animation skeleton. */ - AZ::u32 GetJointIndex(size_t ragdollNodeIndex) const; + size_t GetJointIndex(size_t ragdollNodeIndex) const; const AZ::Vector3& GetCurrentPos() const; const AZ::Vector3& GetLastPos() const; @@ -83,7 +83,7 @@ namespace EMotionFX void SetVelocityEvaluator(RagdollVelocityEvaluator* evaluator); RagdollVelocityEvaluator* GetVelocityEvaluator() const; - void GetWorldSpaceTransform(const Pose* pose, AZ::u32 jointIndex, AZ::Vector3& outPosition, AZ::Quaternion& outRotation); + void GetWorldSpaceTransform(const Pose* pose, size_t jointIndex, AZ::Vector3& outPosition, AZ::Quaternion& outRotation); void FindNextRagdollParentForJoint(Node* joint, Node*& outParentJoint, AZ::Outcome& outRagdollParentNodeIndex) const; typedef const AZStd::function& DrawLineFunction; @@ -93,8 +93,8 @@ namespace EMotionFX void ReadRagdollStateFromActorInstance(Physics::RagdollState& outRagdollState, AZ::Vector3& outRagdollPos, AZ::Quaternion& outRagdollRot); void ReadRagdollState(Physics::RagdollState& outRagdollState, AZ::Vector3& outRagdollPos, AZ::Quaternion& outRagdollRot); - AZStd::vector m_ragdollNodeIndices; /**< Stores the ragdoll node indices for each joint in the animation skeleton, MCORE_INVALIDINDEX32 in case a given joint is not part of the ragdoll. [0, Actor::GetNumNodes()-1] */ - AZStd::vector m_jointIndicesByRagdollNodeIndices; /**< Stores the animation skeleton joint indices for each ragdoll node. [0, Physics::Ragdoll::GetNumNodes()-1] */ + AZStd::vector m_ragdollNodeIndices; /**< Stores the ragdoll node indices for each joint in the animation skeleton, InvalidIndex in case a given joint is not part of the ragdoll. [0, Actor::GetNumNodes()-1] */ + AZStd::vector m_jointIndicesByRagdollNodeIndices; /**< Stores the animation skeleton joint indices for each ragdoll node. [0, Physics::Ragdoll::GetNumNodes()-1] */ ActorInstance* m_actorInstance; Node* m_ragdollRootJoint; Physics::Ragdoll* m_ragdoll; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp index 6c2c070e50..085d164a94 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.cpp @@ -7,6 +7,7 @@ */ #include +#include #include "Recorder.h" #include "RecorderBus.h" #include "ActorInstance.h" @@ -47,10 +48,10 @@ namespace EMotionFX serializeContext->Class() ->Version(1) - ->Field("positions", &Recorder::TransformTracks::mPositions) - ->Field("rotations", &Recorder::TransformTracks::mRotations) + ->Field("positions", &Recorder::TransformTracks::m_positions) + ->Field("rotations", &Recorder::TransformTracks::m_rotations) #ifndef EMFX_SCALE_DISABLED - ->Field("scales", &Recorder::TransformTracks::mScales) + ->Field("scales", &Recorder::TransformTracks::m_scales) #endif ; } @@ -79,29 +80,28 @@ namespace EMotionFX serializeContext->Class() ->Version(1) - ->Field("fps", &Recorder::RecordSettings::mFPS) - ->Field("recordTransforms", &Recorder::RecordSettings::mRecordTransforms) - ->Field("recordNodeHistory", &Recorder::RecordSettings::mRecordNodeHistory) - ->Field("historyStatesOnly", &Recorder::RecordSettings::mHistoryStatesOnly) - ->Field("recordAnimGraphStates", &Recorder::RecordSettings::mRecordAnimGraphStates) - ->Field("recordEvents", &Recorder::RecordSettings::mRecordEvents) - ->Field("recordScale", &Recorder::RecordSettings::mRecordScale) - ->Field("recordMorphs", &Recorder::RecordSettings::mRecordMorphs) - ->Field("interpolate", &Recorder::RecordSettings::mInterpolate) + ->Field("fps", &Recorder::RecordSettings::m_fps) + ->Field("recordTransforms", &Recorder::RecordSettings::m_recordTransforms) + ->Field("recordNodeHistory", &Recorder::RecordSettings::m_recordNodeHistory) + ->Field("historyStatesOnly", &Recorder::RecordSettings::m_historyStatesOnly) + ->Field("recordAnimGraphStates", &Recorder::RecordSettings::m_recordAnimGraphStates) + ->Field("recordEvents", &Recorder::RecordSettings::m_recordEvents) + ->Field("recordScale", &Recorder::RecordSettings::m_recordScale) + ->Field("recordMorphs", &Recorder::RecordSettings::m_recordMorphs) + ->Field("interpolate", &Recorder::RecordSettings::m_interpolate) ; } Recorder::Recorder() : BaseObject() { - mIsInPlayMode = false; - mIsRecording = false; - mAutoPlay = false; - mRecordTime = 0.0f; - mLastRecordTime = 0.0f; - mCurrentPlayTime = 0.0f; - - mObjects.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); + m_isInPlayMode = false; + m_isRecording = false; + m_autoPlay = false; + m_recordTime = 0.0f; + m_lastRecordTime = 0.0f; + m_currentPlayTime = 0.0f; + EMotionFX::ActorInstanceNotificationBus::Handler::BusConnect(); } @@ -133,30 +133,30 @@ namespace EMotionFX ->Version(1) ->Field("actorInstanceDatas", &Recorder::m_actorInstanceDatas) ->Field("timeDeltas", &Recorder::m_timeDeltas) - ->Field("settings", &Recorder::mRecordSettings) + ->Field("settings", &Recorder::m_recordSettings) ; } // enable or disable auto play mode void Recorder::SetAutoPlay(bool enabled) { - mAutoPlay = enabled; + m_autoPlay = enabled; } // set the current play time void Recorder::SetCurrentPlayTime(float timeInSeconds) { - mCurrentPlayTime = timeInSeconds; + m_currentPlayTime = timeInSeconds; - if (mCurrentPlayTime < 0.0f) + if (m_currentPlayTime < 0.0f) { - mCurrentPlayTime = 0.0f; + m_currentPlayTime = 0.0f; } - if (mCurrentPlayTime > mRecordTime) + if (m_currentPlayTime > m_recordTime) { - mCurrentPlayTime = mRecordTime; + m_currentPlayTime = m_recordTime; } } @@ -165,21 +165,21 @@ namespace EMotionFX void Recorder::StartPlayBack() { StopRecording(); - mIsInPlayMode = true; + m_isInPlayMode = true; } // stop playback mode void Recorder::StopPlayBack() { - mIsInPlayMode = false; + m_isInPlayMode = false; } // rewind the playback void Recorder::Rewind() { - mCurrentPlayTime = 0.0f; + m_currentPlayTime = 0.0f; } bool Recorder::HasRecording() const @@ -192,13 +192,13 @@ namespace EMotionFX { Lock(); - mIsInPlayMode = false; - mIsRecording = false; - mAutoPlay = false; - mRecordTime = 0.0f; - mLastRecordTime = 0.0f; - mCurrentPlayTime = 0.0f; - mRecordSettings.m_actorInstances.clear(); + m_isInPlayMode = false; + m_isRecording = false; + m_autoPlay = false; + m_recordTime = 0.0f; + m_lastRecordTime = 0.0f; + m_currentPlayTime = 0.0f; + m_recordSettings.m_actorInstances.clear(); m_timeDeltas.clear(); // delete all actor instance datas @@ -225,18 +225,18 @@ namespace EMotionFX m_sessionUuid = AZ::Uuid::Create(); // we are recording again - mRecordSettings = settings; - mIsRecording = true; + m_recordSettings = settings; + m_isRecording = true; // Add all actor instances if we did not specify them explicitly. - if (mRecordSettings.m_actorInstances.empty()) + if (m_recordSettings.m_actorInstances.empty()) { - const uint32 numActorInstances = GetActorManager().GetNumActorInstances(); - mRecordSettings.m_actorInstances.resize(numActorInstances); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = GetActorManager().GetNumActorInstances(); + m_recordSettings.m_actorInstances.resize(numActorInstances); + for (size_t i = 0; i < numActorInstances; ++i) { ActorInstance* actorInstance = GetActorManager().GetActorInstance(i); - mRecordSettings.m_actorInstances[i] = actorInstance; + m_recordSettings.m_actorInstances[i] = actorInstance; } } @@ -255,9 +255,9 @@ namespace EMotionFX void Recorder::UpdatePlayMode(float timeDelta) { // increase the playtime if we are in automatic play mode and playback is enabled - if (mIsInPlayMode && mAutoPlay) + if (m_isInPlayMode && m_autoPlay) { - SetCurrentPlayTime(mCurrentPlayTime + timeDelta); + SetCurrentPlayTime(m_currentPlayTime + timeDelta); } } @@ -268,18 +268,18 @@ namespace EMotionFX Lock(); // if we are not recording there is nothing to do - if (mIsRecording == false) + if (m_isRecording == false) { Unlock(); return; } // increase the time we record - mRecordTime += timeDelta; + m_recordTime += timeDelta; // save a sample when more time passed than the desired sample rate - const float sampleRate = 1.0f / (float)mRecordSettings.mFPS; - if (mRecordTime - mLastRecordTime >= sampleRate) + const float sampleRate = 1.0f / (float)m_recordSettings.m_fps; + if (m_recordTime - m_lastRecordTime >= sampleRate) { RecordCurrentFrame(timeDelta); } @@ -296,7 +296,7 @@ namespace EMotionFX Lock(); } - mIsRecording = false; + m_isRecording = false; FinalizeAllNodeHistoryItems(); if (lock) @@ -309,7 +309,7 @@ namespace EMotionFX // prepare for recording by resizing and preallocating space/arrays void Recorder::PrepareForRecording() { - const size_t numActorInstances = mRecordSettings.m_actorInstances.size(); + const size_t numActorInstances = m_recordSettings.m_actorInstances.size(); m_actorInstanceDatas.resize(numActorInstances); for (size_t i = 0; i < numActorInstances; ++i) { @@ -317,54 +317,54 @@ namespace EMotionFX ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[i]; // link it to the right actor instance - ActorInstance* actorInstance = mRecordSettings.m_actorInstances[i]; - actorInstanceData.mActorInstance = actorInstance; + ActorInstance* actorInstance = m_recordSettings.m_actorInstances[i]; + actorInstanceData.m_actorInstance = actorInstance; // add the transform tracks - if (mRecordSettings.mRecordTransforms) + if (m_recordSettings.m_recordTransforms) { // for all nodes in the actor instance - const uint32 numNodes = actorInstance->GetNumNodes(); + const size_t numNodes = actorInstance->GetNumNodes(); actorInstanceData.m_transformTracks.resize(numNodes); - for (uint32 n = 0; n < numNodes; ++n) + for (size_t n = 0; n < numNodes; ++n) { - actorInstanceData.m_transformTracks[n].mPositions.Reserve(mRecordSettings.mNumPreAllocTransformKeys); - actorInstanceData.m_transformTracks[n].mRotations.Reserve(mRecordSettings.mNumPreAllocTransformKeys); + actorInstanceData.m_transformTracks[n].m_positions.Reserve(m_recordSettings.m_numPreAllocTransformKeys); + actorInstanceData.m_transformTracks[n].m_rotations.Reserve(m_recordSettings.m_numPreAllocTransformKeys); EMFX_SCALECODE ( - if (mRecordSettings.mRecordScale) + if (m_recordSettings.m_recordScale) { - actorInstanceData.m_transformTracks[n].mScales.Reserve(mRecordSettings.mNumPreAllocTransformKeys); + actorInstanceData.m_transformTracks[n].m_scales.Reserve(m_recordSettings.m_numPreAllocTransformKeys); } ) } } // if recording transforms // if recording morph targets, resize the morphs array - if (mRecordSettings.mRecordMorphs) + if (m_recordSettings.m_recordMorphs) { - const uint32 numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); - actorInstanceData.mMorphTracks.Resize(numMorphs); - for (uint32 m = 0; m < numMorphs; ++m) + const size_t numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); + actorInstanceData.m_morphTracks.resize(numMorphs); + for (size_t m = 0; m < numMorphs; ++m) { - actorInstanceData.mMorphTracks[m].Reserve(256); + actorInstanceData.m_morphTracks[m].Reserve(256); } } // add the animgraph data - if (mRecordSettings.mRecordAnimGraphStates) + if (m_recordSettings.m_recordAnimGraphStates) { if (actorInstance->GetAnimGraphInstance()) { - actorInstanceData.mAnimGraphData = new AnimGraphInstanceData(); - actorInstanceData.mAnimGraphData->mAnimGraphInstance = actorInstance->GetAnimGraphInstance(); - if (mRecordSettings.mInitialAnimGraphAnimBytes > 0) + actorInstanceData.m_animGraphData = new AnimGraphInstanceData(); + actorInstanceData.m_animGraphData->m_animGraphInstance = actorInstance->GetAnimGraphInstance(); + if (m_recordSettings.m_initialAnimGraphAnimBytes > 0) { - actorInstanceData.mAnimGraphData->mDataBuffer = (uint8*)MCore::Allocate(mRecordSettings.mInitialAnimGraphAnimBytes, EMFX_MEMCATEGORY_RECORDER); + actorInstanceData.m_animGraphData->m_dataBuffer = (uint8*)MCore::Allocate(m_recordSettings.m_initialAnimGraphAnimBytes, EMFX_MEMCATEGORY_RECORDER); } - actorInstanceData.mAnimGraphData->mDataBufferSize = mRecordSettings.mInitialAnimGraphAnimBytes; + actorInstanceData.m_animGraphData->m_dataBufferSize = m_recordSettings.m_initialAnimGraphAnimBytes; } } // if recording animgraphs } // for all actor instances @@ -381,21 +381,21 @@ namespace EMotionFX { for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - const ActorInstance* actorInstance = actorInstanceData->mActorInstance; + const ActorInstance* actorInstance = actorInstanceData->m_actorInstance; if (actorInstanceData->m_transformTracks.empty()) { continue; } - const uint32 numNodes = actorInstance->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = actorInstance->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { - actorInstanceData->m_transformTracks[n].mPositions.Shrink(); - actorInstanceData->m_transformTracks[n].mRotations.Shrink(); + actorInstanceData->m_transformTracks[n].m_positions.Shrink(); + actorInstanceData->m_transformTracks[n].m_rotations.Shrink(); EMFX_SCALECODE ( - actorInstanceData->m_transformTracks[n].mScales.Shrink(); + actorInstanceData->m_transformTracks[n].m_scales.Shrink(); ) } } @@ -424,13 +424,13 @@ namespace EMotionFX m_timeDeltas.emplace_back(timeDelta); // record the current transforms - if (mRecordSettings.mRecordTransforms) + if (m_recordSettings.m_recordTransforms) { RecordCurrentTransforms(); } // record the current anim graph states - if (mRecordSettings.mRecordAnimGraphStates) + if (m_recordSettings.m_recordAnimGraphStates) { if (!RecordCurrentAnimGraphStates()) { @@ -444,25 +444,25 @@ namespace EMotionFX RecordMainLocalTransforms(); // record morphs - if (mRecordSettings.mRecordMorphs) + if (m_recordSettings.m_recordMorphs) { RecordMorphs(); } // update (while recording) the node history items - if (mRecordSettings.mRecordNodeHistory) + if (m_recordSettings.m_recordNodeHistory) { UpdateNodeHistoryItems(); } // recordo the events - if (mRecordSettings.mRecordEvents) + if (m_recordSettings.m_recordEvents) { RecordEvents(); } // update the last record time - mLastRecordTime = mRecordTime; + m_lastRecordTime = m_recordTime; } @@ -470,17 +470,17 @@ namespace EMotionFX void Recorder::RecordMorphs() { // for all actor instances - const uint32 numActorInstances = static_cast(m_actorInstanceDatas.size()); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = m_actorInstanceDatas.size(); + for (size_t i = 0; i < numActorInstances; ++i) { ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[i]; - ActorInstance* actorInstance = actorInstanceData.mActorInstance; + ActorInstance* actorInstance = actorInstanceData.m_actorInstance; - const uint32 numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); - for (uint32 m = 0; m < numMorphs; ++m) + const size_t numMorphs = actorInstance->GetMorphSetupInstance()->GetNumMorphTargets(); + for (size_t m = 0; m < numMorphs; ++m) { - KeyTrackLinearDynamic& morphTrack = actorInstanceData.mMorphTracks[i]; // morph animation data - morphTrack.AddKey(mRecordTime, actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->GetWeight()); + KeyTrackLinearDynamic& morphTrack = actorInstanceData.m_morphTracks[i]; // morph animation data + morphTrack.AddKey(m_recordTime, actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->GetWeight()); } } } @@ -492,13 +492,13 @@ namespace EMotionFX // for all actor instances for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - ActorInstance* actorInstance = actorInstanceData->mActorInstance; + ActorInstance* actorInstance = actorInstanceData->m_actorInstance; const Transform& transform = actorInstance->GetLocalSpaceTransform(); #ifndef EMFX_SCALE_DISABLED - AddTransformKey(actorInstanceData->mActorLocalTransform, transform.mPosition, transform.mRotation, transform.mScale); + AddTransformKey(actorInstanceData->m_actorLocalTransform, transform.m_position, transform.m_rotation, transform.m_scale); #else - AddTransformKey(actorInstanceData->mActorLocalTransform, transform.mPosition, transform.mRotation, AZ::Vector3(1.0f, 1.0f, 1.0f)); + AddTransformKey(actorInstanceData->m_actorLocalTransform, transform.m_position, transform.m_rotation, AZ::Vector3(1.0f, 1.0f, 1.0f)); #endif } } @@ -509,19 +509,19 @@ namespace EMotionFX { for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - ActorInstance* actorInstance = actorInstanceData->mActorInstance; + ActorInstance* actorInstance = actorInstanceData->m_actorInstance; const TransformData* transformData = actorInstance->GetTransformData(); { - const uint32 numNodes = actorInstance->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = actorInstance->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { const Transform& localTransform = transformData->GetCurrentPose()->GetLocalSpaceTransform(n); #ifndef EMFX_SCALE_DISABLED - AddTransformKey(actorInstanceData->m_transformTracks[n], localTransform.mPosition, localTransform.mRotation, localTransform.mScale); + AddTransformKey(actorInstanceData->m_transformTracks[n], localTransform.m_position, localTransform.m_rotation, localTransform.m_scale); #else - AddTransformKey(actorInstanceData->m_transformTracks[n], localTransform.mPosition, localTransform.mRotation, AZ::Vector3(1.0f, 1.0f, 1.0f)); + AddTransformKey(actorInstanceData->m_transformTracks[n], localTransform.m_position, localTransform.m_rotation, AZ::Vector3(1.0f, 1.0f, 1.0f)); #endif } } @@ -535,44 +535,43 @@ namespace EMotionFX // for all actor instances for (const ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - if (actorInstanceData->mAnimGraphData == nullptr) + if (actorInstanceData->m_animGraphData == nullptr) { continue; } { // get some shortcuts - AnimGraphInstanceData& animGraphInstanceData = *actorInstanceData->mAnimGraphData; - AnimGraphInstance* animGraphInstance = animGraphInstanceData.mAnimGraphInstance; + AnimGraphInstanceData& animGraphInstanceData = *actorInstanceData->m_animGraphData; + AnimGraphInstance* animGraphInstance = animGraphInstanceData.m_animGraphInstance; const AnimGraph* animGraph = animGraphInstance->GetAnimGraph(); // add a new frame - MCore::Array& frames = animGraphInstanceData.mFrames; - if (frames.GetLength() > 0) + AZStd::vector& frames = animGraphInstanceData.m_frames; + if (!frames.empty()) { - const uint32 byteOffset = frames.GetLast().mByteOffset + frames.GetLast().mNumBytes; - frames.AddEmpty(); - frames.GetLast().mByteOffset = byteOffset; - frames.GetLast().mNumBytes = 0; + const size_t byteOffset = frames.back().m_byteOffset + frames.back().m_numBytes; + frames.emplace_back(); + frames.back().m_byteOffset = byteOffset; + frames.back().m_numBytes = 0; } else { - frames.AddEmpty(); - frames.GetLast().mByteOffset = 0; - frames.GetLast().mNumBytes = 0; + frames.emplace_back(); + frames.back().m_byteOffset = 0; + frames.back().m_numBytes = 0; } // get the current frame - AnimGraphAnimFrame& currentFrame = frames.GetLast(); - currentFrame.mTimeValue = mRecordTime; + AnimGraphAnimFrame& currentFrame = frames.back(); + currentFrame.m_timeValue = m_recordTime; // save the parameter values - const uint32 numParams = static_cast(animGraphInstance->GetAnimGraph()->GetNumValueParameters()); - currentFrame.mParameterValues.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); - currentFrame.mParameterValues.Resize(numParams); - for (uint32 p = 0; p < numParams; ++p) + const size_t numParams = animGraphInstance->GetAnimGraph()->GetNumValueParameters(); + currentFrame.m_parameterValues.resize(numParams); + for (size_t p = 0; p < numParams; ++p) { - currentFrame.mParameterValues[p] = animGraphInstance->GetParameterValue(p)->Clone(); + currentFrame.m_parameterValues[p] = AZStd::unique_ptr(animGraphInstance->GetParameterValue(p)->Clone()); } // recursively save all unique datas @@ -582,9 +581,7 @@ namespace EMotionFX } // increase the frames counter - animGraphInstanceData.mNumFrames++; - - //MCore::LogInfo("Frame %d = %d bytes (offset=%d), with %d objects - dataBuffer = %d kb", animGraphInstanceData.mNumFrames, frames.GetLast().mNumBytes, frames.GetLast().mByteOffset, frames.GetLast().mObjectInfos.GetLength(), animGraphInstanceData.mDataBufferSize / 1024); + animGraphInstanceData.m_numFrames++; } } // for all actor instances return true; @@ -595,74 +592,74 @@ namespace EMotionFX bool Recorder::SaveUniqueData(AnimGraphInstance* animGraphInstance, AnimGraphObject* object, AnimGraphInstanceData& animGraphInstanceData) { // get the current frame's data pointer - AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames.GetLast(); - const uint32 frameOffset = currentFrame.mByteOffset; + AnimGraphAnimFrame& currentFrame = animGraphInstanceData.m_frames.back(); + const size_t frameOffset = currentFrame.m_byteOffset; // prepare the objects array - mObjects.Clear(false); - mObjects.Reserve(1024); + m_objects.clear(); + m_objects.reserve(1024); // collect the objects we are going to save for this frame - object->RecursiveCollectObjects(mObjects); + object->RecursiveCollectObjects(m_objects); // resize the object infos array - const uint32 numObjects = mObjects.GetLength(); - currentFrame.mObjectInfos.Resize(numObjects); + const size_t numObjects = m_objects.size(); + currentFrame.m_objectInfos.resize(numObjects); // calculate how much memory we need for this frame - uint32 requiredFrameBytes = 0; - for (uint32 i = 0; i < numObjects; ++i) + size_t requiredFrameBytes = 0; + for (const AnimGraphObject* animGraphObject : m_objects) { - requiredFrameBytes += mObjects[i]->SaveUniqueData(animGraphInstance, nullptr); + requiredFrameBytes += animGraphObject->SaveUniqueData(animGraphInstance, nullptr); } // make sure we have at least the given amount of space in the buffer we are going to write the frame data to - if (!AssureAnimGraphBufferSize(animGraphInstanceData, requiredFrameBytes + currentFrame.mByteOffset)) + if (!AssureAnimGraphBufferSize(animGraphInstanceData, requiredFrameBytes + currentFrame.m_byteOffset)) { return false; } - uint8* dataPointer = &animGraphInstanceData.mDataBuffer[frameOffset]; + uint8* dataPointer = &animGraphInstanceData.m_dataBuffer[frameOffset]; // save all the unique datas for the objects - for (uint32 i = 0; i < numObjects; ++i) + for (size_t i = 0; i < numObjects; ++i) { // store the object info - AnimGraphObject* curObject = mObjects[i]; - currentFrame.mObjectInfos[i].mObject = curObject; - currentFrame.mObjectInfos[i].mFrameByteOffset = currentFrame.mNumBytes; + AnimGraphObject* curObject = m_objects[i]; + currentFrame.m_objectInfos[i].m_object = curObject; + currentFrame.m_objectInfos[i].m_frameByteOffset = currentFrame.m_numBytes; // write the unique data - const uint32 numBytesWritten = curObject->SaveUniqueData(animGraphInstance, dataPointer); + const size_t numBytesWritten = curObject->SaveUniqueData(animGraphInstance, dataPointer); // increase some offsets/pointers - currentFrame.mNumBytes += numBytesWritten; + currentFrame.m_numBytes += numBytesWritten; dataPointer += numBytesWritten; } // make sure we have a match here, otherwise some of the object->SaveUniqueData(dataPointer) returns different values than object->SaveUniqueData(nullptr) - MCORE_ASSERT(requiredFrameBytes == currentFrame.mNumBytes); + MCORE_ASSERT(requiredFrameBytes == currentFrame.m_numBytes); return true; } // make sure our anim graph anim buffer is big enough to hold a specified amount of bytes - bool Recorder::AssureAnimGraphBufferSize(AnimGraphInstanceData& animGraphInstanceData, uint32 numBytes) + bool Recorder::AssureAnimGraphBufferSize(AnimGraphInstanceData& animGraphInstanceData, size_t numBytes) { // if the buffer is big enough, do nothing - if (animGraphInstanceData.mDataBufferSize >= numBytes) + if (animGraphInstanceData.m_dataBufferSize >= numBytes) { return true; } // we need to reallocate to grow the buffer - const uint32 newNumBytes = animGraphInstanceData.mDataBufferSize + (numBytes - animGraphInstanceData.mDataBufferSize) * 100; // allocate 100 frames ahead - void* newBuffer = MCore::Realloc(animGraphInstanceData.mDataBuffer, newNumBytes, EMFX_MEMCATEGORY_RECORDER); + const size_t newNumBytes = animGraphInstanceData.m_dataBufferSize + (numBytes - animGraphInstanceData.m_dataBufferSize) * 100; // allocate 100 frames ahead + void* newBuffer = MCore::Realloc(animGraphInstanceData.m_dataBuffer, newNumBytes, EMFX_MEMCATEGORY_RECORDER); MCORE_ASSERT(newBuffer); if (newBuffer) { - animGraphInstanceData.mDataBuffer = static_cast(newBuffer); - animGraphInstanceData.mDataBufferSize = newNumBytes; + animGraphInstanceData.m_dataBuffer = static_cast(newBuffer); + animGraphInstanceData.m_dataBufferSize = newNumBytes; return true; } RecorderNotificationBus::Broadcast(&RecorderNotificationBus::Events::OnRecordingFailed, @@ -682,51 +679,51 @@ namespace EMotionFX #endif // check if we need to add a position key at all - if (track.mPositions.GetNumKeys() > 0) + if (track.m_positions.GetNumKeys() > 0) { - const AZ::Vector3 lastPos = track.mPositions.GetLastKey()->GetValue(); + const AZ::Vector3 lastPos = track.m_positions.GetLastKey()->GetValue(); if (!pos.IsClose(lastPos, 0.0001f)) { - track.mPositions.AddKey(mRecordTime, pos); + track.m_positions.AddKey(m_recordTime, pos); } } else { - track.mPositions.AddKey(mRecordTime, pos); + track.m_positions.AddKey(m_recordTime, pos); } // check if we need to add a rotation key at all - if (track.mRotations.GetNumKeys() > 0) + if (track.m_rotations.GetNumKeys() > 0) { - const AZ::Quaternion lastRot = track.mRotations.GetLastKey()->GetValue(); + const AZ::Quaternion lastRot = track.m_rotations.GetLastKey()->GetValue(); if (!rot.IsClose(lastRot, 0.0001f)) { - track.mRotations.AddKey(mRecordTime, rot); + track.m_rotations.AddKey(m_recordTime, rot); } } else { - track.mRotations.AddKey(mRecordTime, rot); + track.m_rotations.AddKey(m_recordTime, rot); } EMFX_SCALECODE ( - if (mRecordSettings.mRecordScale) + if (m_recordSettings.m_recordScale) { // check if we need to add a scale key - if (track.mScales.GetNumKeys() > 0) + if (track.m_scales.GetNumKeys() > 0) { - const AZ::Vector3 lastScale = track.mScales.GetLastKey()->GetValue(); + const AZ::Vector3 lastScale = track.m_scales.GetLastKey()->GetValue(); if (!scale.IsClose(lastScale, 0.0001f)) { - track.mScales.AddKey(mRecordTime, scale); + track.m_scales.AddKey(m_recordTime, scale); } } else { - track.mScales.AddKey(mRecordTime, scale); + track.m_scales.AddKey(m_recordTime, scale); } } ) @@ -734,7 +731,7 @@ namespace EMotionFX void Recorder::SampleAndApplyTransforms(float timeInSeconds, ActorInstance* actorInstance) const { - const AZStd::vector& recordedActorInstances = mRecordSettings.m_actorInstances; + const AZStd::vector& recordedActorInstances = m_recordSettings.m_actorInstances; const auto iterator = AZStd::find(recordedActorInstances.begin(), recordedActorInstances.end(), actorInstance); if (iterator != recordedActorInstances.end()) { @@ -747,16 +744,16 @@ namespace EMotionFX { for (const ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - if(actorInstanceData->mAnimGraphData) + if(actorInstanceData->m_animGraphData) { - SampleAndApplyAnimGraphStates(timeInSeconds, *actorInstanceData->mAnimGraphData); + SampleAndApplyAnimGraphStates(timeInSeconds, *actorInstanceData->m_animGraphData); } } } void Recorder::SampleAndApplyMainTransform(float timeInSeconds, ActorInstance* actorInstance) const { - const AZStd::vector& recordedActorInstances = mRecordSettings.m_actorInstances; + const AZStd::vector& recordedActorInstances = m_recordSettings.m_actorInstances; const auto iterator = AZStd::find(recordedActorInstances.begin(), recordedActorInstances.end(), actorInstance); if (iterator != recordedActorInstances.end()) { @@ -767,19 +764,18 @@ namespace EMotionFX void Recorder::SampleAndApplyMorphs(float timeInSeconds, ActorInstance* actorInstance) const { - const AZStd::vector& recordedActorInstances = mRecordSettings.m_actorInstances; + const AZStd::vector& recordedActorInstances = m_recordSettings.m_actorInstances; const auto iterator = AZStd::find(recordedActorInstances.begin(), recordedActorInstances.end(), actorInstance); if (iterator != recordedActorInstances.end()) { - const size_t index = iterator - recordedActorInstances.begin(); + const size_t index = AZStd::distance(recordedActorInstances.begin(), iterator); const ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[index]; - const uint32 numMorphs = actorInstanceData.mMorphTracks.GetLength(); + const size_t numMorphs = actorInstanceData.m_morphTracks.size(); if (numMorphs == actorInstance->GetMorphSetupInstance()->GetNumMorphTargets()) { - for (uint32 i = 0; i < numMorphs; ++i) + for (size_t i = 0; i < numMorphs; ++i) { - actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->SetWeight(actorInstanceData.mMorphTracks[i].GetValueAtTime(timeInSeconds)); - // actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->SetManualMode(true); + actorInstance->GetMorphSetupInstance()->GetMorphTarget(i)->SetWeight(actorInstanceData.m_morphTracks[i].GetValueAtTime(timeInSeconds)); } } } @@ -789,17 +785,17 @@ namespace EMotionFX { // get the actor instance const ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[actorInstanceIndex]; - ActorInstance* actorInstance = actorInstanceData.mActorInstance; + ActorInstance* actorInstance = actorInstanceData.m_actorInstance; // sample and apply - const TransformTracks& track = actorInstanceData.mActorLocalTransform; - actorInstance->SetLocalSpacePosition(track.mPositions.GetValueAtTime(timeInSeconds, nullptr, nullptr, mRecordSettings.mInterpolate)); - actorInstance->SetLocalSpaceRotation(track.mRotations.GetValueAtTime(timeInSeconds, nullptr, nullptr, mRecordSettings.mInterpolate)); + const TransformTracks& track = actorInstanceData.m_actorLocalTransform; + actorInstance->SetLocalSpacePosition(track.m_positions.GetValueAtTime(timeInSeconds, nullptr, nullptr, m_recordSettings.m_interpolate)); + actorInstance->SetLocalSpaceRotation(track.m_rotations.GetValueAtTime(timeInSeconds, nullptr, nullptr, m_recordSettings.m_interpolate)); EMFX_SCALECODE ( - if (mRecordSettings.mRecordScale) + if (m_recordSettings.m_recordScale) { - actorInstance->SetLocalSpaceScale(track.mScales.GetValueAtTime(timeInSeconds, nullptr, nullptr, mRecordSettings.mInterpolate)); + actorInstance->SetLocalSpaceScale(track.m_scales.GetValueAtTime(timeInSeconds, nullptr, nullptr, m_recordSettings.m_interpolate)); } ) } @@ -807,26 +803,26 @@ namespace EMotionFX void Recorder::SampleAndApplyTransforms(float timeInSeconds, size_t actorInstanceIndex) const { const ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[actorInstanceIndex]; - ActorInstance* actorInstance = actorInstanceData.mActorInstance; + ActorInstance* actorInstance = actorInstanceData.m_actorInstance; TransformData* transformData = actorInstance->GetTransformData(); // for all nodes in the actor instance Transform outTransform; - const uint32 numNodes = actorInstance->GetNumNodes(); - for (uint32 n = 0; n < numNodes; ++n) + const size_t numNodes = actorInstance->GetNumNodes(); + for (size_t n = 0; n < numNodes; ++n) { outTransform = transformData->GetCurrentPose()->GetLocalSpaceTransform(n); const TransformTracks& track = actorInstanceData.m_transformTracks[n]; // build the output transform by sampling the keytracks - outTransform.mPosition = track.mPositions.GetValueAtTime(timeInSeconds, nullptr, nullptr, mRecordSettings.mInterpolate); - outTransform.mRotation = track.mRotations.GetValueAtTime(timeInSeconds, nullptr, nullptr, mRecordSettings.mInterpolate); + outTransform.m_position = track.m_positions.GetValueAtTime(timeInSeconds, nullptr, nullptr, m_recordSettings.m_interpolate); + outTransform.m_rotation = track.m_rotations.GetValueAtTime(timeInSeconds, nullptr, nullptr, m_recordSettings.m_interpolate); EMFX_SCALECODE ( - if (mRecordSettings.mRecordScale) + if (m_recordSettings.m_recordScale) { - outTransform.mScale = track.mScales.GetValueAtTime(timeInSeconds, nullptr, nullptr, mRecordSettings.mInterpolate); + outTransform.m_scale = track.m_scales.GetValueAtTime(timeInSeconds, nullptr, nullptr, m_recordSettings.m_interpolate); } ) @@ -838,67 +834,61 @@ namespace EMotionFX void Recorder::SampleAndApplyAnimGraphStates(float timeInSeconds, const AnimGraphInstanceData& animGraphInstanceData) const { // find out the frame number - const uint32 frameNumber = FindAnimGraphDataFrameNumber(timeInSeconds); - if (frameNumber == MCORE_INVALIDINDEX32) + const size_t frameNumber = FindAnimGraphDataFrameNumber(timeInSeconds); + if (frameNumber == InvalidIndex) { return; } // for all animgraph instances that we recorded, restore their internal states - AnimGraphInstance* animGraphInstance = animGraphInstanceData.mAnimGraphInstance; + AnimGraphInstance* animGraphInstance = animGraphInstanceData.m_animGraphInstance; // get the real frame number (clamped) - const uint32 realFrameNumber = MCore::Min(frameNumber, animGraphInstanceData.mFrames.GetLength() - 1); - const AnimGraphAnimFrame& currentFrame = animGraphInstanceData.mFrames[realFrameNumber]; + const size_t realFrameNumber = AZStd::min(frameNumber, animGraphInstanceData.m_frames.size() - 1); + const AnimGraphAnimFrame& currentFrame = animGraphInstanceData.m_frames[realFrameNumber]; // get the data and objects buffers - const uint32 byteOffset = currentFrame.mByteOffset; - const uint8* frameDataBuffer = &animGraphInstanceData.mDataBuffer[byteOffset]; - const MCore::Array& frameObjects = currentFrame.mObjectInfos; + const size_t byteOffset = currentFrame.m_byteOffset; + const uint8* frameDataBuffer = &animGraphInstanceData.m_dataBuffer[byteOffset]; + const AZStd::vector& frameObjects = currentFrame.m_objectInfos; // first lets update all parameter values - MCORE_ASSERT(currentFrame.mParameterValues.GetLength() == animGraphInstance->GetAnimGraph()->GetNumParameters()); - const uint32 numParameters = currentFrame.mParameterValues.GetLength(); - for (uint32 p = 0; p < numParameters; ++p) + MCORE_ASSERT(currentFrame.m_parameterValues.size() == animGraphInstance->GetAnimGraph()->GetNumParameters()); + const size_t numParameters = currentFrame.m_parameterValues.size(); + for (size_t p = 0; p < numParameters; ++p) { // make sure the parameters are of the same type - MCORE_ASSERT(animGraphInstance->GetParameterValue(p)->GetType() == currentFrame.mParameterValues[p]->GetType()); - animGraphInstance->GetParameterValue(p)->InitFrom(currentFrame.mParameterValues[p]); + MCORE_ASSERT(animGraphInstance->GetParameterValue(p)->GetType() == currentFrame.m_parameterValues[p]->GetType()); + animGraphInstance->GetParameterValue(p)->InitFrom(currentFrame.m_parameterValues[p].get()); } // process all objects for this frame - uint32 totalBytesRead = 0; - const uint32 numObjects = frameObjects.GetLength(); - for (uint32 a = 0; a < numObjects; ++a) + size_t totalBytesRead = 0; + const size_t numObjects = frameObjects.size(); + for (size_t a = 0; a < numObjects; ++a) { const AnimGraphAnimObjectInfo& objectInfo = frameObjects[a]; - const uint32 numBytesRead = objectInfo.mObject->LoadUniqueData(animGraphInstance, &frameDataBuffer[objectInfo.mFrameByteOffset]); + const size_t numBytesRead = objectInfo.m_object->LoadUniqueData(animGraphInstance, &frameDataBuffer[objectInfo.m_frameByteOffset]); totalBytesRead += numBytesRead; } // make sure this matches, otherwise the data read is not the same as we have written - MCORE_ASSERT(totalBytesRead == currentFrame.mNumBytes); + MCORE_ASSERT(totalBytesRead == currentFrame.m_numBytes); } bool Recorder::GetHasRecorded(ActorInstance* actorInstance) const { - return AZStd::find(mRecordSettings.m_actorInstances.begin(), mRecordSettings.m_actorInstances.end(), actorInstance) - != mRecordSettings.m_actorInstances.end(); + return AZStd::find(m_recordSettings.m_actorInstances.begin(), m_recordSettings.m_actorInstances.end(), actorInstance) + != m_recordSettings.m_actorInstances.end(); } - uint32 Recorder::FindActorInstanceDataIndex(ActorInstance* actorInstance) const + size_t Recorder::FindActorInstanceDataIndex(ActorInstance* actorInstance) const { - // for all actor instances - const uint32 numActorInstances = static_cast(m_actorInstanceDatas.size()); - for (uint32 a = 0; a < numActorInstances; ++a) + const auto found = AZStd::find_if(begin(m_actorInstanceDatas), end(m_actorInstanceDatas), [actorInstance](const ActorInstanceData* data) { - if (m_actorInstanceDatas[a]->mActorInstance == actorInstance) - { - return a; - } - } - - return MCORE_INVALIDINDEX32; + return data->m_actorInstance == actorInstance; + }); + return found != end(m_actorInstanceDatas) ? AZStd::distance(begin(m_actorInstanceDatas), found) : InvalidIndex; } void Recorder::UpdateNodeHistoryItems() @@ -907,56 +897,47 @@ namespace EMotionFX for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { // get the animgraph instance - AnimGraphInstance* animGraphInstance = actorInstanceData->mActorInstance->GetAnimGraphInstance(); + AnimGraphInstance* animGraphInstance = actorInstanceData->m_actorInstance->GetAnimGraphInstance(); if (animGraphInstance == nullptr) { continue; } // collect all active motion nodes - animGraphInstance->CollectActiveAnimGraphNodes(&mActiveNodes); + animGraphInstance->CollectActiveAnimGraphNodes(&m_activeNodes); // get the history items as shortcut - MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; // finalize items - const size_t numActiveNodes = mActiveNodes.size(); - const uint32 numHistoryItems = historyItems.GetLength(); - for (uint32 h = 0; h < numHistoryItems; ++h) + for (NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[h]; - if (curItem->mIsFinalized) + if (curItem->m_isFinalized) { continue; } // check if we have an active node for the given item - size_t index = MCORE_INVALIDINDEX32; - for (size_t x = 0; x < numActiveNodes; ++x) + const bool haveActiveNode = AZStd::find_if(begin(m_activeNodes), end(m_activeNodes), [curItem](const AnimGraphNode* activeNode) { - if (mActiveNodes[x]->GetId() == curItem->mNodeId) - { - index = x; - break; - } - } + return activeNode->GetId() == curItem->m_nodeId; + }) != end(m_activeNodes); // the node got deactivated, finalize the item - if (index == MCORE_INVALIDINDEX32) + if (haveActiveNode) { - curItem->mGlobalWeights.Optimize(0.0001f); - curItem->mLocalWeights.Optimize(0.0001f); - curItem->mPlayTimes.Optimize(0.0001f); - curItem->mIsFinalized = true; - curItem->mEndTime = mRecordTime; + curItem->m_globalWeights.Optimize(0.0001f); + curItem->m_localWeights.Optimize(0.0001f); + curItem->m_playTimes.Optimize(0.0001f); + curItem->m_isFinalized = true; + curItem->m_endTime = m_recordTime; continue; } } // iterate over all active nodes - for (size_t i = 0; i < numActiveNodes; ++i) + for (const AnimGraphNode* activeNode : m_activeNodes) { - AnimGraphNode* activeNode = mActiveNodes[i]; if (activeNode == animGraphInstance->GetRootNode()) // skip the root node { continue; @@ -965,7 +946,7 @@ namespace EMotionFX const AZ::TypeId typeID = azrtti_typeid(activeNode); // if the parent isn't a state machine then it isn't a state - if (mRecordSettings.mHistoryStatesOnly) + if (m_recordSettings.m_historyStatesOnly) { if (azrtti_typeid(activeNode->GetParentNode()) != azrtti_typeid()) { @@ -974,63 +955,63 @@ namespace EMotionFX } // make sure this node is on our capture list - if (!mRecordSettings.mNodeHistoryTypes.empty()) + if (!m_recordSettings.m_nodeHistoryTypes.empty()) { - if (mRecordSettings.mNodeHistoryTypes.find(typeID) == mRecordSettings.mNodeHistoryTypes.end()) + if (m_recordSettings.m_nodeHistoryTypes.find(typeID) == m_recordSettings.m_nodeHistoryTypes.end()) { continue; } } // skip node types we do not want to capture - if (!mRecordSettings.mNodeHistoryTypesToIgnore.empty()) + if (!m_recordSettings.m_nodeHistoryTypesToIgnore.empty()) { - if (mRecordSettings.mNodeHistoryTypesToIgnore.find(typeID) != mRecordSettings.mNodeHistoryTypesToIgnore.end()) + if (m_recordSettings.m_nodeHistoryTypesToIgnore.find(typeID) != m_recordSettings.m_nodeHistoryTypesToIgnore.end()) { continue; } } // try to locate an existing item - NodeHistoryItem* item = FindNodeHistoryItem(*actorInstanceData, activeNode, mRecordTime); + NodeHistoryItem* item = FindNodeHistoryItem(*actorInstanceData, activeNode, m_recordTime); if (item == nullptr) { item = new NodeHistoryItem(); - item->mName = activeNode->GetName(); - item->mAnimGraphID = animGraphInstance->GetAnimGraph()->GetID(); - item->mStartTime = mRecordTime; - item->mIsFinalized = false; - item->mTrackIndex = FindFreeNodeHistoryItemTrack(*actorInstanceData, item); - item->mNodeId = activeNode->GetId(); - item->mColor = activeNode->GetVisualizeColor(); - item->mTypeColor = activeNode->GetVisualColor(); - item->mCategoryID = (uint32)activeNode->GetPaletteCategory(); - item->mNodeType = typeID; - item->mAnimGraphInstance = animGraphInstance; - item->mGlobalWeights.Reserve(1024); - item->mLocalWeights.Reserve(1024); - item->mPlayTimes.Reserve(1024); + item->m_name = activeNode->GetName(); + item->m_animGraphId = animGraphInstance->GetAnimGraph()->GetID(); + item->m_startTime = m_recordTime; + item->m_isFinalized = false; + item->m_trackIndex = FindFreeNodeHistoryItemTrack(*actorInstanceData, item); + item->m_nodeId = activeNode->GetId(); + item->m_color = activeNode->GetVisualizeColor(); + item->m_typeColor = activeNode->GetVisualColor(); + item->m_categoryId = (uint32)activeNode->GetPaletteCategory(); + item->m_nodeType = typeID; + item->m_animGraphInstance = animGraphInstance; + item->m_globalWeights.Reserve(1024); + item->m_localWeights.Reserve(1024); + item->m_playTimes.Reserve(1024); // get the motion instance if (typeID == azrtti_typeid()) { - AnimGraphMotionNode* motionNode = static_cast(activeNode); + const AnimGraphMotionNode* motionNode = static_cast(activeNode); MotionInstance* motionInstance = motionNode->FindMotionInstance(animGraphInstance); if (motionInstance) { - item->mMotionID = motionInstance->GetMotion()->GetID(); - AzFramework::StringFunc::Path::GetFileName(item->mMotionFileName.c_str(), item->mMotionFileName); + item->m_motionId = motionInstance->GetMotion()->GetID(); + AzFramework::StringFunc::Path::GetFileName(item->m_motionFileName.c_str(), item->m_motionFileName); } } - historyItems.Add(item); + historyItems.emplace_back(item); } // add the weight key and update infos const AnimGraphNodeData* uniqueData = activeNode->FindOrCreateUniqueNodeData(animGraphInstance); - const float keyTime = mRecordTime - item->mStartTime; - item->mGlobalWeights.AddKey(keyTime, uniqueData->GetGlobalWeight()); - item->mLocalWeights.AddKey(keyTime, uniqueData->GetLocalWeight()); + const float keyTime = m_recordTime - item->m_startTime; + item->m_globalWeights.AddKey(keyTime, uniqueData->GetGlobalWeight()); + item->m_localWeights.AddKey(keyTime, uniqueData->GetLocalWeight()); float normalizedTime = uniqueData->GetCurrentPlayTime(); const float duration = uniqueData->GetDuration(); @@ -1043,27 +1024,25 @@ namespace EMotionFX normalizedTime = 0.0f; } - item->mPlayTimes.AddKey(keyTime, normalizedTime); - item->mEndTime = mRecordTime; + item->m_playTimes.AddKey(keyTime, normalizedTime); + item->m_endTime = m_recordTime; } } // for all actor instances } // try to find a given node history item - Recorder::NodeHistoryItem* Recorder::FindNodeHistoryItem(const ActorInstanceData& actorInstanceData, AnimGraphNode* node, float recordTime) const + Recorder::NodeHistoryItem* Recorder::FindNodeHistoryItem(const ActorInstanceData& actorInstanceData, const AnimGraphNode* node, float recordTime) const { - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; + for (NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; - if (curItem->mNodeId == node->GetId() && curItem->mStartTime <= recordTime && curItem->mIsFinalized == false) + if (curItem->m_nodeId == node->GetId() && curItem->m_startTime <= recordTime && curItem->m_isFinalized == false) { return curItem; } - if (curItem->mNodeId == node->GetId() && curItem->mStartTime <= recordTime && curItem->mEndTime >= recordTime && curItem->mIsFinalized) + if (curItem->m_nodeId == node->GetId() && curItem->m_startTime <= recordTime && curItem->m_endTime >= recordTime && curItem->m_isFinalized) { return curItem; } @@ -1074,51 +1053,43 @@ namespace EMotionFX // find a free track - uint32 Recorder::FindFreeNodeHistoryItemTrack(const ActorInstanceData& actorInstanceData, NodeHistoryItem* item) const + size_t Recorder::FindFreeNodeHistoryItemTrack(const ActorInstanceData& actorInstanceData, NodeHistoryItem* item) const { - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; bool found = false; - uint32 trackIndex = 0; + size_t trackIndex = 0; while (found == false) { bool hasCollision = false; - for (uint32 i = 0; i < numItems; ++i) + for (const NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; - if (curItem->mTrackIndex != trackIndex) + if (curItem->m_trackIndex != trackIndex) { continue; } // if the current item is not active anymore - if (curItem->mIsFinalized) + if (curItem->m_isFinalized) { // if the start time of the item we try to insert is within the range of this item - if (item->mStartTime > curItem->mStartTime && item->mStartTime < curItem->mEndTime) + if (item->m_startTime > curItem->m_startTime && item->m_startTime < curItem->m_endTime) { hasCollision = true; break; } // if the end time of this item is within the range of this item - if (item->mEndTime > curItem->mStartTime && item->mEndTime < curItem->mEndTime) + if (item->m_endTime > curItem->m_startTime && item->m_endTime < curItem->m_endTime) { hasCollision = true; break; } - /* - if (MCore::Compare::CheckIfIsClose(item->mStartTime, curItem->mStartTime, 0.001f) || MCore::Compare::CheckIfIsClose(item->mStartTime, curItem->mEndTime, 0.001f)) - { - hasCollision = true; - break; - }*/ } else // if the current item is still active and has no real end time yet { - if (item->mStartTime >= curItem->mStartTime) + if (item->m_startTime >= curItem->m_startTime) { hasCollision = true; break; @@ -1141,17 +1112,15 @@ namespace EMotionFX // find the maximum track index - uint32 Recorder::CalcMaxNodeHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const + size_t Recorder::CalcMaxNodeHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const { - uint32 result = 0; - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + size_t result = 0; + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; + for (const NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; - if (curItem->mTrackIndex > result) + if (curItem->m_trackIndex > result) { - result = curItem->mTrackIndex; + result = curItem->m_trackIndex; } } @@ -1160,17 +1129,15 @@ namespace EMotionFX // find the maximum event track index - uint32 Recorder::CalcMaxEventHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const + size_t Recorder::CalcMaxEventHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const { - uint32 result = 0; - const MCore::Array& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + size_t result = 0; + const AZStd::vector& historyItems = actorInstanceData.m_eventHistoryItems; + for (const EventHistoryItem* curItem : historyItems) { - EventHistoryItem* curItem = historyItems[i]; - if (curItem->mTrackIndex > result) + if (curItem->m_trackIndex > result) { - result = curItem->mTrackIndex; + result = curItem->m_trackIndex; } } @@ -1179,14 +1146,14 @@ namespace EMotionFX // find the maximum track index - uint32 Recorder::CalcMaxNodeHistoryTrackIndex() const + size_t Recorder::CalcMaxNodeHistoryTrackIndex() const { - uint32 result = 0; + size_t result = 0; // for all actor instances for (const ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - result = MCore::Max(result, CalcMaxNodeHistoryTrackIndex(*actorInstanceData)); + result = AZStd::max(result, CalcMaxNodeHistoryTrackIndex(*actorInstanceData)); } return result; @@ -1200,29 +1167,28 @@ namespace EMotionFX for (const ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { // get the animgraph instance - AnimGraphInstance* animGraphInstance = actorInstanceData->mActorInstance->GetAnimGraphInstance(); + AnimGraphInstance* animGraphInstance = actorInstanceData->m_actorInstance->GetAnimGraphInstance(); if (animGraphInstance == nullptr) { continue; } // collect all active motion nodes - animGraphInstance->CollectActiveAnimGraphNodes(&mActiveNodes); + animGraphInstance->CollectActiveAnimGraphNodes(&m_activeNodes); // get the history items as shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; // finalize all items - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (NodeHistoryItem* historyItem : historyItems) { // remove unneeded key frames - if (historyItems[i]->mIsFinalized == false) + if (historyItem->m_isFinalized == false) { - historyItems[i]->mGlobalWeights.Optimize(0.0001f); - historyItems[i]->mLocalWeights.Optimize(0.0001f); - historyItems[i]->mPlayTimes.Optimize(0.0001f); - historyItems[i]->mIsFinalized = true; + historyItem->m_globalWeights.Optimize(0.0001f); + historyItem->m_localWeights.Optimize(0.0001f); + historyItem->m_playTimes.Optimize(0.0001f); + historyItem->m_isFinalized = true; } } } @@ -1236,7 +1202,7 @@ namespace EMotionFX for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { // get the animgraph instance - AnimGraphInstance* animGraphInstance = actorInstanceData->mActorInstance->GetAnimGraphInstance(); + AnimGraphInstance* animGraphInstance = actorInstanceData->m_actorInstance->GetAnimGraphInstance(); if (animGraphInstance == nullptr) { continue; @@ -1246,35 +1212,35 @@ namespace EMotionFX const AnimGraphEventBuffer& eventBuffer = animGraphInstance->GetEventBuffer(); // iterate over all events - MCore::Array& historyItems = actorInstanceData->mEventHistoryItems; - const uint32 numEvents = eventBuffer.GetNumEvents(); - for (uint32 i = 0; i < numEvents; ++i) + AZStd::vector& historyItems = actorInstanceData->m_eventHistoryItems; + const size_t numEvents = eventBuffer.GetNumEvents(); + for (size_t i = 0; i < numEvents; ++i) { const EventInfo& eventInfo = eventBuffer.GetEvent(i); if (eventInfo.m_eventState == EventInfo::EventInfo::ACTIVE) { continue; } - EventHistoryItem* item = FindEventHistoryItem(*actorInstanceData, eventInfo, mRecordTime); + EventHistoryItem* item = FindEventHistoryItem(*actorInstanceData, eventInfo, m_recordTime); if (item == nullptr) // create a new one { item = new EventHistoryItem(); // TODO - //item->mEventIndex = GetEventManager().FindEventTypeIndex(eventInfo.mTypeID); - item->mEventInfo = eventInfo; - item->mIsTickEvent = eventInfo.mEvent->GetIsTickEvent(); - item->mStartTime = mRecordTime; - item->mAnimGraphID = animGraphInstance->GetAnimGraph()->GetID(); - item->mEmitterNodeId= eventInfo.mEmitter->GetId(); - item->mColor = eventInfo.mEmitter->GetVisualizeColor(); + //item->m_eventIndex = GetEventManager().FindEventTypeIndex(eventInfo.m_typeID); + item->m_eventInfo = eventInfo; + item->m_isTickEvent = eventInfo.m_event->GetIsTickEvent(); + item->m_startTime = m_recordTime; + item->m_animGraphId = animGraphInstance->GetAnimGraph()->GetID(); + item->m_emitterNodeId= eventInfo.m_emitter->GetId(); + item->m_color = eventInfo.m_emitter->GetVisualizeColor(); - item->mTrackIndex = FindFreeEventHistoryItemTrack(*actorInstanceData, item); + item->m_trackIndex = FindFreeEventHistoryItemTrack(*actorInstanceData, item); - historyItems.Add(item); + historyItems.emplace_back(item); } - item->mEndTime = mRecordTime; + item->m_endTime = m_recordTime; } } } @@ -1284,13 +1250,10 @@ namespace EMotionFX Recorder::EventHistoryItem* Recorder::FindEventHistoryItem(const ActorInstanceData& actorInstanceData, const EventInfo& eventInfo, float recordTime) { MCORE_UNUSED(recordTime); - const MCore::Array& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + const AZStd::vector& historyItems = actorInstanceData.m_eventHistoryItems; + for (const EventHistoryItem* curItem : historyItems) { - EventHistoryItem* curItem = historyItems[i]; - - if (curItem->mStartTime < eventInfo.mTimeValue) + if (curItem->m_startTime < eventInfo.m_timeValue) { continue; } @@ -1301,25 +1264,23 @@ namespace EMotionFX // find a free event track index - uint32 Recorder::FindFreeEventHistoryItemTrack(const ActorInstanceData& actorInstanceData, EventHistoryItem* item) const + size_t Recorder::FindFreeEventHistoryItemTrack(const ActorInstanceData& actorInstanceData, EventHistoryItem* item) const { - const MCore::Array& historyItems = actorInstanceData.mEventHistoryItems; - const uint32 numItems = historyItems.GetLength(); + const AZStd::vector& historyItems = actorInstanceData.m_eventHistoryItems; bool found = false; - uint32 trackIndex = 0; + size_t trackIndex = 0; while (found == false) { bool hasCollision = false; - for (uint32 i = 0; i < numItems; ++i) + for (const EventHistoryItem* curItem : historyItems) { - EventHistoryItem* curItem = historyItems[i]; - if (curItem->mTrackIndex != trackIndex) + if (curItem->m_trackIndex != trackIndex) { continue; } - if (MCore::Compare::CheckIfIsClose(curItem->mStartTime, item->mStartTime, 0.01f)) + if (MCore::Compare::CheckIfIsClose(curItem->m_startTime, item->m_startTime, 0.01f)) { hasCollision = true; break; @@ -1341,7 +1302,7 @@ namespace EMotionFX // find the frame number for a time value - uint32 Recorder::FindAnimGraphDataFrameNumber(float timeValue) const + size_t Recorder::FindAnimGraphDataFrameNumber(float timeValue) const { // check if we recorded any actor instances at all if (m_actorInstanceDatas.empty()) @@ -1351,18 +1312,17 @@ namespace EMotionFX // just search in the first actor instances data const ActorInstanceData& actorInstanceData = *m_actorInstanceDatas[0]; - const AnimGraphInstanceData* animGraphData = actorInstanceData.mAnimGraphData; + const AnimGraphInstanceData* animGraphData = actorInstanceData.m_animGraphData; if (animGraphData == nullptr) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - const uint32 numFrames = animGraphData->mFrames.GetLength(); + const size_t numFrames = animGraphData->m_frames.size(); if (numFrames == 0) { - return MCORE_INVALIDINDEX32; + return InvalidIndex; } - else if (numFrames == 1) { return 0; @@ -1373,22 +1333,22 @@ namespace EMotionFX return 0; } - if (timeValue > animGraphData->mFrames.GetLast().mTimeValue) + if (timeValue > animGraphData->m_frames.back().m_timeValue) { - return animGraphData->mFrames.GetLength() - 1; + return animGraphData->m_frames.size() - 1; } - for (uint32 i = 0; i < numFrames - 1; ++i) + for (size_t i = 0; i < numFrames - 1; ++i) { - const AnimGraphAnimFrame& curFrame = animGraphData->mFrames[i]; - const AnimGraphAnimFrame& nextFrame = animGraphData->mFrames[i + 1]; - if (curFrame.mTimeValue <= timeValue && nextFrame.mTimeValue > timeValue) + const AnimGraphAnimFrame& curFrame = animGraphData->m_frames[i]; + const AnimGraphAnimFrame& nextFrame = animGraphData->m_frames[i + 1]; + if (curFrame.m_timeValue <= timeValue && nextFrame.m_timeValue > timeValue) { return i; } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } void Recorder::RemoveActorInstanceFromRecording(ActorInstance* actorInstance) @@ -1396,15 +1356,15 @@ namespace EMotionFX Lock(); // Remove the actor instance from the record settings. - AZStd::vector& recordedActorInstances = mRecordSettings.m_actorInstances; + AZStd::vector& recordedActorInstances = m_recordSettings.m_actorInstances; recordedActorInstances.erase(AZStd::remove_if(recordedActorInstances.begin(), recordedActorInstances.end(), [&actorInstance](ActorInstance* recordedActorInstance){ return recordedActorInstance == actorInstance;}), recordedActorInstances.end()); // Remove the actual recorded data. - for (uint32 i = 0; i < m_actorInstanceDatas.size();) + for (size_t i = 0; i < m_actorInstanceDatas.size();) { - if (m_actorInstanceDatas[i]->mActorInstance == actorInstance) + if (m_actorInstanceDatas[i]->m_actorInstance == actorInstance) { delete m_actorInstanceDatas[i]; m_actorInstanceDatas.erase(AZStd::next(m_actorInstanceDatas.begin(), i)); @@ -1424,16 +1384,16 @@ namespace EMotionFX for (ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - if (actorInstanceData->mAnimGraphData && actorInstanceData->mAnimGraphData->mAnimGraphInstance) + if (actorInstanceData->m_animGraphData && actorInstanceData->m_animGraphData->m_animGraphInstance) { - AnimGraph* curAnimGraph = actorInstanceData->mAnimGraphData->mAnimGraphInstance->GetAnimGraph(); + AnimGraph* curAnimGraph = actorInstanceData->m_animGraphData->m_animGraphInstance->GetAnimGraph(); if (animGraph != curAnimGraph) { continue; } - delete actorInstanceData->mAnimGraphData; - actorInstanceData->mAnimGraphData = nullptr; + delete actorInstanceData->m_animGraphData; + actorInstanceData->m_animGraphData = nullptr; } } @@ -1449,103 +1409,101 @@ namespace EMotionFX void Recorder::Lock() { - mLock.Lock(); + m_lock.Lock(); } void Recorder::Unlock() { - mLock.Unlock(); + m_lock.Unlock(); } // extract sorted active items - void Recorder::ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, MCore::Array* outItems, MCore::Array* outMap) + void Recorder::ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, AZStd::vector* outItems, AZStd::vector* outMap) const { // clear the map array - const uint32 maxIndex = CalcMaxNodeHistoryTrackIndex(actorInstanceData); - outItems->Resize(maxIndex + 1); - for (uint32 i = 0; i <= maxIndex; ++i) + const size_t maxIndex = CalcMaxNodeHistoryTrackIndex(actorInstanceData); + outItems->resize(maxIndex + 1); + for (size_t i = 0; i <= maxIndex; ++i) { ExtractedNodeHistoryItem item; - item.mTrackIndex = i; - item.mValue = 0.0f; - item.mKeyTrackSampleTime = 0.0f; - item.mNodeHistoryItem = nullptr; - outItems->SetElem(i, item); + item.m_trackIndex = i; + item.m_value = 0.0f; + item.m_keyTrackSampleTime = 0.0f; + item.m_nodeHistoryItem = nullptr; + outItems->emplace(AZStd::next(begin(*outItems), i), AZStd::move(item)); } // find all node history items - const MCore::Array& historyItems = actorInstanceData.mNodeHistoryItems; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + const AZStd::vector& historyItems = actorInstanceData.m_nodeHistoryItems; + for (NodeHistoryItem* curItem : historyItems) { - NodeHistoryItem* curItem = historyItems[i]; - if (curItem->mStartTime <= timeValue && curItem->mEndTime > timeValue) + if (curItem->m_startTime <= timeValue && curItem->m_endTime > timeValue) { ExtractedNodeHistoryItem item; - item.mTrackIndex = curItem->mTrackIndex; - item.mKeyTrackSampleTime = timeValue - curItem->mStartTime; - item.mNodeHistoryItem = curItem; + item.m_trackIndex = curItem->m_trackIndex; + item.m_keyTrackSampleTime = timeValue - curItem->m_startTime; + item.m_nodeHistoryItem = curItem; switch (valueType) { case VALUETYPE_GLOBALWEIGHT: - item.mValue = curItem->mGlobalWeights.GetValueAtTime(item.mKeyTrackSampleTime, nullptr, nullptr, mRecordSettings.mInterpolate); + item.m_value = curItem->m_globalWeights.GetValueAtTime(item.m_keyTrackSampleTime, nullptr, nullptr, m_recordSettings.m_interpolate); break; case VALUETYPE_LOCALWEIGHT: - item.mValue = curItem->mLocalWeights.GetValueAtTime(item.mKeyTrackSampleTime, nullptr, nullptr, mRecordSettings.mInterpolate); + item.m_value = curItem->m_localWeights.GetValueAtTime(item.m_keyTrackSampleTime, nullptr, nullptr, m_recordSettings.m_interpolate); break; case VALUETYPE_PLAYTIME: - item.mValue = curItem->mPlayTimes.GetValueAtTime(item.mKeyTrackSampleTime, nullptr, nullptr, mRecordSettings.mInterpolate); + item.m_value = curItem->m_playTimes.GetValueAtTime(item.m_keyTrackSampleTime, nullptr, nullptr, m_recordSettings.m_interpolate); break; default: MCORE_ASSERT(false); // unsupported mode - item.mValue = curItem->mGlobalWeights.GetValueAtTime(item.mKeyTrackSampleTime, nullptr, nullptr, mRecordSettings.mInterpolate); + item.m_value = curItem->m_globalWeights.GetValueAtTime(item.m_keyTrackSampleTime, nullptr, nullptr, m_recordSettings.m_interpolate); } - outItems->SetElem(curItem->mTrackIndex, item); + outItems->emplace(AZStd::next(begin(*outItems), curItem->m_trackIndex), item); } } // build the map - outMap->Resize(maxIndex + 1); - for (uint32 i = 0; i <= maxIndex; ++i) + outMap->resize(maxIndex + 1); + for (size_t i = 0; i <= maxIndex; ++i) { - outMap->SetElem(i, i); + outMap->emplace(AZStd::next(begin(*outMap), i), i); } // sort if desired if (sort) { - outItems->Sort(); + AZStd::sort(begin(*outItems), end(*outItems)); - for (uint32 i = 0; i <= maxIndex; ++i) + for (size_t i = 0; i <= maxIndex; ++i) { - outMap->SetElem(outItems->GetItem(i).mTrackIndex, i); + outMap->emplace(AZStd::next(begin(*outMap), outItems->at(i).m_trackIndex), i); } } } - AZ::u32 Recorder::CalcMaxNumActiveMotions(const ActorInstanceData& actorInstanceData) const + size_t Recorder::CalcMaxNumActiveMotions(const ActorInstanceData& actorInstanceData) const { - AZ::u32 result = 0; + size_t result = 0; // Array of flags that each iteration will use to determine if a given track has already been counted in or not. AZStd::vector trackFlags; const size_t maxNumTracks = static_cast(CalcMaxNodeHistoryTrackIndex()) + 1; trackFlags.resize(maxNumTracks); - const uint32 numNodeHistoryItems = actorInstanceData.mNodeHistoryItems.GetLength(); - for (uint32 i = 0; i < numNodeHistoryItems; ++i) + const size_t numNodeHistoryItems = actorInstanceData.m_nodeHistoryItems.size(); + for (size_t i = 0; i < numNodeHistoryItems; ++i) { - EMotionFX::Recorder::NodeHistoryItem* item = actorInstanceData.mNodeHistoryItems[i]; + EMotionFX::Recorder::NodeHistoryItem* item = actorInstanceData.m_nodeHistoryItems[i]; // Only process motion history items. - if (item->mMotionID == MCORE_INVALIDINDEX32) + if (item->m_motionId == MCORE_INVALIDINDEX32) { continue; } @@ -1557,50 +1515,50 @@ namespace EMotionFX } // We at least have a single active motion. - AZ::u32 intermediateResult = 1; - trackFlags[item->mTrackIndex] = true; + size_t intermediateResult = 1; + trackFlags[item->m_trackIndex] = true; - for (uint32 j = 0; j < numNodeHistoryItems; ++j) + for (size_t j = 0; j < numNodeHistoryItems; ++j) { - EMotionFX::Recorder::NodeHistoryItem* innerItem = actorInstanceData.mNodeHistoryItems[j]; + EMotionFX::Recorder::NodeHistoryItem* innerItem = actorInstanceData.m_nodeHistoryItems[j]; // Did we count this track in already? If yes, skip. - if (trackFlags[innerItem->mTrackIndex]) + if (trackFlags[innerItem->m_trackIndex]) { continue; } // Skip self comparison and only process motion history items. - if (i == j || innerItem->mMotionID == MCORE_INVALIDINDEX32) + if (i == j || innerItem->m_motionId == MCORE_INVALIDINDEX32) { continue; } // Are the item and innerItem events overlapping? - if ((item->mStartTime >= innerItem->mStartTime && item->mStartTime <= innerItem->mEndTime) || - (item->mEndTime >= innerItem->mStartTime && item->mEndTime <= innerItem->mEndTime) || - (innerItem->mStartTime >= item->mStartTime && innerItem->mStartTime <= item->mEndTime) || - (innerItem->mEndTime >= item->mStartTime && innerItem->mEndTime <= item->mEndTime)) + if ((item->m_startTime >= innerItem->m_startTime && item->m_startTime <= innerItem->m_endTime) || + (item->m_endTime >= innerItem->m_startTime && item->m_endTime <= innerItem->m_endTime) || + (innerItem->m_startTime >= item->m_startTime && innerItem->m_startTime <= item->m_endTime) || + (innerItem->m_endTime >= item->m_startTime && innerItem->m_endTime <= item->m_endTime)) { intermediateResult++; - trackFlags[innerItem->mTrackIndex] = true; + trackFlags[innerItem->m_trackIndex] = true; } } - result = MCore::Max(result, intermediateResult); + result = AZStd::max(result, intermediateResult); } return result; } - AZ::u32 Recorder::CalcMaxNumActiveMotions() const + size_t Recorder::CalcMaxNumActiveMotions() const { - AZ::u32 result = 0; + size_t result = 0; for (const ActorInstanceData* actorInstanceData : m_actorInstanceDatas) { - result = MCore::Max(result, CalcMaxNumActiveMotions(*actorInstanceData)); + result = AZStd::max(result, CalcMaxNumActiveMotions(*actorInstanceData)); } return result; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h index 3c9ec5ece8..fe87d36ea1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Recorder.h @@ -15,7 +15,7 @@ #include "BaseObject.h" #include #include "MCore/Source/Color.h" -#include +#include #include #include #include @@ -59,33 +59,33 @@ namespace EMotionFX AZ_TYPE_INFO(EMotionFX::Recorder::RecordSettings, "{A3F9D69E-3543-4B9D-B6F1-C0D5BAB1EDB1}"); AZStd::vector m_actorInstances; /**< The actor instances to record, or specify none to record all (default=record all). */ - AZStd::unordered_set mNodeHistoryTypes; /**< The array of type node type IDs to capture. Empty array means everything. */ - AZStd::unordered_set mNodeHistoryTypesToIgnore; /**< The array of type node type IDs to NOT capture. Empty array means nothing to ignore. */ - uint32 mFPS; /**< The rate at which to sample (default=15). */ - uint32 mNumPreAllocTransformKeys; /**< Pre-allocate space for this amount of transformation keys per node per actor instance (default=32). */ - uint32 mInitialAnimGraphAnimBytes; /**< The number of bytes to allocate to store the anim graph recording (default=2*1024*1024, which is 2mb). This is only used when actually recording anim graph internal state animation. */ - bool mRecordTransforms; /**< Record transformations? (default=true). */ - bool mRecordAnimGraphStates; /**< Record the anim graph internal state? (default=false). */ - bool mRecordNodeHistory; /**< Record the node history? (default=false). */ - bool mHistoryStatesOnly; /**< Record only states in the node history? (default=false, and only used when mRecordNodeHistory is true). */ - bool mRecordScale; /**< Record scale changes when recording transforms? */ - bool mRecordEvents; /**< Record events (default=false). */ - bool mRecordMorphs; /**< Record morph target weight animation (default=true). */ - bool mInterpolate; /**< Interpolate playback? (default=false) */ + AZStd::unordered_set m_nodeHistoryTypes; /**< The array of type node type IDs to capture. Empty array means everything. */ + AZStd::unordered_set m_nodeHistoryTypesToIgnore; /**< The array of type node type IDs to NOT capture. Empty array means nothing to ignore. */ + uint32 m_fps; /**< The rate at which to sample (default=15). */ + uint32 m_numPreAllocTransformKeys; /**< Pre-allocate space for this amount of transformation keys per node per actor instance (default=32). */ + size_t m_initialAnimGraphAnimBytes; /**< The number of bytes to allocate to store the anim graph recording (default=2*1024*1024, which is 2mb). This is only used when actually recording anim graph internal state animation. */ + bool m_recordTransforms; /**< Record transformations? (default=true). */ + bool m_recordAnimGraphStates; /**< Record the anim graph internal state? (default=false). */ + bool m_recordNodeHistory; /**< Record the node history? (default=false). */ + bool m_historyStatesOnly; /**< Record only states in the node history? (default=false, and only used when m_recordNodeHistory is true). */ + bool m_recordScale; /**< Record scale changes when recording transforms? */ + bool m_recordEvents; /**< Record events (default=false). */ + bool m_recordMorphs; /**< Record morph target weight animation (default=true). */ + bool m_interpolate; /**< Interpolate playback? (default=false) */ RecordSettings() { - mFPS = 60; - mNumPreAllocTransformKeys = 32; - mInitialAnimGraphAnimBytes = 1 * 1024 * 1024; // 1 megabyte - mRecordTransforms = true; - mRecordNodeHistory = false; - mHistoryStatesOnly = false; - mRecordAnimGraphStates = false; - mRecordEvents = false; - mRecordScale = true; - mRecordMorphs = true; - mInterpolate = false; + m_fps = 60; + m_numPreAllocTransformKeys = 32; + m_initialAnimGraphAnimBytes = 1 * 1024 * 1024; // 1 megabyte + m_recordTransforms = true; + m_recordNodeHistory = false; + m_historyStatesOnly = false; + m_recordAnimGraphStates = false; + m_recordEvents = false; + m_recordScale = true; + m_recordMorphs = true; + m_interpolate = false; } static void Reflect(AZ::ReflectContext* context); @@ -94,25 +94,25 @@ namespace EMotionFX struct EMFX_API EventHistoryItem { - EventInfo mEventInfo; - uint32 mEventIndex; /**< The index to use in combination with GetEventManager().GetEvent(index). */ - uint32 mTrackIndex; - AnimGraphNodeId mEmitterNodeId; - uint32 mAnimGraphID; - AZ::Color mColor; - float mStartTime; - float mEndTime; - bool mIsTickEvent; + EventInfo m_eventInfo; + size_t m_eventIndex; /**< The index to use in combination with GetEventManager().GetEvent(index). */ + size_t m_trackIndex; + AnimGraphNodeId m_emitterNodeId; + uint32 m_animGraphId; + AZ::Color m_color; + float m_startTime; + float m_endTime; + bool m_isTickEvent; EventHistoryItem() { - mEventIndex = MCORE_INVALIDINDEX32; - mTrackIndex = MCORE_INVALIDINDEX32; - mEmitterNodeId = AnimGraphNodeId(); - mAnimGraphID = MCORE_INVALIDINDEX32; + m_eventIndex = InvalidIndex; + m_trackIndex = InvalidIndex; + m_emitterNodeId = AnimGraphNodeId(); + m_animGraphId = MCORE_INVALIDINDEX32; const AZ::u32 col = MCore::GenerateColor(); - mColor = AZ::Color( + m_color = AZ::Color( MCore::ExtractRed(col)/255.0f, MCore::ExtractGreen(col)/255.0f, MCore::ExtractBlue(col)/255.0f, @@ -122,40 +122,40 @@ namespace EMotionFX struct EMFX_API NodeHistoryItem { - AZStd::string mName; - AZStd::string mMotionFileName; - float mStartTime; // time the motion starts being active - float mEndTime; // time the motion stops being active - KeyTrackLinearDynamic mGlobalWeights; // the global weights at given time values - KeyTrackLinearDynamic mLocalWeights; // the local weights at given time values - KeyTrackLinearDynamic mPlayTimes; // normalized time values (current time in the node/motion) - uint32 mMotionID; // the ID of the Motion object used - uint32 mTrackIndex; // the track index - uint32 mCachedKey; // a cached key - AnimGraphNodeId mNodeId; // animgraph node Id - AnimGraphInstance* mAnimGraphInstance; // the anim graph instance this node was recorded from - AZ::Color mColor; // the node viz color - AZ::Color mTypeColor; // the node type color - uint32 mAnimGraphID; // the animgraph ID - AZ::TypeId mNodeType; // the node type (Uuid) - uint32 mCategoryID; // the category ID - bool mIsFinalized; // is this a finalized item? + AZStd::string m_name; + AZStd::string m_motionFileName; + float m_startTime; // time the motion starts being active + float m_endTime; // time the motion stops being active + KeyTrackLinearDynamic m_globalWeights; // the global weights at given time values + KeyTrackLinearDynamic m_localWeights; // the local weights at given time values + KeyTrackLinearDynamic m_playTimes; // normalized time values (current time in the node/motion) + uint32 m_motionId; // the ID of the Motion object used + size_t m_trackIndex; // the track index + size_t m_cachedKey; // a cached key + AnimGraphNodeId m_nodeId; // animgraph node Id + AnimGraphInstance* m_animGraphInstance; // the anim graph instance this node was recorded from + AZ::Color m_color; // the node viz color + AZ::Color m_typeColor; // the node type color + uint32 m_animGraphId; // the animgraph ID + AZ::TypeId m_nodeType; // the node type (Uuid) + uint32 m_categoryId; // the category ID + bool m_isFinalized; // is this a finalized item? NodeHistoryItem() { - mStartTime = 0.0f; - mEndTime = 0.0f; - mMotionID = MCORE_INVALIDINDEX32; - mTrackIndex = MCORE_INVALIDINDEX32; - mCachedKey = MCORE_INVALIDINDEX32; - mNodeId = AnimGraphNodeId(); - mAnimGraphInstance = nullptr; - mAnimGraphID = MCORE_INVALIDINDEX32; - mNodeType = AZ::TypeId::CreateNull(); - mCategoryID = MCORE_INVALIDINDEX32; - mColor.Set(1.0f, 0.0f, 0.0f, 1.0f); - mTypeColor.Set(1.0f, 0.0f, 0.0f, 1.0f); - mIsFinalized = false; + m_startTime = 0.0f; + m_endTime = 0.0f; + m_motionId = MCORE_INVALIDINDEX32; + m_trackIndex = InvalidIndex; + m_cachedKey = InvalidIndex; + m_nodeId = AnimGraphNodeId(); + m_animGraphInstance = nullptr; + m_animGraphId = MCORE_INVALIDINDEX32; + m_nodeType = AZ::TypeId::CreateNull(); + m_categoryId = MCORE_INVALIDINDEX32; + m_color.Set(1.0f, 0.0f, 0.0f, 1.0f); + m_typeColor.Set(1.0f, 0.0f, 0.0f, 1.0f); + m_isFinalized = false; } }; @@ -168,13 +168,13 @@ namespace EMotionFX struct EMFX_API ExtractedNodeHistoryItem { - NodeHistoryItem* mNodeHistoryItem; - uint32 mTrackIndex; - float mValue; - float mKeyTrackSampleTime; + NodeHistoryItem* m_nodeHistoryItem; + size_t m_trackIndex; + float m_value; + float m_keyTrackSampleTime; - friend bool operator< (const ExtractedNodeHistoryItem& a, const ExtractedNodeHistoryItem& b) { return (a.mValue > b.mValue); } - friend bool operator==(const ExtractedNodeHistoryItem& a, const ExtractedNodeHistoryItem& b) { return (a.mValue == b.mValue); } + friend bool operator< (const ExtractedNodeHistoryItem& a, const ExtractedNodeHistoryItem& b) { return (a.m_value > b.m_value); } + friend bool operator==(const ExtractedNodeHistoryItem& a, const ExtractedNodeHistoryItem& b) { return (a.m_value == b.m_value); } }; struct EMFX_API TransformTracks final @@ -183,66 +183,82 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); - KeyTrackLinearDynamic mPositions; - KeyTrackLinearDynamic mRotations; + KeyTrackLinearDynamic m_positions; + KeyTrackLinearDynamic m_rotations; #ifndef EMFX_SCALE_DISABLED - KeyTrackLinearDynamic mScales; + KeyTrackLinearDynamic m_scales; #endif }; struct EMFX_API AnimGraphAnimObjectInfo { - uint32 mFrameByteOffset; - AnimGraphObject* mObject; + size_t m_frameByteOffset; + AnimGraphObject* m_object; }; struct EMFX_API AnimGraphAnimFrame { - float mTimeValue; - uint32 mByteOffset; - uint32 mNumBytes; - MCore::Array mObjectInfos; - MCore::Array mParameterValues; - - AnimGraphAnimFrame() - { - mTimeValue = 0.0f; - mByteOffset = 0; - mNumBytes = 0; - } + float m_timeValue = 0.0f; + size_t m_byteOffset = 0; + size_t m_numBytes = 0; + AZStd::vector m_objectInfos{}; + AZStd::vector> m_parameterValues{}; + }; - ~AnimGraphAnimFrame() + struct EMFX_API AnimGraphInstanceData + { + AnimGraphInstance* m_animGraphInstance = nullptr; + size_t m_numFrames = 0; + size_t m_dataBufferSize = 0; + uint8* m_dataBuffer = nullptr; + AZStd::vector m_frames{}; + + AnimGraphInstanceData() = default; + AnimGraphInstanceData(const AnimGraphInstanceData&) = delete; + AnimGraphInstanceData(AnimGraphInstanceData&& rhs) { - const uint32 numParams = mParameterValues.GetLength(); - for (uint32 i = 0; i < numParams; ++i) + if (&rhs == this) { - delete mParameterValues[i]; + return; } + m_animGraphInstance = rhs.m_animGraphInstance; + m_numFrames = rhs.m_numFrames; + m_dataBufferSize = rhs.m_dataBufferSize; + m_dataBuffer = rhs.m_dataBuffer; + m_frames = AZStd::move(rhs.m_frames); + rhs.m_animGraphInstance = nullptr; + rhs.m_numFrames = 0; + rhs.m_dataBufferSize = 0; + rhs.m_dataBuffer = nullptr; + rhs.m_frames = {}; } - }; - - struct EMFX_API AnimGraphInstanceData - { - AnimGraphInstance* mAnimGraphInstance; - uint32 mNumFrames; - uint32 mDataBufferSize; - uint8* mDataBuffer; - MCore::Array mFrames; - AnimGraphInstanceData() + AnimGraphInstanceData& operator=(const AnimGraphInstanceData&) = delete; + AnimGraphInstanceData& operator=(AnimGraphInstanceData&& rhs) { - mAnimGraphInstance = nullptr; - mNumFrames = 0; - mDataBufferSize = 0; - mDataBuffer = nullptr; + if (&rhs == this) + { + return *this; + } + m_animGraphInstance = rhs.m_animGraphInstance; + m_numFrames = rhs.m_numFrames; + m_dataBufferSize = rhs.m_dataBufferSize; + m_dataBuffer = rhs.m_dataBuffer; + m_frames = AZStd::move(rhs.m_frames); + rhs.m_animGraphInstance = nullptr; + rhs.m_numFrames = 0; + rhs.m_dataBufferSize = 0; + rhs.m_dataBuffer = nullptr; + rhs.m_frames = {}; + return *this; } ~AnimGraphInstanceData() { - MCore::Free(mDataBuffer); + MCore::Free(m_dataBuffer); } }; @@ -251,45 +267,40 @@ namespace EMotionFX AZ_TYPE_INFO(EMotionFX::Recorder::ActorInstanceData, "{955A7EF9-5DC6-4548-BB72-10C974CF3886}"); AZ_CLASS_ALLOCATOR_DECL - ActorInstance* mActorInstance; // the actor instance this data is about - AnimGraphInstanceData* mAnimGraphData; // the anim graph instance data + ActorInstance* m_actorInstance; // the actor instance this data is about + AnimGraphInstanceData* m_animGraphData; // the anim graph instance data AZStd::vector m_transformTracks; // the transformation tracks, one for each node - MCore::Array mNodeHistoryItems; // node history items - MCore::Array mEventHistoryItems; // event history item - TransformTracks mActorLocalTransform; // the actor instance's local transformation - MCore::Array< KeyTrackLinearDynamic > mMorphTracks; // morph animation data + AZStd::vector m_nodeHistoryItems; // node history items + AZStd::vector m_eventHistoryItems; // event history item + TransformTracks m_actorLocalTransform; // the actor instance's local transformation + AZStd::vector< KeyTrackLinearDynamic > m_morphTracks; // morph animation data ActorInstanceData() { - mNodeHistoryItems.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); - mEventHistoryItems.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); - mMorphTracks.SetMemoryCategory(EMFX_MEMCATEGORY_RECORDER); - mNodeHistoryItems.Reserve(64); - mEventHistoryItems.Reserve(1024); - mMorphTracks.Reserve(32); - mAnimGraphData = nullptr; - mActorInstance = nullptr; + m_nodeHistoryItems.reserve(64); + m_eventHistoryItems.reserve(1024); + m_morphTracks.reserve(32); + m_animGraphData = nullptr; + m_actorInstance = nullptr; } ~ActorInstanceData() { // clear the node history items - const uint32 numMotionItems = mNodeHistoryItems.GetLength(); - for (uint32 i = 0; i < numMotionItems; ++i) + for (NodeHistoryItem* nodeHistoryItem : m_nodeHistoryItems) { - delete mNodeHistoryItems[i]; + delete nodeHistoryItem; } - mNodeHistoryItems.Clear(); + m_nodeHistoryItems.clear(); // clear the event history items - const uint32 numEventItems = mEventHistoryItems.GetLength(); - for (uint32 i = 0; i < numEventItems; ++i) + for (auto & eventHistoryItem : m_eventHistoryItems) { - delete mEventHistoryItems[i]; + delete eventHistoryItem; } - mEventHistoryItems.Clear(); + m_eventHistoryItems.clear(); - delete mAnimGraphData; + delete m_animGraphData; } static void Reflect(AZ::ReflectContext* context); @@ -302,7 +313,6 @@ namespace EMotionFX static Recorder* Create(); - void Reserve(uint32 numTransformKeys); bool HasRecording() const; void Clear(); void StartRecording(const RecordSettings& settings); @@ -324,28 +334,28 @@ namespace EMotionFX void SampleAndApplyAnimGraphs(float timeInSeconds) const; void SampleAndApplyMorphs(float timeInSeconds, ActorInstance* actorInstance) const; - MCORE_INLINE float GetRecordTime() const { return mRecordTime; } - MCORE_INLINE float GetCurrentPlayTime() const { return mCurrentPlayTime; } - MCORE_INLINE bool GetIsRecording() const { return mIsRecording; } - MCORE_INLINE bool GetIsInPlayMode() const { return mIsInPlayMode; } - MCORE_INLINE bool GetIsInAutoPlayMode() const { return mAutoPlay; } + MCORE_INLINE float GetRecordTime() const { return m_recordTime; } + MCORE_INLINE float GetCurrentPlayTime() const { return m_currentPlayTime; } + MCORE_INLINE bool GetIsRecording() const { return m_isRecording; } + MCORE_INLINE bool GetIsInPlayMode() const { return m_isInPlayMode; } + MCORE_INLINE bool GetIsInAutoPlayMode() const { return m_autoPlay; } bool GetHasRecorded(ActorInstance* actorInstance) const; - MCORE_INLINE const RecordSettings& GetRecordSettings() const { return mRecordSettings; } + MCORE_INLINE const RecordSettings& GetRecordSettings() const { return m_recordSettings; } const AZ::Uuid& GetSessionUuid() const { return m_sessionUuid; } const AZStd::vector& GetTimeDeltas() { return m_timeDeltas; } MCORE_INLINE size_t GetNumActorInstanceDatas() const { return m_actorInstanceDatas.size(); } - MCORE_INLINE ActorInstanceData& GetActorInstanceData(uint32 index) { return *m_actorInstanceDatas[index]; } - MCORE_INLINE const ActorInstanceData& GetActorInstanceData(uint32 index) const { return *m_actorInstanceDatas[index]; } - uint32 FindActorInstanceDataIndex(ActorInstance* actorInstance) const; + MCORE_INLINE ActorInstanceData& GetActorInstanceData(size_t index) { return *m_actorInstanceDatas[index]; } + MCORE_INLINE const ActorInstanceData& GetActorInstanceData(size_t index) const { return *m_actorInstanceDatas[index]; } + size_t FindActorInstanceDataIndex(ActorInstance* actorInstance) const; - uint32 CalcMaxNodeHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const; - uint32 CalcMaxNodeHistoryTrackIndex() const; - uint32 CalcMaxEventHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const; - AZ::u32 CalcMaxNumActiveMotions(const ActorInstanceData& actorInstanceData) const; - AZ::u32 CalcMaxNumActiveMotions() const; + size_t CalcMaxNodeHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const; + size_t CalcMaxNodeHistoryTrackIndex() const; + size_t CalcMaxEventHistoryTrackIndex(const ActorInstanceData& actorInstanceData) const; + size_t CalcMaxNumActiveMotions(const ActorInstanceData& actorInstanceData) const; + size_t CalcMaxNumActiveMotions() const; - void ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, MCore::Array* outItems, MCore::Array* outMap); + void ExtractNodeHistoryItems(const ActorInstanceData& actorInstanceData, float timeValue, bool sort, EValueType valueType, AZStd::vector* outItems, AZStd::vector* outMap) const; void StartPlayBack(); void StopPlayBack(); @@ -357,19 +367,19 @@ namespace EMotionFX void Unlock(); private: - RecordSettings mRecordSettings; + RecordSettings m_recordSettings; AZStd::vector m_actorInstanceDatas; AZStd::vector m_timeDeltas; // The value of the time deltas whenever a key is made - MCore::Array mObjects; - AZStd::vector mActiveNodes; /**< A temp array to store active animgraph nodes in. */ - MCore::Mutex mLock; + AZStd::vector m_objects; + AZStd::vector m_activeNodes; /**< A temp array to store active animgraph nodes in. */ + MCore::Mutex m_lock; AZ::TypeId m_sessionUuid; - float mRecordTime; - float mLastRecordTime; - float mCurrentPlayTime; - bool mIsRecording; - bool mIsInPlayMode; - bool mAutoPlay; + float m_recordTime; + float m_lastRecordTime; + float m_currentPlayTime; + bool m_isRecording; + bool m_isInPlayMode; + bool m_autoPlay; void PrepareForRecording(); void RecordMorphs(); @@ -390,12 +400,12 @@ namespace EMotionFX // /param numBytes bytes. Returns true if the buffer is big enough // after the operation, false otherwise. False indicates there's not // enough memory to accommodate the request - bool AssureAnimGraphBufferSize(AnimGraphInstanceData& animGraphInstanceData, uint32 numBytes); - NodeHistoryItem* FindNodeHistoryItem(const ActorInstanceData& actorInstanceData, AnimGraphNode* node, float recordTime) const; - uint32 FindFreeNodeHistoryItemTrack(const ActorInstanceData& actorInstanceData, NodeHistoryItem* item) const; + bool AssureAnimGraphBufferSize(AnimGraphInstanceData& animGraphInstanceData, size_t numBytes); + NodeHistoryItem* FindNodeHistoryItem(const ActorInstanceData& actorInstanceData, const AnimGraphNode* node, float recordTime) const; + size_t FindFreeNodeHistoryItemTrack(const ActorInstanceData& actorInstanceData, NodeHistoryItem* item) const; void FinalizeAllNodeHistoryItems(); EventHistoryItem* FindEventHistoryItem(const ActorInstanceData& actorInstanceData, const EventInfo& eventInfo, float recordTime); - uint32 FindFreeEventHistoryItemTrack(const ActorInstanceData& actorInstanceData, EventHistoryItem* item) const; - uint32 FindAnimGraphDataFrameNumber(float timeValue) const; + size_t FindFreeEventHistoryItemTrack(const ActorInstanceData& actorInstanceData, EventHistoryItem* item) const; + size_t FindAnimGraphDataFrameNumber(float timeValue) const; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp index afa3d8099d..1e3171d419 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.cpp @@ -26,8 +26,7 @@ namespace EMotionFX RepositioningLayerPass::RepositioningLayerPass(MotionLayerSystem* motionLayerSystem) : LayerPass(motionLayerSystem) { - mHierarchyPath.SetMemoryCategory(EMFX_MEMCATEGORY_MOTIONS_MOTIONSYSTEMS); - mLastReposNode = MCORE_INVALIDINDEX32; + m_lastReposNode = InvalidIndex; } @@ -54,7 +53,7 @@ namespace EMotionFX // The main function that processes the pass. void RepositioningLayerPass::Process() { - ActorInstance* actorInstance = mMotionSystem->GetActorInstance(); + ActorInstance* actorInstance = m_motionSystem->GetActorInstance(); if (!actorInstance->GetMotionExtractionEnabled()) { actorInstance->SetTrajectoryDeltaTransform(Transform::CreateIdentityWithZeroScale()); @@ -64,7 +63,7 @@ namespace EMotionFX // Get the motion extraction node and check if we are actually playing any motions. Actor* actor = actorInstance->GetActor(); Node* motionExtractNode = actor->GetMotionExtractionNode(); - if (!motionExtractNode || mMotionSystem->GetNumMotionInstances() == 0) + if (!motionExtractNode || m_motionSystem->GetNumMotionInstances() == 0) { actorInstance->SetTrajectoryDeltaTransform(Transform::CreateIdentityWithZeroScale()); return; @@ -78,10 +77,10 @@ namespace EMotionFX // Bottom up traversal of the layers. bool firstBlend = true; - const uint32 numMotionInstances = mMotionSystem->GetNumMotionInstances(); - for (uint32 i = numMotionInstances - 1; i != MCORE_INVALIDINDEX32; --i) + const size_t numMotionInstances = m_motionSystem->GetNumMotionInstances(); + for (size_t i = numMotionInstances - 1; i != InvalidIndex; --i) { - MotionInstance* motionInstance = mMotionSystem->GetMotionInstance(i); + MotionInstance* motionInstance = m_motionSystem->GetMotionInstance(i); if (!motionInstance->GetMotionExtractionEnabled()) { continue; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h index a704f83e21..333749141a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/RepositioningLayerPass.h @@ -11,7 +11,7 @@ // include required headers #include "EMotionFXConfig.h" #include "LayerPass.h" -#include +#include namespace EMotionFX @@ -59,8 +59,8 @@ namespace EMotionFX private: - MCore::Array mHierarchyPath; /**< The path of node indices to the repositioning node. */ - uint32 mLastReposNode; /**< The last repositioning node index that was used. When this changes, the hierarchy path has to be updated. */ + AZStd::vector m_hierarchyPath; /**< The path of node indices to the repositioning node. */ + size_t m_lastReposNode; /**< The last repositioning node index that was used. When this changes, the hierarchy path has to be updated. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp index 8c98bad5a4..8615ac623b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.cpp @@ -98,7 +98,7 @@ namespace EMotionFX } } - SimulatedJoint::SimulatedJoint(SimulatedObject* object, AZ::u32 skeletonJointIndex) + SimulatedJoint::SimulatedJoint(SimulatedObject* object, size_t skeletonJointIndex) : m_object(object) , m_jointIndex(skeletonJointIndex) { @@ -163,7 +163,7 @@ namespace EMotionFX { return nullptr; } - const AZ::u32 parentIndex = skeletonJoint->GetParentIndex(); + const size_t parentIndex = skeletonJoint->GetParentIndex(); return m_object->FindSimulatedJointBySkeletonJointIndex(parentIndex); } @@ -176,11 +176,11 @@ namespace EMotionFX { return nullptr; } - const AZ::u32 childCount = skeletonJoint->GetNumChildNodes(); + const size_t childCount = skeletonJoint->GetNumChildNodes(); size_t count = 0; - for (AZ::u32 i = 0; i < childCount; ++i) + for (size_t i = 0; i < childCount; ++i) { - const AZ::u32 skeletonChildJointIndex = skeletonJoint->GetChildIndex(i); + const size_t skeletonChildJointIndex = skeletonJoint->GetChildIndex(i); if (m_object->FindSimulatedJointBySkeletonJointIndex(skeletonChildJointIndex)) { if (count == childIndex) @@ -214,11 +214,11 @@ namespace EMotionFX { return 0; } - const AZ::u32 childCount = skeletonJoint->GetNumChildNodes(); + const size_t childCount = skeletonJoint->GetNumChildNodes(); size_t count = 0; - for (AZ::u32 i = 0; i < childCount; ++i) + for (size_t i = 0; i < childCount; ++i) { - const AZ::u32 childIndex = skeletonJoint->GetChildIndex(i); + const size_t childIndex = skeletonJoint->GetChildIndex(i); if (m_object->FindSimulatedJointBySkeletonJointIndex(childIndex)) { count++; @@ -239,7 +239,7 @@ namespace EMotionFX return sum; } - AZ::u32 SimulatedJoint::CalculateChildIndex() const + size_t SimulatedJoint::CalculateChildIndex() const { const Actor* actor = m_object->GetSimulatedObjectSetup()->GetActor(); const SimulatedJoint* parentJoint = FindParentSimulatedJoint(); @@ -250,11 +250,11 @@ namespace EMotionFX { return 0; } - const AZ::u32 numChildSkeletonJoints = parentSkeletonJoint->GetNumChildNodes(); - AZ::u32 childSimulatedJointIndex = 0; - for (AZ::u32 i = 0; i < numChildSkeletonJoints; ++i) + const size_t numChildSkeletonJoints = parentSkeletonJoint->GetNumChildNodes(); + size_t childSimulatedJointIndex = 0; + for (size_t i = 0; i < numChildSkeletonJoints; ++i) { - AZ::u32 childJointIndex = parentSkeletonJoint->GetChildIndex(i); + size_t childJointIndex = parentSkeletonJoint->GetChildIndex(i); SimulatedJoint* childSimulatedJoint = m_object->FindSimulatedJointBySkeletonJointIndex(childJointIndex); if (childSimulatedJoint) { @@ -271,8 +271,8 @@ namespace EMotionFX } // If the simuated joint doesn't have a parent joint, it should be a root joint. - AZ::u32 rootJointIndex = static_cast(m_object->GetSimulatedRootJointIndex(this)); - AZ_Error("EMotionFX", rootJointIndex != MCORE_INVALIDINDEX32, "This joint should be a root joint."); + size_t rootJointIndex = m_object->GetSimulatedRootJointIndex(this); + AZ_Error("EMotionFX", rootJointIndex != InvalidIndex, "This joint should be a root joint."); return rootJointIndex; } @@ -280,7 +280,7 @@ namespace EMotionFX { if (m_object) { - return m_object->GetSimulatedRootJointIndex(this) != MCORE_INVALIDINDEX32; + return m_object->GetSimulatedRootJointIndex(this) != InvalidIndex; } return false; @@ -320,7 +320,7 @@ namespace EMotionFX m_rootJoints.clear(); } - SimulatedJoint* SimulatedObject::FindSimulatedJointBySkeletonJointIndex(AZ::u32 skeletonJointIndex) const + SimulatedJoint* SimulatedObject::FindSimulatedJointBySkeletonJointIndex(size_t skeletonJointIndex) const { for (SimulatedJoint* joint : m_joints) { @@ -348,10 +348,10 @@ namespace EMotionFX const auto found = AZStd::find(m_rootJoints.begin(), m_rootJoints.end(), rootJoint); if (found != m_rootJoints.end()) { - return static_cast(AZStd::distance(m_rootJoints.begin(), found)); + return AZStd::distance(m_rootJoints.begin(), found); } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } void SimulatedObject::Reflect(AZ::ReflectContext* context) @@ -430,13 +430,13 @@ namespace EMotionFX BuildRootJointList(); } - SimulatedJoint* SimulatedObject::AddSimulatedJoint(AZ::u32 jointIndex) + SimulatedJoint* SimulatedObject::AddSimulatedJoint(size_t jointIndex) { AddSimulatedJoints({ jointIndex }); return FindSimulatedJointBySkeletonJointIndex(jointIndex); } - void SimulatedObject::AddSimulatedJoints(AZStd::vector jointIndexes) + void SimulatedObject::AddSimulatedJoints(AZStd::vector jointIndexes) { AZStd::sort(jointIndexes.begin(), jointIndexes.end()); @@ -445,10 +445,10 @@ namespace EMotionFX BuildRootJointList(); } - void SimulatedObject::AddSimulatedJointAndChildren(AZ::u32 jointIndex) + void SimulatedObject::AddSimulatedJointAndChildren(size_t jointIndex) { - AZStd::vector jointsToAdd; - AZStd::queue toVisit; + AZStd::vector jointsToAdd; + AZStd::queue toVisit; toVisit.emplace(jointIndex); const Skeleton* skeleton = m_simulatedObjectSetup->GetActor()->GetSkeleton(); @@ -456,7 +456,7 @@ namespace EMotionFX // Collect all the joint indices to add while (!toVisit.empty()) { - const AZ::u32 currentIndex = toVisit.front(); + const size_t currentIndex = toVisit.front(); toVisit.pop(); jointsToAdd.emplace_back(currentIndex); @@ -467,7 +467,7 @@ namespace EMotionFX const size_t childNodeCount = node->GetNumChildNodes(); for (size_t i = 0; i < childNodeCount; ++i) { - const AZ::u32 childNodeIndex = node->GetChildIndex(static_cast(i)); + const size_t childNodeIndex = node->GetChildIndex(i); toVisit.emplace(childNodeIndex); } } @@ -484,7 +484,7 @@ namespace EMotionFX BuildRootJointList(); } - void SimulatedObject::MergeAndMakeJoints(const AZStd::vector& jointsToAdd) + void SimulatedObject::MergeAndMakeJoints(const AZStd::vector& jointsToAdd) { AZStd::vector newJointList; @@ -537,7 +537,7 @@ namespace EMotionFX return AZStd::string::format("%zu joint%s selected", jointCounts, jointCounts == 1? "" : "s"); } - void SimulatedObject::RemoveSimulatedJoint(AZ::u32 jointIndex, bool removeChildren) + void SimulatedObject::RemoveSimulatedJoint(size_t jointIndex, bool removeChildren) { // If we order the joints storage so that the leaf node always comes late than its parent, we can do the remove in one iteration. bool removed = false; @@ -578,7 +578,7 @@ namespace EMotionFX size_t childNodeCount = node->GetNumChildNodes(); for (size_t i = 0; i < childNodeCount; ++i) { - const AZ::u32 childNodeIndex = node->GetChildIndex(static_cast(i)); + const size_t childNodeIndex = node->GetChildIndex(i); if (FindSimulatedJointBySkeletonJointIndex(childNodeIndex)) { RemoveSimulatedJoint(childNodeIndex, true); @@ -602,12 +602,12 @@ namespace EMotionFX currentParents.emplace(current); toCheck.erase(toCheck.find(joint)); - while (current && current->GetSkeletonJointIndex() != MCORE_INVALIDINDEX32 && !((seenJoints.find(current) != seenJoints.end()) || (toCheck.find(current) != toCheck.end()))) + while (current && current->GetSkeletonJointIndex() != InvalidIndex && !((seenJoints.find(current) != seenJoints.end()) || (toCheck.find(current) != toCheck.end()))) { current = current->FindParentSimulatedJoint(); } - if (!current || current->GetSkeletonJointIndex() == MCORE_INVALIDINDEX32) + if (!current || current->GetSkeletonJointIndex() == InvalidIndex) { // We reached the top of the model without seeing any other // model index (or parent thereof) in modelIndices. This is a diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.h b/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.h index 6d052172bc..57deef4cad 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SimulatedObjectSetup.h @@ -50,7 +50,7 @@ namespace EMotionFX }; SimulatedJoint() = default; - SimulatedJoint(SimulatedObject* object, AZ::u32 skeletonJointIndex); + SimulatedJoint(SimulatedObject* object, size_t skeletonJointIndex); ~SimulatedJoint() override = default; SimulatedJoint* FindParentSimulatedJoint() const; @@ -58,12 +58,12 @@ namespace EMotionFX AZ::Outcome CalculateSimulatedJointIndex() const; size_t CalculateNumChildSimulatedJoints() const; size_t CalculateNumChildSimulatedJointsRecursive() const; - AZ::u32 CalculateChildIndex() const; + size_t CalculateChildIndex() const; bool InitAfterLoading(SimulatedObject* object); void SetSimulatedObject(SimulatedObject* object) { m_object = object; } - void SetSkeletonJointIndex(AZ::u32 jointIndex) { m_jointIndex = jointIndex; } + void SetSkeletonJointIndex(size_t jointIndex) { m_jointIndex = jointIndex; } void SetConeAngleLimit(float degrees) { m_coneAngleLimit = degrees; } void SetMass(float mass) { m_mass = mass; } void SetCollisionRadius(float radius) @@ -81,7 +81,7 @@ namespace EMotionFX void SetGeometricAutoExclusion(bool enabled) { m_autoExcludeGeometric = enabled; } SimulatedObject* GetSimulatedObject() const { return m_object; } - AZ::u32 GetSkeletonJointIndex() const { return m_jointIndex; } + size_t GetSkeletonJointIndex() const { return m_jointIndex; } float GetConeAngleLimit() const { return m_coneAngleLimit; } float GetMass() const { return m_mass; } float GetCollisionRadius() const { return m_radius; } @@ -101,7 +101,7 @@ namespace EMotionFX AZ::Crc32 GetPinnedOptionVisibility() const; SimulatedObject* m_object = nullptr; /**< The simulated object we belong to. */ - AZ::u32 m_jointIndex = 0; /**< The joint index inside the skeleton of the actor. */ + size_t m_jointIndex = 0; /**< The joint index inside the skeleton of the actor. */ AZStd::string m_jointName; /**< The joint name in the actor skeleton. */ float m_coneAngleLimit = 60.0f; /**< The conic angular limit, in degrees. A value of 180 means there are no limits. */ float m_mass = 1.0f; /**< The mass of the joint. */ @@ -129,12 +129,12 @@ namespace EMotionFX void Clear(); - SimulatedJoint* FindSimulatedJointBySkeletonJointIndex(AZ::u32 skeletonJointIndex) const; + SimulatedJoint* FindSimulatedJointBySkeletonJointIndex(size_t skeletonJointIndex) const; bool ContainsSimulatedJoint(const SimulatedJoint* joint) const; - SimulatedJoint* AddSimulatedJoint(AZ::u32 jointIndex); - void AddSimulatedJoints(AZStd::vector jointIndexes); - void AddSimulatedJointAndChildren(AZ::u32 jointIndex); - void RemoveSimulatedJoint(AZ::u32 jointIndex, bool removeChildren = false); + SimulatedJoint* AddSimulatedJoint(size_t jointIndex); + void AddSimulatedJoints(AZStd::vector jointIndexes); + void AddSimulatedJointAndChildren(size_t jointIndex); + void RemoveSimulatedJoint(size_t jointIndex, bool removeChildren = false); size_t GetNumSimulatedJoints() const { return m_joints.size(); } SimulatedJoint* GetSimulatedRootJoint(size_t rootIndex) const; @@ -167,7 +167,7 @@ namespace EMotionFX void SetSimulatedObjectSetup(SimulatedObjectSetup* setup) { m_simulatedObjectSetup = setup; } void BuildRootJointList(); void SortJointList(); - void MergeAndMakeJoints(const AZStd::vector& jointsToAdd); + void MergeAndMakeJoints(const AZStd::vector& jointsToAdd); AZStd::string GetJointsTextOverride() const; AZStd::string GetColliderTag(int index) const; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp index a8c78ee823..f5ba7856ac 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.cpp @@ -45,13 +45,13 @@ namespace EMotionFX const ActorManager& actorManager = GetActorManager(); // reset stats - mNumUpdated.SetValue(0); - mNumVisible.SetValue(0); - mNumSampled.SetValue(0); + m_numUpdated.SetValue(0); + m_numVisible.SetValue(0); + m_numSampled.SetValue(0); // propagate root actor instance visibility to their attachments - const uint32 numRootActorInstances = GetActorManager().GetNumRootActorInstances(); - for (uint32 i = 0; i < numRootActorInstances; ++i) + const size_t numRootActorInstances = GetActorManager().GetNumRootActorInstances(); + for (size_t i = 0; i < numRootActorInstances; ++i) { ActorInstance* rootInstance = actorManager.GetRootActorInstance(i); if (rootInstance->GetIsEnabled() == false) @@ -62,17 +62,8 @@ namespace EMotionFX rootInstance->RecursiveSetIsVisible(rootInstance->GetIsVisible()); } - /* // make sure parents of attachments are updated as well - const uint32 numActorInstances = actorManager.GetNumActorInstances(); - for (uint32 i=0; iGetIsVisible()) - actorInstance->RecursiveSetIsVisibleTowardsRoot( true ); - }*/ - // process all root actor instances, and execute them and their attachments - for (uint32 i = 0; i < numRootActorInstances; ++i) + for (size_t i = 0; i < numRootActorInstances; ++i) { ActorInstance* rootActorInstance = actorManager.GetRootActorInstance(i); if (rootActorInstance->GetIsEnabled() == false) @@ -90,7 +81,7 @@ namespace EMotionFX { actorInstance->SetThreadIndex(0); - mNumUpdated.Increment(); + m_numUpdated.Increment(); const bool isVisible = actorInstance->GetIsVisible(); @@ -104,21 +95,21 @@ namespace EMotionFX if (isVisible) { - mNumSampled.Increment(); + m_numSampled.Increment(); } } if (isVisible) { - mNumVisible.Increment(); + m_numVisible.Increment(); } // update the transformations actorInstance->UpdateTransformations(timePassedInSeconds, isVisible, sampleMotions); // recursively process the attachments - const uint32 numAttachments = actorInstance->GetNumAttachments(); - for (uint32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = actorInstance->GetNumAttachments(); + for (size_t i = 0; i < numAttachments; ++i) { ActorInstance* attachment = actorInstance->GetAttachment(i)->GetAttachmentActorInstance(); if (attachment && attachment->GetIsEnabled()) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.h b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.h index 76b496e6d8..49f1725cc0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SingleThreadScheduler.h @@ -73,14 +73,14 @@ namespace EMotionFX * @param actorInstance The actor instance to insert. * @param startStep An offset in the schedule where to start trying to insert the actor instances. */ - void RecursiveInsertActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) override { MCORE_UNUSED(actorInstance); MCORE_UNUSED(startStep); } + void RecursiveInsertActorInstance(ActorInstance* actorInstance, size_t startStep = 0) override { MCORE_UNUSED(actorInstance); MCORE_UNUSED(startStep); } /** * Recursively remove an actor instance and its attachments from the schedule. * @param actorInstance The actor instance to remove. * @param startStep An offset in the schedule where to start trying to remove from. */ - void RecursiveRemoveActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) override { MCORE_UNUSED(actorInstance); MCORE_UNUSED(startStep); } + void RecursiveRemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) override { MCORE_UNUSED(actorInstance); MCORE_UNUSED(startStep); } /** * Remove a single actor instance from the schedule. This will not remove its attachments. @@ -88,7 +88,7 @@ namespace EMotionFX * @param startStep An offset in the schedule where to start trying to remove from. * @result Returns the offset in the schedule where the actor instance was removed. */ - uint32 RemoveActorInstance(ActorInstance* actorInstance, uint32 startStep = 0) override { MCORE_UNUSED(actorInstance); MCORE_UNUSED(startStep); return 0; } + size_t RemoveActorInstance(ActorInstance* actorInstance, size_t startStep = 0) override { MCORE_UNUSED(actorInstance); MCORE_UNUSED(startStep); return 0; } protected: /** diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp index e1c6ca88f7..24983c3a71 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.cpp @@ -22,8 +22,6 @@ namespace EMotionFX // constructor Skeleton::Skeleton() { - m_nodes.SetMemoryCategory(EMFX_MEMCATEGORY_SKELETON); - m_rootNodes.SetMemoryCategory(EMFX_MEMCATEGORY_SKELETON); } @@ -46,14 +44,13 @@ namespace EMotionFX { Skeleton* result = Skeleton::Create(); - const uint32 numNodes = m_nodes.GetLength(); - result->ReserveNodes(numNodes); + result->ReserveNodes(m_nodes.size()); result->m_rootNodes = m_rootNodes; // clone the nodes - for (uint32 i = 0; i < numNodes; ++i) + for (const Node* node : m_nodes) { - result->AddNode(m_nodes[i]->Clone(result)); + result->AddNode(node->Clone(result)); } result->m_bindPose = m_bindPose; @@ -63,22 +60,22 @@ namespace EMotionFX // reserve memory - void Skeleton::ReserveNodes(uint32 numNodes) + void Skeleton::ReserveNodes(size_t numNodes) { - m_nodes.Reserve(numNodes); + m_nodes.reserve(numNodes); } // add a node void Skeleton::AddNode(Node* node) { - m_nodes.Add(node); + m_nodes.emplace_back(node); m_nodesMap[node->GetNameString()] = node; } // remove a node - void Skeleton::RemoveNode(uint32 nodeIndex, bool delFromMem) + void Skeleton::RemoveNode(size_t nodeIndex, bool delFromMem) { m_nodesMap.erase(m_nodes[nodeIndex]->GetNameString()); if (delFromMem) @@ -86,7 +83,7 @@ namespace EMotionFX m_nodes[nodeIndex]->Destroy(); } - m_nodes.Remove(nodeIndex); + m_nodes.erase(AZStd::next(begin(m_nodes), nodeIndex)); } @@ -95,14 +92,13 @@ namespace EMotionFX { if (delFromMem) { - const uint32 numNodes = m_nodes.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + for (Node* node : m_nodes) { - m_nodes[i]->Destroy(); + node->Destroy(); } } - m_nodes.Clear(); + m_nodes.clear(); m_nodesMap.clear(); m_bindPose.Clear(); } @@ -134,38 +130,28 @@ namespace EMotionFX Node* Skeleton::FindNodeByNameNoCase(const char* name) const { // check the names for all nodes - const uint32 numNodes = m_nodes.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const auto foundNode = AZStd::find_if(begin(m_nodes), end(m_nodes), [name](const Node* node) { - if (AzFramework::StringFunc::Equal(m_nodes[i]->GetNameString().c_str(), name, false /* no case */)) - { - return m_nodes[i]; - } - } - - return nullptr; + return AzFramework::StringFunc::Equal(node->GetNameString(), name, false /* no case */); + }); + return foundNode != end(m_nodes) ? *foundNode : nullptr; } // search for a node on ID - Node* Skeleton::FindNodeByID(uint32 id) const + Node* Skeleton::FindNodeByID(size_t id) const { // check the ID's for all nodes - const uint32 numNodes = m_nodes.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const auto foundNode = AZStd::find_if(begin(m_nodes), end(m_nodes), [id](const Node* node) { - if (m_nodes[i]->GetID() == id) - { - return m_nodes[i]; - } - } - - return nullptr; + return node->GetID() == id; + }); + return foundNode != end(m_nodes) ? *foundNode : nullptr; } // set a given node - void Skeleton::SetNode(uint32 index, Node* node) + void Skeleton::SetNode(size_t index, Node* node) { if (m_nodes[index]) { @@ -178,11 +164,11 @@ namespace EMotionFX // set the number of nodes - void Skeleton::SetNumNodes(uint32 numNodes) + void Skeleton::SetNumNodes(size_t numNodes) { - uint32 oldLength = m_nodes.GetLength(); - m_nodes.Resize(numNodes); - for (uint32 i = oldLength; i < numNodes; ++i) + size_t oldLength = m_nodes.size(); + m_nodes.resize(numNodes); + for (size_t i = oldLength; i < numNodes; ++i) { m_nodes[i] = nullptr; } @@ -191,10 +177,10 @@ namespace EMotionFX // update the node indices - void Skeleton::UpdateNodeIndexValues(uint32 startNode) + void Skeleton::UpdateNodeIndexValues(size_t startNode) { - const uint32 numNodes = m_nodes.GetLength(); - for (uint32 i = startNode; i < numNodes; ++i) + const size_t numNodes = m_nodes.size(); + for (size_t i = startNode; i < numNodes; ++i) { m_nodes[i]->SetNodeIndex(i); } @@ -202,38 +188,38 @@ namespace EMotionFX // reserve memory for the root nodes array - void Skeleton::ReserveRootNodes(uint32 numNodes) + void Skeleton::ReserveRootNodes(size_t numNodes) { - m_rootNodes.Reserve(numNodes); + m_rootNodes.reserve(numNodes); } // add a root node - void Skeleton::AddRootNode(uint32 nodeIndex) + void Skeleton::AddRootNode(size_t nodeIndex) { - m_rootNodes.Add(nodeIndex); + m_rootNodes.emplace_back(nodeIndex); } // remove a given root node - void Skeleton::RemoveRootNode(uint32 nr) + void Skeleton::RemoveRootNode(size_t nr) { - m_rootNodes.Remove(nr); + m_rootNodes.erase(AZStd::next(begin(m_rootNodes), nr)); } // remove all root nodes void Skeleton::RemoveAllRootNodes() { - m_rootNodes.Clear(); + m_rootNodes.clear(); } // log all node names void Skeleton::LogNodes() { - const uint32 numNodes = m_nodes.GetLength(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_nodes.size(); + for (size_t i = 0; i < numNodes; ++i) { MCore::LogInfo("%d = '%s'", i, m_nodes[i]->GetName()); } @@ -241,10 +227,10 @@ namespace EMotionFX // calculate the hierarchy depth for a given node - uint32 Skeleton::CalcHierarchyDepthForNode(uint32 nodeIndex) const + size_t Skeleton::CalcHierarchyDepthForNode(size_t nodeIndex) const { - uint32 result = 0; - Node* curNode = m_nodes[nodeIndex]; + size_t result = 0; + const Node* curNode = m_nodes[nodeIndex]; while (curNode->GetParentNode()) { result++; @@ -255,18 +241,18 @@ namespace EMotionFX } - Node* Skeleton::FindNodeAndIndexByName(const AZStd::string& name, AZ::u32& outIndex) const + Node* Skeleton::FindNodeAndIndexByName(const AZStd::string& name, size_t& outIndex) const { if (name.empty()) { - outIndex = MCORE_INVALIDINDEX32; + outIndex = InvalidIndex; return nullptr; } Node* joint = FindNodeByNameNoCase(name.c_str()); if (!joint) { - outIndex = MCORE_INVALIDINDEX32; + outIndex = InvalidIndex; return nullptr; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h index 1b9c09749c..01d3e9dee8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Skeleton.h @@ -12,7 +12,7 @@ #include "EMotionFXConfig.h" #include "BaseObject.h" #include "Pose.h" -#include +#include namespace EMotionFX @@ -32,12 +32,12 @@ namespace EMotionFX Skeleton* Clone(); - MCORE_INLINE uint32 GetNumNodes() const { return m_nodes.GetLength(); } - MCORE_INLINE Node* GetNode(uint32 index) const { return m_nodes[index]; } + MCORE_INLINE size_t GetNumNodes() const { return m_nodes.size(); } + MCORE_INLINE Node* GetNode(size_t index) const { return m_nodes[index]; } - void ReserveNodes(uint32 numNodes); + void ReserveNodes(size_t numNodes); void AddNode(Node* node); - void RemoveNode(uint32 nodeIndex, bool delFromMem = true); + void RemoveNode(size_t nodeIndex, bool delFromMem = true); void RemoveAllNodes(bool delFromMem = true); MCORE_INLINE const Pose* GetBindPose() const { return &m_bindPose; } @@ -57,7 +57,7 @@ namespace EMotionFX * @param outIndex This will contain the resulting index, or MCORE_INVALIDINDEX32 in case not found. * @result This returns a pointer to the joint or nullptr when not found. In case of a nullptr, the outIndex will be set to MCORE_INVALIDINDEX32 as well. */ - Node* FindNodeAndIndexByName(const AZStd::string& name, AZ::u32& outIndex) const; + Node* FindNodeAndIndexByName(const AZStd::string& name, size_t& outIndex) const; /** * Search for a node by name (non case sensitive), returns nullptr when no node can be found. @@ -75,21 +75,21 @@ namespace EMotionFX * @param id The ID to search for. * @return A pointer to the node, or nullptr when no node with the given ID found. */ - Node* FindNodeByID(uint32 id) const; + Node* FindNodeByID(size_t id) const; /** * Set the value of a given node. * @param index The node number, which must be in range of [0..GetNumNodes()-1]. * @param node The node value to set at this index. */ - void SetNode(uint32 index, Node* node); + void SetNode(size_t index, Node* node); /** * Set the number of nodes. * This resizes the array of pointers to nodes, but doesn't actually create the nodes. * @param numNodes The number of nodes to allocate space for. */ - void SetNumNodes(uint32 numNodes); + void SetNumNodes(size_t numNodes); /** * Update all the node index values that are returned by the Node::GetNodeIndex() method. @@ -97,41 +97,41 @@ namespace EMotionFX * the nodes have to be updated. As node number 5 could become node number 4 in the example case. * @param startNode The node number to start updating from. */ - void UpdateNodeIndexValues(uint32 startNode = 0); + void UpdateNodeIndexValues(size_t startNode = 0); /** * Get the number of root nodes in the actor. A root node is a node without any parent. * @result The number of root nodes inside the actor. */ - MCORE_INLINE uint32 GetNumRootNodes() const { return m_rootNodes.GetLength(); } + MCORE_INLINE size_t GetNumRootNodes() const { return m_rootNodes.size(); } /** * Get the node number/index of a given root node. * @param nr The root node number, which must be in range of [0..GetNumRootNodes()-1]. * @result The node index of the given root node. */ - MCORE_INLINE uint32 GetRootNodeIndex(uint32 nr) const { return m_rootNodes[nr]; } + MCORE_INLINE size_t GetRootNodeIndex(size_t nr) const { return m_rootNodes[nr]; } /** * Pre-allocate space for the root nodes array. * This does not alter the value returned by GetNumRootNodes() though. * @param numNodes The absolute number of nodes to pre-allocate space for. */ - void ReserveRootNodes(uint32 numNodes); + void ReserveRootNodes(size_t numNodes); /** * Add a root node to the actor. * This doesn't modify the node itself, but it will add the node to the list of root nodes. * @param nodeIndex The node number/index to add and mark as root node inside the actor. */ - void AddRootNode(uint32 nodeIndex); + void AddRootNode(size_t nodeIndex); /** * Remove a given root node from the list of root nodes stored inside the actor. * This doesn't really remove the node itself, but it just unregisters it as root node inside the actor. * @param nr The root node to remove, which must be in range of [0..GetNumRootNodes()-1]. */ - void RemoveRootNode(uint32 nr); + void RemoveRootNode(size_t nr); /** * Removes all root nodes from the actor. @@ -141,12 +141,12 @@ namespace EMotionFX void RemoveAllRootNodes(); void LogNodes(); - uint32 CalcHierarchyDepthForNode(uint32 nodeIndex) const; + size_t CalcHierarchyDepthForNode(size_t nodeIndex) const; private: - MCore::Array m_nodes; /**< The nodes, including root nodes. */ + AZStd::vector m_nodes; /**< The nodes, including root nodes. */ mutable AZStd::unordered_map m_nodesMap; - MCore::Array m_rootNodes; /**< The root nodes only. */ + AZStd::vector m_rootNodes; /**< The root nodes only. */ Pose m_bindPose; /**< The bind pose. */ Skeleton(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp index 3ccfa85ca8..5a3c01802e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.cpp @@ -23,8 +23,8 @@ namespace EMotionFX { if (allocData) { - mData.SetNumPreCachedElements(2); // assume 2 weights per vertex - mData.Resize(numAttributes); + m_data.SetNumPreCachedElements(2); // assume 2 weights per vertex + m_data.Resize(numAttributes); } } @@ -65,25 +65,25 @@ namespace EMotionFX // add a given influence (using a bone and a weight) void SkinningInfoVertexAttributeLayer::AddInfluence(size_t attributeNr, size_t nodeNr, float weight, size_t boneNr) { - mData.Add(attributeNr, SkinInfluence(static_cast(nodeNr), weight, static_cast(boneNr))); + m_data.Add(attributeNr, SkinInfluence(static_cast(nodeNr), weight, static_cast(boneNr))); } // remove the given skin influence void SkinningInfoVertexAttributeLayer::RemoveInfluence(size_t attributeNr, size_t influenceNr) { - mData.Remove(attributeNr, influenceNr); + m_data.Remove(attributeNr, influenceNr); } // the uv vertex attribute layer VertexAttributeLayer* SkinningInfoVertexAttributeLayer::Clone() { - SkinningInfoVertexAttributeLayer* clone = aznew SkinningInfoVertexAttributeLayer(mNumAttributes); + SkinningInfoVertexAttributeLayer* clone = aznew SkinningInfoVertexAttributeLayer(m_numAttributes); // copy over the data - clone->mData = mData; - clone->mNameID = mNameID; + clone->m_data = m_data; + clone->m_nameId = m_nameId; // return the clone return clone; @@ -93,14 +93,14 @@ namespace EMotionFX // swap attribute data data void SkinningInfoVertexAttributeLayer::SwapAttributes(uint32 attribA, uint32 attribB) { - mData.Swap(attribA, attribB); + m_data.Swap(attribA, attribB); } // remove attributes void SkinningInfoVertexAttributeLayer::RemoveAttributes(uint32 startAttributeNr, uint32 endAttributeNr) { - mData.RemoveRows(startAttributeNr, endAttributeNr, true); + m_data.RemoveRows(startAttributeNr, endAttributeNr, true); } @@ -108,7 +108,7 @@ namespace EMotionFX void SkinningInfoVertexAttributeLayer::RemapInfluences(size_t oldNodeNr, size_t newNodeNr) { // get the number of vertices/attributes - const size_t numAttributes = mData.GetNumRows(); + const size_t numAttributes = m_data.GetNumRows(); for (size_t a = 0; a < numAttributes; ++a) { // iterate through all influences and compare them with the old node @@ -129,7 +129,7 @@ namespace EMotionFX void SkinningInfoVertexAttributeLayer::RemoveAllInfluencesForNode(size_t nodeNr) { // get the number of vertices/attributes - const size_t numAttributes = mData.GetNumRows(); + const size_t numAttributes = m_data.GetNumRows(); for (size_t a = 0; a < numAttributes; ++a) { // iterate through all influences and compare them with the given node @@ -159,7 +159,7 @@ namespace EMotionFX } // get the number of vertices/attributes - const size_t numAttributes = mData.GetNumRows(); + const size_t numAttributes = m_data.GetNumRows(); for (size_t a = 0; a < numAttributes; ++a) { // get the number of influences for the current vertex @@ -183,7 +183,7 @@ namespace EMotionFX // optimize the memory usage void SkinningInfoVertexAttributeLayer::OptimizeMemoryUsage() { - mData.Shrink(); + m_data.Shrink(); } @@ -191,7 +191,7 @@ namespace EMotionFX void SkinningInfoVertexAttributeLayer::OptimizeInfluences(float tolerance, size_t maxWeights) { // get the number of vertices/attributes - const size_t numAttributes = mData.GetNumRows(); + const size_t numAttributes = m_data.GetNumRows(); for (size_t a = 0; a < numAttributes; ++a) { if (GetNumInfluences(a) == 0) @@ -257,7 +257,7 @@ namespace EMotionFX const float remaining = 1.0f - totalWeight; for (size_t i = 0; i < numInfluences; ++i) { - const float percentage = mData.GetElement(a, i).GetWeight() / totalWeight; + const float percentage = m_data.GetElement(a, i).GetWeight() / totalWeight; GetInfluence(a, i)->SetWeight(GetInfluence(a, i)->GetWeight() + percentage * remaining); } } @@ -308,20 +308,20 @@ namespace EMotionFX GetInfluence(attributeNr, 0)->SetWeight(1.0f); } - AZStd::set SkinningInfoVertexAttributeLayer::CalcLocalJointIndices(AZ::u32 numOrgVertices) + AZStd::set SkinningInfoVertexAttributeLayer::CalcLocalJointIndices(AZ::u32 numOrgVertices) { - AZStd::set result; + AZStd::set result; for (AZ::u32 i = 0; i < numOrgVertices; i++) { // now we have located the skinning information for this vertex, we can see if our bones array // already contains the bone it uses by traversing all influences for this vertex, and checking // if the bone of that influence already is in the array with used bones - const uint32 numInfluences = static_cast(GetNumInfluences(i)); - for (uint32 a = 0; a < numInfluences; ++a) + const size_t numInfluences = GetNumInfluences(i); + for (size_t a = 0; a < numInfluences; ++a) { EMotionFX::SkinInfluence* influence = GetInfluence(i, a); - const AZ::u32 jointNr = influence->GetNodeNr(); + const uint16 jointNr = influence->GetNodeNr(); result.emplace(jointNr); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h index c2a77ba13b..1dfec9926f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SkinningInfoVertexAttributeLayer.h @@ -28,9 +28,9 @@ namespace EMotionFX * Default constructor. */ SkinInfluence() - : mWeight(0.0f) - , mBoneNr(0) - , mNodeNr(0) {} + : m_weight(0.0f) + , m_boneNr(0) + , m_nodeNr(0) {} /** * Constructor. @@ -39,52 +39,52 @@ namespace EMotionFX * @param boneNr The bone number, used as optimization inside the softskin deformer. */ SkinInfluence(uint16 nodeNr, float weight, uint16 boneNr = 0) - : mWeight(weight) - , mBoneNr(boneNr) - , mNodeNr(nodeNr) {} + : m_weight(weight) + , m_boneNr(boneNr) + , m_nodeNr(nodeNr) {} /** * Get the weight of this influence. * @result The weight, which should be in range of [0..1]. */ - MCORE_INLINE float GetWeight() const { return mWeight; } + MCORE_INLINE float GetWeight() const { return m_weight; } /** * Adjust the weight value. * @param weight The weight value, which must be in range of [0..1]. */ - void SetWeight(float weight) { mWeight = weight; } + void SetWeight(float weight) { m_weight = weight; } /** * Get the node number that points inside an actor. * So this number is an index you can pass to Actor::GetNode(...) to get the actual node that acts as bone. * @result The node number, which points inside the nodes array of the actor. */ - MCORE_INLINE uint16 GetNodeNr() const { return mNodeNr; } + MCORE_INLINE uint16 GetNodeNr() const { return m_nodeNr; } /** * Set the node number that points inside an actor. * So this number is an index you can pass to Actor::GetNode(...) to get the actual node that acts as bone. * @param nodeNr The node number, which points inside the nodes array of the actor. */ - void SetNodeNr(uint16 nodeNr) { mNodeNr = nodeNr; } + void SetNodeNr(uint16 nodeNr) { m_nodeNr = nodeNr; } /** * Set the bone number, used for precalculations. * @param boneNr The bone number. */ - void SetBoneNr(uint16 boneNr) { mBoneNr = boneNr; } + void SetBoneNr(uint16 boneNr) { m_boneNr = boneNr; } /** * Get the bone number, which is used for precalculations. * @result The bone number. */ - MCORE_INLINE uint16 GetBoneNr() const { return mBoneNr; } + MCORE_INLINE uint16 GetBoneNr() const { return m_boneNr; } private: - float mWeight; /**< The weight value, between 0 and 1. */ - uint16 mBoneNr; /**< A bone number, which points in an array of bone info structs used for precalculating the skinning matrices. */ - uint16 mNodeNr; /**< The node number inside the actor which acts as a bone. */ + float m_weight; /**< The weight value, between 0 and 1. */ + uint16 m_boneNr; /**< A bone number, which points in an array of bone info structs used for precalculating the skinning matrices. */ + uint16 m_nodeNr; /**< The node number inside the actor which acts as a bone. */ }; @@ -149,7 +149,7 @@ namespace EMotionFX * @param attributeNr The attribute/vertex number. * @result The number of influences. */ - MCORE_INLINE size_t GetNumInfluences(size_t attributeNr) { return mData.GetNumElements(attributeNr); } + MCORE_INLINE size_t GetNumInfluences(size_t attributeNr) { return m_data.GetNumElements(attributeNr); } /** * Get a given influence. @@ -157,21 +157,21 @@ namespace EMotionFX * @param influenceNr The influence number, which must be in range of [0..GetNumInfluences()] * @result The given influence. */ - MCORE_INLINE SkinInfluence* GetInfluence(size_t attributeNr, size_t influenceNr) { return &mData.GetElement(attributeNr, influenceNr); } + MCORE_INLINE SkinInfluence* GetInfluence(size_t attributeNr, size_t influenceNr) { return &m_data.GetElement(attributeNr, influenceNr); } /** * Get direct access to the jagged 2D array that contains the skinning influence data. * This can be used in the importers for fast loading and not having to add influence per influence. * @result A reference to the 2D array containing all the skinning influences. */ - MCORE_INLINE MCore::Array2D& GetArray2D() { return mData; } + MCORE_INLINE MCore::Array2D& GetArray2D() { return m_data; } /** * Collect all unique joint indices used by the skin. * @param numOrgVertices The number of original vertices in the mesh. * @result Vector of unique joint indices used by the skinning info layer. */ - AZStd::set CalcLocalJointIndices(AZ::u32 numOrgVertices); + AZStd::set CalcLocalJointIndices(AZ::u32 numOrgVertices); /** * Clone the vertex attribute layer. @@ -251,7 +251,7 @@ namespace EMotionFX void CollapseInfluences(size_t attributeNr); private: - MCore::Array2D mData; /**< The stored influence data. The Array2D template allows a different number of skinning influences per vertex. */ + MCore::Array2D m_data; /**< The stored influence data. The Array2D template allows a different number of skinning influences per vertex. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp index c1a8bbd65c..9b9c808eac 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.cpp @@ -34,8 +34,8 @@ namespace EMotionFX // destructor SoftSkinDeformer::~SoftSkinDeformer() { - mNodeNumbers.clear(); - mBoneMatrices.clear(); + m_nodeNumbers.clear(); + m_boneMatrices.clear(); } @@ -61,14 +61,14 @@ namespace EMotionFX // clone this class - MeshDeformer* SoftSkinDeformer::Clone(Mesh* mesh) + MeshDeformer* SoftSkinDeformer::Clone(Mesh* mesh) const { // create the new cloned deformer SoftSkinDeformer* result = aznew SoftSkinDeformer(mesh); // copy the bone info (for precalc/optimization reasons) - result->mNodeNumbers = mNodeNumbers; - result->mBoneMatrices = mBoneMatrices; + result->m_nodeNumbers = m_nodeNumbers; + result->m_boneMatrices = m_boneMatrices; // return the result return result; @@ -86,24 +86,24 @@ namespace EMotionFX const AZ::Matrix3x4* skinningMatrices = transformData->GetSkinningMatrices(); // precalc the skinning matrices - const size_t numBones = mBoneMatrices.size(); + const size_t numBones = m_boneMatrices.size(); for (size_t i = 0; i < numBones; i++) { - const uint32 nodeIndex = mNodeNumbers[i]; - mBoneMatrices[i] = skinningMatrices[nodeIndex]; + const size_t nodeIndex = m_nodeNumbers[i]; + m_boneMatrices[i] = skinningMatrices[nodeIndex]; } // find the skinning layer - SkinningInfoVertexAttributeLayer* layer = (SkinningInfoVertexAttributeLayer*)mMesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); + SkinningInfoVertexAttributeLayer* layer = (SkinningInfoVertexAttributeLayer*)m_mesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); AZ_Assert(layer, "Cannot find skinning info"); // Perform the skinning. - AZ::Vector3* __restrict positions = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_POSITIONS)); - AZ::Vector3* __restrict normals = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_NORMALS)); - AZ::Vector4* __restrict tangents = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_TANGENTS)); - AZ::Vector3* __restrict bitangents = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_BITANGENTS)); - AZ::u32* __restrict orgVerts = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS)); - SkinVertexRange(0, mMesh->GetNumVertices(), positions, normals, tangents, bitangents, orgVerts, layer); + AZ::Vector3* __restrict positions = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_POSITIONS)); + AZ::Vector3* __restrict normals = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_NORMALS)); + AZ::Vector4* __restrict tangents = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_TANGENTS)); + AZ::Vector3* __restrict bitangents = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_BITANGENTS)); + AZ::u32* __restrict orgVerts = static_cast(m_mesh->FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS)); + SkinVertexRange(0, m_mesh->GetNumVertices(), positions, normals, tangents, bitangents, orgVerts, layer); } @@ -134,7 +134,7 @@ namespace EMotionFX for (size_t i = 0; i < numInfluences; ++i) { const SkinInfluence* influence = layer->GetInfluence(orgVertex, i); - MCore::Skin(mBoneMatrices[influence->GetBoneNr()], &vtxPos, &normal, &tangent, &bitangent, &newPos, &newNormal, &newTangent, &newBitangent, influence->GetWeight()); + MCore::Skin(m_boneMatrices[influence->GetBoneNr()], &vtxPos, &normal, &tangent, &bitangent, &newPos, &newNormal, &newTangent, &newBitangent, influence->GetWeight()); } newTangent.SetW(tangents[v].GetW()); @@ -163,7 +163,7 @@ namespace EMotionFX for (size_t i = 0; i < numInfluences; ++i) { const SkinInfluence* influence = layer->GetInfluence(orgVertex, i); - MCore::Skin(mBoneMatrices[influence->GetBoneNr()], &vtxPos, &normal, &tangent, &newPos, &newNormal, &newTangent, influence->GetWeight()); + MCore::Skin(m_boneMatrices[influence->GetBoneNr()], &vtxPos, &normal, &tangent, &newPos, &newNormal, &newTangent, influence->GetWeight()); } newTangent.SetW(tangents[v].GetW()); @@ -190,7 +190,7 @@ namespace EMotionFX for (size_t i = 0; i < numInfluences; ++i) { const SkinInfluence* influence = layer->GetInfluence(orgVertex, i); - MCore::Skin(mBoneMatrices[influence->GetBoneNr()], &vtxPos, &normal, &newPos, &newNormal, influence->GetWeight()); + MCore::Skin(m_boneMatrices[influence->GetBoneNr()], &vtxPos, &normal, &newPos, &newNormal, influence->GetWeight()); } // output the skinned values @@ -202,31 +202,28 @@ namespace EMotionFX // initialize the mesh deformer - void SoftSkinDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) + void SoftSkinDeformer::Reinitialize(Actor* actor, Node* node, size_t lodLevel) { MCORE_UNUSED(actor); MCORE_UNUSED(node); MCORE_UNUSED(lodLevel); // clear the bone information array - mBoneMatrices.clear(); - mNodeNumbers.clear(); + m_boneMatrices.clear(); + m_nodeNumbers.clear(); // if there is no mesh - if (mMesh == nullptr) + if (m_mesh == nullptr) { return; } // get the attribute number - SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)mMesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); + SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)m_mesh->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(); + const uint32 numOrgVerts = m_mesh->GetNumOrgVertices(); for (uint32 i = 0; i < numOrgVerts; i++) { // now we have located the skinning information for this vertex, we can see if our bones array @@ -240,23 +237,20 @@ namespace EMotionFX SkinInfluence* influence = skinningLayer->GetInfluence(i, a); // get the bone index in the array - uint32 boneIndex = FindLocalBoneIndex(influence->GetNodeNr()); + size_t boneIndex = FindLocalBoneIndex(influence->GetNodeNr()); // if the bone is not found in our array - if (boneIndex == MCORE_INVALIDINDEX32) + if (boneIndex == InvalidIndex) { // add the bone to the array of bones in this deformer - mNodeNumbers.emplace_back(influence->GetNodeNr()); - mBoneMatrices.emplace_back(mat); - boneIndex = static_cast(mBoneMatrices.size()) - 1; + m_nodeNumbers.emplace_back(influence->GetNodeNr()); + m_boneMatrices.emplace_back(mat); + boneIndex = m_boneMatrices.size() - 1; } // set the bone number in the influence influence->SetBoneNr(static_cast(boneIndex)); - //MCore::LogInfo("influence %d/%d = %s with weight %f [nodeIndex=%d] [boneIndex=%d]", a+1, numInfluences, actor->GetNode(influence->GetNodeNr())->GetName(), influence->GetWeight(), influence->GetNodeNr(), boneIndex); } } - // get rid of all items in the used bones array - // mBones.Shrink(); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h index 497f38f764..ce157baf49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinDeformer.h @@ -71,14 +71,14 @@ namespace EMotionFX * @param node The node where the mesh belongs to during this initialization. * @param lodLevel The LOD level of the mesh the mesh deformer works on. */ - void Reinitialize(Actor* actor, Node* node, uint32 lodLevel) override; + void Reinitialize(Actor* actor, Node* node, size_t lodLevel) override; /** * Creates an exact clone (copy) of this deformer, and returns a pointer to it. * @param mesh The mesh to apply the deformer on. * @result A pointer to the newly created clone of this deformer. */ - MeshDeformer* Clone(Mesh* mesh) override; + MeshDeformer* Clone(Mesh* mesh) const override; /** * Returns the unique type ID of the deformer. @@ -100,26 +100,26 @@ 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 size_t GetNumLocalBones() const { return mNodeNumbers.size(); } + MCORE_INLINE size_t GetNumLocalBones() const { return m_nodeNumbers.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 mNodeNumbers[index]; } + MCORE_INLINE size_t GetLocalBone(size_t index) const { return m_nodeNumbers[index]; } /** * 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) { mNodeNumbers.reserve(numBones); mBoneMatrices.reserve(numBones); } + MCORE_INLINE void ReserveLocalBones(size_t numBones) { m_nodeNumbers.reserve(numBones); m_boneMatrices.reserve(numBones); } protected: - AZStd::vector mBoneMatrices; - AZStd::vector mNodeNumbers; + AZStd::vector m_boneMatrices; + AZStd::vector m_nodeNumbers; /** * Default constructor. @@ -135,20 +135,12 @@ namespace EMotionFX /** * Find the entry number that uses a specified node number. * @param nodeIndex The node number to search for. - * @result The index inside the mBones member array, which uses the given node. + * @result The index inside the m_bones member array, which uses the given node. */ - MCORE_INLINE uint32 FindLocalBoneIndex(uint32 nodeIndex) const + MCORE_INLINE size_t FindLocalBoneIndex(size_t nodeIndex) const { - const size_t numBones = mNodeNumbers.size(); - for (size_t i = 0; i < numBones; ++i) - { - if (mNodeNumbers[i] == nodeIndex) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + const auto foundBoneIndex = AZStd::find(begin(m_nodeNumbers), end(m_nodeNumbers), nodeIndex); + return foundBoneIndex != end(m_nodeNumbers) ? AZStd::distance(begin(m_nodeNumbers), foundBoneIndex) : InvalidIndex; } void SkinVertexRange(uint32 startVertex, uint32 endVertex, AZ::Vector3* positions, AZ::Vector3* normals, AZ::Vector4* tangents, AZ::Vector3* bitangents, uint32* orgVerts, SkinningInfoVertexAttributeLayer* layer); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinManager.h b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinManager.h index 946fd531d2..3682bc1abb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SoftSkinManager.h @@ -51,8 +51,6 @@ namespace EMotionFX SoftSkinDeformer* CreateDeformer(Mesh* mesh); private: - //bool mDetectedSSE; /**< Does the cpu support SSE instructions? */ - /** * The constructor. * When constructed, the class checks if SSE is available on the hardware. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp index adaea2e6c2..83cbc41a36 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.cpp @@ -47,7 +47,7 @@ namespace EMotionFX m_collisionObjects.reserve(3); } - void SpringSolver::CreateCollider(AZ::u32 skeletonJointIndex, const AzPhysics::ShapeColliderPair& shapePair) + void SpringSolver::CreateCollider(size_t skeletonJointIndex, const AzPhysics::ShapeColliderPair& shapePair) { const Physics::ShapeConfiguration* shapeConfig = shapePair.second.get(); if (!shapeConfig) @@ -77,7 +77,7 @@ namespace EMotionFX { if (exclusionColliderTag == colliderTag) { - const AZ::u32 colliderIndex = aznumeric_caster(m_collisionObjects.size() - 1); + const size_t colliderIndex = m_collisionObjects.size() - 1; particle.m_colliderExclusions.emplace_back(colliderIndex); break; } @@ -105,7 +105,7 @@ namespace EMotionFX if (shapePair.first->m_tag == colliderTag) { // Make sure we can find the joint in the skeleton. - AZ::u32 skeletonJointIndex; + size_t skeletonJointIndex; if (!actor->GetSkeleton()->FindNodeAndIndexByName(nodeConfig.m_name, skeletonJointIndex)) { AZ_Warning("EMotionFX", false, "Cannot find joint '%s' to attach the collider to. Skipping this collider inside simulation '%s'.", nodeConfig.m_name.c_str(), m_name.c_str()); @@ -176,7 +176,7 @@ namespace EMotionFX } } - void SpringSolver::CheckAndExcludeCollider(AZ::u32 colliderIndex, const SimulatedJoint* joint) + void SpringSolver::CheckAndExcludeCollider(size_t colliderIndex, const SimulatedJoint* joint) { const size_t particleIndex = FindParticle(joint->GetSkeletonJointIndex()); AZ_Assert(particleIndex != InvalidIndex, "Expected particle to be found for this joint."); @@ -208,7 +208,7 @@ namespace EMotionFX const size_t numColliders = m_collisionObjects.size(); for (size_t colliderIndex = 0; colliderIndex < numColliders; ++colliderIndex) { - CheckAndExcludeCollider(static_cast(colliderIndex), joint); + CheckAndExcludeCollider(colliderIndex, joint); } break; } @@ -221,7 +221,7 @@ namespace EMotionFX { if (m_collisionObjects[colliderIndex].m_jointIndex == joint->GetSkeletonJointIndex()) { - CheckAndExcludeCollider(static_cast(colliderIndex), joint); + CheckAndExcludeCollider(colliderIndex, joint); } } break; @@ -235,13 +235,13 @@ namespace EMotionFX { if (joint->GetSkeletonJointIndex() == m_collisionObjects[colliderIndex].m_jointIndex) { - CheckAndExcludeCollider(static_cast(colliderIndex), joint); + CheckAndExcludeCollider(colliderIndex, joint); } const SimulatedJoint* parentJoint = joint->FindParentSimulatedJoint(); if (parentJoint && parentJoint->GetSkeletonJointIndex() == m_collisionObjects[colliderIndex].m_jointIndex) { - CheckAndExcludeCollider(static_cast(colliderIndex), joint); + CheckAndExcludeCollider(colliderIndex, joint); } const size_t numChildJoints = joint->CalculateNumChildSimulatedJoints(); @@ -250,7 +250,7 @@ namespace EMotionFX const SimulatedJoint* childJoint = joint->FindChildSimulatedJoint(childIndex); if (m_collisionObjects[colliderIndex].m_jointIndex == childJoint->GetSkeletonJointIndex()) { - CheckAndExcludeCollider(static_cast(colliderIndex), joint); + CheckAndExcludeCollider(colliderIndex, joint); } } } @@ -271,8 +271,8 @@ namespace EMotionFX SpringSolver::Particle* SpringSolver::AddJoint(const SimulatedJoint* joint) { AZ_Assert(joint, "Expected the joint be a valid pointer."); - const AZ::u32 jointIndex = joint->GetSkeletonJointIndex(); - if (jointIndex == InvalidIndex32) + const size_t jointIndex = joint->GetSkeletonJointIndex(); + if (jointIndex == InvalidIndex) { return nullptr; } @@ -409,10 +409,10 @@ namespace EMotionFX // Initialize all rest lengths. for (Spring& spring : m_springs) { - const AZ::u32 jointIndexA = m_particles[spring.m_particleA].m_joint->GetSkeletonJointIndex(); - const AZ::u32 jointIndexB = m_particles[spring.m_particleB].m_joint->GetSkeletonJointIndex(); + const size_t jointIndexA = m_particles[spring.m_particleA].m_joint->GetSkeletonJointIndex(); + const size_t jointIndexB = m_particles[spring.m_particleB].m_joint->GetSkeletonJointIndex(); const Pose* bindPose = m_actorInstance->GetTransformData()->GetBindPose(); - const float restLength = (bindPose->GetModelSpaceTransform(jointIndexB).mPosition - bindPose->GetModelSpaceTransform(jointIndexA).mPosition).GetLength(); + const float restLength = (bindPose->GetModelSpaceTransform(jointIndexB).m_position - bindPose->GetModelSpaceTransform(jointIndexA).m_position).GetLength(); if (restLength > AZ::Constants::FloatEpsilon) { spring.m_restLength = restLength; @@ -472,7 +472,7 @@ namespace EMotionFX const float radius = particle.m_joint->GetCollisionRadius() * scaleFactor; if (radius > 0.0f) { - const AZ::Quaternion& jointRotation = pose.GetWorldSpaceTransform(particle.m_joint->GetSkeletonJointIndex()).mRotation; + const AZ::Quaternion& jointRotation = pose.GetWorldSpaceTransform(particle.m_joint->GetSkeletonJointIndex()).m_rotation; drawData->DrawWireframeSphere(particle.m_pos, radius, AZ::Color(0.3f, 0.3f, 0.3f, 1.0f), jointRotation, 12, 12); } } @@ -485,7 +485,7 @@ namespace EMotionFX { if (collider.GetType() == CollisionObject::CollisionType::Sphere) { - const AZ::Quaternion& jointRotation = pose.GetWorldSpaceTransform(collider.m_jointIndex).mRotation; + const AZ::Quaternion& jointRotation = pose.GetWorldSpaceTransform(collider.m_jointIndex).m_rotation; drawData->DrawWireframeSphere(collider.m_globalStart, collider.m_scaledRadius, color * 0.65f, jointRotation, 16, 16); } else if (collider.GetType() == CollisionObject::CollisionType::Capsule) @@ -526,7 +526,7 @@ namespace EMotionFX return m_gravity; } - size_t SpringSolver::FindParticle(AZ::u32 jointIndex) const + size_t SpringSolver::FindParticle(size_t jointIndex) const { const size_t numParticles = m_particles.size(); for (size_t i = 0; i < numParticles; ++i) @@ -562,16 +562,16 @@ namespace EMotionFX AZ_Assert(joint->GetMass() > AZ::Constants::FloatEpsilon, "Expected mass to be larger than zero."); Particle particle; particle.m_joint = joint; - particle.m_pos = m_actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(joint->GetSkeletonJointIndex()).mPosition; + particle.m_pos = m_actorInstance->GetTransformData()->GetBindPose()->GetModelSpaceTransform(joint->GetSkeletonJointIndex()).m_position; particle.m_oldPos = particle.m_pos; - particle.m_parentParticleIndex = static_cast(m_parentParticle); + particle.m_parentParticleIndex = m_parentParticle; m_particles.emplace_back(particle); return m_particles.size() - 1; } - bool SpringSolver::AddSupportSpring(AZ::u32 nodeA, AZ::u32 nodeB, float restLength) + bool SpringSolver::AddSupportSpring(size_t nodeA, size_t nodeB, float restLength) { - if (nodeA == InvalidIndex32 || nodeB == InvalidIndex32) + if (nodeA == InvalidIndex || nodeB == InvalidIndex) { return false; } @@ -586,8 +586,8 @@ namespace EMotionFX if (restLength < 0.0f) { const Pose* pose = m_actorInstance->GetTransformData()->GetCurrentPose(); - const AZ::Vector3 posA = pose->GetWorldSpaceTransform(nodeA).mPosition; - const AZ::Vector3 posB = pose->GetWorldSpaceTransform(nodeB).mPosition; + const AZ::Vector3 posA = pose->GetWorldSpaceTransform(nodeA).m_position; + const AZ::Vector3 posB = pose->GetWorldSpaceTransform(nodeB).m_position; restLength = (posB - posA).GetLength(); } @@ -608,7 +608,7 @@ namespace EMotionFX return AddSupportSpring(nodeA->GetNodeIndex(), nodeB->GetNodeIndex(), restLength); } - bool SpringSolver::RemoveJoint(AZ::u32 jointIndex) + bool SpringSolver::RemoveJoint(size_t jointIndex) { const size_t particleIndex = FindParticle(jointIndex); if (particleIndex == InvalidIndex) @@ -646,7 +646,7 @@ namespace EMotionFX return RemoveJoint(node->GetNodeIndex()); } - bool SpringSolver::RemoveSupportSpring(AZ::u32 jointIndexA, AZ::u32 jointIndexB) + bool SpringSolver::RemoveSupportSpring(size_t jointIndexA, size_t jointIndexB) { const size_t particleA = FindParticle(jointIndexA); if (particleA == InvalidIndex) @@ -695,7 +695,7 @@ namespace EMotionFX float SpringSolver::GetScaleFactor() const { #ifndef EMFX_SCALE_DISABLED - float scaleFactor = m_actorInstance->GetWorldSpaceTransform().mScale.GetX(); + float scaleFactor = m_actorInstance->GetWorldSpaceTransform().m_scale.GetX(); if (AZ::IsClose(scaleFactor, 0.0f, AZ::Constants::FloatEpsilon)) { return AZ::Constants::FloatEpsilon; @@ -725,7 +725,7 @@ namespace EMotionFX if (stiffnessFactor > 0.0f) { const Transform jointWorldTransform = pose.GetWorldSpaceTransform(joint->GetSkeletonJointIndex()); - const AZ::Vector3 force = (jointWorldTransform.mPosition - particle.m_pos) + particle.m_externalForce; + const AZ::Vector3 force = (jointWorldTransform.m_position - particle.m_pos) + particle.m_externalForce; particle.m_force += force * stiffnessFactor; } @@ -816,30 +816,30 @@ namespace EMotionFX } else if (pinnedA && pinnedB) { - particleA.m_pos = worldTransformA.mPosition; - particleB.m_pos = worldTransformB.mPosition; + particleA.m_pos = worldTransformA.m_position; + particleB.m_pos = worldTransformB.m_position; } else if (pinnedB) { - particleB.m_pos = worldTransformB.mPosition; + particleB.m_pos = worldTransformB.m_position; particleA.m_pos += delta * diff; } else // Only particleA is pinned. { - particleA.m_pos = worldTransformA.mPosition; + particleA.m_pos = worldTransformA.m_position; particleB.m_pos -= delta * diff; } // Apply cone limit when needed. if (particleB.m_joint->GetConeAngleLimit() < 180.0f - 0.001f) { - if (particleB.m_parentParticleIndex != InvalidIndex32) + if (particleB.m_parentParticleIndex != InvalidIndex) { particleB.m_limitDir = particleB.m_pos - m_particles[particleB.m_parentParticleIndex].m_pos; } else { - particleB.m_limitDir = worldTransformA.mPosition - worldTransformB.mPosition; + particleB.m_limitDir = worldTransformA.m_position - worldTransformB.m_position; } PerformConeLimit(particleA, particleB, particleB.m_limitDir); } @@ -886,7 +886,7 @@ namespace EMotionFX const SimulatedJoint* joint = particle.m_joint; if (joint->IsPinned()) { - particle.m_pos = pose.GetWorldSpaceTransform(joint->GetSkeletonJointIndex()).mPosition; + particle.m_pos = pose.GetWorldSpaceTransform(joint->GetSkeletonJointIndex()).m_position; particle.m_oldPos = particle.m_pos; particle.m_force = AZ::Vector3::CreateZero(); } @@ -954,15 +954,15 @@ namespace EMotionFX const Particle& particleB = m_particles[spring.m_particleB]; Transform modelTransformB = pose.GetModelSpaceTransform(particleB.m_joint->GetSkeletonJointIndex()); const Transform& modelTransformA = pose.GetModelSpaceTransform(particleA.m_joint->GetSkeletonJointIndex()); - const AZ::Vector3 oldDir = (modelTransformA.mPosition - modelTransformB.mPosition).GetNormalizedSafe(); + const AZ::Vector3 oldDir = (modelTransformA.m_position - modelTransformB.m_position).GetNormalizedSafe(); const AZ::Vector3 newDir = m_actorInstance->GetWorldSpaceTransformInversed().TransformVector(particleA.m_pos - particleB.m_pos).GetNormalizedSafe(); - modelTransformB.mRotation = AZ::Quaternion::CreateShortestArc(oldDir, newDir).GetNormalized() * modelTransformB.mRotation; - modelTransformB.mRotation.Normalize(); + modelTransformB.m_rotation = AZ::Quaternion::CreateShortestArc(oldDir, newDir).GetNormalized() * modelTransformB.m_rotation; + modelTransformB.m_rotation.Normalize(); if (spring.m_allowStretch) { - modelTransformB.mPosition = particleB.m_pos; + modelTransformB.m_position = particleB.m_pos; } pose.SetModelSpaceTransform(particleB.m_joint->GetSkeletonJointIndex(), modelTransformB); @@ -1008,7 +1008,7 @@ namespace EMotionFX { for (CollisionObject& colObject : m_collisionObjects) { - if (colObject.m_jointIndex != InvalidIndex32) + if (colObject.m_jointIndex != InvalidIndex) { const Transform jointWorldTransform = pose.GetWorldSpaceTransform(colObject.m_jointIndex); colObject.m_globalStart = jointWorldTransform.TransformPoint(colObject.m_start); @@ -1028,7 +1028,7 @@ namespace EMotionFX { for (CollisionObject& colObject : m_collisionObjects) { - if (colObject.m_jointIndex != InvalidIndex32) + if (colObject.m_jointIndex != InvalidIndex) { const Transform& jointTransform = pose.GetModelSpaceTransform(colObject.m_jointIndex); colObject.m_globalStart = jointTransform.TransformPoint(colObject.m_start); @@ -1072,7 +1072,7 @@ namespace EMotionFX for (size_t colliderIndex = 0; colliderIndex < numColliders; ++colliderIndex) { // Skip colliders in the exclusion list. - if (AZStd::find(particle.m_colliderExclusions.begin(), particle.m_colliderExclusions.end(), static_cast(colliderIndex)) != particle.m_colliderExclusions.end()) + if (AZStd::find(particle.m_colliderExclusions.begin(), particle.m_colliderExclusions.end(), colliderIndex) != particle.m_colliderExclusions.end()) { continue; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.h b/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.h index 6d4b2e8128..ce77d1c655 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SpringSolver.h @@ -54,8 +54,8 @@ namespace EMotionFX AZ::Vector3 m_force = AZ::Vector3::CreateZero(); /**< The internal force, which contains the gravity and other pulling and pushing forces. */ AZ::Vector3 m_externalForce = AZ::Vector3::CreateZero(); /**< A user defined external force, which is added on top of the internal force. Can be used to simulate wind etc. */ AZ::Vector3 m_limitDir = AZ::Vector3::CreateZero(); /**< The joint limit direction vector, used for the cone angle limit. This is the center direction of the cone. */ - AZStd::vector m_colliderExclusions; /**< Index values inside the collider array. Colliders listed in this list should be ignored durin collision detection. */ - AZ::u32 m_parentParticleIndex = ~0U; /**< The parent particle index. */ + AZStd::vector m_colliderExclusions; /**< Index values inside the collider array. Colliders listed in this list should be ignored durin collision detection. */ + size_t m_parentParticleIndex = InvalidIndex; /**< The parent particle index. */ }; class EMFX_API CollisionObject @@ -76,7 +76,7 @@ namespace EMotionFX private: CollisionType m_type = CollisionType::Sphere; /**< The collision primitive type (a sphere, or capsule, etc). */ - AZ::u32 m_jointIndex = ~0U; /**< The joint index to attach to, or ~0 for non-attached. */ + size_t m_jointIndex = InvalidIndex; /**< The joint index to attach to, or ~0 for non-attached. */ AZ::Vector3 m_globalStart = AZ::Vector3::CreateZero(); /**< The world space start position, or the world space center in case of a sphere. */ AZ::Vector3 m_globalEnd = AZ::Vector3::CreateZero(); /**< The world space end position. This is ignored in case of a sphere. */ AZ::Vector3 m_start = AZ::Vector3::CreateZero(); /**< The start of the primitive. In case of a sphere the center, in case of a capsule the start of the capsule. */ @@ -108,7 +108,7 @@ namespace EMotionFX AZ_INLINE Particle& GetParticle(size_t index) { return m_particles[index]; } AZ_INLINE size_t GetNumParticles() const { return m_particles.size(); } - AZ_INLINE Spring& GetSpring(AZ::u32 index) { return m_springs[index]; } + AZ_INLINE Spring& GetSpring(size_t index) { return m_springs[index]; } AZ_INLINE size_t GetNumSprings() const { return m_springs.size(); } void SetParentParticle(size_t parentParticleIndex) { m_parentParticle = parentParticleIndex; } @@ -119,12 +119,12 @@ namespace EMotionFX size_t GetNumIterations() const; Particle* AddJoint(const SimulatedJoint* joint); - bool AddSupportSpring(AZ::u32 nodeA, AZ::u32 nodeB, float restLength = -1.0f); + bool AddSupportSpring(size_t nodeA, size_t nodeB, float restLength = -1.0f); bool AddSupportSpring(AZStd::string_view nodeNameA, AZStd::string_view nodeNameB, float restLength = -1.0f); - bool RemoveJoint(AZ::u32 jointIndex); + bool RemoveJoint(size_t jointIndex); bool RemoveJoint(AZStd::string_view nodeName); - bool RemoveSupportSpring(AZ::u32 jointIndexA, AZ::u32 jointIndexB); + bool RemoveSupportSpring(size_t jointIndexA, size_t jointIndexB); bool RemoveSupportSpring(AZStd::string_view nodeNameA, AZStd::string_view nodeNameB); void SetStiffnessFactor(float factor) { m_stiffnessFactor = factor; } @@ -135,19 +135,19 @@ namespace EMotionFX float GetGravityFactor() const { return m_gravityFactor; } float GetDampingFactor() const { return m_dampingFactor; } - size_t FindParticle(AZ::u32 jointIndex) const; + size_t FindParticle(size_t jointIndex) const; Particle* FindParticle(AZStd::string_view nodeName); AZ_INLINE void RemoveCollisionObject(size_t index) { m_collisionObjects.erase(m_collisionObjects.begin() + index); } AZ_INLINE void RemoveAllCollisionObjects() { m_collisionObjects.clear(); } - AZ_INLINE CollisionObject& GetCollisionObject(AZ::u32 index) { return m_collisionObjects[index]; } + AZ_INLINE CollisionObject& GetCollisionObject(size_t index) { return m_collisionObjects[index]; } AZ_INLINE size_t GetNumCollisionObjects() const { return m_collisionObjects.size(); } AZ_INLINE bool GetCollisionEnabled() const { return m_collisionDetection; } AZ_INLINE void SetCollisionEnabled(bool enabled) { m_collisionDetection = enabled; } private: void InitColliders(const InitSettings& initSettings); - void CreateCollider(AZ::u32 skeletonJointIndex, const AzPhysics::ShapeColliderPair& shapePair); + void CreateCollider(size_t skeletonJointIndex, const AzPhysics::ShapeColliderPair& shapePair); void InitColliderFromColliderSetupShape(CollisionObject& collider); void InitCollidersFromColliderSetupShapes(); bool RecursiveAddJoint(const SimulatedJoint* joint, size_t parentParticleIndex); @@ -166,7 +166,7 @@ namespace EMotionFX bool PerformCollision(AZ::Vector3& inOutPos, float jointRadius, const Particle& particle); void PerformConeLimit(Particle& particleA, Particle& particleB, const AZ::Vector3& inputDir); bool CheckIsJointInsideCollider(const CollisionObject& colObject, const Particle& particle) const; - void CheckAndExcludeCollider(AZ::u32 colliderIndex, const SimulatedJoint* joint); + void CheckAndExcludeCollider(size_t colliderIndex, const SimulatedJoint* joint); void UpdateFixedParticles(const Pose& pose); void Stabilize(const Pose& inputPose, Pose& pose, size_t numFrames=5); void InitAutoColliderExclusion(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp index 8147116048..ab89b0f4b2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.cpp @@ -20,15 +20,15 @@ namespace EMotionFX StandardMaterialLayer::StandardMaterialLayer() : BaseObject() { - mLayerTypeID = LAYERTYPE_UNKNOWN; - mFileNameID = MCORE_INVALIDINDEX32; - mBlendMode = LAYERBLENDMODE_NONE; - mAmount = 1.0f; - mUOffset = 0.0f; - mVOffset = 0.0f; - mUTiling = 1.0f; - mVTiling = 1.0f; - mRotationRadians = 0.0f; + m_layerTypeId = LAYERTYPE_UNKNOWN; + m_fileNameId = MCORE_INVALIDINDEX32; + m_blendMode = LAYERBLENDMODE_NONE; + m_amount = 1.0f; + m_uOffset = 0.0f; + m_vOffset = 0.0f; + m_uTiling = 1.0f; + m_vTiling = 1.0f; + m_rotationRadians = 0.0f; } @@ -36,17 +36,17 @@ namespace EMotionFX StandardMaterialLayer::StandardMaterialLayer(uint32 layerType, const char* fileName, float amount) : BaseObject() { - mLayerTypeID = layerType; - mAmount = amount; - mUOffset = 0.0f; - mVOffset = 0.0f; - mUTiling = 1.0f; - mVTiling = 1.0f; - mRotationRadians = 0.0f; - mBlendMode = LAYERBLENDMODE_NONE; + m_layerTypeId = layerType; + m_amount = amount; + m_uOffset = 0.0f; + m_vOffset = 0.0f; + m_uTiling = 1.0f; + m_vTiling = 1.0f; + m_rotationRadians = 0.0f; + m_blendMode = LAYERBLENDMODE_NONE; // calculate the ID - mFileNameID = MCore::GetStringIdPool().GenerateIdForString(fileName); + m_fileNameId = MCore::GetStringIdPool().GenerateIdForString(fileName); } @@ -73,22 +73,22 @@ namespace EMotionFX // init from another layer void StandardMaterialLayer::InitFrom(StandardMaterialLayer* layer) { - mLayerTypeID = layer->mLayerTypeID; - mFileNameID = layer->mFileNameID; - mBlendMode = layer->mBlendMode; - mAmount = layer->mAmount; - mUOffset = layer->mUOffset; - mVOffset = layer->mVOffset; - mUTiling = layer->mUTiling; - mVTiling = layer->mVTiling; - mRotationRadians = layer->mRotationRadians; + m_layerTypeId = layer->m_layerTypeId; + m_fileNameId = layer->m_fileNameId; + m_blendMode = layer->m_blendMode; + m_amount = layer->m_amount; + m_uOffset = layer->m_uOffset; + m_vOffset = layer->m_vOffset; + m_uTiling = layer->m_uTiling; + m_vTiling = layer->m_vTiling; + m_rotationRadians = layer->m_rotationRadians; } // return the layer type string const char* StandardMaterialLayer::GetTypeString() const { - switch (mLayerTypeID) + switch (m_layerTypeId) { case LAYERTYPE_UNKNOWN: { @@ -163,7 +163,7 @@ namespace EMotionFX // return the blend mode string const char* StandardMaterialLayer::GetBlendModeString() const { - switch (mBlendMode) + switch (m_blendMode) { case LAYERBLENDMODE_NONE: { @@ -225,116 +225,116 @@ namespace EMotionFX float StandardMaterialLayer::GetUOffset() const { - return mUOffset; + return m_uOffset; } float StandardMaterialLayer::GetVOffset() const { - return mVOffset; + return m_vOffset; } float StandardMaterialLayer::GetUTiling() const { - return mUTiling; + return m_uTiling; } float StandardMaterialLayer::GetVTiling() const { - return mVTiling; + return m_vTiling; } float StandardMaterialLayer::GetRotationRadians() const { - return mRotationRadians; + return m_rotationRadians; } void StandardMaterialLayer::SetUOffset(float uOffset) { - mUOffset = uOffset; + m_uOffset = uOffset; } void StandardMaterialLayer::SetVOffset(float vOffset) { - mVOffset = vOffset; + m_vOffset = vOffset; } void StandardMaterialLayer::SetUTiling(float uTiling) { - mUTiling = uTiling; + m_uTiling = uTiling; } void StandardMaterialLayer::SetVTiling(float vTiling) { - mVTiling = vTiling; + m_vTiling = vTiling; } void StandardMaterialLayer::SetRotationRadians(float rotationRadians) { - mRotationRadians = rotationRadians; + m_rotationRadians = rotationRadians; } const char* StandardMaterialLayer::GetFileName() const { - return MCore::GetStringIdPool().GetName(mFileNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_fileNameId).c_str(); } const AZStd::string& StandardMaterialLayer::GetFileNameString() const { - return MCore::GetStringIdPool().GetName(mFileNameID); + return MCore::GetStringIdPool().GetName(m_fileNameId); } void StandardMaterialLayer::SetFileName(const char* fileName) { // calculate the new ID - mFileNameID = MCore::GetStringIdPool().GenerateIdForString(fileName); + m_fileNameId = MCore::GetStringIdPool().GenerateIdForString(fileName); } void StandardMaterialLayer::SetAmount(float amount) { - mAmount = amount; + m_amount = amount; } float StandardMaterialLayer::GetAmount() const { - return mAmount; + return m_amount; } uint32 StandardMaterialLayer::GetType() const { - return mLayerTypeID; + return m_layerTypeId; } void StandardMaterialLayer::SetType(uint32 typeID) { - mLayerTypeID = typeID; + m_layerTypeId = typeID; } void StandardMaterialLayer::SetBlendMode(unsigned char layerBlendMode) { - mBlendMode = layerBlendMode; + m_blendMode = layerBlendMode; } unsigned char StandardMaterialLayer::GetBlendMode() const { - return mBlendMode; + return m_blendMode; } @@ -346,18 +346,16 @@ namespace EMotionFX StandardMaterial::StandardMaterial(const char* name) : Material(name) { - mAmbient = MCore::RGBAColor(0.2f, 0.2f, 0.2f); - mDiffuse = MCore::RGBAColor(1.0f, 0.0f, 0.0f); - mSpecular = MCore::RGBAColor(1.0f, 1.0f, 1.0f); - mEmissive = MCore::RGBAColor(1.0f, 0.0f, 0.0f); - mShine = 100.0f; - mShineStrength = 1.0f; - mOpacity = 1.0f; - mIOR = 1.5f; - mDoubleSided = true; - mWireFrame = false; - - mLayers.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MATERIALS); + m_ambient = MCore::RGBAColor(0.2f, 0.2f, 0.2f); + m_diffuse = MCore::RGBAColor(1.0f, 0.0f, 0.0f); + m_specular = MCore::RGBAColor(1.0f, 1.0f, 1.0f); + m_emissive = MCore::RGBAColor(1.0f, 0.0f, 0.0f); + m_shine = 100.0f; + m_shineStrength = 1.0f; + m_opacity = 1.0f; + m_ior = 1.5f; + m_doubleSided = true; + m_wireFrame = false; } @@ -386,24 +384,24 @@ namespace EMotionFX StandardMaterial* standardMaterial = static_cast(clone); // copy the attributes - standardMaterial->mAmbient = mAmbient; - standardMaterial->mDiffuse = mDiffuse; - standardMaterial->mSpecular = mSpecular; - standardMaterial->mEmissive = mEmissive; - standardMaterial->mShine = mShine; - standardMaterial->mShineStrength = mShineStrength; - standardMaterial->mOpacity = mOpacity; - standardMaterial->mIOR = mIOR; - standardMaterial->mDoubleSided = mDoubleSided; - standardMaterial->mWireFrame = mWireFrame; + standardMaterial->m_ambient = m_ambient; + standardMaterial->m_diffuse = m_diffuse; + standardMaterial->m_specular = m_specular; + standardMaterial->m_emissive = m_emissive; + standardMaterial->m_shine = m_shine; + standardMaterial->m_shineStrength = m_shineStrength; + standardMaterial->m_opacity = m_opacity; + standardMaterial->m_ior = m_ior; + standardMaterial->m_doubleSided = m_doubleSided; + standardMaterial->m_wireFrame = m_wireFrame; // copy the layers - const uint32 numLayers = mLayers.GetLength(); - standardMaterial->mLayers.Resize(numLayers); - for (uint32 i = 0; i < numLayers; ++i) + const size_t numLayers = m_layers.size(); + standardMaterial->m_layers.resize(numLayers); + for (size_t i = 0; i < numLayers; ++i) { - standardMaterial->mLayers[i] = StandardMaterialLayer::Create(); - standardMaterial->mLayers[i]->InitFrom(mLayers[i]); + standardMaterial->m_layers[i] = StandardMaterialLayer::Create(); + standardMaterial->m_layers[i]->InitFrom(m_layers[i]); } // return the result @@ -420,193 +418,190 @@ namespace EMotionFX { layer->Destroy(); } - mLayers.RemoveByValue(layer); + if (const auto it = AZStd::find(begin(m_layers), end(m_layers), layer); it != end(m_layers)) + { + m_layers.erase(it); + } } } void StandardMaterial::SetAmbient(const MCore::RGBAColor& ambient) { - mAmbient = ambient; + m_ambient = ambient; } void StandardMaterial::SetDiffuse(const MCore::RGBAColor& diffuse) { - mDiffuse = diffuse; + m_diffuse = diffuse; } void StandardMaterial::SetSpecular(const MCore::RGBAColor& specular) { - mSpecular = specular; + m_specular = specular; } void StandardMaterial::SetEmissive(const MCore::RGBAColor& emissive) { - mEmissive = emissive; + m_emissive = emissive; } void StandardMaterial::SetShine(float shine) { - mShine = shine; + m_shine = shine; } void StandardMaterial::SetShineStrength(float shineStrength) { - mShineStrength = shineStrength; + m_shineStrength = shineStrength; } void StandardMaterial::SetOpacity(float opacity) { - mOpacity = opacity; + m_opacity = opacity; } void StandardMaterial::SetIOR(float ior) { - mIOR = ior; + m_ior = ior; } void StandardMaterial::SetDoubleSided(bool doubleSided) { - mDoubleSided = doubleSided; + m_doubleSided = doubleSided; } void StandardMaterial::SetWireFrame(bool wireFrame) { - mWireFrame = wireFrame; + m_wireFrame = wireFrame; } const MCore::RGBAColor& StandardMaterial::GetAmbient() const { - return mAmbient; + return m_ambient; } const MCore::RGBAColor& StandardMaterial::GetDiffuse() const { - return mDiffuse; + return m_diffuse; } const MCore::RGBAColor& StandardMaterial::GetSpecular() const { - return mSpecular; + return m_specular; } const MCore::RGBAColor& StandardMaterial::GetEmissive() const { - return mEmissive; + return m_emissive; } float StandardMaterial::GetShine() const { - return mShine; + return m_shine; } float StandardMaterial::GetShineStrength() const { - return mShineStrength; + return m_shineStrength; } float StandardMaterial::GetOpacity() const { - return mOpacity; + return m_opacity; } float StandardMaterial::GetIOR() const { - return mIOR; + return m_ior; } bool StandardMaterial::GetDoubleSided() const { - return mDoubleSided; + return m_doubleSided; } bool StandardMaterial::GetWireFrame() const { - return mWireFrame; + return m_wireFrame; } StandardMaterialLayer* StandardMaterial::AddLayer(StandardMaterialLayer* layer) { - mLayers.Add(layer); + m_layers.emplace_back(layer); return layer; } - uint32 StandardMaterial::GetNumLayers() const + size_t StandardMaterial::GetNumLayers() const { - return mLayers.GetLength(); + return m_layers.size(); } - StandardMaterialLayer* StandardMaterial::GetLayer(uint32 nr) + StandardMaterialLayer* StandardMaterial::GetLayer(size_t nr) { - MCORE_ASSERT(nr < mLayers.GetLength()); - return mLayers[nr]; + MCORE_ASSERT(nr < m_layers.size()); + return m_layers[nr]; } - void StandardMaterial::RemoveLayer(uint32 nr, bool delFromMem) + void StandardMaterial::RemoveLayer(size_t nr, bool delFromMem) { - MCORE_ASSERT(nr < mLayers.GetLength()); + MCORE_ASSERT(nr < m_layers.size()); if (delFromMem) { - mLayers[nr]->Destroy(); + m_layers[nr]->Destroy(); } - mLayers.Remove(nr); + m_layers.erase(AZStd::next(begin(m_layers), nr)); } void StandardMaterial::RemoveAllLayers() { - const uint32 numLayers = mLayers.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + for (StandardMaterialLayer* layer : m_layers) { - mLayers[i]->Destroy(); + layer->Destroy(); } - mLayers.Clear(); + m_layers.clear(); } - uint32 StandardMaterial::FindLayer(uint32 layerType) const + size_t StandardMaterial::FindLayer(uint32 layerType) const { // search through all layers - const uint32 numLayers = mLayers.GetLength(); - for (uint32 i = 0; i < numLayers; ++i) + const auto foundLayer = AZStd::find_if(begin(m_layers), end(m_layers), [layerType](const StandardMaterialLayer* layer) { - if (mLayers[i]->GetType() == layerType) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + return layer->GetType() == layerType; + }); + return foundLayer != end(m_layers) ? AZStd::distance(begin(m_layers), foundLayer) : InvalidIndex; } - void StandardMaterial::ReserveLayers(uint32 numLayers) + void StandardMaterial::ReserveLayers(size_t numLayers) { - mLayers.Reserve(numLayers); + m_layers.reserve(numLayers); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h index 659157d96d..6e90d8cf1f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/StandardMaterial.h @@ -223,15 +223,15 @@ namespace EMotionFX float GetRotationRadians() const; private: - uint32 mFileNameID; /**< The filename of the texture, without extension or path. */ - uint32 mLayerTypeID; /**< The layer type. See the enum for some possibilities. */ - float mAmount; /**< The amount value, between 0 and 1. This can for example represent how intens the layer is. */ - float mUOffset; /**< U offset (horizontal texture shift). */ - float mVOffset; /**< V offset (vertical texture shift). */ - float mUTiling; /**< Horizontal tiling factor. */ - float mVTiling; /**< Vertical tiling factor. */ - float mRotationRadians; /**< Texture rotation in radians. */ - unsigned char mBlendMode; /**< The blend mode is used to control how successive layers of textures are combined together. */ + uint32 m_fileNameId; /**< The filename of the texture, without extension or path. */ + uint32 m_layerTypeId; /**< The layer type. See the enum for some possibilities. */ + float m_amount; /**< The amount value, between 0 and 1. This can for example represent how intens the layer is. */ + float m_uOffset; /**< U offset (horizontal texture shift). */ + float m_vOffset; /**< V offset (vertical texture shift). */ + float m_uTiling; /**< Horizontal tiling factor. */ + float m_vTiling; /**< Vertical tiling factor. */ + float m_rotationRadians; /**< Texture rotation in radians. */ + unsigned char m_blendMode; /**< The blend mode is used to control how successive layers of textures are combined together. */ /** * Default constructor. @@ -403,7 +403,7 @@ namespace EMotionFX * This does not influence the return value of GetNumLayers(). * @param numLayers The number of layers to pre-allocate space for. */ - void ReserveLayers(uint32 numLayers); + void ReserveLayers(size_t numLayers); /** * Add a given layer to this material. @@ -415,21 +415,21 @@ namespace EMotionFX * Get the number of texture layers in this material. * @result The number of layers. */ - uint32 GetNumLayers() const; + size_t GetNumLayers() const; /** * Get a specific layer. * @param nr The material layer number to get. * @result A pointer to the material layer. */ - StandardMaterialLayer* GetLayer(uint32 nr); + StandardMaterialLayer* GetLayer(size_t nr); /** * Remove a specified material layer (also deletes it from memory). * @param nr The material layer number to remove. * @param delFromMem Set to true if it should be deleted from memory as well. */ - void RemoveLayer(uint32 nr, bool delFromMem = true); + void RemoveLayer(size_t nr, bool delFromMem = true); /** * Removes all material layers from this material (includes deletion from memory). @@ -442,14 +442,14 @@ namespace EMotionFX * Find the layer number which is of the given type. * If you for example want to search for a diffuse layer, you make a call like: * - * uint32 layerNumber = material->FindLayer( StandardMaterialLayer::LAYERTYPE_DIFFUSE ); + * size_t layerNumber = material->FindLayer( StandardMaterialLayer::LAYERTYPE_DIFFUSE ); * * This will return a value the layer number, which can be accessed with the GetLayer(layerNumber) method. * A value of MCORE_INVALIDINDEX32 will be returned in case no layer of the specified type could be found. * @param layerType The layer type you want to search on, for a list of valid types, see the enum inside StandardMaterialLayer. * @result Returns the layer number or MCORE_INVALIDINDEX32 when it could not be found. */ - uint32 FindLayer(uint32 layerType) const; + size_t FindLayer(uint32 layerType) const; /** * Creates a clone of the material, including it's layers. @@ -471,17 +471,17 @@ namespace EMotionFX protected: - MCore::Array< StandardMaterialLayer* > mLayers; /**< StandardMaterial layers. */ - MCore::RGBAColor mAmbient; /**< Ambient color. */ - MCore::RGBAColor mDiffuse; /**< Diffuse color. */ - MCore::RGBAColor mSpecular; /**< Specular color. */ - MCore::RGBAColor mEmissive; /**< Self illumination color. */ - float mShine; /**< The shine value, from the phong component (the power). */ - float mShineStrength; /**< Shine strength. */ - float mOpacity; /**< The opacity amount [1.0=full opac, 0.0=full transparent]. */ - float mIOR; /**< Index of refraction. */ - bool mDoubleSided; /**< Double sided?. */ - bool mWireFrame; /**< Render in wireframe?. */ + AZStd::vector< StandardMaterialLayer* > m_layers; /**< StandardMaterial layers. */ + MCore::RGBAColor m_ambient; /**< Ambient color. */ + MCore::RGBAColor m_diffuse; /**< Diffuse color. */ + MCore::RGBAColor m_specular; /**< Specular color. */ + MCore::RGBAColor m_emissive; /**< Self illumination color. */ + float m_shine; /**< The shine value, from the phong component (the power). */ + float m_shineStrength; /**< Shine strength. */ + float m_opacity; /**< The opacity amount [1.0=full opac, 0.0=full transparent]. */ + float m_ior; /**< Index of refraction. */ + bool m_doubleSided; /**< Double sided?. */ + bool m_wireFrame; /**< Render in wireframe?. */ /** * Constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp index df7a38486a..548816b82c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.cpp @@ -19,18 +19,17 @@ namespace EMotionFX // constructor - SubMesh::SubMesh(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, uint32 numBones) + SubMesh::SubMesh(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, size_t numBones) { - mParentMesh = parentMesh; - mNumVertices = numVerts; - mNumIndices = numIndices; - mNumPolygons = numPolygons; - mStartIndex = startIndex; - mStartVertex = startVertex; - mStartPolygon = startPolygon; - mMaterial = materialIndex; - - mBones.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_MESHES); + m_parentMesh = parentMesh; + m_numVertices = numVerts; + m_numIndices = numIndices; + m_numPolygons = numPolygons; + m_startIndex = startIndex; + m_startVertex = startVertex; + m_startPolygon = startPolygon; + m_material = materialIndex; + SetNumBones(numBones); } @@ -42,7 +41,7 @@ namespace EMotionFX // create - SubMesh* SubMesh::Create(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, uint32 numBones) + SubMesh* SubMesh::Create(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, size_t numBones) { return aznew SubMesh(parentMesh, startVertex, startIndex, startPolygon, numVerts, numIndices, numPolygons, materialIndex, numBones); } @@ -51,27 +50,16 @@ namespace EMotionFX // clone the submesh SubMesh* SubMesh::Clone(Mesh* newParentMesh) { - SubMesh* clone = aznew SubMesh(newParentMesh, mStartVertex, mStartIndex, mStartPolygon, mNumVertices, mNumIndices, mNumPolygons, mMaterial, mBones.GetLength()); - clone->mBones = mBones; + SubMesh* clone = aznew SubMesh(newParentMesh, m_startVertex, m_startIndex, m_startPolygon, m_numVertices, m_numIndices, m_numPolygons, m_material, m_bones.size()); + clone->m_bones = m_bones; return clone; } // remap bone (oldNodeNr) to bone (newNodeNr) - void SubMesh::RemapBone(uint16 oldNodeNr, uint16 newNodeNr) + void SubMesh::RemapBone(size_t oldNodeNr, size_t newNodeNr) { - // get the number of bones stored inside the submesh - const uint32 numBones = mBones.GetLength(); - - // iterate through all bones and remap the bones - for (uint32 i = 0; i < numBones; ++i) - { - // remap the bone - if (mBones[i] == oldNodeNr) - { - mBones[i] = newNodeNr; - } - } + AZStd::replace(m_bones.begin(), m_bones.end(), oldNodeNr, newNodeNr); } @@ -79,10 +67,10 @@ namespace EMotionFX void SubMesh::ReinitBonesArray(SkinningInfoVertexAttributeLayer* skinLayer) { // clear the bones array - mBones.Clear(false); + m_bones.clear(); // get shortcuts to the original vertex numbers - const uint32* orgVertices = (uint32*)mParentMesh->FindOriginalVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); + const uint32* orgVertices = (uint32*)m_parentMesh->FindOriginalVertexData(Mesh::ATTRIB_ORGVTXNUMBERS); // for all vertices in the submesh const uint32 startVertex = GetStartVertex(); @@ -98,12 +86,12 @@ namespace EMotionFX { // if the bone is disabled SkinInfluence* influence = skinLayer->GetInfluence(orgVertex, i); - const uint32 nodeNr = influence->GetNodeNr(); + const uint16 nodeNr = influence->GetNodeNr(); // put the node index in the bones array in case it isn't in already - if (mBones.Contains(nodeNr) == false) + if (AZStd::find(begin(m_bones), end(m_bones), nodeNr) == end(m_bones)) { - mBones.Add(nodeNr); + m_bones.emplace_back(nodeNr); } } } @@ -128,144 +116,136 @@ namespace EMotionFX uint32 SubMesh::GetStartIndex() const { - return mStartIndex; + return m_startIndex; } uint32 SubMesh::GetStartVertex() const { - return mStartVertex; + return m_startVertex; } uint32 SubMesh::GetStartPolygon() const { - return mStartPolygon; + return m_startPolygon; } uint32* SubMesh::GetIndices() const { - return (uint32*)(((uint8*)mParentMesh->GetIndices()) + mStartIndex * sizeof(uint32)); + return (uint32*)(((uint8*)m_parentMesh->GetIndices()) + m_startIndex * sizeof(uint32)); } uint8* SubMesh::GetPolygonVertexCounts() const { - uint8* polyVertCounts = mParentMesh->GetPolygonVertexCounts(); - return &polyVertCounts[mStartPolygon]; + uint8* polyVertCounts = m_parentMesh->GetPolygonVertexCounts(); + return &polyVertCounts[m_startPolygon]; } uint32 SubMesh::GetNumVertices() const { - return mNumVertices; + return m_numVertices; } uint32 SubMesh::GetNumIndices() const { - return mNumIndices; + return m_numIndices; } uint32 SubMesh::GetNumPolygons() const { - return mNumPolygons; + return m_numPolygons; } Mesh* SubMesh::GetParentMesh() const { - return mParentMesh; + return m_parentMesh; } void SubMesh::SetParentMesh(Mesh* mesh) { - mParentMesh = mesh; + m_parentMesh = mesh; } void SubMesh::SetMaterial(uint32 materialIndex) { - mMaterial = materialIndex; + m_material = materialIndex; } uint32 SubMesh::GetMaterial() const { - return mMaterial; + return m_material; } void SubMesh::SetStartIndex(uint32 indexOffset) { - mStartIndex = indexOffset; + m_startIndex = indexOffset; } void SubMesh::SetStartPolygon(uint32 polygonNumber) { - mStartPolygon = polygonNumber; + m_startPolygon = polygonNumber; } void SubMesh::SetStartVertex(uint32 vertexOffset) { - mStartVertex = vertexOffset; + m_startVertex = vertexOffset; } void SubMesh::SetNumIndices(uint32 numIndices) { - mNumIndices = numIndices; + m_numIndices = numIndices; } void SubMesh::SetNumVertices(uint32 numVertices) { - mNumVertices = numVertices; + m_numVertices = numVertices; } - uint32 SubMesh::FindBoneIndex(uint32 nodeNr) const + size_t SubMesh::FindBoneIndex(size_t nodeNr) const { - const uint32 numBones = mBones.GetLength(); - for (uint32 i = 0; i < numBones; ++i) - { - if (mBones[i] == nodeNr) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; + const auto foundBone = AZStd::find(m_bones.begin(), m_bones.end(), nodeNr); + return foundBone != m_bones.end() ? AZStd::distance(m_bones.begin(), foundBone) : InvalidIndex; } // remove the given bone - void SubMesh::RemoveBone(uint16 index) + void SubMesh::RemoveBone(size_t index) { - mBones.Remove(index); + m_bones.erase(AZStd::next(begin(m_bones), index)); } - void SubMesh::SetNumBones(uint32 numBones) + void SubMesh::SetNumBones(size_t numBones) { if (numBones == 0) { - mBones.Clear(); + m_bones.clear(); } else { - mBones.Resize(numBones); + m_bones.resize(numBones); } } - void SubMesh::SetBone(uint32 index, uint32 nodeIndex) + void SubMesh::SetBone(size_t index, size_t nodeIndex) { - mBones[index] = nodeIndex; + m_bones[index] = nodeIndex; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h index df798536da..57e3f2b486 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/SubMesh.h @@ -11,7 +11,7 @@ // include the required headers #include "EMotionFXConfig.h" #include "BaseObject.h" -#include +#include namespace EMotionFX @@ -55,7 +55,7 @@ namespace EMotionFX * @param materialIndex The material. * @param numBones The number of bones inside the submesh. */ - static SubMesh* Create(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, uint32 numBones); + static SubMesh* Create(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, size_t numBones); /** * Get the start index. This is the offset in the index array of the parent mesh where the index data for this @@ -178,48 +178,48 @@ namespace EMotionFX * Set the number of bones that is being used by this submesh. * @param numBones The number of bones used by the submesh. */ - void SetNumBones(uint32 numBones); + void SetNumBones(size_t numBones); /** * Set the index of a given bone. * @param index The bone number, which must be in range of [0..GetNumBones()-1]. * @param nodeIndex The node index number that acts as bone on this submesh. */ - void SetBone(uint32 index, uint32 nodeIndex); + void SetBone(size_t index, size_t nodeIndex); /** * Get the number of bones used by this submesh. * @result The number of bones used by this submesh. */ - MCORE_INLINE uint32 GetNumBones() const { return mBones.GetLength(); } + MCORE_INLINE size_t GetNumBones() const { return m_bones.size(); } /** * Get the node index for a given bone. * @param index The bone number, which must be in range of [0..GetNumBones()-1]. * @result The node index value for the given bone. */ - MCORE_INLINE uint32 GetBone(uint32 index) const { return mBones[index]; } + MCORE_INLINE size_t GetBone(size_t index) const { return m_bones[index]; } /** * Get direct access to the bone values, by getting a pointer to the first bone index. * Each integer in the array represents the node number that acts as bone on this submesh. * @result A pointer to the array of bones used by this submesh. */ - MCORE_INLINE uint32* GetBones() { return mBones.GetPtr(); } + MCORE_INLINE size_t* GetBones() { return m_bones.data(); } /** * Get direct access to the bones array. * Each integer in the array represents the node number that acts as bone on this submesh. * @result A read only reference to the array of bones used by this submesh. */ - MCORE_INLINE const MCore::Array& GetBonesArray() const { return mBones; } + MCORE_INLINE const AZStd::vector& GetBonesArray() const { return m_bones; } /** * Get direct access to the bones array. * Each integer in the array represents the node number that acts as bone on this submesh. * @result A reference to the array of bones used by this submesh. */ - MCORE_INLINE MCore::Array& GetBonesArray() { return mBones; } + MCORE_INLINE AZStd::vector& GetBonesArray() { return m_bones; } /** * Reinitialize the bones. @@ -236,20 +236,20 @@ namespace EMotionFX * @result The bone number inside the submesh, which is in range of [0..GetNumBones()-1]. * A value of MCORE_INVALIDINDEX32 is returned when the specified node isn't used as bone inside this submesh. */ - uint32 FindBoneIndex(uint32 nodeNr) const; + size_t FindBoneIndex(size_t nodeNr) const; /** * Remap bone to a new bone. This will overwrite the given old bones with the new one. * @param oldNodeNr The node number to be searched and replaced. * @param newNodeNr The node number with which the old bones will be replaced with. */ - void RemapBone(uint16 oldNodeNr, uint16 newNodeNr); + void RemapBone(size_t oldNodeNr, size_t newNodeNr); /** * Remove the given bone from the bones list. * @param index The index of the bone to be removed in range of [0..GetNumBones()-1]. */ - void RemoveBone(uint16 index); + void RemoveBone(size_t index); /** * Clone the submesh. @@ -268,15 +268,15 @@ namespace EMotionFX protected: - MCore::Array mBones; /**< The collection of bones. These are stored as node numbers that point into the actor. */ - uint32 mStartVertex; /**< The start vertex number in the vertex data arrays of the parent mesh. */ - uint32 mStartIndex; /**< The start index number in the index array of the parent mesh. */ - uint32 mStartPolygon; /**< The start polygon number in the polygon vertex count array of the parent mesh. */ - uint32 mNumVertices; /**< The number of vertices in this submesh. */ - uint32 mNumIndices; /**< The number of indices in this submesh. */ - uint32 mNumPolygons; /**< The number of polygons in this submesh. */ - uint32 mMaterial; /**< The material index, which points into the materials array in the Node class. */ - Mesh* mParentMesh; /**< The parent mesh. */ + AZStd::vector m_bones; /**< The collection of bones. These are stored as node numbers that point into the actor. */ + uint32 m_startVertex; /**< The start vertex number in the vertex data arrays of the parent mesh. */ + uint32 m_startIndex; /**< The start index number in the index array of the parent mesh. */ + uint32 m_startPolygon; /**< The start polygon number in the polygon vertex count array of the parent mesh. */ + uint32 m_numVertices; /**< The number of vertices in this submesh. */ + uint32 m_numIndices; /**< The number of indices in this submesh. */ + uint32 m_numPolygons; /**< The number of polygons in this submesh. */ + uint32 m_material; /**< The material index, which points into the materials array in the Node class. */ + Mesh* m_parentMesh; /**< The parent mesh. */ /** * Constructor. @@ -290,7 +290,7 @@ namespace EMotionFX * @param materialIndex The material. * @param numBones The number of bones inside the submesh. */ - SubMesh(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, uint32 numBones); + SubMesh(Mesh* parentMesh, uint32 startVertex, uint32 startIndex, uint32 startPolygon, uint32 numVerts, uint32 numIndices, uint32 numPolygons, uint32 materialIndex, size_t numBones); /** * Destructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.cpp index e0e3f2ba3c..d36a568245 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.cpp @@ -19,14 +19,14 @@ namespace EMotionFX ThreadData::ThreadData() : BaseObject() { - mThreadIndex = MCORE_INVALIDINDEX32; + m_threadIndex = MCORE_INVALIDINDEX32; } // constructor ThreadData::ThreadData(uint32 threadIndex) { - mThreadIndex = threadIndex; + m_threadIndex = threadIndex; } @@ -52,12 +52,12 @@ namespace EMotionFX void ThreadData::SetThreadIndex(uint32 index) { - mThreadIndex = index; + m_threadIndex = index; } uint32 ThreadData::GetThreadIndex() const { - return mThreadIndex; + return m_threadIndex; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h b/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h index 1cee75200c..3ad8ae605a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ThreadData.h @@ -13,7 +13,7 @@ #include "BaseObject.h" #include "AnimGraphPosePool.h" #include "AnimGraphRefCountedDataPool.h" -#include +#include namespace EMotionFX @@ -34,16 +34,16 @@ namespace EMotionFX void SetThreadIndex(uint32 index); uint32 GetThreadIndex() const; - MCORE_INLINE const AnimGraphPosePool& GetPosePool() const { return mPosePool; } - MCORE_INLINE AnimGraphPosePool& GetPosePool() { return mPosePool; } + MCORE_INLINE const AnimGraphPosePool& GetPosePool() const { return m_posePool; } + MCORE_INLINE AnimGraphPosePool& GetPosePool() { return m_posePool; } - MCORE_INLINE AnimGraphRefCountedDataPool& GetRefCountedDataPool() { return mRefCountedDataPool; } - MCORE_INLINE const AnimGraphRefCountedDataPool& GetRefCountedDataPool() const { return mRefCountedDataPool; } + MCORE_INLINE AnimGraphRefCountedDataPool& GetRefCountedDataPool() { return m_refCountedDataPool; } + MCORE_INLINE const AnimGraphRefCountedDataPool& GetRefCountedDataPool() const { return m_refCountedDataPool; } private: - uint32 mThreadIndex; - AnimGraphPosePool mPosePool; - AnimGraphRefCountedDataPool mRefCountedDataPool; + uint32 m_threadIndex; + AnimGraphPosePool m_posePool; + AnimGraphRefCountedDataPool m_refCountedDataPool; ThreadData(); ThreadData(uint32 threadIndex); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp index 77f3382d6c..d8b9015044 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Transform.cpp @@ -52,12 +52,12 @@ namespace EMotionFX // set void Transform::Set(const AZ::Vector3& position, const AZ::Quaternion& rotation) { - mRotation = rotation; - mPosition = position; + m_rotation = rotation; + m_position = position; EMFX_SCALECODE ( - mScale = AZ::Vector3::CreateOne(); + m_scale = AZ::Vector3::CreateOne(); ) } @@ -69,12 +69,12 @@ namespace EMotionFX MCORE_UNUSED(scale); #endif - mRotation = rotation; - mPosition = position; + m_rotation = rotation; + m_position = position; EMFX_SCALECODE ( - mScale = scale; + m_scale = scale; ) } @@ -82,19 +82,19 @@ namespace EMotionFX // check if this transform is equal to another bool Transform::operator == (const Transform& right) const { - if (MCore::Compare::CheckIfIsClose(mPosition, right.mPosition, MCore::Math::epsilon) == false) + if (MCore::Compare::CheckIfIsClose(m_position, right.m_position, MCore::Math::epsilon) == false) { return false; } - if (MCore::Compare::CheckIfIsClose(mRotation, right.mRotation, MCore::Math::epsilon) == false) + if (MCore::Compare::CheckIfIsClose(m_rotation, right.m_rotation, MCore::Math::epsilon) == false) { return false; } EMFX_SCALECODE ( - if (MCore::Compare::CheckIfIsClose(mScale, right.mScale, MCore::Math::epsilon) == false) + if (MCore::Compare::CheckIfIsClose(m_scale, right.m_scale, MCore::Math::epsilon) == false) { return false; } @@ -107,19 +107,19 @@ namespace EMotionFX // check if this transform is not equal to another bool Transform::operator != (const Transform& right) const { - if (MCore::Compare::CheckIfIsClose(mPosition, right.mPosition, MCore::Math::epsilon)) + if (MCore::Compare::CheckIfIsClose(m_position, right.m_position, MCore::Math::epsilon)) { return true; } - if (MCore::Compare::CheckIfIsClose(mRotation, right.mRotation, MCore::Math::epsilon)) + if (MCore::Compare::CheckIfIsClose(m_rotation, right.m_rotation, MCore::Math::epsilon)) { return true; } EMFX_SCALECODE ( - if (MCore::Compare::CheckIfIsClose(mScale, right.mScale, MCore::Math::epsilon)) + if (MCore::Compare::CheckIfIsClose(m_scale, right.m_scale, MCore::Math::epsilon)) { return true; } @@ -178,15 +178,15 @@ namespace EMotionFX void Transform::InitFromAZTransform(const AZ::Transform& transform) { #ifndef EMFX_SCALE_DISABLED - mPosition = transform.GetTranslation(); - mScale = AZ::Vector3(transform.GetUniformScale()); - mRotation = transform.GetRotation(); + m_position = transform.GetTranslation(); + m_scale = AZ::Vector3(transform.GetUniformScale()); + m_rotation = transform.GetRotation(); #else - mPosition = transform.GetTranslation(); - mRotation = transform.GetRotation(); + m_position = transform.GetTranslation(); + m_rotation = transform.GetRotation(); #endif - mRotation.Normalize(); + m_rotation.Normalize(); } @@ -196,10 +196,10 @@ namespace EMotionFX AZ::Transform result; #ifndef EMFX_SCALE_DISABLED - result = MCore::CreateFromQuaternionAndTranslationAndScale(mRotation, mPosition, mScale); + result = MCore::CreateFromQuaternionAndTranslationAndScale(m_rotation, m_position, m_scale); #else - result = AZ::Transform::CreateFromQuaternionAndTranslation(mRotation, mPosition); + result = AZ::Transform::CreateFromQuaternionAndTranslation(m_rotation, m_position); #endif return result; @@ -209,35 +209,35 @@ namespace EMotionFX // identity the transform void Transform::Identity() { - mPosition = AZ::Vector3::CreateZero(); - mRotation = AZ::Quaternion::CreateIdentity(); + m_position = AZ::Vector3::CreateZero(); + m_rotation = AZ::Quaternion::CreateIdentity(); EMFX_SCALECODE ( - mScale = AZ::Vector3::CreateOne(); + m_scale = AZ::Vector3::CreateOne(); ) } // Zero out the position, scale, and rotation. void Transform::Zero() { - mPosition = AZ::Vector3::CreateZero(); - mRotation = AZ::Quaternion::CreateZero(); + m_position = AZ::Vector3::CreateZero(); + m_rotation = AZ::Quaternion::CreateZero(); EMFX_SCALECODE ( - mScale = AZ::Vector3::CreateZero(); + m_scale = AZ::Vector3::CreateZero(); ) } // Zero out the position and scale, but set quaternion to identity. void Transform::IdentityWithZeroScale() { - mPosition = AZ::Vector3::CreateZero(); - mRotation = AZ::Quaternion::CreateIdentity(); + m_position = AZ::Vector3::CreateZero(); + m_rotation = AZ::Quaternion::CreateIdentity(); EMFX_SCALECODE ( - mScale = AZ::Vector3::CreateZero(); + m_scale = AZ::Vector3::CreateZero(); ); } @@ -245,17 +245,17 @@ namespace EMotionFX Transform& Transform::PreMultiply(const Transform& other) { #ifdef EMFX_SCALE_DISABLED - mPosition += mRotation * other.mPosition; + m_position += m_rotation * other.m_position; #else - mPosition += mRotation.TransformVector((other.mPosition * mScale)); + m_position += m_rotation.TransformVector((other.m_position * m_scale)); #endif - mRotation = mRotation * other.mRotation; - mRotation.Normalize(); + m_rotation = m_rotation * other.m_rotation; + m_rotation.Normalize(); EMFX_SCALECODE ( - mScale = mScale * other.mScale; + m_scale = m_scale * other.m_scale; ) return *this; @@ -274,25 +274,25 @@ namespace EMotionFX AZ::Vector3 Transform::TransformPoint(const AZ::Vector3& point) const { #ifdef EMFX_SCALE_DISABLED - return mPosition + mRotation * point; + return m_position + m_rotation * point; #else - return mPosition + mRotation.TransformVector((point * mScale)); + return m_position + m_rotation.TransformVector((point * m_scale)); #endif } AZ::Vector3 Transform::RotateVector(const AZ::Vector3& v) const { - return mRotation.TransformVector(v); + return m_rotation.TransformVector(v); } AZ::Vector3 Transform::TransformVector(const AZ::Vector3& v) const { #ifdef EMFX_SCALE_DISABLED - return mRotation.TransformVector(v); + return m_rotation.TransformVector(v); #else - return mRotation.TransformVector((v * mScale)); + return m_rotation.TransformVector((v * m_scale)); #endif } @@ -301,17 +301,17 @@ namespace EMotionFX Transform& Transform::Multiply(const Transform& other) { #ifdef EMFX_SCALE_DISABLED - mPosition = other.mRotation.TransformVector(mPosition) + other.mPosition; + m_position = other.m_rotation.TransformVector(m_position) + other.m_position; #else - mPosition = other.mRotation.TransformVector((mPosition * other.mScale)) + other.mPosition; + m_position = other.m_rotation.TransformVector((m_position * other.m_scale)) + other.m_position; #endif - mRotation = other.mRotation * mRotation; - mRotation.Normalize(); + m_rotation = other.m_rotation * m_rotation; + m_rotation.Normalize(); EMFX_SCALECODE ( - mScale = other.mScale * mScale; + m_scale = other.m_scale * m_scale; ) return *this; } @@ -329,7 +329,7 @@ namespace EMotionFX // normalize the quaternions Transform& Transform::Normalize() { - mRotation.Normalize(); + m_rotation.Normalize(); return *this; } @@ -348,15 +348,15 @@ namespace EMotionFX { EMFX_SCALECODE ( - mScale = mScale.GetReciprocal(); + m_scale = m_scale.GetReciprocal(); ) - mRotation = mRotation.GetConjugate(); + m_rotation = m_rotation.GetConjugate(); #ifdef EMFX_SCALE_DISABLED - mPosition = mRotation.TransformVector(-mPosition); + m_position = m_rotation.TransformVector(-m_position); #else - mPosition = mRotation.TransformVector(-mPosition) * mScale; + m_position = m_rotation.TransformVector(-m_position) * m_scale; #endif return *this; @@ -376,14 +376,14 @@ namespace EMotionFX Transform& Transform::Mirror(const AZ::Vector3& planeNormal) { // mirror the position over the plane with the specified normal - mPosition = MCore::Mirror(mPosition, planeNormal); + m_position = MCore::Mirror(m_position, planeNormal); // mirror the quaternion axis component - AZ::Vector3 mirrored = MCore::Mirror(AZ::Vector3(mRotation.GetX(), mRotation.GetY(), mRotation.GetZ()), planeNormal); + AZ::Vector3 mirrored = MCore::Mirror(AZ::Vector3(m_rotation.GetX(), m_rotation.GetY(), m_rotation.GetZ()), planeNormal); // update the rotation quaternion with inverted angle - mRotation.Set(mirrored.GetX(), mirrored.GetY(), mirrored.GetZ(), -mRotation.GetW()); - mRotation.Normalize(); + m_rotation.Set(mirrored.GetX(), mirrored.GetY(), mirrored.GetZ(), -m_rotation.GetW()); + m_rotation.Normalize(); return *this; } @@ -396,14 +396,14 @@ namespace EMotionFX ApplyMirrorFlags(this, mirrorFlags); // mirror the position over the plane with the specified normal - mPosition = MCore::Mirror(mPosition, planeNormal); + m_position = MCore::Mirror(m_position, planeNormal); // mirror the quaternion axis component - AZ::Vector3 mirrored = MCore::Mirror(AZ::Vector3(mRotation.GetX(), mRotation.GetY(), mRotation.GetZ()), planeNormal); + AZ::Vector3 mirrored = MCore::Mirror(AZ::Vector3(m_rotation.GetX(), m_rotation.GetY(), m_rotation.GetZ()), planeNormal); // update the rotation quaternion with inverted angle - mRotation.Set(mirrored.GetX(), mirrored.GetY(), mirrored.GetZ(), -mRotation.GetW()); - mRotation.Normalize(); + m_rotation.Set(mirrored.GetX(), mirrored.GetY(), mirrored.GetZ(), -m_rotation.GetW()); + m_rotation.Normalize(); return *this; } @@ -422,17 +422,17 @@ namespace EMotionFX void Transform::PreMultiply(const Transform& other, Transform* outResult) const { #ifdef EMFX_SCALE_DISABLED - outResult->mPosition = mPosition + mRotation.TransformVector(other.mPosition); + outResult->m_position = m_position + m_rotation.TransformVector(other.m_position); #else - outResult->mPosition = mPosition + (mRotation.TransformVector(other.mPosition) * mScale); + outResult->m_position = m_position + (m_rotation.TransformVector(other.m_position) * m_scale); #endif - outResult->mRotation = mRotation * other.mRotation; - outResult->mRotation.Normalize(); + outResult->m_rotation = m_rotation * other.m_rotation; + outResult->m_rotation.Normalize(); EMFX_SCALECODE ( - outResult->mScale = mScale * other.mScale; + outResult->m_scale = m_scale * other.m_scale; ) } @@ -441,17 +441,17 @@ namespace EMotionFX void Transform::Multiply(const Transform& other, Transform* outResult) const { #ifdef EMFX_SCALE_DISABLED - outResult->mPosition = other.mPosition + other.mRotation.TransformVector(mPosition); + outResult->m_position = other.m_position + other.m_rotation.TransformVector(m_position); #else - outResult->mPosition = other.mPosition + (other.mRotation.TransformVector(mPosition) * other.mScale); + outResult->m_position = other.m_position + (other.m_rotation.TransformVector(m_position) * other.m_scale); #endif - outResult->mRotation = other.mRotation * mRotation; - outResult->mRotation.Normalize(); + outResult->m_rotation = other.m_rotation * m_rotation; + outResult->m_rotation.Normalize(); EMFX_SCALECODE ( - outResult->mScale = other.mScale * mScale; + outResult->m_scale = other.m_scale * m_scale; ) } @@ -469,18 +469,18 @@ namespace EMotionFX void Transform::CalcRelativeTo(const Transform& relativeTo, Transform* outTransform) const { #ifndef EMFX_SCALE_DISABLED - const AZ::Vector3 invScale = relativeTo.mScale.GetReciprocal(); - const AZ::Quaternion invRot = relativeTo.mRotation.GetConjugate(); + const AZ::Vector3 invScale = relativeTo.m_scale.GetReciprocal(); + const AZ::Quaternion invRot = relativeTo.m_rotation.GetConjugate(); - outTransform->mPosition = (invRot.TransformVector(mPosition - relativeTo.mPosition)) * invScale; - outTransform->mRotation = invRot * mRotation; - outTransform->mScale = mScale * invScale; + outTransform->m_position = (invRot.TransformVector(m_position - relativeTo.m_position)) * invScale; + outTransform->m_rotation = invRot * m_rotation; + outTransform->m_scale = m_scale * invScale; #else - const AZ::Quaternion invRot = relativeTo.mRotation.GetConjugate(); - outTransform->mPosition = invRot.TransformVector(mPosition - relativeTo.mPosition); - outTransform->mRotation = invRot * mRotation; + const AZ::Quaternion invRot = relativeTo.m_rotation.GetConjugate(); + outTransform->m_position = invRot.TransformVector(m_position - relativeTo.m_position); + outTransform->m_rotation = invRot * m_rotation; #endif - outTransform->mRotation.Normalize(); + outTransform->m_rotation.Normalize(); } @@ -497,16 +497,16 @@ namespace EMotionFX void Transform::Mirror(const AZ::Vector3& planeNormal, Transform* outResult) const { // mirror the position over the normal - outResult->mPosition = MCore::Mirror(mPosition, planeNormal); + outResult->m_position = MCore::Mirror(m_position, planeNormal); // mirror the quaternion axis component - AZ::Vector3 mirrored = MCore::Mirror(AZ::Vector3(mRotation.GetX(), mRotation.GetY(), mRotation.GetZ()), planeNormal); - outResult->mRotation.Set(mirrored.GetX(), mirrored.GetY(), mirrored.GetZ(), -mRotation.GetW()); // store the mirrored quat - outResult->mRotation.Normalize(); + AZ::Vector3 mirrored = MCore::Mirror(AZ::Vector3(m_rotation.GetX(), m_rotation.GetY(), m_rotation.GetZ()), planeNormal); + outResult->m_rotation.Set(mirrored.GetX(), mirrored.GetY(), mirrored.GetZ(), -m_rotation.GetW()); // store the mirrored quat + outResult->m_rotation.Normalize(); EMFX_SCALECODE ( - outResult->mScale = mScale; + outResult->m_scale = m_scale; ) } @@ -518,9 +518,9 @@ namespace EMotionFX return false; #else return ( - !MCore::Compare::CheckIfIsClose(mScale.GetX(), 1.0f, MCore::Math::epsilon) || - !MCore::Compare::CheckIfIsClose(mScale.GetY(), 1.0f, MCore::Math::epsilon) || - !MCore::Compare::CheckIfIsClose(mScale.GetZ(), 1.0f, MCore::Math::epsilon)); + !MCore::Compare::CheckIfIsClose(m_scale.GetX(), 1.0f, MCore::Math::epsilon) || + !MCore::Compare::CheckIfIsClose(m_scale.GetY(), 1.0f, MCore::Math::epsilon) || + !MCore::Compare::CheckIfIsClose(m_scale.GetZ(), 1.0f, MCore::Math::epsilon)); #endif } @@ -528,12 +528,12 @@ namespace EMotionFX // blend into another transform Transform& Transform::Blend(const Transform& dest, float weight) { - mPosition = MCore::LinearInterpolate(mPosition, dest.mPosition, weight); - mRotation = MCore::NLerp(mRotation, dest.mRotation, weight); + m_position = MCore::LinearInterpolate(m_position, dest.m_position, weight); + m_rotation = MCore::NLerp(m_rotation, dest.m_rotation, weight); EMFX_SCALECODE ( - mScale = MCore::LinearInterpolate(mScale, dest.mScale, weight); + m_scale = MCore::LinearInterpolate(m_scale, dest.m_scale, weight); ) return *this; @@ -543,18 +543,18 @@ namespace EMotionFX // additive blend Transform& Transform::BlendAdditive(const Transform& dest, const Transform& orgTransform, float weight) { - const AZ::Vector3 relPos = dest.mPosition - orgTransform.mPosition; - const AZ::Quaternion& orgRot = orgTransform.mRotation; - const AZ::Quaternion rot = MCore::NLerp(orgRot, dest.mRotation, weight); + const AZ::Vector3 relPos = dest.m_position - orgTransform.m_position; + const AZ::Quaternion& orgRot = orgTransform.m_rotation; + const AZ::Quaternion rot = MCore::NLerp(orgRot, dest.m_rotation, weight); // apply the relative changes - mRotation = mRotation * (orgRot.GetConjugate() * rot); - mRotation.Normalize(); - mPosition += (relPos * weight); + m_rotation = m_rotation * (orgRot.GetConjugate() * rot); + m_rotation.Normalize(); + m_position += (relPos * weight); EMFX_SCALECODE ( - mScale += (dest.mScale - orgTransform.mScale) * weight; + m_scale += (dest.m_scale - orgTransform.m_scale) * weight; ) return *this; @@ -563,13 +563,13 @@ namespace EMotionFX Transform& Transform::ApplyAdditive(const Transform& additive) { - mPosition += additive.mPosition; - mRotation = mRotation * additive.mRotation; - mRotation.Normalize(); + m_position += additive.m_position; + m_rotation = m_rotation * additive.m_rotation; + m_rotation.Normalize(); EMFX_SCALECODE ( - mScale *= additive.mScale; + m_scale *= additive.m_scale; ) return *this; } @@ -577,11 +577,11 @@ namespace EMotionFX Transform& Transform::ApplyAdditive(const Transform& additive, float weight) { - mPosition += additive.mPosition * weight; - mRotation = MCore::NLerp(mRotation, mRotation * additive.mRotation, weight); + m_position += additive.m_position * weight; + m_rotation = MCore::NLerp(m_rotation, m_rotation * additive.m_rotation, weight); EMFX_SCALECODE ( - mScale *= AZ::Vector3::CreateOne().Lerp(additive.mScale, weight); + m_scale *= AZ::Vector3::CreateOne().Lerp(additive.m_scale, weight); ) return *this; } @@ -590,21 +590,21 @@ namespace EMotionFX // sum the transforms Transform& Transform::Add(const Transform& other, float weight) { - mPosition += other.mPosition * weight; + m_position += other.m_position * weight; // make sure we use the correct hemisphere - if (mRotation.Dot(other.mRotation) < 0.0f) + if (m_rotation.Dot(other.m_rotation) < 0.0f) { - mRotation += -(other.mRotation) * weight; + m_rotation += -(other.m_rotation) * weight; } else { - mRotation += other.mRotation * weight; + m_rotation += other.m_rotation * weight; } EMFX_SCALECODE ( - mScale += other.mScale * weight; + m_scale += other.m_scale * weight; ) return *this; @@ -614,11 +614,11 @@ namespace EMotionFX // add a transform Transform& Transform::Add(const Transform& other) { - mPosition += other.mPosition; - mRotation += other.mRotation; + m_position += other.m_position; + m_rotation += other.m_rotation; EMFX_SCALECODE ( - mScale += other.mScale; + m_scale += other.m_scale; ) return *this; } @@ -627,11 +627,11 @@ namespace EMotionFX // subtract a transform Transform& Transform::Subtract(const Transform& other) { - mPosition -= other.mPosition; - mRotation -= other.mRotation; + m_position -= other.m_position; + m_rotation -= other.m_rotation; EMFX_SCALECODE ( - mScale -= other.mScale; + m_scale -= other.m_scale; ) return *this; } @@ -645,22 +645,22 @@ namespace EMotionFX MCore::LogInfo("Transform(%s):", name); } - MCore::LogInfo("mPosition = %.6f, %.6f, %.6f", - static_cast(mPosition.GetX()), - static_cast(mPosition.GetY()), - static_cast(mPosition.GetZ())); - MCore::LogInfo("mRotation = %.6f, %.6f, %.6f, %.6f", - static_cast(mRotation.GetX()), - static_cast(mRotation.GetY()), - static_cast(mRotation.GetZ()), - static_cast(mRotation.GetW())); + MCore::LogInfo("m_position = %.6f, %.6f, %.6f", + static_cast(m_position.GetX()), + static_cast(m_position.GetY()), + static_cast(m_position.GetZ())); + MCore::LogInfo("m_rotation = %.6f, %.6f, %.6f, %.6f", + static_cast(m_rotation.GetX()), + static_cast(m_rotation.GetY()), + static_cast(m_rotation.GetZ()), + static_cast(m_rotation.GetW())); EMFX_SCALECODE ( - MCore::LogInfo("mScale = %.6f, %.6f, %.6f", - static_cast(mScale.GetX()), - static_cast(mScale.GetY()), - static_cast(mScale.GetZ())); + MCore::LogInfo("m_scale = %.6f, %.6f, %.6f", + static_cast(m_scale.GetX()), + static_cast(m_scale.GetY()), + static_cast(m_scale.GetZ())); ) } @@ -675,26 +675,26 @@ namespace EMotionFX if (mirrorFlags & Actor::MIRRORFLAG_INVERT_X) { - inOutTransform->mRotation.SetW(inOutTransform->mRotation.GetW() * -1.0f); - inOutTransform->mRotation.SetX(inOutTransform->mRotation.GetX() * -1.0f); - inOutTransform->mPosition.SetY(inOutTransform->mPosition.GetY() * -1.0f); - inOutTransform->mPosition.SetZ(inOutTransform->mPosition.GetZ() * -1.0f); + inOutTransform->m_rotation.SetW(inOutTransform->m_rotation.GetW() * -1.0f); + inOutTransform->m_rotation.SetX(inOutTransform->m_rotation.GetX() * -1.0f); + inOutTransform->m_position.SetY(inOutTransform->m_position.GetY() * -1.0f); + inOutTransform->m_position.SetZ(inOutTransform->m_position.GetZ() * -1.0f); return; } if (mirrorFlags & Actor::MIRRORFLAG_INVERT_Y) { - inOutTransform->mRotation.SetW(inOutTransform->mRotation.GetW() * -1.0f); - inOutTransform->mRotation.SetY(inOutTransform->mPosition.GetY() * -1.0f); - inOutTransform->mPosition.SetX(inOutTransform->mPosition.GetX() * -1.0f); - inOutTransform->mPosition.SetZ(inOutTransform->mPosition.GetZ() * -1.0f); + inOutTransform->m_rotation.SetW(inOutTransform->m_rotation.GetW() * -1.0f); + inOutTransform->m_rotation.SetY(inOutTransform->m_position.GetY() * -1.0f); + inOutTransform->m_position.SetX(inOutTransform->m_position.GetX() * -1.0f); + inOutTransform->m_position.SetZ(inOutTransform->m_position.GetZ() * -1.0f); return; } if (mirrorFlags & Actor::MIRRORFLAG_INVERT_Z) { - inOutTransform->mRotation.SetW(inOutTransform->mRotation.GetW() * -1.0f); - inOutTransform->mRotation.SetZ(inOutTransform->mPosition.GetZ() * -1.0f); - inOutTransform->mPosition.SetX(inOutTransform->mPosition.GetX() * -1.0f); - inOutTransform->mPosition.SetY(inOutTransform->mPosition.GetY() * -1.0f); + inOutTransform->m_rotation.SetW(inOutTransform->m_rotation.GetW() * -1.0f); + inOutTransform->m_rotation.SetZ(inOutTransform->m_position.GetZ() * -1.0f); + inOutTransform->m_position.SetX(inOutTransform->m_position.GetX() * -1.0f); + inOutTransform->m_position.SetY(inOutTransform->m_position.GetY() * -1.0f); return; } } @@ -748,13 +748,13 @@ namespace EMotionFX // Only keep translation over the XY plane and assume a height of 0. if (!(flags & MOTIONEXTRACT_CAPTURE_Z)) { - mPosition.SetZ(0.0f); + m_position.SetZ(0.0f); } // Only keep the rotation on the Z axis. - mRotation.SetX(0.0f); - mRotation.SetY(0.0f); - mRotation.Normalize(); + m_rotation.SetX(0.0f); + m_rotation.SetY(0.0f); + m_rotation.Normalize(); } @@ -764,12 +764,12 @@ namespace EMotionFX Transform result(*this); // Only keep translation over the XY plane and assume a height of 0. - result.mPosition.SetZ(0.0f); + result.m_position.SetZ(0.0f); // Only keep the rotation on the Z axis. - result.mRotation.SetX(0.0f); - result.mRotation.SetY(0.0f); - result.mRotation.Normalize(); + result.m_rotation.SetX(0.0f); + result.m_rotation.SetY(0.0f); + result.m_rotation.Normalize(); return result; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Transform.h b/Gems/EMotionFX/Code/EMotionFX/Source/Transform.h index 950d39fb55..764de9e8f9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Transform.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Transform.h @@ -137,10 +137,10 @@ namespace EMotionFX bool operator != (const Transform& right) const; public: - AZ::Quaternion mRotation; /**< The rotation. */ - AZ::Vector3 mPosition; /**< The position. */ + AZ::Quaternion m_rotation; /**< The rotation. */ + AZ::Vector3 m_position; /**< The position. */ #ifndef EMFX_SCALE_DISABLED - AZ::Vector3 mScale; /**< The scale. */ + AZ::Vector3 m_scale; /**< The scale. */ #endif } MCORE_ALIGN_POST(16); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp index 7701771952..5349c16ec0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.cpp @@ -25,10 +25,10 @@ namespace EMotionFX TransformData::TransformData() : BaseObject() { - mSkinningMatrices = nullptr; - mBindPose = nullptr; - mNumTransforms = 0; - mHasUniqueBindPose = false; + m_skinningMatrices = nullptr; + m_bindPose = nullptr; + m_numTransforms = 0; + m_hasUniqueBindPose = false; } @@ -49,17 +49,17 @@ namespace EMotionFX // get rid of all allocated data void TransformData::Release() { - MCore::AlignedFree(mSkinningMatrices); + MCore::AlignedFree(m_skinningMatrices); - if (mHasUniqueBindPose) + if (m_hasUniqueBindPose) { - delete mBindPose; + delete m_bindPose; } - mPose.Clear(); - mSkinningMatrices = nullptr; - mBindPose = nullptr; - mNumTransforms = 0; + m_pose.Clear(); + m_skinningMatrices = nullptr; + m_bindPose = nullptr; + m_numTransforms = 0; } @@ -69,33 +69,33 @@ namespace EMotionFX Release(); // link to the given actor instance - mPose.LinkToActorInstance(actorInstance); + m_pose.LinkToActorInstance(actorInstance); // release all memory if we want to resize to zero nodes - const uint32 numNodes = actorInstance->GetNumNodes(); + const size_t numNodes = actorInstance->GetNumNodes(); if (numNodes == 0) { Release(); return; } - mSkinningMatrices = (AZ::Matrix3x4*)MCore::AlignedAllocate(sizeof(AZ::Matrix3x4) * numNodes, static_cast(AZStd::alignment_of()), EMFX_MEMCATEGORY_TRANSFORMDATA); - mNumTransforms = numNodes; + m_skinningMatrices = (AZ::Matrix3x4*)MCore::AlignedAllocate(sizeof(AZ::Matrix3x4) * numNodes, static_cast(AZStd::alignment_of()), EMFX_MEMCATEGORY_TRANSFORMDATA); + m_numTransforms = numNodes; - if (mHasUniqueBindPose) + if (m_hasUniqueBindPose) { - mBindPose = new Pose(); - mBindPose->LinkToActorInstance(actorInstance); + m_bindPose = new Pose(); + m_bindPose->LinkToActorInstance(actorInstance); } else { - mBindPose = actorInstance->GetActor()->GetBindPose(); + m_bindPose = actorInstance->GetActor()->GetBindPose(); } // now initialize the data with the actor transforms - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { - mSkinningMatrices[i] = AZ::Matrix3x4::CreateIdentity(); + m_skinningMatrices[i] = AZ::Matrix3x4::CreateIdentity(); } } @@ -103,53 +103,53 @@ namespace EMotionFX // make the bind pose transforms unique void TransformData::MakeBindPoseTransformsUnique() { - if (mHasUniqueBindPose) + if (m_hasUniqueBindPose) { return; } - const ActorInstance* actorInstance = mPose.GetActorInstance(); - mHasUniqueBindPose = true; - mBindPose = new Pose(); - mBindPose->LinkToActorInstance(actorInstance); - *mBindPose = *actorInstance->GetActor()->GetBindPose(); + const ActorInstance* actorInstance = m_pose.GetActorInstance(); + m_hasUniqueBindPose = true; + m_bindPose = new Pose(); + m_bindPose->LinkToActorInstance(actorInstance); + *m_bindPose = *actorInstance->GetActor()->GetBindPose(); } EMFX_SCALECODE ( // set the scaling value for the node and all child nodes - void TransformData::SetBindPoseLocalScaleInherit(uint32 nodeIndex, const AZ::Vector3& scale) + void TransformData::SetBindPoseLocalScaleInherit(size_t nodeIndex, const AZ::Vector3& scale) { - const ActorInstance* actorInstance = mPose.GetActorInstance(); + const ActorInstance* actorInstance = m_pose.GetActorInstance(); const Actor* actor = actorInstance->GetActor(); // get the node index and the number of children of the given node const Node* node = actor->GetSkeleton()->GetNode(nodeIndex); - const uint32 numChilds = node->GetNumChildNodes(); + const size_t numChilds = node->GetNumChildNodes(); // set the new scale for the given node SetBindPoseLocalScale(nodeIndex, scale); // iterate through the children and set their scale recursively - for (uint32 i = 0; i < numChilds; ++i) + for (size_t i = 0; i < numChilds; ++i) { SetBindPoseLocalScaleInherit(node->GetChildIndex(i), scale); } } // update the local space scale - void TransformData::SetBindPoseLocalScale(uint32 nodeIndex, const AZ::Vector3& scale) + void TransformData::SetBindPoseLocalScale(size_t nodeIndex, const AZ::Vector3& scale) { - Transform newTransform = mBindPose->GetLocalSpaceTransform(nodeIndex); - newTransform.mScale = scale; - mBindPose->SetLocalSpaceTransform(nodeIndex, newTransform); + Transform newTransform = m_bindPose->GetLocalSpaceTransform(nodeIndex); + newTransform.m_scale = scale; + m_bindPose->SetLocalSpaceTransform(nodeIndex, newTransform); } ) // EMFX_SCALECODE // set the number of morph weights - void TransformData::SetNumMorphWeights(uint32 numMorphWeights) + void TransformData::SetNumMorphWeights(size_t numMorphWeights) { - mPose.ResizeNumMorphs(numMorphWeights); + m_pose.ResizeNumMorphs(numMorphWeights); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h index fa0d430871..71c2ee6446 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/TransformData.h @@ -64,56 +64,56 @@ namespace EMotionFX * The size of the returned array is equal to the amount of nodes in the actor or the value returned by GetNumTransforms() * @result The array of skinning matrices. */ - MCORE_INLINE AZ::Matrix3x4* GetSkinningMatrices() { return mSkinningMatrices; } + MCORE_INLINE AZ::Matrix3x4* GetSkinningMatrices() { return m_skinningMatrices; } /** * Get the skinning matrices (offset from the pose), in read-only (const) mode. * The size of the returned array is equal to the amount of nodes in the actor or the value returned by GetNumTransforms() * @result The array of skinning matrices. */ - MCORE_INLINE const AZ::Matrix3x4* GetSkinningMatrices() const { return mSkinningMatrices; } + MCORE_INLINE const AZ::Matrix3x4* GetSkinningMatrices() const { return m_skinningMatrices; } - MCORE_INLINE Pose* GetBindPose() const { return mBindPose; } - MCORE_INLINE const Pose* GetCurrentPose() const { return &mPose; } - MCORE_INLINE Pose* GetCurrentPose() { return &mPose; } + MCORE_INLINE Pose* GetBindPose() const { return m_bindPose; } + MCORE_INLINE const Pose* GetCurrentPose() const { return &m_pose; } + MCORE_INLINE Pose* GetCurrentPose() { return &m_pose; } /** * Reset the local space transform of a given node to its bind pose local space transform. * @param nodeIndex The node number, which must be in range of [0..GetNumTransforms()-1]. */ - void ResetToBindPoseTransformation(uint32 nodeIndex) { mPose.SetLocalSpaceTransform(nodeIndex, mBindPose->GetLocalSpaceTransform(nodeIndex)); } + void ResetToBindPoseTransformation(size_t nodeIndex) { m_pose.SetLocalSpaceTransform(nodeIndex, m_bindPose->GetLocalSpaceTransform(nodeIndex)); } /** * Reset all local space transforms to the local space transforms of the bind pose. */ void ResetToBindPoseTransformations() { - for (uint32 i = 0; i < mNumTransforms; ++i) + for (size_t i = 0; i < m_numTransforms; ++i) { - mPose.SetLocalSpaceTransform(i, mBindPose->GetLocalSpaceTransform(i)); + m_pose.SetLocalSpaceTransform(i, m_bindPose->GetLocalSpaceTransform(i)); } } EMFX_SCALECODE ( - void SetBindPoseLocalScaleInherit(uint32 nodeIndex, const AZ::Vector3& scale); - void SetBindPoseLocalScale(uint32 nodeIndex, const AZ::Vector3& scale); + void SetBindPoseLocalScaleInherit(size_t nodeIndex, const AZ::Vector3& scale); + void SetBindPoseLocalScale(size_t nodeIndex, const AZ::Vector3& scale); ) - MCORE_INLINE const ActorInstance* GetActorInstance() const { return mPose.GetActorInstance(); } - MCORE_INLINE uint32 GetNumTransforms() const { return mNumTransforms; } + MCORE_INLINE const ActorInstance* GetActorInstance() const { return m_pose.GetActorInstance(); } + MCORE_INLINE size_t GetNumTransforms() const { return m_numTransforms; } void MakeBindPoseTransformsUnique(); - void SetNumMorphWeights(uint32 numMorphWeights); + void SetNumMorphWeights(size_t numMorphWeights); private: - Pose mPose; /**< The current pose. */ - Pose* mBindPose; /**< The bind pose, which can be unique or point to the bind pose in the actor. */ - AZ::Matrix3x4* mSkinningMatrices; /**< The matrices used for skinning. They are the offset to the bind pose. */ - uint32 mNumTransforms; /**< The number of transforms, which is equal to the number of nodes in the linked actor instance. */ - bool mHasUniqueBindPose; /**< Do we have a unique bind pose (when set to true) or do we use the one from the Actor object (when set to false)? */ + Pose m_pose; /**< The current pose. */ + Pose* m_bindPose; /**< The bind pose, which can be unique or point to the bind pose in the actor. */ + AZ::Matrix3x4* m_skinningMatrices; /**< The matrices used for skinning. They are the offset to the bind pose. */ + size_t m_numTransforms; /**< The number of transforms, which is equal to the number of nodes in the linked actor instance. */ + bool m_hasUniqueBindPose; /**< Do we have a unique bind pose (when set to true) or do we use the one from the Actor object (when set to false)? */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.cpp index 25614c17a9..722d599b2d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.cpp @@ -21,9 +21,9 @@ namespace EMotionFX VertexAttributeLayer::VertexAttributeLayer(uint32 numAttributes, bool keepOriginals) : BaseObject() { - mNumAttributes = numAttributes; - mKeepOriginals = keepOriginals; - mNameID = MCore::GetStringIdPool().GenerateIdForString(""); + m_numAttributes = numAttributes; + m_keepOriginals = keepOriginals; + m_nameId = MCore::GetStringIdPool().GenerateIdForString(""); } @@ -44,27 +44,27 @@ namespace EMotionFX // set the name void VertexAttributeLayer::SetName(const char* name) { - mNameID = MCore::GetStringIdPool().GenerateIdForString(name); + m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); } // get the name const char* VertexAttributeLayer::GetName() const { - return MCore::GetStringIdPool().GetName(mNameID).c_str(); + return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } // get the name string const AZStd::string& VertexAttributeLayer::GetNameString() const { - return MCore::GetStringIdPool().GetName(mNameID); + return MCore::GetStringIdPool().GetName(m_nameId); } // get the name ID uint32 VertexAttributeLayer::GetNameID() const { - return mNameID; + return m_nameId; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.h b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.h index 1affcb9b79..525061b5a7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayer.h @@ -72,7 +72,7 @@ namespace EMotionFX * Get the number of attributes inside this layer. * @result The number of attributes. */ - MCORE_INLINE uint32 GetNumAttributes() const { return mNumAttributes; } + MCORE_INLINE uint32 GetNumAttributes() const { return m_numAttributes; } /** * Check if this class also stores original vertex data or not. @@ -82,7 +82,7 @@ namespace EMotionFX * The initialization to the original data happens inside the ResetToOriginalData method. * @result Returns true when this class also stores the original (undeformed) data, next to the current (deformed) data. */ - MCORE_INLINE bool GetKeepOriginals() const { return mKeepOriginals; } + MCORE_INLINE bool GetKeepOriginals() const { return m_keepOriginals; } /** * Reset the layer data to it's original data. @@ -129,9 +129,9 @@ namespace EMotionFX protected: - uint32 mNumAttributes; /**< The number of attributes inside this layer. */ - uint32 mNameID; /**< The name ID. */ - bool mKeepOriginals; /**< Should we store a copy of the original data as well? */ + uint32 m_numAttributes; /**< The number of attributes inside this layer. */ + uint32 m_nameId; /**< The name ID. */ + bool m_keepOriginals; /**< Should we store a copy of the original data as well? */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.cpp index c0bf0c3a54..b1757c09d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.cpp @@ -20,22 +20,22 @@ namespace EMotionFX VertexAttributeLayerAbstractData::VertexAttributeLayerAbstractData(uint32 numAttributes, uint32 typeID, uint32 attribSizeInBytes, bool keepOriginals) : VertexAttributeLayer(numAttributes, keepOriginals) { - mData = nullptr; - mSwapBuffer = nullptr; - mTypeID = typeID; - mAttribSizeInBytes = attribSizeInBytes; + m_data = nullptr; + m_swapBuffer = nullptr; + m_typeId = typeID; + m_attribSizeInBytes = attribSizeInBytes; // allocate the data - const uint32 numBytes = CalcTotalDataSizeInBytes(mKeepOriginals); - mData = (uint8*)MCore::AlignedAllocate(numBytes, 16, EMFX_MEMCATEGORY_GEOMETRY_VERTEXATTRIBUTES); + const uint32 numBytes = CalcTotalDataSizeInBytes(m_keepOriginals); + m_data = (uint8*)MCore::AlignedAllocate(numBytes, 16, EMFX_MEMCATEGORY_GEOMETRY_VERTEXATTRIBUTES); } // the destructor VertexAttributeLayerAbstractData::~VertexAttributeLayerAbstractData() { - MCore::AlignedFree(mData); - MCore::AlignedFree(mSwapBuffer); + MCore::AlignedFree(m_data); + MCore::AlignedFree(m_swapBuffer); } @@ -49,7 +49,7 @@ namespace EMotionFX // get the layer type uint32 VertexAttributeLayerAbstractData::GetType() const { - return mTypeID; + return m_typeId; } @@ -63,13 +63,13 @@ namespace EMotionFX // calculate the total data size uint32 VertexAttributeLayerAbstractData::CalcTotalDataSizeInBytes(bool includeOriginals) const { - if (includeOriginals && mKeepOriginals) + if (includeOriginals && m_keepOriginals) { - return (mAttribSizeInBytes * mNumAttributes) << 1; // multiplied by two, as we store the originals right after it + return (m_attribSizeInBytes * m_numAttributes) << 1; // multiplied by two, as we store the originals right after it } else { - return mAttribSizeInBytes * mNumAttributes; + return m_attribSizeInBytes * m_numAttributes; } } @@ -78,13 +78,13 @@ namespace EMotionFX VertexAttributeLayer* VertexAttributeLayerAbstractData::Clone() { // create the clone - VertexAttributeLayerAbstractData* clone = aznew VertexAttributeLayerAbstractData(mNumAttributes, mTypeID, mAttribSizeInBytes, mKeepOriginals); + VertexAttributeLayerAbstractData* clone = aznew VertexAttributeLayerAbstractData(m_numAttributes, m_typeId, m_attribSizeInBytes, m_keepOriginals); // copy over the data uint8* cloneData = (uint8*)clone->GetData(); - MCore::MemCopy(cloneData, mData, CalcTotalDataSizeInBytes(true)); + MCore::MemCopy(cloneData, m_data, CalcTotalDataSizeInBytes(true)); - clone->mNameID = mNameID; + clone->m_nameId = m_nameId; return clone; } @@ -93,7 +93,7 @@ namespace EMotionFX void VertexAttributeLayerAbstractData::ResetToOriginalData() { // if we dont have any original data, there is nothing to do - if (mKeepOriginals == false) + if (m_keepOriginals == false) { return; } @@ -111,9 +111,9 @@ namespace EMotionFX void VertexAttributeLayerAbstractData::SwapAttributes(uint32 attribA, uint32 attribB) { // create a swap buffer if we haven't got it already - if (mSwapBuffer == nullptr) + if (m_swapBuffer == nullptr) { - mSwapBuffer = (uint8*)MCore::AlignedAllocate(mAttribSizeInBytes, 16, EMFX_MEMCATEGORY_GEOMETRY_VERTEXATTRIBUTES); + m_swapBuffer = (uint8*)MCore::AlignedAllocate(m_attribSizeInBytes, 16, EMFX_MEMCATEGORY_GEOMETRY_VERTEXATTRIBUTES); } // get the locations of where the attributes are stored @@ -121,18 +121,18 @@ namespace EMotionFX uint8* attribPtrB = (uint8*)GetData(attribB); // swap the attribute data - MCore::MemCopy(mSwapBuffer, attribPtrA, mAttribSizeInBytes); // copy attribute A into the temp swap buffer - MCore::MemCopy(attribPtrA, attribPtrB, mAttribSizeInBytes); // copy attribute B into A - MCore::MemCopy(attribPtrB, mSwapBuffer, mAttribSizeInBytes); // copy the temp swap buffer data into attribute B + MCore::MemCopy(m_swapBuffer, attribPtrA, m_attribSizeInBytes); // copy attribute A into the temp swap buffer + MCore::MemCopy(attribPtrA, attribPtrB, m_attribSizeInBytes); // copy attribute B into A + MCore::MemCopy(attribPtrB, m_swapBuffer, m_attribSizeInBytes); // copy the temp swap buffer data into attribute B // swap the originals - if (mKeepOriginals) + if (m_keepOriginals) { attribPtrA = (uint8*)GetOriginalData(attribA); attribPtrB = (uint8*)GetOriginalData(attribB); - MCore::MemCopy(mSwapBuffer, attribPtrA, mAttribSizeInBytes); // copy attribute A into the temp swap buffer - MCore::MemCopy(attribPtrA, attribPtrB, mAttribSizeInBytes); // copy attribute B into A - MCore::MemCopy(attribPtrB, mSwapBuffer, mAttribSizeInBytes); // copy the temp swap buffer data into attribute B + MCore::MemCopy(m_swapBuffer, attribPtrA, m_attribSizeInBytes); // copy attribute A into the temp swap buffer + MCore::MemCopy(attribPtrA, attribPtrB, m_attribSizeInBytes); // copy attribute B into A + MCore::MemCopy(attribPtrB, m_swapBuffer, m_attribSizeInBytes); // copy the temp swap buffer data into attribute B } } @@ -140,8 +140,8 @@ namespace EMotionFX // remove the swap buffer from memory void VertexAttributeLayerAbstractData::RemoveSwapBuffer() { - MCore::AlignedFree(mSwapBuffer); - mSwapBuffer = nullptr; + MCore::AlignedFree(m_swapBuffer); + m_swapBuffer = nullptr; } @@ -149,11 +149,11 @@ namespace EMotionFX void VertexAttributeLayerAbstractData::RemoveAttributes(uint32 startAttributeNr, uint32 endAttributeNr) { // perform some checks on the input data - MCORE_ASSERT(startAttributeNr < mNumAttributes); - MCORE_ASSERT(endAttributeNr < mNumAttributes); + MCORE_ASSERT(startAttributeNr < m_numAttributes); + MCORE_ASSERT(endAttributeNr < m_numAttributes); // Store the original number of bytes for the reallocation - const size_t numOriginalBytes = CalcTotalDataSizeInBytes(mKeepOriginals); + const size_t numOriginalBytes = CalcTotalDataSizeInBytes(m_keepOriginals); // make sure the start attribute number is lower than the end uint32 start = startAttributeNr; @@ -174,33 +174,33 @@ namespace EMotionFX } // remove the attributes from the current data - const uint32 numBytesToMove = (mNumAttributes - end - 1) * mAttribSizeInBytes; + const uint32 numBytesToMove = (m_numAttributes - end - 1) * m_attribSizeInBytes; if (numBytesToMove > 0) { - MCore::MemMove(mData + start * mAttribSizeInBytes, mData + (end + 1) * mAttribSizeInBytes, numBytesToMove); + MCore::MemMove(m_data + start * m_attribSizeInBytes, m_data + (end + 1) * m_attribSizeInBytes, numBytesToMove); } // remove the attributes from the original data - if (mKeepOriginals) + if (m_keepOriginals) { // remove them from the original data uint8* orgData = (uint8*)GetOriginalData(); if (numBytesToMove > 0) { - MCore::MemMove(orgData + start * mAttribSizeInBytes, orgData + (end + 1) * mAttribSizeInBytes, numBytesToMove); + MCore::MemMove(orgData + start * m_attribSizeInBytes, orgData + (end + 1) * m_attribSizeInBytes, numBytesToMove); } // remove the created gap between the current data and original data, as both original and current data remain in the same continuous piece of memory - MCore::MemMove(mData + (mNumAttributes - numAttribsToRemove) * mAttribSizeInBytes, orgData, (mNumAttributes - numAttribsToRemove) * mAttribSizeInBytes); + MCore::MemMove(m_data + (m_numAttributes - numAttribsToRemove) * m_attribSizeInBytes, orgData, (m_numAttributes - numAttribsToRemove) * m_attribSizeInBytes); } // decrease the number of attributes - mNumAttributes -= numAttribsToRemove; + m_numAttributes -= numAttribsToRemove; // reallocate, to make the data array smaller - const uint32 numBytes = CalcTotalDataSizeInBytes(mKeepOriginals); - mData = (uint8*)MCore::AlignedRealloc(mData, numBytes, numOriginalBytes, 16, EMFX_MEMCATEGORY_GEOMETRY_VERTEXATTRIBUTES); + const uint32 numBytes = CalcTotalDataSizeInBytes(m_keepOriginals); + m_data = (uint8*)MCore::AlignedRealloc(m_data, numBytes, numOriginalBytes, 16, EMFX_MEMCATEGORY_GEOMETRY_VERTEXATTRIBUTES); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.h b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.h index f2520e6b70..fcd625dbb3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/VertexAttributeLayerAbstractData.h @@ -92,13 +92,13 @@ namespace EMotionFX * Get a pointer to the data for a given attribute. You have to typecast the data yourself. * @result A pointer to the vertex data of the specified attribute number. */ - MCORE_INLINE void* GetData(uint32 attributeNr) { return (mData + mAttribSizeInBytes * attributeNr); } + MCORE_INLINE void* GetData(uint32 attributeNr) { return (m_data + m_attribSizeInBytes * attributeNr); } /** * Get a pointer to the data. You have to typecast the data yourself. * @result A pointer to the vertex data. */ - MCORE_INLINE void* GetData() override { return mData; } + MCORE_INLINE void* GetData() override { return m_data; } /** * Get the size of one attribute in bytes. @@ -106,7 +106,7 @@ namespace EMotionFX * equal to sizeof(Vector3). * @result The size of a single attribute, in bytes. */ - MCORE_INLINE uint32 GetAttributeSizeInBytes() const { return mAttribSizeInBytes; } + MCORE_INLINE uint32 GetAttributeSizeInBytes() const { return m_attribSizeInBytes; } /** * Get a pointer to the original data, as it is stored in the base pose, before any mesh deformers have been applied. @@ -115,13 +115,13 @@ namespace EMotionFX */ MCORE_INLINE void* GetOriginalData() override { - if (mKeepOriginals) + if (m_keepOriginals) { - return (mData + (mAttribSizeInBytes * mNumAttributes)); + return (m_data + (m_attribSizeInBytes * m_numAttributes)); } else { - return mData; + return m_data; } } @@ -132,13 +132,13 @@ namespace EMotionFX */ MCORE_INLINE void* GetOriginalData(uint32 attributeNr) { - if (mKeepOriginals) + if (m_keepOriginals) { - return (mData + (mAttribSizeInBytes * mNumAttributes) + (mAttribSizeInBytes * attributeNr)); + return (m_data + (m_attribSizeInBytes * m_numAttributes) + (m_attribSizeInBytes * attributeNr)); } else { - return (mData + mAttribSizeInBytes * attributeNr); + return (m_data + m_attribSizeInBytes * attributeNr); } } @@ -166,10 +166,10 @@ namespace EMotionFX bool GetIsAbstractDataClass() const override; private: - uint8* mData; /**< The buffer containing the data. */ - uint8* mSwapBuffer; /**< The swap buffer, used for swapping items. This will only be allocated once you call SwapAttribute, like the LOD generation system does. */ - uint32 mAttribSizeInBytes; /**< The size of a single attribute, in bytes. */ - uint32 mTypeID; /**< The type ID that identifies the type of the data, for example if it is position data, normal data, or colors, etc. */ + uint8* m_data; /**< The buffer containing the data. */ + uint8* m_swapBuffer; /**< The swap buffer, used for swapping items. This will only be allocated once you call SwapAttribute, like the LOD generation system does. */ + uint32 m_attribSizeInBytes; /**< The size of a single attribute, in bytes. */ + uint32 m_typeId; /**< The type ID that identifies the type of the data, for example if it is position data, normal data, or colors, etc. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp index 4fb82ec3e1..b46fa645d1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Commands.cpp @@ -396,8 +396,8 @@ namespace EMStudio { motionSet->SetDirtyFlag(dirtyFlag); - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { EMotionFX::MotionSet* childSet = motionSet->GetChildSet(i); RecursiveSetDirtyFlag(childSet, dirtyFlag); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.cpp index 26addcf6e8..4c62d48610 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.cpp @@ -19,23 +19,23 @@ namespace EMStudio // constructor DockWidgetPlugin::DockWidgetPlugin() : EMStudioPlugin() - , mDock() + , m_dock() { } // destructor DockWidgetPlugin::~DockWidgetPlugin() { - if (!mDock.isNull()) + if (!m_dock.isNull()) { - // Disconnecting all signals from mDock to this object since we are + // Disconnecting all signals from m_dock to this object since we are // destroying it. Some plugins connect to visibility change that gets // triggered from removeDockWidget. Calling those slots at this point // is not safe since the plugin is being destroyed. - mDock->disconnect(this); + m_dock->disconnect(this); - EMStudio::GetMainWindow()->removeDockWidget(mDock); - delete mDock; + EMStudio::GetMainWindow()->removeDockWidget(m_dock); + delete m_dock; } } @@ -47,13 +47,13 @@ namespace EMStudio // check if we have a window that uses this object name bool DockWidgetPlugin::GetHasWindowWithObjectName(const AZStd::string& objectName) { - if (mDock.isNull()) + if (m_dock.isNull()) { return false; } // check if the object name is equal to the one of the dock widget - return objectName == FromQtString(mDock->objectName()); + return objectName == FromQtString(m_dock->objectName()); } @@ -75,25 +75,25 @@ namespace EMStudio // set the interface title void DockWidgetPlugin::SetInterfaceTitle(const char* name) { - if (!mDock.isNull()) + if (!m_dock.isNull()) { - mDock->setWindowTitle(name); + m_dock->setWindowTitle(name); } } QDockWidget* DockWidgetPlugin::GetDockWidget() { - if (!mDock.isNull()) + if (!m_dock.isNull()) { - return mDock; + return m_dock; } // get the main window QMainWindow* mainWindow = GetMainWindow(); // create a window for the plugin - mDock = new RemovePluginOnCloseDockWidget(mainWindow, GetName(), this); - mDock->setAllowedAreas(Qt::AllDockWidgetAreas); + m_dock = new RemovePluginOnCloseDockWidget(mainWindow, GetName(), this); + m_dock->setAllowedAreas(Qt::AllDockWidgetAreas); QDockWidget::DockWidgetFeatures features = QDockWidget::NoDockWidgetFeatures; if (GetIsClosable()) @@ -113,11 +113,11 @@ namespace EMStudio features |= QDockWidget::DockWidgetFloatable; } - mDock->setFeatures(features); + m_dock->setFeatures(features); - mainWindow->addDockWidget(Qt::RightDockWidgetArea, mDock); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, m_dock); - return mDock; + return m_dock; } QWidget* DockWidgetPlugin::CreateErrorContentWidget(const char* errorMessage) const diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.h index ac58dd9be7..0db8a68ff6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/DockWidgetPlugin.h @@ -41,7 +41,7 @@ namespace EMStudio virtual void SetInterfaceTitle(const char* name); void CreateBaseInterface(const char* objectName) override; - QString GetObjectName() const override { AZ_Assert(mDock, "mDock is null"); return mDock->objectName(); } + QString GetObjectName() const override { AZ_Assert(m_dock, "m_dock is null"); return m_dock->objectName(); } void SetObjectName(const QString& name) override { GetDockWidget()->setObjectName(name); } virtual QSize GetInitialWindowSize() const { return QSize(500, 650); } @@ -53,6 +53,6 @@ namespace EMStudio protected: QWidget* CreateErrorContentWidget(const char* errorMessage) const; - QPointer mDock; + QPointer m_dock; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp index 93073891de..2321d7c71b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.cpp @@ -62,12 +62,12 @@ namespace EMStudio // Flag that we have an editor around EMotionFX::GetEMotionFX().SetIsInEditorMode(true); - mHTMLLinkString.reserve(32768); - mEventProcessingCallback = nullptr; - mAutoLoadLastWorkspace = false; - mAvoidRendering = false; + m_htmlLinkString.reserve(32768); + m_eventProcessingCallback = nullptr; + m_autoLoadLastWorkspace = false; + m_avoidRendering = false; - mApp = app; + m_app = app; AZ::AllocatorInstance::Create(); @@ -86,20 +86,20 @@ namespace EMStudio MCore::GetLogManager().SetLogLevels(MCore::LogCallback::LOGLEVEL_ALL); // Register editor specific commands. - mCommandManager = new CommandSystem::CommandManager(); - mCommandManager->RegisterCommand(new CommandSaveActorAssetInfo()); - mCommandManager->RegisterCommand(new CommandSaveMotionAssetInfo()); - mCommandManager->RegisterCommand(new CommandSaveMotionSet()); - mCommandManager->RegisterCommand(new CommandSaveAnimGraph()); - mCommandManager->RegisterCommand(new CommandSaveWorkspace()); - mCommandManager->RegisterCommand(new CommandEditorLoadAnimGraph()); - mCommandManager->RegisterCommand(new CommandEditorLoadMotionSet()); - - mEventPresetManager = new MotionEventPresetManager(); - mPluginManager = new PluginManager(); - mLayoutManager = new LayoutManager(); - mNotificationWindowManager = new NotificationWindowManager(); - mCompileDate = AZStd::string::format("%s", MCORE_DATE); + m_commandManager = new CommandSystem::CommandManager(); + m_commandManager->RegisterCommand(new CommandSaveActorAssetInfo()); + m_commandManager->RegisterCommand(new CommandSaveMotionAssetInfo()); + m_commandManager->RegisterCommand(new CommandSaveMotionSet()); + m_commandManager->RegisterCommand(new CommandSaveAnimGraph()); + m_commandManager->RegisterCommand(new CommandSaveWorkspace()); + m_commandManager->RegisterCommand(new CommandEditorLoadAnimGraph()); + m_commandManager->RegisterCommand(new CommandEditorLoadMotionSet()); + + m_eventPresetManager = new MotionEventPresetManager(); + m_pluginManager = new PluginManager(); + m_layoutManager = new LayoutManager(); + m_notificationWindowManager = new NotificationWindowManager(); + m_compileDate = AZStd::string::format("%s", MCORE_DATE); EMotionFX::SkeletonOutlinerNotificationBus::Handler::BusConnect(); @@ -113,33 +113,33 @@ namespace EMStudio { EMotionFX::SkeletonOutlinerNotificationBus::Handler::BusDisconnect(); - if (mEventProcessingCallback) + if (m_eventProcessingCallback) { - EMStudio::GetCommandManager()->RemoveCallback(mEventProcessingCallback, false); - delete mEventProcessingCallback; + EMStudio::GetCommandManager()->RemoveCallback(m_eventProcessingCallback, false); + delete m_eventProcessingCallback; } // delete all animgraph instances etc ClearScene(); - delete mEventPresetManager; - delete mPluginManager; - delete mLayoutManager; - delete mNotificationWindowManager; - delete mMainWindow; - delete mCommandManager; + delete m_eventPresetManager; + delete m_pluginManager; + delete m_layoutManager; + delete m_notificationWindowManager; + delete m_mainWindow; + delete m_commandManager; AZ::AllocatorInstance::Destroy(); } MainWindow* EMStudioManager::GetMainWindow() { - if (mMainWindow.isNull()) + if (m_mainWindow.isNull()) { - mMainWindow = new MainWindow(); - mMainWindow->Init(); + m_mainWindow = new MainWindow(); + m_mainWindow->Init(); } - return mMainWindow; + return m_mainWindow; } @@ -166,18 +166,18 @@ namespace EMStudio int EMStudioManager::ExecuteApp() { - MCORE_ASSERT(mApp); - MCORE_ASSERT(mMainWindow); + MCORE_ASSERT(m_app); + MCORE_ASSERT(m_mainWindow); #if !defined(EMFX_EMSTUDIOLYEMBEDDED) // try to load all plugins AZStd::string pluginDir = MysticQt::GetAppDir() + "Plugins/"; - mPluginManager->LoadPluginsFromDirectory(pluginDir.c_str()); + m_pluginManager->LoadPluginsFromDirectory(pluginDir.c_str()); #endif // EMFX_EMSTUDIOLYEMBEDDED // Give a chance to every plugin to reflect data - const uint32 numPlugins = mPluginManager->GetNumPlugins(); + const size_t numPlugins = m_pluginManager->GetNumPlugins(); if (numPlugins) { AZ::SerializeContext* serializeContext = nullptr; @@ -188,33 +188,33 @@ namespace EMStudio } else { - for (uint32 i = 0; i < numPlugins; ++i) + for (size_t i = 0; i < numPlugins; ++i) { - EMStudioPlugin* plugin = mPluginManager->GetPlugin(i); + EMStudioPlugin* plugin = m_pluginManager->GetPlugin(i); plugin->Reflect(serializeContext); } } } // Register the command event processing callback. - mEventProcessingCallback = new EventProcessingCallback(); - EMStudio::GetCommandManager()->RegisterCallback(mEventProcessingCallback); + m_eventProcessingCallback = new EventProcessingCallback(); + EMStudio::GetCommandManager()->RegisterCallback(m_eventProcessingCallback); // Update the main window create window item with, so that it shows all loaded plugins. - mMainWindow->UpdateCreateWindowMenu(); + m_mainWindow->UpdateCreateWindowMenu(); // Set the recover save path. - MCore::FileSystem::mSecureSavePath = GetManager()->GetRecoverFolder().c_str(); + MCore::FileSystem::s_secureSavePath = GetManager()->GetRecoverFolder().c_str(); // Show the main dialog and wait until it closes. MCore::LogInfo("EMotion Studio initialized..."); #if !defined(EMFX_EMSTUDIOLYEMBEDDED) - mMainWindow->show(); + m_mainWindow->show(); #endif // EMFX_EMSTUDIOLYEMBEDDED // Show the recover window in case we have some .recover files in the recovery folder. - const QString secureSavePath = MCore::FileSystem::mSecureSavePath.c_str(); + const QString secureSavePath = MCore::FileSystem::s_secureSavePath.c_str(); const QStringList recoverFileList = QDir(secureSavePath).entryList(QStringList("*.recover"), QDir::Files); if (!recoverFileList.empty()) { @@ -240,16 +240,16 @@ namespace EMStudio // Show the recover files window only in case there is a valid file to recover. if (!recoverStringArray.empty()) { - RecoverFilesWindow* recoverFilesWindow = new RecoverFilesWindow(mMainWindow, recoverStringArray); + RecoverFilesWindow* recoverFilesWindow = new RecoverFilesWindow(m_mainWindow, recoverStringArray); recoverFilesWindow->exec(); } } - mApp->processEvents(); + m_app->processEvents(); #if !defined(EMFX_EMSTUDIOLYEMBEDDED) // execute the application - return mApp->exec(); + return m_app->exec(); #else return 0; #endif // EMFX_EMSTUDIOLYEMBEDDED @@ -263,12 +263,12 @@ namespace EMStudio const char* EMStudioManager::ConstructHTMLLink(const char* text, const MCore::RGBAColor& color) { - int32 r = aznumeric_cast(color.r * 256); - int32 g = aznumeric_cast(color.g * 256); - int32 b = aznumeric_cast(color.b * 256); + int32 r = aznumeric_cast(color.m_r * 256); + int32 g = aznumeric_cast(color.m_g * 256); + int32 b = aznumeric_cast(color.m_b * 256); - mHTMLLinkString = AZStd::string::format("%s", r, g, b, text, text); - return mHTMLLinkString.c_str(); + m_htmlLinkString = AZStd::string::format("%s", r, g, b, text, text); + return m_htmlLinkString.c_str(); } @@ -320,12 +320,12 @@ namespace EMStudio } - void EMStudioManager::SetVisibleJointIndices(const AZStd::unordered_set& visibleJointIndices) + void EMStudioManager::SetVisibleJointIndices(const AZStd::unordered_set& visibleJointIndices) { m_visibleJointIndices = visibleJointIndices; } - void EMStudioManager::SetSelectedJointIndices(const AZStd::unordered_set& selectedJointIndices) + void EMStudioManager::SetSelectedJointIndices(const AZStd::unordered_set& selectedJointIndices) { m_selectedJointIndices = selectedJointIndices; } @@ -432,7 +432,7 @@ namespace EMStudio } // add and return the manipulator - mTransformationManipulators.Add(manipulator); + m_transformationManipulators.emplace_back(manipulator); return manipulator; } @@ -440,14 +440,17 @@ namespace EMStudio // remove the given gizmo from the array void EMStudioManager::RemoveTransformationManipulator(MCommon::TransformationManipulator* manipulator) { - mTransformationManipulators.RemoveByValue(manipulator); + if (const auto it = AZStd::find(begin(m_transformationManipulators), end(m_transformationManipulators), manipulator); it != end(m_transformationManipulators)) + { + m_transformationManipulators.erase(it); + } } // returns the gizmo array - MCore::Array* EMStudioManager::GetTransformationManipulators() + AZStd::vector* EMStudioManager::GetTransformationManipulators() { - return &mTransformationManipulators; + return &m_transformationManipulators; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h index c485d15b01..909f0231f3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioManager.h @@ -59,15 +59,15 @@ namespace EMStudio EMStudioManager(QApplication* app, int& argc, char* argv[]); ~EMStudioManager(); - const char* GetCompileDate() const { return mCompileDate.c_str(); } + const char* GetCompileDate() const { return m_compileDate.c_str(); } - MCORE_INLINE QApplication* GetApp() { return mApp; } - MCORE_INLINE bool HasMainWindow() const { return !mMainWindow.isNull(); } + MCORE_INLINE QApplication* GetApp() { return m_app; } + MCORE_INLINE bool HasMainWindow() const { return !m_mainWindow.isNull(); } MainWindow* GetMainWindow(); - MCORE_INLINE PluginManager* GetPluginManager() { return mPluginManager; } - MCORE_INLINE LayoutManager* GetLayoutManager() { return mLayoutManager; } - MCORE_INLINE NotificationWindowManager* GetNotificationWindowManager() { return mNotificationWindowManager; } - MCORE_INLINE CommandSystem::CommandManager* GetCommandManager() { return mCommandManager; } + MCORE_INLINE PluginManager* GetPluginManager() { return m_pluginManager; } + MCORE_INLINE LayoutManager* GetLayoutManager() { return m_layoutManager; } + MCORE_INLINE NotificationWindowManager* GetNotificationWindowManager() { return m_notificationWindowManager; } + MCORE_INLINE CommandSystem::CommandManager* GetCommandManager() { return m_commandManager; } AZStd::string GetAppDataFolder() const; AZStd::string GetRecoverFolder() const; AZStd::string GetAutosavesFolder() const; @@ -76,10 +76,10 @@ namespace EMStudio static void RenderText(QPainter& painter, const QString& text, const QColor& textColor, const QFont& font, const QFontMetrics& fontMetrics, Qt::Alignment textAlignment, const QRect& rect); // motion event presets - MotionEventPresetManager* GetEventPresetManger() const { return mEventPresetManager; } + MotionEventPresetManager* GetEventPresetManger() const { return m_eventPresetManager; } - void SetAutoLoadLastWorkspace(bool autoLoad) { mAutoLoadLastWorkspace = autoLoad; } - bool GetAutoLoadLastWorkspace() const { return mAutoLoadLastWorkspace; } + void SetAutoLoadLastWorkspace(bool autoLoad) { m_autoLoadLastWorkspace = autoLoad; } + bool GetAutoLoadLastWorkspace() const { return m_autoLoadLastWorkspace; } const char* ConstructHTMLLink(const char* text, const MCore::RGBAColor& color = MCore::RGBAColor(0.95315f, 0.609375f, 0.109375f)); void SetWidgetAsInvalidInput(QWidget* widget); @@ -93,44 +93,44 @@ namespace EMStudio void LogInfo(); // in case the array is empty, all nodes are shown - void SetVisibleJointIndices(const AZStd::unordered_set& visibleJointIndices); - const AZStd::unordered_set& GetVisibleJointIndices() const { return m_visibleJointIndices; } + void SetVisibleJointIndices(const AZStd::unordered_set& visibleJointIndices); + const AZStd::unordered_set& GetVisibleJointIndices() const { return m_visibleJointIndices; } - void SetSelectedJointIndices(const AZStd::unordered_set& selectedJointIndices); - const AZStd::unordered_set& GetSelectedJointIndices() const { return m_selectedJointIndices; } + void SetSelectedJointIndices(const AZStd::unordered_set& selectedJointIndices); + const AZStd::unordered_set& GetSelectedJointIndices() const { return m_selectedJointIndices; } - Workspace* GetWorkspace() { return &mWorkspace; } + Workspace* GetWorkspace() { return &m_workspace; } // functions for adding/removing gizmos MCommon::TransformationManipulator* AddTransformationManipulator(MCommon::TransformationManipulator* manipulator); void RemoveTransformationManipulator(MCommon::TransformationManipulator* manipulator); - MCore::Array* GetTransformationManipulators(); + AZStd::vector* GetTransformationManipulators(); void ClearScene(); // remove animgraphs, animgraph instances and actors - MCORE_INLINE bool GetAvoidRendering() const { return mAvoidRendering; } - MCORE_INLINE void SetAvoidRendering(bool avoidRendering) { mAvoidRendering = avoidRendering; } - MCORE_INLINE bool GetIgnoreVisibility() const { return mIgnoreVisible; } - MCORE_INLINE void SetIgnoreVisibility(bool ignoreVisible) { mIgnoreVisible = ignoreVisible; } + MCORE_INLINE bool GetAvoidRendering() const { return m_avoidRendering; } + MCORE_INLINE void SetAvoidRendering(bool avoidRendering) { m_avoidRendering = avoidRendering; } + MCORE_INLINE bool GetIgnoreVisibility() const { return m_ignoreVisible; } + MCORE_INLINE void SetIgnoreVisibility(bool ignoreVisible) { m_ignoreVisible = ignoreVisible; } MCORE_INLINE bool GetSkipSourceControlCommands() { return m_skipSourceControlCommands; } MCORE_INLINE void SetSkipSourceControlCommands(bool skip) { m_skipSourceControlCommands = skip; } private: - MCore::Array mTransformationManipulators; - QPointer mMainWindow; - QApplication* mApp; - PluginManager* mPluginManager; - LayoutManager* mLayoutManager; - NotificationWindowManager* mNotificationWindowManager; - CommandSystem::CommandManager* mCommandManager; - AZStd::string mCompileDate; - AZStd::unordered_set m_visibleJointIndices; - AZStd::unordered_set m_selectedJointIndices; - Workspace mWorkspace; - bool mAutoLoadLastWorkspace; - AZStd::string mHTMLLinkString; - bool mAvoidRendering; - bool mIgnoreVisible = false; - MotionEventPresetManager* mEventPresetManager; + AZStd::vector m_transformationManipulators; + QPointer m_mainWindow; + QApplication* m_app; + PluginManager* m_pluginManager; + LayoutManager* m_layoutManager; + NotificationWindowManager* m_notificationWindowManager; + CommandSystem::CommandManager* m_commandManager; + AZStd::string m_compileDate; + AZStd::unordered_set m_visibleJointIndices; + AZStd::unordered_set m_selectedJointIndices; + Workspace m_workspace; + bool m_autoLoadLastWorkspace; + AZStd::string m_htmlLinkString; + bool m_avoidRendering; + bool m_ignoreVisible = false; + MotionEventPresetManager* m_eventPresetManager; bool m_skipSourceControlCommands = false; // SkeletonOutlinerNotificationBus @@ -146,11 +146,11 @@ namespace EMStudio void OnPostExecuteCommand(MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine, bool wasSuccess, const AZStd::string& outResult) override; void OnPreExecuteCommandGroup(MCore::CommandGroup* group, bool undo) override { MCORE_UNUSED(group); MCORE_UNUSED(undo); } void OnPostExecuteCommandGroup(MCore::CommandGroup* group, bool wasSuccess) override { MCORE_UNUSED(group); MCORE_UNUSED(wasSuccess); } - void OnAddCommandToHistory(uint32 historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) override { MCORE_UNUSED(historyIndex); MCORE_UNUSED(group); MCORE_UNUSED(command); MCORE_UNUSED(commandLine); } - void OnRemoveCommand(uint32 historyIndex) override { MCORE_UNUSED(historyIndex); } - void OnSetCurrentCommand(uint32 index) override { MCORE_UNUSED(index); } + void OnAddCommandToHistory(size_t historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) override { MCORE_UNUSED(historyIndex); MCORE_UNUSED(group); MCORE_UNUSED(command); MCORE_UNUSED(commandLine); } + void OnRemoveCommand(size_t historyIndex) override { MCORE_UNUSED(historyIndex); } + void OnSetCurrentCommand(size_t index) override { MCORE_UNUSED(index); } }; - EventProcessingCallback* mEventProcessingCallback; + EventProcessingCallback* m_eventProcessingCallback; }; 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 49f306c7e0..0de4ab946c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioPlugin.h @@ -80,16 +80,16 @@ namespace EMStudio RenderInfo(MCommon::RenderUtil* renderUtil, MCommon::Camera* camera, uint32 screenWidth, uint32 screenHeight) { - mRenderUtil = renderUtil; - mCamera = camera; - mScreenWidth = screenWidth; - mScreenHeight = screenHeight; + m_renderUtil = renderUtil; + m_camera = camera; + m_screenWidth = screenWidth; + m_screenHeight = screenHeight; } - MCommon::RenderUtil* mRenderUtil; - MCommon::Camera* mCamera; - uint32 mScreenWidth; - uint32 mScreenHeight; + MCommon::RenderUtil* m_renderUtil; + MCommon::Camera* m_camera; + uint32 m_screenWidth; + uint32 m_screenHeight; }; virtual void Render(RenderPlugin* renderPlugin, RenderInfo* renderInfo) { MCORE_UNUSED(renderPlugin); MCORE_UNUSED(renderInfo); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.cpp index 76febd63cf..5a89729e49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.cpp @@ -46,11 +46,11 @@ namespace EMStudio FileManager::FileManager(QWidget* parent) : QObject(parent) { - mLastActorFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); - mLastMotionSetFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); - mLastAnimGraphFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); - mLastWorkspaceFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); - mLastNodeMapFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); + m_lastActorFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); + m_lastMotionSetFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); + m_lastAnimGraphFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); + m_lastWorkspaceFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); + m_lastNodeMapFolder = EMotionFX::GetEMotionFX().GetAssetSourceFolder().c_str(); // Connect to the asset catalog bus for product asset changes. AzFramework::AssetCatalogEventBus::Handler::BusConnect(); @@ -89,8 +89,8 @@ namespace EMStudio if (AzFramework::StringFunc::Equal(extension.c_str(), "motion")) { - const AZ::u32 motionCount = EMotionFX::GetMotionManager().GetNumMotions(); - for (AZ::u32 i = 0; i < motionCount; ++i) + const size_t motionCount = EMotionFX::GetMotionManager().GetNumMotions(); + for (size_t i = 0; i < motionCount; ++i) { EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); if (motion->GetIsOwnedByRuntime()) @@ -107,8 +107,8 @@ namespace EMStudio if (AzFramework::StringFunc::Equal(extension.c_str(), "actor")) { - const AZ::u32 actorCount = EMotionFX::GetActorManager().GetNumActors(); - for (AZ::u32 i = 0; i < actorCount; ++i) + const size_t actorCount = EMotionFX::GetActorManager().GetNumActors(); + for (size_t i = 0; i < actorCount; ++i) { EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); if (actor->GetIsOwnedByRuntime()) @@ -202,8 +202,8 @@ namespace EMStudio if (AzFramework::StringFunc::Equal(extension.c_str(), "motionset")) { - const AZ::u32 motionSetCount = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (AZ::u32 i = 0; i < motionSetCount; ++i) + const size_t motionSetCount = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < motionSetCount; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); if (motionSet->GetIsOwnedByRuntime()) @@ -220,8 +220,8 @@ namespace EMStudio if (AzFramework::StringFunc::Equal(extension.c_str(), "animgraph")) { - const AZ::u32 animGraphCount = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (AZ::u32 i = 0; i < animGraphCount; ++i) + const size_t animGraphCount = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < animGraphCount; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (animGraph->GetIsOwnedByRuntime()) @@ -416,14 +416,14 @@ namespace EMStudio QString selectedFilter; const AZStd::string filename = QFileDialog::getSaveFileName(parent, // parent "Save", // caption - GetLastUsedFolder(mLastActorFolder), // directory + GetLastUsedFolder(m_lastActorFolder), // directory "EMotion FX Actor Files (*.actor)", &selectedFilter, options).toUtf8().data(); GetManager()->SetAvoidRendering(false); - UpdateLastUsedFolder(filename.c_str(), mLastActorFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastActorFolder); return filename; } @@ -456,12 +456,12 @@ namespace EMStudio QString selectedFilter; AZStd::string filename = QFileDialog::getOpenFileName(parent, // parent "Open", // caption - GetLastUsedFolder(mLastWorkspaceFolder), // directory + GetLastUsedFolder(m_lastWorkspaceFolder), // directory "EMotionFX Editor Workspace Files (*.emfxworkspace);;All Files (*)", &selectedFilter, options).toUtf8().data(); - UpdateLastUsedFolder(filename.c_str(), mLastWorkspaceFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastWorkspaceFolder); GetManager()->SetAvoidRendering(false); return filename; } @@ -475,7 +475,7 @@ namespace EMStudio QString selectedFilter; AZStd::string filename = QFileDialog::getSaveFileName(parent, // parent "Save", // caption - GetLastUsedFolder(mLastWorkspaceFolder), // directory + GetLastUsedFolder(m_lastWorkspaceFolder), // directory "EMotionFX Editor Workspace Files (*.emfxworkspace)", &selectedFilter, options).toUtf8().data(); @@ -488,7 +488,7 @@ namespace EMStudio return AZStd::string(); } - UpdateLastUsedFolder(filename.c_str(), mLastWorkspaceFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastWorkspaceFolder); return filename; } @@ -557,20 +557,20 @@ namespace EMStudio QString selectedFilter; AZStd::string filename = QFileDialog::getSaveFileName(parent, // parent "Save", // caption - GetLastUsedFolder(mLastMotionSetFolder), // directory + GetLastUsedFolder(m_lastMotionSetFolder), // directory "EMotion FX Motion Set Files (*.motionset)", &selectedFilter, options).toUtf8().data(); GetManager()->SetAvoidRendering(false); - UpdateLastUsedFolder(filename.c_str(), mLastMotionSetFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastMotionSetFolder); return filename; } - void FileManager::SaveMotionSet(const char* filename, EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup) + void FileManager::SaveMotionSet(const char* filename, const EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup) { const AZStd::string command = AZStd::string::format("SaveMotionSet -motionSetID %i -filename \"%s\"", motionSet->GetID(), filename); @@ -595,7 +595,7 @@ namespace EMStudio } - void FileManager::SaveMotionSet(QWidget* parent, EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup) + void FileManager::SaveMotionSet(QWidget* parent, const EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup) { AZStd::string filename = motionSet->GetFilename(); @@ -636,14 +636,14 @@ namespace EMStudio QString selectedFilter; AZStd::string filename = QFileDialog::getSaveFileName(parent, // parent "Save", // caption - GetLastUsedFolder(mLastAnimGraphFolder), // directory + GetLastUsedFolder(m_lastAnimGraphFolder), // directory "EMotion FX Anim Graph Files (*.animgraph);;All Files (*)", &selectedFilter, options).toUtf8().data(); GetManager()->SetAvoidRendering(false); - UpdateLastUsedFolder(filename.c_str(), mLastAnimGraphFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastAnimGraphFolder); return filename; } @@ -658,14 +658,14 @@ namespace EMStudio QString selectedFilter; const AZStd::string filename = QFileDialog::getOpenFileName(parent, // parent "Open", // caption - GetLastUsedFolder(mLastNodeMapFolder), // directory + GetLastUsedFolder(m_lastNodeMapFolder), // directory "Node Map Files (*.nodeMap);;All Files (*)", &selectedFilter, options).toUtf8().data(); GetManager()->SetAvoidRendering(false); - UpdateLastUsedFolder(filename.c_str(), mLastNodeMapFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastNodeMapFolder); return filename; } @@ -679,14 +679,14 @@ namespace EMStudio QString selectedFilter; const AZStd::string filename = QFileDialog::getSaveFileName(parent, // parent "Save", // caption - GetLastUsedFolder(mLastNodeMapFolder), // directory + GetLastUsedFolder(m_lastNodeMapFolder), // directory "Node Map Files (*.nodeMap);;All Files (*)", &selectedFilter, options).toUtf8().data(); GetManager()->SetAvoidRendering(false); - UpdateLastUsedFolder(filename.c_str(), mLastNodeMapFolder); + UpdateLastUsedFolder(filename.c_str(), m_lastNodeMapFolder); return filename; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h index e27a9c23b5..98d7de188d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/FileManager.h @@ -21,7 +21,7 @@ #include #include "EMStudioConfig.h" #include -#include +#include #include #include #include @@ -82,8 +82,8 @@ namespace EMStudio // motion set file dialogs AZStd::string LoadMotionSetFileDialog(QWidget* parent); AZStd::string SaveMotionSetFileDialog(QWidget* parent); - void SaveMotionSet(QWidget* parent, EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup = nullptr); - void SaveMotionSet(const char* filename, EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup = nullptr); + void SaveMotionSet(QWidget* parent, const EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup = nullptr); + void SaveMotionSet(const char* filename, const EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup = nullptr); // motion file dialogs AZStd::string LoadMotionFileDialog(QWidget* parent); @@ -106,13 +106,13 @@ namespace EMStudio private: AZStd::vector m_savedSourceAssets; - QString mLastActorFolder; - QString mLastMotionSetFolder; - QString mLastAnimGraphFolder; - QString mLastWorkspaceFolder; - QString mLastNodeMapFolder; + QString m_lastActorFolder; + QString m_lastMotionSetFolder; + QString m_lastAnimGraphFolder; + QString m_lastWorkspaceFolder; + QString m_lastNodeMapFolder; - bool mSkipFileChangedCheck; + bool m_skipFileChangedCheck; void UpdateLastUsedFolder(const char* filename, QString& outLastFolder) const; QString GetLastUsedFolder(const QString& lastUsedFolder) const; 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 7355b1da0a..bccf4e1be3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.cpp @@ -34,8 +34,8 @@ namespace EMStudio KeyboardShortcutsWindow::KeyboardShortcutsWindow(QWidget* parent) : QWidget(parent) { - mSelectedGroup = -1; - mShortcutReceiverDialog = nullptr; + m_selectedGroup = -1; + m_shortcutReceiverDialog = nullptr; // fill the table Init(); @@ -52,51 +52,51 @@ namespace EMStudio void KeyboardShortcutsWindow::Init() { // create the node groups table - mTableWidget = new QTableWidget(); + m_tableWidget = new QTableWidget(); // create the table widget - mTableWidget->setSortingEnabled(false); - mTableWidget->setAlternatingRowColors(true); - mTableWidget->setCornerButtonEnabled(false); - mTableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mTableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); + m_tableWidget->setSortingEnabled(false); + m_tableWidget->setAlternatingRowColors(true); + m_tableWidget->setCornerButtonEnabled(false); + m_tableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); // set the table to row single selection - mTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTableWidget->setSelectionMode(QAbstractItemView::SingleSelection); + m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); - connect(mTableWidget, &QTableWidget::cellDoubleClicked, this, &KeyboardShortcutsWindow::OnShortcutChange); + connect(m_tableWidget, &QTableWidget::cellDoubleClicked, this, &KeyboardShortcutsWindow::OnShortcutChange); // create the list widget - mListWidget = new QListWidget(); - mListWidget->setAlternatingRowColors(true); - connect(mListWidget, &QListWidget::itemSelectionChanged, this, &KeyboardShortcutsWindow::OnGroupSelectionChanged); + m_listWidget = new QListWidget(); + m_listWidget->setAlternatingRowColors(true); + connect(m_listWidget, &QListWidget::itemSelectionChanged, this, &KeyboardShortcutsWindow::OnGroupSelectionChanged); // build the layout - mHLayout = new QHBoxLayout(); - mHLayout->setMargin(0); - mHLayout->setAlignment(Qt::AlignLeft); + m_hLayout = new QHBoxLayout(); + m_hLayout->setMargin(0); + m_hLayout->setAlignment(Qt::AlignLeft); - mHLayout->addWidget(mListWidget); + m_hLayout->addWidget(m_listWidget); QVBoxLayout* vLayout = new QVBoxLayout(); vLayout->setMargin(0); - vLayout->addWidget(mTableWidget); + vLayout->addWidget(m_tableWidget); QLabel* label = new QLabel("Double-click to adjust shortcut"); label->setAlignment(Qt::AlignCenter); vLayout->addWidget(label); - mHLayout->addLayout(vLayout); + m_hLayout->addLayout(vLayout); // set the main layout - setLayout(mHLayout); + setLayout(m_hLayout); ReInit(); // automatically select the first entry - if (mListWidget->count() > 0) + if (m_listWidget->count() > 0) { - mListWidget->setCurrentRow(0); + m_listWidget->setCurrentRow(0); } } @@ -115,14 +115,14 @@ namespace EMStudio // reconstruct the whole interface void KeyboardShortcutsWindow::ReInit() { - mTableWidget->blockSignals(true); + m_tableWidget->blockSignals(true); // clear - mListWidget->clear(); + m_listWidget->clear(); // make the list widget smaller than the table - mListWidget->setMinimumWidth(150); - mListWidget->setMaximumWidth(150); + m_listWidget->setMinimumWidth(150); + m_listWidget->setMaximumWidth(150); // add the groups to the left list widget MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); @@ -130,13 +130,13 @@ namespace EMStudio for (uint32 i = 0; i < numGroups; ++i) { MysticQt::KeyboardShortcutManager::Group* group = shortcutManager->GetGroup(i); - mListWidget->addItem(FromStdString(group->GetName())); + m_listWidget->addItem(FromStdString(group->GetName())); } - mTableWidget->blockSignals(false); + m_tableWidget->blockSignals(false); // automatically select the first entry - mListWidget->setCurrentRow(mSelectedGroup); + m_listWidget->setCurrentRow(m_selectedGroup); } @@ -144,37 +144,37 @@ namespace EMStudio void KeyboardShortcutsWindow::OnGroupSelectionChanged() { // get the group index - mSelectedGroup = mListWidget->currentRow(); - if (mSelectedGroup == -1) + m_selectedGroup = m_listWidget->currentRow(); + if (m_selectedGroup == -1) { return; } // clear the table - mTableWidget->clear(); + m_tableWidget->clear(); // set header item for the table - mTableWidget->setColumnCount(2); + m_tableWidget->setColumnCount(2); QTableWidgetItem* headerItem = new QTableWidgetItem("Action"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(0, headerItem); + m_tableWidget->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem("Shortcut"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(1, headerItem); + m_tableWidget->setHorizontalHeaderItem(1, headerItem); // set the vertical header not visible - QHeaderView* verticalHeader = mTableWidget->verticalHeader(); + QHeaderView* verticalHeader = m_tableWidget->verticalHeader(); verticalHeader->setVisible(false); // get access to the shortcut group and some data MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - MysticQt::KeyboardShortcutManager::Group* group = shortcutManager->GetGroup(mSelectedGroup); + MysticQt::KeyboardShortcutManager::Group* group = shortcutManager->GetGroup(m_selectedGroup); const size_t numActions = group->GetNumActions(); // set the row count - mTableWidget->setRowCount(aznumeric_caster(numActions)); + m_tableWidget->setRowCount(aznumeric_caster(numActions)); // fill the table with the media root folders for (uint32 i = 0; i < numActions; ++i) @@ -185,25 +185,25 @@ namespace EMStudio // add the item to the table and set the row height QTableWidgetItem* item = new QTableWidgetItem(action->m_qaction->text()); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); - mTableWidget->setItem(i, 0, item); + m_tableWidget->setItem(i, 0, item); const QString keyText = ConstructStringFromShortcut(action->m_qaction->shortcut()); item = new QTableWidgetItem(keyText); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); - mTableWidget->setItem(i, 1, item); + m_tableWidget->setItem(i, 1, item); - mTableWidget->setRowHeight(i, 21); + m_tableWidget->setRowHeight(i, 21); } // resize the first column - mTableWidget->resizeColumnToContents(0); + m_tableWidget->resizeColumnToContents(0); // needed to have the last column stretching correctly - mTableWidget->setColumnWidth(1, 0); + m_tableWidget->setColumnWidth(1, 0); // set the last column to take the whole space - mTableWidget->horizontalHeader()->setStretchLastSection(true); + m_tableWidget->horizontalHeader()->setStretchLastSection(true); } @@ -211,7 +211,7 @@ namespace EMStudio MysticQt::KeyboardShortcutManager::Group* KeyboardShortcutsWindow::GetCurrentGroup() const { // get access to the group - int32 groupIndex = mListWidget->currentRow(); + int32 groupIndex = m_listWidget->currentRow(); if (groupIndex == -1) { return nullptr; @@ -237,17 +237,17 @@ namespace EMStudio MysticQt::KeyboardShortcutManager::Action* action = group->GetAction(row); ShortcutReceiverDialog shortcutWindow(this, action, group); - mShortcutReceiverDialog = &shortcutWindow; + m_shortcutReceiverDialog = &shortcutWindow; if (shortcutWindow.exec() == QDialog::Accepted) { // handle conflicts - if (shortcutWindow.mConflictDetected) + if (shortcutWindow.m_conflictDetected) { - shortcutWindow.mConflictAction->m_qaction->setShortcut({}); + shortcutWindow.m_conflictAction->m_qaction->setShortcut({}); } // adjust the shortcut action - action->m_qaction->setShortcut(shortcutWindow.mKey); + action->m_qaction->setShortcut(shortcutWindow.m_key); // save the new shortcuts QSettings settings(FromStdString(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioKeyboardShortcuts.cfg")), QSettings::IniFormat, this); @@ -256,7 +256,7 @@ namespace EMStudio // reinit the window ReInit(); } - mShortcutReceiverDialog = nullptr; + m_shortcutReceiverDialog = nullptr; } @@ -275,12 +275,12 @@ namespace EMStudio // reset to default after pressing context menu void KeyboardShortcutsWindow::OnResetToDefault() { - if (mContextMenuAction == nullptr) + if (m_contextMenuAction == nullptr) { return; } - mContextMenuAction->m_qaction->setShortcut(mContextMenuAction->m_defaultKeySequence); + m_contextMenuAction->m_qaction->setShortcut(m_contextMenuAction->m_defaultKeySequence); ReInit(); } @@ -289,13 +289,13 @@ namespace EMStudio // assign a new key after pressing the context menu item void KeyboardShortcutsWindow::OnAssignNewKey() { - if (mContextMenuAction == nullptr) + if (m_contextMenuAction == nullptr) { return; } // assign the new shortcut - OnShortcutChange(mContextMenuActionIndex, 0); + OnShortcutChange(m_contextMenuActionIndex, 0); } @@ -303,7 +303,7 @@ namespace EMStudio void KeyboardShortcutsWindow::contextMenuEvent(QContextMenuEvent* event) { // find the table widget item at the clicked position - QTableWidgetItem* clickedItem = mTableWidget->itemAt(mTableWidget->viewport()->mapFromGlobal(event->globalPos())); + QTableWidgetItem* clickedItem = m_tableWidget->itemAt(m_tableWidget->viewport()->mapFromGlobal(event->globalPos())); if (clickedItem == nullptr) { return; @@ -315,8 +315,8 @@ namespace EMStudio MysticQt::KeyboardShortcutManager::Group* group = GetCurrentGroup(); // get access to the action - mContextMenuAction = group->GetAction(actionIndex); - mContextMenuActionIndex = actionIndex; + m_contextMenuAction = group->GetAction(actionIndex); + m_contextMenuActionIndex = actionIndex; // create the context menu QMenu menu(this); @@ -343,33 +343,33 @@ namespace EMStudio setWindowTitle(" "); layout->addWidget(new QLabel("Press the new shortcut on the keyboard:")); - mOrgAction = action; - mOrgGroup = group; + m_orgAction = action; + m_orgGroup = group; - mConflictAction = nullptr; - mConflictDetected = false; - mKey = action->m_qaction->shortcut(); + m_conflictAction = nullptr; + m_conflictDetected = false; + m_key = action->m_qaction->shortcut(); - QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(mKey); + QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(m_key); - mLabel = new QLabel(keyText); - mLabel->setAlignment(Qt::AlignHCenter); - QFont font = mLabel->font(); + m_label = new QLabel(keyText); + m_label->setAlignment(Qt::AlignHCenter); + QFont font = m_label->font(); font.setPointSize(14); font.setBold(true); - mLabel->setFont(font); - layout->addWidget(mLabel); + m_label->setFont(font); + layout->addWidget(m_label); - mConflictKeyLabel = new QLabel(""); - mConflictKeyLabel->setAlignment(Qt::AlignHCenter); - layout->addWidget(mConflictKeyLabel); + m_conflictKeyLabel = new QLabel(""); + m_conflictKeyLabel->setAlignment(Qt::AlignHCenter); + layout->addWidget(m_conflictKeyLabel); QHBoxLayout* buttonLayout = new QHBoxLayout(); buttonLayout->setMargin(0); - mOKButton = new QPushButton("OK"); - buttonLayout->addWidget(mOKButton); - connect(mOKButton, &QPushButton::clicked, this, &ShortcutReceiverDialog::accept); + m_okButton = new QPushButton("OK"); + buttonLayout->addWidget(m_okButton); + connect(m_okButton, &QPushButton::clicked, this, &ShortcutReceiverDialog::accept); QPushButton* defaultButton = new QPushButton("Default"); buttonLayout->addWidget(defaultButton); @@ -391,7 +391,7 @@ namespace EMStudio // reset the shortcut to its default value void ShortcutReceiverDialog::ResetToDefault() { - mKey = mOrgAction->m_defaultKeySequence; + m_key = m_orgAction->m_defaultKeySequence; UpdateInterface(); } @@ -403,41 +403,41 @@ namespace EMStudio MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); // check if the currently assigned shortcut is already taken by another shortcut - mConflictAction = shortcutManager->FindShortcut(mKey, mOrgGroup); - if (mConflictAction == nullptr || mConflictAction == mOrgAction) + m_conflictAction = shortcutManager->FindShortcut(m_key, m_orgGroup); + if (m_conflictAction == nullptr || m_conflictAction == m_orgAction) { - mOKButton->setToolTip(""); - mLabel->setStyleSheet(""); - mConflictKeyLabel->setStyleSheet(""); - mConflictKeyLabel->setText(""); - mConflictDetected = false; + m_okButton->setToolTip(""); + m_label->setStyleSheet(""); + m_conflictKeyLabel->setStyleSheet(""); + m_conflictKeyLabel->setText(""); + m_conflictDetected = false; } else { - mLabel->setStyleSheet("color: rgb(244, 156, 28);"); - mConflictKeyLabel->setStyleSheet("color: rgb(244, 156, 28);"); + m_label->setStyleSheet("color: rgb(244, 156, 28);"); + m_conflictKeyLabel->setStyleSheet("color: rgb(244, 156, 28);"); - mConflictDetected = true; + m_conflictDetected = true; - if (mConflictAction) + if (m_conflictAction) { - mOKButton->setToolTip(QString("Assigning new shortcut will unassign '%1' automatically.").arg(mConflictAction->m_qaction->text())); + m_okButton->setToolTip(QString("Assigning new shortcut will unassign '%1' automatically.").arg(m_conflictAction->m_qaction->text())); - MysticQt::KeyboardShortcutManager::Group* conflictGroup = shortcutManager->FindGroupForShortcut(mConflictAction); + MysticQt::KeyboardShortcutManager::Group* conflictGroup = shortcutManager->FindGroupForShortcut(m_conflictAction); if (conflictGroup) { - mConflictKeyLabel->setText(QString("Conflicts with: %1 -> %2").arg(FromStdString(conflictGroup->GetName())).arg(mConflictAction->m_qaction->text())); + m_conflictKeyLabel->setText(QString("Conflicts with: %1 -> %2").arg(FromStdString(conflictGroup->GetName())).arg(m_conflictAction->m_qaction->text())); } else { - mConflictKeyLabel->setText(QString("Conflicts with: %1").arg(mConflictAction->m_qaction->text())); + m_conflictKeyLabel->setText(QString("Conflicts with: %1").arg(m_conflictAction->m_qaction->text())); } } } // adjust the label text to the new shortcut - const QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(mKey); - mLabel->setText(keyText); + const QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(m_key); + m_label->setText(keyText); } // called when the user pressed a new shortcut @@ -460,7 +460,7 @@ namespace EMStudio } else { - mKey = event->key() | event->modifiers(); + m_key = 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 bcc33ae9f8..bf109af0ca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.h @@ -39,18 +39,18 @@ namespace EMStudio void keyPressEvent(QKeyEvent* event) override; void UpdateInterface(); - QKeySequence mKey; - bool mConflictDetected; - MysticQt::KeyboardShortcutManager::Action* mConflictAction; + QKeySequence m_key; + bool m_conflictDetected; + MysticQt::KeyboardShortcutManager::Action* m_conflictAction; private slots: void ResetToDefault(); private: - QLabel* mLabel; - QLabel* mConflictKeyLabel; - QPushButton* mOKButton; - MysticQt::KeyboardShortcutManager::Action* mOrgAction; - MysticQt::KeyboardShortcutManager::Group* mOrgGroup; + QLabel* m_label; + QLabel* m_conflictKeyLabel; + QPushButton* m_okButton; + MysticQt::KeyboardShortcutManager::Action* m_orgAction; + MysticQt::KeyboardShortcutManager::Group* m_orgGroup; }; @@ -79,13 +79,13 @@ namespace EMStudio void OnAssignNewKey(); private: - QTableWidget* mTableWidget; - QListWidget* mListWidget; - QHBoxLayout* mHLayout; - int mSelectedGroup; - MysticQt::KeyboardShortcutManager::Action* mContextMenuAction; - int mContextMenuActionIndex; - ShortcutReceiverDialog* mShortcutReceiverDialog; + QTableWidget* m_tableWidget; + QListWidget* m_listWidget; + QHBoxLayout* m_hLayout; + int m_selectedGroup; + MysticQt::KeyboardShortcutManager::Action* m_contextMenuAction; + int m_contextMenuActionIndex; + ShortcutReceiverDialog* m_shortcutReceiverDialog; void contextMenuEvent(QContextMenuEvent* event) override; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.cpp index bc2b98bd99..e2dbb3df60 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.cpp @@ -26,7 +26,7 @@ namespace EMStudio { LayoutManager::LayoutManager() { - mIsSwitching = false; + m_isSwitching = false; } LayoutManager::~LayoutManager() @@ -109,25 +109,25 @@ namespace EMStudio } LayoutHeader header; - header.mFileTypeCode[0] = 'E'; - header.mFileTypeCode[1] = 'M'; - header.mFileTypeCode[2] = 'S'; - header.mFileTypeCode[3] = 'L'; - header.mFileTypeCode[4] = 'A'; - header.mFileTypeCode[5] = 'Y'; - header.mFileTypeCode[6] = 'O'; - header.mFileTypeCode[7] = 'U'; - header.mFileTypeCode[8] = 'T'; - header.mEMFXVersionHigh = EMotionFX::GetEMotionFX().GetHighVersion(); - header.mEMFXVersionLow = EMotionFX::GetEMotionFX().GetLowVersion(); - - azstrcpy(header.mEMFXCompileDate, 64, EMotionFX::GetEMotionFX().GetCompilationDate()); - azstrcpy(header.mCompileDate, 64, MCORE_DATE); - azstrcpy(header.mDescription, 256, ""); - - header.mLayoutVersionHigh = 0; - header.mLayoutVersionLow = 1; - header.mNumPlugins = GetPluginManager()->GetNumActivePlugins(); + header.m_fileTypeCode[0] = 'E'; + header.m_fileTypeCode[1] = 'M'; + header.m_fileTypeCode[2] = 'S'; + header.m_fileTypeCode[3] = 'L'; + header.m_fileTypeCode[4] = 'A'; + header.m_fileTypeCode[5] = 'Y'; + header.m_fileTypeCode[6] = 'O'; + header.m_fileTypeCode[7] = 'U'; + header.m_fileTypeCode[8] = 'T'; + header.m_emfxVersionHigh = EMotionFX::GetEMotionFX().GetHighVersion(); + header.m_emfxVersionLow = EMotionFX::GetEMotionFX().GetLowVersion(); + + azstrcpy(header.m_emfxCompileDate, 64, EMotionFX::GetEMotionFX().GetCompilationDate()); + azstrcpy(header.m_compileDate, 64, MCORE_DATE); + azstrcpy(header.m_description, 256, ""); + + header.m_layoutVersionHigh = 0; + header.m_layoutVersionLow = 1; + header.m_numPlugins = aznumeric_caster(GetPluginManager()->GetNumActivePlugins()); if (file.write((char*)&header, sizeof(LayoutHeader)) == -1) { MCore::LogWarning("Failed to write layout header to layout file '%s'", filename); @@ -135,7 +135,7 @@ namespace EMStudio } // For each plugin (window) save the object name. - for (uint32 i = 0; i < header.mNumPlugins; ++i) + for (uint32 i = 0; i < header.m_numPlugins; ++i) { EMStudioPlugin* plugin = GetPluginManager()->GetActivePlugin(i); @@ -145,16 +145,14 @@ namespace EMStudio // Save the plugin header. LayoutPluginHeader pluginHeader; - pluginHeader.mDataSize = static_cast(memFile.GetFileSize()); - pluginHeader.mDataVersion = plugin->GetLayoutDataVersion(); + pluginHeader.m_dataSize = static_cast(memFile.GetFileSize()); + pluginHeader.m_dataVersion = plugin->GetLayoutDataVersion(); - azstrcpy(pluginHeader.mObjectName, 128, FromQtString(plugin->GetObjectName()).c_str()); - azstrcpy(pluginHeader.mPluginName, 128, plugin->GetName()); + azstrcpy(pluginHeader.m_objectName, 128, FromQtString(plugin->GetObjectName()).c_str()); + azstrcpy(pluginHeader.m_pluginName, 128, plugin->GetName()); file.write((char*)&pluginHeader, sizeof(LayoutPluginHeader)); - //MCore::LogDetailedInfo("pluginHeader.mDataSize = %d bytes (version=%d) (name=%s)", pluginHeader.mDataSize, pluginHeader.mDataVersion, pluginHeader.mPluginName); - if (memFile.GetMemoryStart()) { if (file.write((char*)memFile.GetMemoryStart(), memFile.GetFileSize()) == -1) @@ -195,17 +193,17 @@ namespace EMStudio bool LayoutManager::LoadLayout(const char* filename) { // If we are already switching, skip directly. - if (mIsSwitching) + if (m_isSwitching) { return true; } - mIsSwitching = true; + m_isSwitching = true; QFile file(filename); if (file.open(QIODevice::ReadOnly) == false) { - mIsSwitching = false; + m_isSwitching = false; return false; } @@ -218,42 +216,31 @@ namespace EMStudio if (file.read((char*)&header, sizeof(LayoutHeader)) == -1) { MCore::LogWarning("Error reading header from layout file '%s'", filename); - mIsSwitching = false; + m_isSwitching = false; return false; } // Check if this is a valid layout file. - if (header.mFileTypeCode[0] != 'E' || header.mFileTypeCode[1] != 'M' || header.mFileTypeCode[2] != 'S' || - header.mFileTypeCode[3] != 'L' || header.mFileTypeCode[4] != 'A' || header.mFileTypeCode[5] != 'Y' || header.mFileTypeCode[6] != 'O' || header.mFileTypeCode[7] != 'U' || header.mFileTypeCode[8] != 'T') + if (header.m_fileTypeCode[0] != 'E' || header.m_fileTypeCode[1] != 'M' || header.m_fileTypeCode[2] != 'S' || + header.m_fileTypeCode[3] != 'L' || header.m_fileTypeCode[4] != 'A' || header.m_fileTypeCode[5] != 'Y' || header.m_fileTypeCode[6] != 'O' || header.m_fileTypeCode[7] != 'U' || header.m_fileTypeCode[8] != 'T') { MCore::LogWarning("Failed to load file '%s' as it is not a valid EMotion Studio layout file.", filename); - mIsSwitching = false; + m_isSwitching = false; return false; } - //MCore::LogDetailedInfo("EMotion FX version = v%d.%d", header.mEMFXVersionHigh, header.mEMFXVersionLow / 100); - //MCore::LogDetailedInfo("EMotion FX compile date = %s", header.mEMFXCompileDate); - //MCore::LogDetailedInfo("EMStudio compile date = %s", header.mCompileDate); - //MCore::LogDetailedInfo("Layout description = %s", header.mDescription); - //MCore::LogDetailedInfo("Layout version = v%d.%d", header.mLayoutVersionHigh, header.mLayoutVersionLow); - //MCore::LogDetailedInfo("Num active plugins = %d", header.mNumPlugins); - // Iterate through the plugins and try to reuse them. - for (uint32 i = 0; i < header.mNumPlugins; ++i) + for (uint32 i = 0; i < header.m_numPlugins; ++i) { // load the plugin header LayoutPluginHeader pluginHeader; if (file.read((char*)&pluginHeader, sizeof(LayoutPluginHeader)) == -1) { MCore::LogWarning("Error reading plugin header from layout file '%s'", filename); - mIsSwitching = false; + m_isSwitching = false; return false; } - //MCore::LogDetailedInfo("Loading plugin settings for plugin '%s'...", pluginHeader.mPluginName); - //MCore::LogDetailedInfo(" + Data size = %d bytes", pluginHeader.mDataSize); - //MCore::LogDetailedInfo(" + Data version = %d", pluginHeader.mDataVersion); - EMStudioPlugin* plugin = nullptr; // Check if we already have a window using a similar plugin. @@ -264,10 +251,10 @@ namespace EMStudio while (itActivePlugin != activePlugins.end()) { // Is the plugin name the same as we need to create? - if (AzFramework::StringFunc::Equal((*itActivePlugin)->GetName(), pluginHeader.mPluginName)) + if (AzFramework::StringFunc::Equal((*itActivePlugin)->GetName(), pluginHeader.m_pluginName)) { plugin = *itActivePlugin; - plugin->SetObjectName(pluginHeader.mObjectName); + plugin->SetObjectName(pluginHeader.m_objectName); if (plugin->GetPluginType() == EMStudioPlugin::PLUGINTYPE_DOCKWIDGET) { DockWidgetPlugin* dockPlugin = static_cast(plugin); @@ -289,23 +276,23 @@ namespace EMStudio // Try to create the plugin of this type. if (!plugin) { - plugin = GetPluginManager()->CreateWindowOfType(pluginHeader.mPluginName, pluginHeader.mObjectName); + plugin = GetPluginManager()->CreateWindowOfType(pluginHeader.m_pluginName, pluginHeader.m_objectName); if (!plugin) { - MCore::LogError("Failed to create plugin window of type '%s', with data size %d bytes", pluginHeader.mPluginName, pluginHeader.mDataSize); + MCore::LogError("Failed to create plugin window of type '%s', with data size %d bytes", pluginHeader.m_pluginName, pluginHeader.m_dataSize); // Skip the data. - file.seek(file.pos() + pluginHeader.mDataSize); + file.seek(file.pos() + pluginHeader.m_dataSize); continue; } } - if (plugin->ReadLayoutSettings(file, pluginHeader.mDataSize, pluginHeader.mDataVersion) == false) + if (plugin->ReadLayoutSettings(file, pluginHeader.m_dataSize, pluginHeader.m_dataVersion) == false) { MCore::LogWarning("Error reading plugin settings from layout file '%s'", filename); - mIsSwitching = false; + m_isSwitching = false; return false; } } @@ -321,7 +308,7 @@ namespace EMStudio if (file.read((char*)&stateLength, sizeof(uint32)) == -1) { MCore::LogWarning("Error reading main window state length from layout file '%s'", filename); - mIsSwitching = false; + m_isSwitching = false; return false; } @@ -330,7 +317,7 @@ namespace EMStudio if (layout.size() == 0) { MCore::LogWarning("Error reading main window state data from layout file '%s'", filename); - mIsSwitching = false; + m_isSwitching = false; return false; } @@ -339,13 +326,13 @@ namespace EMStudio GetMainWindow()->UpdateCreateWindowMenu(); // update Window->Create menu // Trigger the OnAfterLoadLayout callbacks. - const uint32 numActivePlugins = pluginManager->GetNumActivePlugins(); - for (uint32 p = 0; p < numActivePlugins; ++p) + const size_t numActivePlugins = pluginManager->GetNumActivePlugins(); + for (size_t p = 0; p < numActivePlugins; ++p) { GetPluginManager()->GetActivePlugin(p)->OnAfterLoadLayout(); } - mIsSwitching = false; + m_isSwitching = false; return true; } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.h index 5aabbd6024..4059f8f006 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LayoutManager.h @@ -17,18 +17,18 @@ namespace EMStudio // layout file header struct LayoutHeader { - char mFileTypeCode[9]; // "EMSLAYOUT", otherwise no valid layout file - uint32 mEMFXVersionHigh; // EMotion FX high version as used in EMStudio - uint32 mEMFXVersionLow; // EMotion FX low version as used in EMStudio - char mEMFXCompileDate[64];// EMotion FX compile date - uint32 mLayoutVersionHigh; // layout file type high version - uint32 mLayoutVersionLow; // layout file type low version - char mCompileDate[64]; // EMStudio compile date - char mDescription[256]; // optional description of the layout - uint32 mNumPlugins; // the number of plugins + char m_fileTypeCode[9]; // "EMSLAYOUT", otherwise no valid layout file + uint32 m_emfxVersionHigh; // EMotion FX high version as used in EMStudio + uint32 m_emfxVersionLow; // EMotion FX low version as used in EMStudio + char m_emfxCompileDate[64];// EMotion FX compile date + uint32 m_layoutVersionHigh; // layout file type high version + uint32 m_layoutVersionLow; // layout file type low version + char m_compileDate[64]; // EMStudio compile date + char m_description[256]; // optional description of the layout + uint32 m_numPlugins; // the number of plugins // followed by: - // LayoutPluginHeader[mNumPlugins] + // LayoutPluginHeader[m_numPlugins] // uint32 mainWindowStateSize // int8 mainWindowState[mainWindowStateSize] }; @@ -36,13 +36,13 @@ namespace EMStudio // the plugin data header struct LayoutPluginHeader { - uint32 mDataSize; // data size of the data which the given plugin will store - char mPluginName[128]; // the name of the plugin (its ID to create as passed to PluginManager::CreateWindowOfType) - char mObjectName[128]; - uint32 mDataVersion; // the data version, to for backward compatibility of loading individual plugin settings from layout files + uint32 m_dataSize; // data size of the data which the given plugin will store + char m_pluginName[128]; // the name of the plugin (its ID to create as passed to PluginManager::CreateWindowOfType) + char m_objectName[128]; + uint32 m_dataVersion; // the data version, to for backward compatibility of loading individual plugin settings from layout files // followed by: - // int8 pluginData[mDataSize] + // int8 pluginData[m_dataSize] }; class EMSTUDIO_API LayoutManager @@ -62,7 +62,7 @@ namespace EMStudio InputDialogValidatable* GetSaveLayoutNameDialog(); private: - bool mIsSwitching; + bool m_isSwitching; InputDialogValidatable* m_inputDialog = nullptr; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.cpp index 090875f20f..179ea26e34 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.cpp @@ -40,101 +40,101 @@ namespace EMStudio const QSettings loadActorSettings(GetConfigFilename(), QSettings::IniFormat, this); // create the load meshes checkbox - mLoadMeshesCheckbox = new QCheckBox("Load Meshes"); + m_loadMeshesCheckbox = new QCheckBox("Load Meshes"); const bool loadMeshesValue = loadActorSettings.value("LoadMeshes", true).toBool(); - mLoadMeshesCheckbox->setChecked(loadMeshesValue); + m_loadMeshesCheckbox->setChecked(loadMeshesValue); // connect the load meshes checkbox to enable/disable all related to mesh - connect(mLoadMeshesCheckbox, &QCheckBox::clicked, this, &LoadActorSettingsWindow::LoadMeshesClicked); + connect(m_loadMeshesCheckbox, &QCheckBox::clicked, this, &LoadActorSettingsWindow::LoadMeshesClicked); // create the load collision meshes checkbox - mLoadCollisionMeshesCheckbox = new QCheckBox("Load Collision Meshes"); + m_loadCollisionMeshesCheckbox = new QCheckBox("Load Collision Meshes"); const bool loadCollisionMeshesValue = loadActorSettings.value("LoadCollisionMeshes", true).toBool(); - mLoadCollisionMeshesCheckbox->setChecked(loadCollisionMeshesValue); + m_loadCollisionMeshesCheckbox->setChecked(loadCollisionMeshesValue); // create the load standard material layers checkbox - mLoadStandardMaterialLayersCheckbox = new QCheckBox("Load Standard Material Layers"); + m_loadStandardMaterialLayersCheckbox = new QCheckBox("Load Standard Material Layers"); const bool loadStandardMaterialLayersValue = loadActorSettings.value("LoadStandardMaterialLayers", true).toBool(); - mLoadStandardMaterialLayersCheckbox->setChecked(loadStandardMaterialLayersValue); + m_loadStandardMaterialLayersCheckbox->setChecked(loadStandardMaterialLayersValue); // create the load skinning info checkbox - mLoadSkinningInfoCheckbox = new QCheckBox("Load Skinning Info"); + m_loadSkinningInfoCheckbox = new QCheckBox("Load Skinning Info"); const bool loadSkinningInfoValue = loadActorSettings.value("LoadSkinningInfo", true).toBool(); - mLoadSkinningInfoCheckbox->setChecked(loadSkinningInfoValue); + m_loadSkinningInfoCheckbox->setChecked(loadSkinningInfoValue); // connect the load meshes checkbox to enable/disable all related to mesh - connect(mLoadSkinningInfoCheckbox, &QCheckBox::clicked, this, &LoadActorSettingsWindow::LoadSkinningInfoClicked); + connect(m_loadSkinningInfoCheckbox, &QCheckBox::clicked, this, &LoadActorSettingsWindow::LoadSkinningInfoClicked); // create the load limits checkbox - mLoadLimitsCheckbox = new QCheckBox("Load Limits"); + m_loadLimitsCheckbox = new QCheckBox("Load Limits"); const bool loadLimitsValue = loadActorSettings.value("LoadLimits", true).toBool(); - mLoadLimitsCheckbox->setChecked(loadLimitsValue); + m_loadLimitsCheckbox->setChecked(loadLimitsValue); // create the load geometry LODs checkbox - mLoadGeometryLODsCheckbox = new QCheckBox("Load Geometry LODs"); + m_loadGeometryLoDsCheckbox = new QCheckBox("Load Geometry LODs"); const bool loadGeometryLODsValue = loadActorSettings.value("LoadGeometryLODs", true).toBool(); - mLoadGeometryLODsCheckbox->setChecked(loadGeometryLODsValue); + m_loadGeometryLoDsCheckbox->setChecked(loadGeometryLODsValue); // create the load skeletal LODs checkbox - mLoadSkeletalLODsCheckbox = new QCheckBox("Load Skeletal LODs"); + m_loadSkeletalLoDsCheckbox = new QCheckBox("Load Skeletal LODs"); const bool loadSkeletalLODsValue = loadActorSettings.value("LoadSkeletalLODs", true).toBool(); - mLoadSkeletalLODsCheckbox->setChecked(loadSkeletalLODsValue); + m_loadSkeletalLoDsCheckbox->setChecked(loadSkeletalLODsValue); // create the load tangents checkbox - mLoadTangentsCheckbox = new QCheckBox("Load Tangents"); + m_loadTangentsCheckbox = new QCheckBox("Load Tangents"); const bool loadTangentsValue = loadActorSettings.value("LoadTangents", true).toBool(); - mLoadTangentsCheckbox->setChecked(loadTangentsValue); + m_loadTangentsCheckbox->setChecked(loadTangentsValue); // create the auto generate tangents checkbox - mAutoGenerateTangentsCheckbox = new QCheckBox("Auto Generate Tangents"); + m_autoGenerateTangentsCheckbox = new QCheckBox("Auto Generate Tangents"); const bool autoGenerateTangentsValue = loadActorSettings.value("AutoGenerateTangents", true).toBool(); - mAutoGenerateTangentsCheckbox->setChecked(autoGenerateTangentsValue); + m_autoGenerateTangentsCheckbox->setChecked(autoGenerateTangentsValue); // create the load morph targets checkbox - mLoadMorphTargetsCheckbox = new QCheckBox("Load Morph Targets"); + m_loadMorphTargetsCheckbox = new QCheckBox("Load Morph Targets"); const bool loadMorphTargetsValue = loadActorSettings.value("LoadMorphTargets", true).toBool(); - mLoadMorphTargetsCheckbox->setChecked(loadMorphTargetsValue); + m_loadMorphTargetsCheckbox->setChecked(loadMorphTargetsValue); // create the dual quaternion skinning checkbox - mDualQuaternionSkinningCheckbox = new QCheckBox("Dual Quaternion Skinning"); + m_dualQuaternionSkinningCheckbox = new QCheckBox("Dual Quaternion Skinning"); const bool dualQuaternionSkinningValue = loadActorSettings.value("DualQuaternionSkinning", false).toBool(); - mDualQuaternionSkinningCheckbox->setChecked(dualQuaternionSkinningValue); + m_dualQuaternionSkinningCheckbox->setChecked(dualQuaternionSkinningValue); // disable the controls if load meshes is not enabled if (loadMeshesValue == false) { - mLoadStandardMaterialLayersCheckbox->setDisabled(true); - mLoadSkinningInfoCheckbox->setDisabled(true); - mLoadGeometryLODsCheckbox->setDisabled(true); - mLoadTangentsCheckbox->setDisabled(true); - mAutoGenerateTangentsCheckbox->setDisabled(true); - mDualQuaternionSkinningCheckbox->setDisabled(true); + m_loadStandardMaterialLayersCheckbox->setDisabled(true); + m_loadSkinningInfoCheckbox->setDisabled(true); + m_loadGeometryLoDsCheckbox->setDisabled(true); + m_loadTangentsCheckbox->setDisabled(true); + m_autoGenerateTangentsCheckbox->setDisabled(true); + m_dualQuaternionSkinningCheckbox->setDisabled(true); } else { // disable dual quaternion skinning control if the load dual skinning info is not enabled if (loadSkinningInfoValue == false) { - mDualQuaternionSkinningCheckbox->setDisabled(true); + m_dualQuaternionSkinningCheckbox->setDisabled(true); } } // create the left part settings layout QVBoxLayout* leftPartSettingsLayout = new QVBoxLayout(); - leftPartSettingsLayout->addWidget(mLoadMeshesCheckbox); - leftPartSettingsLayout->addWidget(mLoadCollisionMeshesCheckbox); - leftPartSettingsLayout->addWidget(mLoadStandardMaterialLayersCheckbox); - leftPartSettingsLayout->addWidget(mLoadSkinningInfoCheckbox); - leftPartSettingsLayout->addWidget(mLoadLimitsCheckbox); + leftPartSettingsLayout->addWidget(m_loadMeshesCheckbox); + leftPartSettingsLayout->addWidget(m_loadCollisionMeshesCheckbox); + leftPartSettingsLayout->addWidget(m_loadStandardMaterialLayersCheckbox); + leftPartSettingsLayout->addWidget(m_loadSkinningInfoCheckbox); + leftPartSettingsLayout->addWidget(m_loadLimitsCheckbox); // create the right part settings layout QVBoxLayout* rightPartSettingsLayout = new QVBoxLayout(); - rightPartSettingsLayout->addWidget(mLoadGeometryLODsCheckbox); - rightPartSettingsLayout->addWidget(mLoadSkeletalLODsCheckbox); - rightPartSettingsLayout->addWidget(mLoadTangentsCheckbox); - rightPartSettingsLayout->addWidget(mAutoGenerateTangentsCheckbox); - rightPartSettingsLayout->addWidget(mLoadMorphTargetsCheckbox); - rightPartSettingsLayout->addWidget(mDualQuaternionSkinningCheckbox); + rightPartSettingsLayout->addWidget(m_loadGeometryLoDsCheckbox); + rightPartSettingsLayout->addWidget(m_loadSkeletalLoDsCheckbox); + rightPartSettingsLayout->addWidget(m_loadTangentsCheckbox); + rightPartSettingsLayout->addWidget(m_autoGenerateTangentsCheckbox); + rightPartSettingsLayout->addWidget(m_loadMorphTargetsCheckbox); + rightPartSettingsLayout->addWidget(m_dualQuaternionSkinningCheckbox); // create the settings layout QHBoxLayout* settingsLayout = new QHBoxLayout(); @@ -189,17 +189,17 @@ namespace EMStudio LoadActorSettingsWindow::LoadActorSettings LoadActorSettingsWindow::GetLoadActorSettings() const { LoadActorSettings loadActorSettings; - loadActorSettings.mLoadMeshes = mLoadMeshesCheckbox->isChecked(); - loadActorSettings.mLoadCollisionMeshes = mLoadCollisionMeshesCheckbox->isChecked(); - loadActorSettings.mLoadStandardMaterialLayers = mLoadStandardMaterialLayersCheckbox->isChecked(); - loadActorSettings.mLoadSkinningInfo = mLoadSkinningInfoCheckbox->isChecked(); - loadActorSettings.mLoadLimits = mLoadLimitsCheckbox->isChecked(); - loadActorSettings.mLoadGeometryLODs = mLoadGeometryLODsCheckbox->isChecked(); - loadActorSettings.mLoadSkeletalLODs = mLoadSkeletalLODsCheckbox->isChecked(); - loadActorSettings.mLoadTangents = mLoadTangentsCheckbox->isChecked(); - loadActorSettings.mAutoGenerateTangents = mAutoGenerateTangentsCheckbox->isChecked(); - loadActorSettings.mLoadMorphTargets = mLoadMorphTargetsCheckbox->isChecked(); - loadActorSettings.mDualQuaternionSkinning = mDualQuaternionSkinningCheckbox->isChecked(); + loadActorSettings.m_loadMeshes = m_loadMeshesCheckbox->isChecked(); + loadActorSettings.m_loadCollisionMeshes = m_loadCollisionMeshesCheckbox->isChecked(); + loadActorSettings.m_loadStandardMaterialLayers = m_loadStandardMaterialLayersCheckbox->isChecked(); + loadActorSettings.m_loadSkinningInfo = m_loadSkinningInfoCheckbox->isChecked(); + loadActorSettings.m_loadLimits = m_loadLimitsCheckbox->isChecked(); + loadActorSettings.m_loadGeometryLoDs = m_loadGeometryLoDsCheckbox->isChecked(); + loadActorSettings.m_loadSkeletalLoDs = m_loadSkeletalLoDsCheckbox->isChecked(); + loadActorSettings.m_loadTangents = m_loadTangentsCheckbox->isChecked(); + loadActorSettings.m_autoGenerateTangents = m_autoGenerateTangentsCheckbox->isChecked(); + loadActorSettings.m_loadMorphTargets = m_loadMorphTargetsCheckbox->isChecked(); + loadActorSettings.m_dualQuaternionSkinning = m_dualQuaternionSkinningCheckbox->isChecked(); return loadActorSettings; } @@ -210,45 +210,45 @@ namespace EMStudio QSettings loadActorSettings(GetConfigFilename(), QSettings::IniFormat, this); // set all values - loadActorSettings.setValue("LoadMeshes", mLoadMeshesCheckbox->isChecked()); - loadActorSettings.setValue("LoadCollisionMeshes", mLoadCollisionMeshesCheckbox->isChecked()); - loadActorSettings.setValue("LoadStandardMaterialLayers", mLoadStandardMaterialLayersCheckbox->isChecked()); - loadActorSettings.setValue("LoadSkinningInfo", mLoadSkinningInfoCheckbox->isChecked()); - loadActorSettings.setValue("LoadLimits", mLoadLimitsCheckbox->isChecked()); - loadActorSettings.setValue("LoadGeometryLODs", mLoadGeometryLODsCheckbox->isChecked()); - loadActorSettings.setValue("LoadSkeletalLODs", mLoadSkeletalLODsCheckbox->isChecked()); - loadActorSettings.setValue("LoadTangents", mLoadTangentsCheckbox->isChecked()); - loadActorSettings.setValue("AutoGenerateTangents", mAutoGenerateTangentsCheckbox->isChecked()); - loadActorSettings.setValue("LoadMorphTargets", mLoadMorphTargetsCheckbox->isChecked()); - loadActorSettings.setValue("DualQuaternionSkinning", mDualQuaternionSkinningCheckbox->isChecked()); + loadActorSettings.setValue("LoadMeshes", m_loadMeshesCheckbox->isChecked()); + loadActorSettings.setValue("LoadCollisionMeshes", m_loadCollisionMeshesCheckbox->isChecked()); + loadActorSettings.setValue("LoadStandardMaterialLayers", m_loadStandardMaterialLayersCheckbox->isChecked()); + loadActorSettings.setValue("LoadSkinningInfo", m_loadSkinningInfoCheckbox->isChecked()); + loadActorSettings.setValue("LoadLimits", m_loadLimitsCheckbox->isChecked()); + loadActorSettings.setValue("LoadGeometryLODs", m_loadGeometryLoDsCheckbox->isChecked()); + loadActorSettings.setValue("LoadSkeletalLODs", m_loadSkeletalLoDsCheckbox->isChecked()); + loadActorSettings.setValue("LoadTangents", m_loadTangentsCheckbox->isChecked()); + loadActorSettings.setValue("AutoGenerateTangents", m_autoGenerateTangentsCheckbox->isChecked()); + loadActorSettings.setValue("LoadMorphTargets", m_loadMorphTargetsCheckbox->isChecked()); + loadActorSettings.setValue("DualQuaternionSkinning", m_dualQuaternionSkinningCheckbox->isChecked()); } void LoadActorSettingsWindow::LoadMeshesClicked(bool checked) { // enable or disable controls - mLoadStandardMaterialLayersCheckbox->setEnabled(checked); - mLoadSkinningInfoCheckbox->setEnabled(checked); - mLoadGeometryLODsCheckbox->setEnabled(checked); - mLoadTangentsCheckbox->setEnabled(checked); - mAutoGenerateTangentsCheckbox->setEnabled(checked); + m_loadStandardMaterialLayersCheckbox->setEnabled(checked); + m_loadSkinningInfoCheckbox->setEnabled(checked); + m_loadGeometryLoDsCheckbox->setEnabled(checked); + m_loadTangentsCheckbox->setEnabled(checked); + m_autoGenerateTangentsCheckbox->setEnabled(checked); // the dual quaternion skinning control is enabled based on the laod skinning info control // when the the load meshes is not enabled, the control is disabled if (checked) { - mDualQuaternionSkinningCheckbox->setEnabled(mLoadSkinningInfoCheckbox->isChecked()); + m_dualQuaternionSkinningCheckbox->setEnabled(m_loadSkinningInfoCheckbox->isChecked()); } else { - mDualQuaternionSkinningCheckbox->setDisabled(true); + m_dualQuaternionSkinningCheckbox->setDisabled(true); } } void LoadActorSettingsWindow::LoadSkinningInfoClicked(bool checked) { - mDualQuaternionSkinningCheckbox->setEnabled(checked); + m_dualQuaternionSkinningCheckbox->setEnabled(checked); } @@ -261,17 +261,17 @@ namespace EMStudio LoadActorSettingsWindow::LoadActorSettings::LoadActorSettings() : - mLoadMeshes(true), - mLoadCollisionMeshes(true), - mLoadStandardMaterialLayers(true), - mLoadSkinningInfo(true), - mLoadLimits(true), - mLoadGeometryLODs(true), - mLoadSkeletalLODs(true), - mLoadTangents(true), - mAutoGenerateTangents(true), - mLoadMorphTargets(true), - mDualQuaternionSkinning(false) + m_loadMeshes(true), + m_loadCollisionMeshes(true), + m_loadStandardMaterialLayers(true), + m_loadSkinningInfo(true), + m_loadLimits(true), + m_loadGeometryLoDs(true), + m_loadSkeletalLoDs(true), + m_loadTangents(true), + m_autoGenerateTangents(true), + m_loadMorphTargets(true), + m_dualQuaternionSkinning(false) { } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.h index eb98036750..265469952b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/LoadActorSettingsWindow.h @@ -26,17 +26,17 @@ namespace EMStudio public: struct LoadActorSettings { - bool mLoadMeshes; - bool mLoadCollisionMeshes; - bool mLoadStandardMaterialLayers; - bool mLoadSkinningInfo; - bool mLoadLimits; - bool mLoadGeometryLODs; - bool mLoadSkeletalLODs; - bool mLoadTangents; - bool mAutoGenerateTangents; - bool mLoadMorphTargets; - bool mDualQuaternionSkinning; + bool m_loadMeshes; + bool m_loadCollisionMeshes; + bool m_loadStandardMaterialLayers; + bool m_loadSkinningInfo; + bool m_loadLimits; + bool m_loadGeometryLoDs; + bool m_loadSkeletalLoDs; + bool m_loadTangents; + bool m_autoGenerateTangents; + bool m_loadMorphTargets; + bool m_dualQuaternionSkinning; LoadActorSettings(); }; @@ -54,16 +54,16 @@ namespace EMStudio private: QString GetConfigFilename() const; - QCheckBox* mLoadMeshesCheckbox; - QCheckBox* mLoadCollisionMeshesCheckbox; - QCheckBox* mLoadStandardMaterialLayersCheckbox; - QCheckBox* mLoadSkinningInfoCheckbox; - QCheckBox* mLoadLimitsCheckbox; - QCheckBox* mLoadGeometryLODsCheckbox; - QCheckBox* mLoadSkeletalLODsCheckbox; - QCheckBox* mLoadTangentsCheckbox; - QCheckBox* mAutoGenerateTangentsCheckbox; - QCheckBox* mLoadMorphTargetsCheckbox; - QCheckBox* mDualQuaternionSkinningCheckbox; + QCheckBox* m_loadMeshesCheckbox; + QCheckBox* m_loadCollisionMeshesCheckbox; + QCheckBox* m_loadStandardMaterialLayersCheckbox; + QCheckBox* m_loadSkinningInfoCheckbox; + QCheckBox* m_loadLimitsCheckbox; + QCheckBox* m_loadGeometryLoDsCheckbox; + QCheckBox* m_loadSkeletalLoDsCheckbox; + QCheckBox* m_loadTangentsCheckbox; + QCheckBox* m_autoGenerateTangentsCheckbox; + QCheckBox* m_loadMorphTargetsCheckbox; + QCheckBox* m_dualQuaternionSkinningCheckbox; }; } // 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 b3e47725c7..8ca4e1de81 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -98,7 +99,7 @@ namespace EMStudio // add the link to the actual object ObjectPointer objPointer; - objPointer.mWorkspace = workspace; + objPointer.m_workspace = workspace; outObjects->push_back(objPointer); } } @@ -112,12 +113,12 @@ namespace EMStudio { // get the current object pointer and skip directly if the type check fails ObjectPointer objPointer = objects[i]; - if (objPointer.mWorkspace == nullptr) + if (objPointer.m_workspace == nullptr) { continue; } - Workspace* workspace = objPointer.mWorkspace; + Workspace* workspace = objPointer.m_workspace; // has the workspace been saved already or is it a new one? if (workspace->GetFilenameString().empty()) @@ -162,9 +163,9 @@ namespace EMStudio {} ~UndoMenuCallback() = default; - void OnRemoveCommand([[maybe_unused]] uint32 historyIndex) override { m_mainWindow->UpdateUndoRedo(); } - void OnSetCurrentCommand([[maybe_unused]] uint32 index) override { m_mainWindow->UpdateUndoRedo(); } - void OnAddCommandToHistory([[maybe_unused]] uint32 historyIndex, [[maybe_unused]] MCore::CommandGroup* group, [[maybe_unused]] MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine) override { m_mainWindow->UpdateUndoRedo(); } + void OnRemoveCommand([[maybe_unused]] size_t historyIndex) override { m_mainWindow->UpdateUndoRedo(); } + void OnSetCurrentCommand([[maybe_unused]] size_t index) override { m_mainWindow->UpdateUndoRedo(); } + void OnAddCommandToHistory([[maybe_unused]] size_t historyIndex, [[maybe_unused]] MCore::CommandGroup* group, [[maybe_unused]] MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine) override { m_mainWindow->UpdateUndoRedo(); } void OnPreExecuteCommand([[maybe_unused]] MCore::CommandGroup* group, [[maybe_unused]] MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine) override {} void OnPostExecuteCommand([[maybe_unused]] MCore::CommandGroup* group, [[maybe_unused]] MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine, [[maybe_unused]] bool wasSuccess, [[maybe_unused]] const AZStd::string& outResult) override {} @@ -182,9 +183,9 @@ namespace EMStudio QHBoxLayout* mainLayout = new QHBoxLayout(); mainLayout->setMargin(0); - mTextEdit = new QTextEdit(); - mTextEdit->setTextInteractionFlags(Qt::NoTextInteraction | Qt::TextSelectableByMouse); - mainLayout->addWidget(mTextEdit); + m_textEdit = new QTextEdit(); + m_textEdit->setTextInteractionFlags(Qt::NoTextInteraction | Qt::TextSelectableByMouse); + mainLayout->addWidget(m_textEdit); setMinimumWidth(600); setMinimumHeight(400); @@ -221,7 +222,7 @@ namespace EMStudio text += "

"; } - mTextEdit->setText(text.c_str()); + m_textEdit->setText(text.c_str()); } MainWindow::MainWindow(QWidget* parent, Qt::WindowFlags flags) @@ -231,45 +232,45 @@ namespace EMStudio , m_undoMenuCallback(nullptr) , m_fancyDockingManager(new AzQtComponents::FancyDocking(this, "emotionstudiosdk")) { - mLoadingOptions = false; - mAutosaveTimer = nullptr; - mPreferencesWindow = nullptr; - mApplicationMode = nullptr; - mDirtyFileManager = nullptr; - mFileManager = nullptr; - mShortcutManager = nullptr; - mNativeEventFilter = nullptr; - mImportActorCallback = nullptr; - mRemoveActorCallback = nullptr; - mRemoveActorInstanceCallback = nullptr; - mImportMotionCallback = nullptr; - mRemoveMotionCallback = nullptr; - mCreateMotionSetCallback = nullptr; - mRemoveMotionSetCallback = nullptr; - mLoadMotionSetCallback = nullptr; - mCreateAnimGraphCallback = nullptr; - mRemoveAnimGraphCallback = nullptr; - mLoadAnimGraphCallback = nullptr; - mSelectCallback = nullptr; - mUnselectCallback = nullptr; + m_loadingOptions = false; + m_autosaveTimer = nullptr; + m_preferencesWindow = nullptr; + m_applicationMode = nullptr; + m_dirtyFileManager = nullptr; + m_fileManager = nullptr; + m_shortcutManager = nullptr; + m_nativeEventFilter = nullptr; + m_importActorCallback = nullptr; + m_removeActorCallback = nullptr; + m_removeActorInstanceCallback = nullptr; + m_importMotionCallback = nullptr; + m_removeMotionCallback = nullptr; + m_createMotionSetCallback = nullptr; + m_removeMotionSetCallback = nullptr; + m_loadMotionSetCallback = nullptr; + m_createAnimGraphCallback = nullptr; + m_removeAnimGraphCallback = nullptr; + m_loadAnimGraphCallback = nullptr; + m_selectCallback = nullptr; + m_unselectCallback = nullptr; m_clearSelectionCallback = nullptr; - mSaveWorkspaceCallback = nullptr; + m_saveWorkspaceCallback = nullptr; } // destructor MainWindow::~MainWindow() { - if (mNativeEventFilter) + if (m_nativeEventFilter) { - QAbstractEventDispatcher::instance()->removeNativeEventFilter(mNativeEventFilter); - delete mNativeEventFilter; - mNativeEventFilter = nullptr; + QAbstractEventDispatcher::instance()->removeNativeEventFilter(m_nativeEventFilter); + delete m_nativeEventFilter; + m_nativeEventFilter = nullptr; } - if (mAutosaveTimer) + if (m_autosaveTimer) { - mAutosaveTimer->stop(); + m_autosaveTimer->stop(); } PluginOptionsNotificationsBus::Router::BusRouterDisconnect(); @@ -279,42 +280,42 @@ namespace EMStudio // results in an empty scene Reset(); - delete mShortcutManager; - delete mFileManager; - delete mDirtyFileManager; + delete m_shortcutManager; + delete m_fileManager; + delete m_dirtyFileManager; // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mImportActorCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveActorCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveActorInstanceCallback, false); - GetCommandManager()->RemoveCommandCallback(mImportMotionCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveMotionCallback, false); - GetCommandManager()->RemoveCommandCallback(mCreateMotionSetCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveMotionSetCallback, false); - GetCommandManager()->RemoveCommandCallback(mLoadMotionSetCallback, false); - GetCommandManager()->RemoveCommandCallback(mCreateAnimGraphCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveAnimGraphCallback, false); - GetCommandManager()->RemoveCommandCallback(mLoadAnimGraphCallback, false); - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_importActorCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeActorCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeActorInstanceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_importMotionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeMotionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_createMotionSetCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeMotionSetCallback, false); + GetCommandManager()->RemoveCommandCallback(m_loadMotionSetCallback, false); + GetCommandManager()->RemoveCommandCallback(m_createAnimGraphCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeAnimGraphCallback, false); + GetCommandManager()->RemoveCommandCallback(m_loadAnimGraphCallback, false); + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); - GetCommandManager()->RemoveCommandCallback(mSaveWorkspaceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_saveWorkspaceCallback, false); GetCommandManager()->RemoveCallback(&m_mainWindowCommandManagerCallback, false); - delete mImportActorCallback; - delete mRemoveActorCallback; - delete mRemoveActorInstanceCallback; - delete mImportMotionCallback; - delete mRemoveMotionCallback; - delete mCreateMotionSetCallback; - delete mRemoveMotionSetCallback; - delete mLoadMotionSetCallback; - delete mCreateAnimGraphCallback; - delete mRemoveAnimGraphCallback; - delete mLoadAnimGraphCallback; - delete mSelectCallback; - delete mUnselectCallback; + delete m_importActorCallback; + delete m_removeActorCallback; + delete m_removeActorInstanceCallback; + delete m_importMotionCallback; + delete m_removeMotionCallback; + delete m_createMotionSetCallback; + delete m_removeMotionSetCallback; + delete m_loadMotionSetCallback; + delete m_createAnimGraphCallback; + delete m_removeAnimGraphCallback; + delete m_loadAnimGraphCallback; + delete m_selectCallback; + delete m_unselectCallback; delete m_clearSelectionCallback; - delete mSaveWorkspaceCallback; + delete m_saveWorkspaceCallback; EMotionFX::ActorEditorRequestBus::Handler::BusDisconnect(); @@ -362,8 +363,8 @@ namespace EMStudio QMenuBar* menuBar = new QMenuBar(menuWidget); menuLayout->addWidget(menuBar); - mApplicationMode = new QComboBox(); - menuLayout->addWidget(mApplicationMode); + m_applicationMode = new QComboBox(); + menuLayout->addWidget(m_applicationMode); setMenuWidget(menuWidget); @@ -372,26 +373,26 @@ namespace EMStudio menu->setObjectName("EMFX.MainWindow.FileMenu"); // reset action - mResetAction = menu->addAction(tr("&Reset"), this, &MainWindow::OnReset, QKeySequence::New); - mResetAction->setObjectName("EMFX.MainWindow.ResetAction"); + m_resetAction = menu->addAction(tr("&Reset"), this, &MainWindow::OnReset, QKeySequence::New); + m_resetAction->setObjectName("EMFX.MainWindow.ResetAction"); // save all - mSaveAllAction = menu->addAction(tr("Save All..."), this, &MainWindow::OnSaveAll, QKeySequence::Save); - mSaveAllAction->setObjectName("EMFX.MainWindow.SaveAllAction"); + m_saveAllAction = menu->addAction(tr("Save All..."), this, &MainWindow::OnSaveAll, QKeySequence::Save); + m_saveAllAction->setObjectName("EMFX.MainWindow.SaveAllAction"); // disable the reset and save all menus until one thing is loaded - mResetAction->setDisabled(true); - mSaveAllAction->setDisabled(true); + m_resetAction->setDisabled(true); + m_saveAllAction->setDisabled(true); menu->addSeparator(); // actor file actions QAction* openAction = menu->addAction(tr("&Open Actor"), this, &MainWindow::OnFileOpenActor, QKeySequence::Open); openAction->setObjectName("EMFX.MainWindow.OpenActorAction"); - mMergeActorAction = menu->addAction(tr("&Merge Actor"), this, &MainWindow::OnFileMergeActor, Qt::CTRL + Qt::Key_I); - mMergeActorAction->setObjectName("EMFX.MainWindow.MergeActorAction"); - mSaveSelectedActorsAction = menu->addAction(tr("&Save Selected Actors"), this, &MainWindow::OnFileSaveSelectedActors); - mSaveSelectedActorsAction->setObjectName("EMFX.MainWindow.SaveActorAction"); + m_mergeActorAction = menu->addAction(tr("&Merge Actor"), this, &MainWindow::OnFileMergeActor, Qt::CTRL + Qt::Key_I); + m_mergeActorAction->setObjectName("EMFX.MainWindow.MergeActorAction"); + m_saveSelectedActorsAction = menu->addAction(tr("&Save Selected Actors"), this, &MainWindow::OnFileSaveSelectedActors); + m_saveSelectedActorsAction->setObjectName("EMFX.MainWindow.SaveActorAction"); // disable the merge actor menu until one actor is in the scene DisableMergeActorMenu(); @@ -400,8 +401,8 @@ namespace EMStudio DisableSaveSelectedActorsMenu(); // recent actors submenu - mRecentActors.Init(menu, mOptions.GetMaxRecentFiles(), "Recent Actors", "recentActorFiles"); - connect(&mRecentActors, &MysticQt::RecentFiles::OnRecentFile, this, &MainWindow::OnRecentFile); + m_recentActors.Init(menu, m_options.GetMaxRecentFiles(), "Recent Actors", "recentActorFiles"); + connect(&m_recentActors, &MysticQt::RecentFiles::OnRecentFile, this, &MainWindow::OnRecentFile); // workspace file actions menu->addSeparator(); @@ -415,8 +416,8 @@ namespace EMStudio saveWorkspaceAsAction->setObjectName("EMFX.MainWindow.SaveWorkspaceAsAction"); // recent workspace submenu - mRecentWorkspaces.Init(menu, mOptions.GetMaxRecentFiles(), "Recent Workspaces", "recentWorkspaces"); - connect(&mRecentWorkspaces, &MysticQt::RecentFiles::OnRecentFile, this, &MainWindow::OnRecentFile); + m_recentWorkspaces.Init(menu, m_options.GetMaxRecentFiles(), "Recent Workspaces", "recentWorkspaces"); + connect(&m_recentWorkspaces, &MysticQt::RecentFiles::OnRecentFile, this, &MainWindow::OnRecentFile); // edit menu menu = menuBar->addMenu(tr("&Edit")); @@ -442,19 +443,19 @@ namespace EMStudio preferencesAction->setObjectName("EMFX.MainWindow.PrefsAction"); // layouts item - mLayoutsMenu = menuBar->addMenu(tr("&Layouts")); - mLayoutsMenu->setObjectName("LayoutsMenu"); + m_layoutsMenu = menuBar->addMenu(tr("&Layouts")); + m_layoutsMenu->setObjectName("LayoutsMenu"); UpdateLayoutsMenu(); // reset the application mode selection and connect it - mApplicationMode->setCurrentIndex(-1); - connect(mApplicationMode, qOverload(&QComboBox::currentIndexChanged), this, qOverload(&MainWindow::ApplicationModeChanged)); - mLayoutLoaded = false; + m_applicationMode->setCurrentIndex(-1); + connect(m_applicationMode, qOverload(&QComboBox::currentIndexChanged), this, qOverload(&MainWindow::ApplicationModeChanged)); + m_layoutLoaded = false; // view item menu = menuBar->addMenu(tr("&View")); - mCreateWindowMenu = menu; - mCreateWindowMenu->setObjectName("ViewMenu"); + m_createWindowMenu = menu; + m_createWindowMenu->setObjectName("ViewMenu"); // help menu menu = menuBar->addMenu(tr("&Help")); @@ -482,27 +483,27 @@ namespace EMStudio SetWindowTitleFromFileName(""); // create the autosave timer - mAutosaveTimer = new QTimer(this); - connect(mAutosaveTimer, &QTimer::timeout, this, &MainWindow::OnAutosaveTimeOut); + m_autosaveTimer = new QTimer(this); + connect(m_autosaveTimer, &QTimer::timeout, this, &MainWindow::OnAutosaveTimeOut); // load preferences PluginOptionsNotificationsBus::Router::BusRouterConnect(); LoadPreferences(); - mAutosaveTimer->setInterval(mOptions.GetAutoSaveInterval() * 60 * 1000); + m_autosaveTimer->setInterval(m_options.GetAutoSaveInterval() * 60 * 1000); // Create the dirty file manager and register the workspace callback. - mDirtyFileManager = new DirtyFileManager; - mDirtyFileManager->AddCallback(new SaveDirtyWorkspaceCallback); + m_dirtyFileManager = new DirtyFileManager; + m_dirtyFileManager->AddCallback(new SaveDirtyWorkspaceCallback); // init the file manager - mFileManager = new EMStudio::FileManager(this); + m_fileManager = new EMStudio::FileManager(this); //////////////////////////////////////////////////////////////////////// // Keyboard Shortcut Manager //////////////////////////////////////////////////////////////////////// // create the shortcut manager - mShortcutManager = new MysticQt::KeyboardShortcutManager(); + m_shortcutManager = new MysticQt::KeyboardShortcutManager(); // load the old shortcuts LoadKeyboardShortcuts(); @@ -513,24 +514,24 @@ namespace EMStudio "AnimGraph", this); animGraphLayoutAction->setShortcut(Qt::Key_1 | Qt::AltModifier); - mShortcutManager->RegisterKeyboardShortcut(animGraphLayoutAction, layoutGroupName, false); - connect(animGraphLayoutAction, &QAction::triggered, [this]{ mApplicationMode->setCurrentIndex(0); }); + m_shortcutManager->RegisterKeyboardShortcut(animGraphLayoutAction, layoutGroupName, false); + connect(animGraphLayoutAction, &QAction::triggered, [this]{ m_applicationMode->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); }); + m_shortcutManager->RegisterKeyboardShortcut(animationLayoutAction, layoutGroupName, false); + connect(animationLayoutAction, &QAction::triggered, [this]{ m_applicationMode->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); }); + m_shortcutManager->RegisterKeyboardShortcut(characterLayoutAction, layoutGroupName, false); + connect(characterLayoutAction, &QAction::triggered, [this]{ m_applicationMode->setCurrentIndex(2); }); addAction(characterLayoutAction); EMotionFX::ActorEditorRequestBus::Handler::BusConnect(); @@ -540,42 +541,42 @@ namespace EMStudio EMotionFX::ActorEditorRequestBus::Handler::BusConnect(); // create and register the command callbacks - mImportActorCallback = new CommandImportActorCallback(false); - mRemoveActorCallback = new CommandRemoveActorCallback(false); - mRemoveActorInstanceCallback = new CommandRemoveActorInstanceCallback(false); - mImportMotionCallback = new CommandImportMotionCallback(false); - mRemoveMotionCallback = new CommandRemoveMotionCallback(false); - mCreateMotionSetCallback = new CommandCreateMotionSetCallback(false); - mRemoveMotionSetCallback = new CommandRemoveMotionSetCallback(false); - mLoadMotionSetCallback = new CommandLoadMotionSetCallback(false); - mCreateAnimGraphCallback = new CommandCreateAnimGraphCallback(false); - mRemoveAnimGraphCallback = new CommandRemoveAnimGraphCallback(false); - mLoadAnimGraphCallback = new CommandLoadAnimGraphCallback(false); - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); + m_importActorCallback = new CommandImportActorCallback(false); + m_removeActorCallback = new CommandRemoveActorCallback(false); + m_removeActorInstanceCallback = new CommandRemoveActorInstanceCallback(false); + m_importMotionCallback = new CommandImportMotionCallback(false); + m_removeMotionCallback = new CommandRemoveMotionCallback(false); + m_createMotionSetCallback = new CommandCreateMotionSetCallback(false); + m_removeMotionSetCallback = new CommandRemoveMotionSetCallback(false); + m_loadMotionSetCallback = new CommandLoadMotionSetCallback(false); + m_createAnimGraphCallback = new CommandCreateAnimGraphCallback(false); + m_removeAnimGraphCallback = new CommandRemoveAnimGraphCallback(false); + m_loadAnimGraphCallback = new CommandLoadAnimGraphCallback(false); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); m_clearSelectionCallback = new CommandClearSelectionCallback(false); - mSaveWorkspaceCallback = new CommandSaveWorkspaceCallback(false); - GetCommandManager()->RegisterCommandCallback("ImportActor", mImportActorCallback); - GetCommandManager()->RegisterCommandCallback("RemoveActor", mRemoveActorCallback); - GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", mRemoveActorInstanceCallback); - GetCommandManager()->RegisterCommandCallback("ImportMotion", mImportMotionCallback); - GetCommandManager()->RegisterCommandCallback("RemoveMotion", mRemoveMotionCallback); - GetCommandManager()->RegisterCommandCallback("CreateMotionSet", mCreateMotionSetCallback); - GetCommandManager()->RegisterCommandCallback("RemoveMotionSet", mRemoveMotionSetCallback); - GetCommandManager()->RegisterCommandCallback("LoadMotionSet", mLoadMotionSetCallback); - GetCommandManager()->RegisterCommandCallback("CreateAnimGraph", mCreateAnimGraphCallback); - GetCommandManager()->RegisterCommandCallback("RemoveAnimGraph", mRemoveAnimGraphCallback); - GetCommandManager()->RegisterCommandCallback("LoadAnimGraph", mLoadAnimGraphCallback); - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); + m_saveWorkspaceCallback = new CommandSaveWorkspaceCallback(false); + GetCommandManager()->RegisterCommandCallback("ImportActor", m_importActorCallback); + GetCommandManager()->RegisterCommandCallback("RemoveActor", m_removeActorCallback); + GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", m_removeActorInstanceCallback); + GetCommandManager()->RegisterCommandCallback("ImportMotion", m_importMotionCallback); + GetCommandManager()->RegisterCommandCallback("RemoveMotion", m_removeMotionCallback); + GetCommandManager()->RegisterCommandCallback("CreateMotionSet", m_createMotionSetCallback); + GetCommandManager()->RegisterCommandCallback("RemoveMotionSet", m_removeMotionSetCallback); + GetCommandManager()->RegisterCommandCallback("LoadMotionSet", m_loadMotionSetCallback); + GetCommandManager()->RegisterCommandCallback("CreateAnimGraph", m_createAnimGraphCallback); + GetCommandManager()->RegisterCommandCallback("RemoveAnimGraph", m_removeAnimGraphCallback); + GetCommandManager()->RegisterCommandCallback("LoadAnimGraph", m_loadAnimGraphCallback); + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); - GetCommandManager()->RegisterCommandCallback("SaveWorkspace", mSaveWorkspaceCallback); + GetCommandManager()->RegisterCommandCallback("SaveWorkspace", m_saveWorkspaceCallback); GetCommandManager()->RegisterCallback(&m_mainWindowCommandManagerCallback); - AZ_Assert(!mNativeEventFilter, "Double initialization?"); - mNativeEventFilter = new NativeEventFilter(this); - QAbstractEventDispatcher::instance()->installNativeEventFilter(mNativeEventFilter); + AZ_Assert(!m_nativeEventFilter, "Double initialization?"); + m_nativeEventFilter = new NativeEventFilter(this); + QAbstractEventDispatcher::instance()->installNativeEventFilter(m_nativeEventFilter); } MainWindow::MainWindowCommandManagerCallback::MainWindowCommandManagerCallback() @@ -964,7 +965,7 @@ namespace EMStudio void MainWindow::OnWorkspaceSaved(const char* filename) { - mRecentWorkspaces.AddRecentFile(filename); + m_recentWorkspaces.AddRecentFile(filename); SetWindowTitleFromFileName(filename); } @@ -974,50 +975,50 @@ namespace EMStudio // enable the menus if at least one actor if (EMotionFX::GetActorManager().GetNumActors() > 0) { - mResetAction->setEnabled(true); - mSaveAllAction->setEnabled(true); + m_resetAction->setEnabled(true); + m_saveAllAction->setEnabled(true); return; } // enable the menus if at least one motion if (EMotionFX::GetMotionManager().GetNumMotions() > 0) { - mResetAction->setEnabled(true); - mSaveAllAction->setEnabled(true); + m_resetAction->setEnabled(true); + m_saveAllAction->setEnabled(true); return; } // enable the menus if at least one motion set if (EMotionFX::GetMotionManager().GetNumMotionSets() > 0) { - mResetAction->setEnabled(true); - mSaveAllAction->setEnabled(true); + m_resetAction->setEnabled(true); + m_saveAllAction->setEnabled(true); return; } // enable the menus if at least one anim graph if (EMotionFX::GetAnimGraphManager().GetNumAnimGraphs() > 0) { - mResetAction->setEnabled(true); - mSaveAllAction->setEnabled(true); + m_resetAction->setEnabled(true); + m_saveAllAction->setEnabled(true); return; } // nothing loaded, disable the menus - mResetAction->setDisabled(true); - mSaveAllAction->setDisabled(true); + m_resetAction->setDisabled(true); + m_saveAllAction->setDisabled(true); } void MainWindow::EnableMergeActorMenu() { - mMergeActorAction->setEnabled(true); + m_mergeActorAction->setEnabled(true); } void MainWindow::DisableMergeActorMenu() { - mMergeActorAction->setDisabled(true); + m_mergeActorAction->setDisabled(true); } @@ -1036,8 +1037,8 @@ namespace EMStudio // enable the actor save selected menu only if one actor or actor instance is selected // it's needed to check here because if one actor is removed it's not selected anymore const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedActors = selectionList.GetNumSelectedActors(); - const uint32 numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numSelectedActors = selectionList.GetNumSelectedActors(); + const size_t numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); if ((numSelectedActors > 0) || (numSelectedActorInstances > 0)) { EnableSaveSelectedActorsMenu(); @@ -1051,13 +1052,13 @@ namespace EMStudio void MainWindow::EnableSaveSelectedActorsMenu() { - mSaveSelectedActorsAction->setEnabled(true); + m_saveSelectedActorsAction->setEnabled(true); } void MainWindow::DisableSaveSelectedActorsMenu() { - mSaveSelectedActorsAction->setDisabled(true); + m_saveSelectedActorsAction->setDisabled(true); } @@ -1086,26 +1087,26 @@ namespace EMStudio PluginManager* pluginManager = GetPluginManager(); // get the number of plugins - const uint32 numPlugins = pluginManager->GetNumPlugins(); + const size_t numPlugins = pluginManager->GetNumPlugins(); // add each plugin name in an array to sort them - MCore::Array sortedPlugins; - sortedPlugins.Reserve(numPlugins); - for (uint32 p = 0; p < numPlugins; ++p) + AZStd::vector sortedPlugins; + sortedPlugins.reserve(numPlugins); + for (size_t p = 0; p < numPlugins; ++p) { EMStudioPlugin* plugin = pluginManager->GetPlugin(p); - sortedPlugins.Add(plugin->GetName()); + sortedPlugins.emplace_back(plugin->GetName()); } - sortedPlugins.Sort(); + AZStd::sort(begin(sortedPlugins), end(sortedPlugins)); // clear the window menu - mCreateWindowMenu->clear(); + m_createWindowMenu->clear(); // for all registered plugins, create a menu items - for (uint32 p = 0; p < numPlugins; ++p) + for (size_t p = 0; p < numPlugins; ++p) { // get the plugin - const uint32 pluginIndex = pluginManager->FindPluginByTypeString(sortedPlugins[p].c_str()); + const size_t pluginIndex = pluginManager->FindPluginByTypeString(sortedPlugins[p].c_str()); EMStudioPlugin* plugin = pluginManager->GetPlugin(pluginIndex); // don't add invisible plugins to the list @@ -1119,14 +1120,14 @@ namespace EMStudio if (plugin->AllowMultipleInstances()) { // create the menu - mCreateWindowMenu->addMenu(plugin->GetName()); + m_createWindowMenu->addMenu(plugin->GetName()); // TODO: add each instance inside the submenu } else { // create the action - QAction* action = mCreateWindowMenu->addAction(plugin->GetName()); + QAction* action = m_createWindowMenu->addAction(plugin->GetName()); action->setData(plugin->GetName()); // connect the action to activate the plugin when clicked on it @@ -1143,7 +1144,7 @@ namespace EMStudio if (activePlugin) { // must use the active plugin, as it needs to be initialized to create window entries - activePlugin->AddWindowMenuEntries(mCreateWindowMenu); + activePlugin->AddWindowMenuEntries(m_createWindowMenu); } } } @@ -1209,20 +1210,20 @@ namespace EMStudio // show the preferences dialog void MainWindow::OnPreferences() { - if (mPreferencesWindow == nullptr) + if (m_preferencesWindow == nullptr) { - mPreferencesWindow = new PreferencesWindow(this); - mPreferencesWindow->Init(); + m_preferencesWindow = new PreferencesWindow(this); + m_preferencesWindow->Init(); - AzToolsFramework::ReflectedPropertyEditor* generalPropertyWidget = mPreferencesWindow->AddCategory("General"); + AzToolsFramework::ReflectedPropertyEditor* generalPropertyWidget = m_preferencesWindow->AddCategory("General"); generalPropertyWidget->ClearInstances(); generalPropertyWidget->InvalidateAll(); - generalPropertyWidget->AddInstance(&mOptions, azrtti_typeid(mOptions)); + generalPropertyWidget->AddInstance(&m_options, azrtti_typeid(m_options)); PluginManager* pluginManager = GetPluginManager(); - const uint32 numPlugins = pluginManager->GetNumActivePlugins(); - for (uint32 i = 0; i < numPlugins; ++i) + const size_t numPlugins = pluginManager->GetNumActivePlugins(); + for (size_t i = 0; i < numPlugins; ++i) { EMStudioPlugin* currentPlugin = pluginManager->GetActivePlugin(i); PluginOptions* pluginOptions = currentPlugin->GetOptions(); @@ -1246,11 +1247,11 @@ namespace EMStudio generalPropertyWidget->InvalidateAll(); // Keyboard shortcuts - KeyboardShortcutsWindow* shortcutsWindow = new KeyboardShortcutsWindow(mPreferencesWindow); - mPreferencesWindow->AddCategory(shortcutsWindow, "Keyboard shortcuts"); + KeyboardShortcutsWindow* shortcutsWindow = new KeyboardShortcutsWindow(m_preferencesWindow); + m_preferencesWindow->AddCategory(shortcutsWindow, "Keyboard shortcuts"); } - mPreferencesWindow->exec(); + m_preferencesWindow->exec(); SavePreferences(); } @@ -1260,7 +1261,7 @@ namespace EMStudio { // open the config file QSettings settings(this); - mOptions.Save(settings, *this); + m_options.Save(settings, *this); } @@ -1269,24 +1270,24 @@ namespace EMStudio { // When a setting changes, OnOptionChanged will save. To avoid saving while settings are being // loaded, we use this flag - mLoadingOptions = true; + m_loadingOptions = true; // open the config file QSettings settings(this); - mOptions = GUIOptions::Load(settings, *this); + m_options = GUIOptions::Load(settings, *this); - mLoadingOptions = false; + m_loadingOptions = false; } void MainWindow::AddRecentActorFile(const QString& fileName) { - mRecentActors.AddRecentFile(fileName.toUtf8().data()); + m_recentActors.AddRecentFile(fileName.toUtf8().data()); } void MainWindow::LoadKeyboardShortcuts() { QSettings shortcutSettings(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioKeyboardShortcuts.cfg").c_str(), QSettings::IniFormat, this); - mShortcutManager->Load(&shortcutSettings); + m_shortcutManager->Load(&shortcutSettings); } void MainWindow::LoadActor(const char* fileName, bool replaceCurrentScene) @@ -1320,17 +1321,17 @@ namespace EMStudio // add the load actor settings LoadActorSettingsWindow::LoadActorSettings loadActorSettings; - loadActorCommand += "-loadMeshes " + AZStd::to_string(loadActorSettings.mLoadMeshes); - loadActorCommand += " -loadTangents " + AZStd::to_string(loadActorSettings.mLoadTangents); - loadActorCommand += " -autoGenTangents " + AZStd::to_string(loadActorSettings.mAutoGenerateTangents); - loadActorCommand += " -loadLimits " + AZStd::to_string(loadActorSettings.mLoadLimits); - loadActorCommand += " -loadGeomLods " + AZStd::to_string(loadActorSettings.mLoadGeometryLODs); - loadActorCommand += " -loadMorphTargets " + AZStd::to_string(loadActorSettings.mLoadMorphTargets); - loadActorCommand += " -loadCollisionMeshes " + AZStd::to_string(loadActorSettings.mLoadCollisionMeshes); - loadActorCommand += " -loadMaterialLayers " + AZStd::to_string(loadActorSettings.mLoadStandardMaterialLayers); - loadActorCommand += " -loadSkinningInfo " + AZStd::to_string(loadActorSettings.mLoadSkinningInfo); - loadActorCommand += " -loadSkeletalLODs " + AZStd::to_string(loadActorSettings.mLoadSkeletalLODs); - loadActorCommand += " -dualQuatSkinning " + AZStd::to_string(loadActorSettings.mDualQuaternionSkinning); + loadActorCommand += "-loadMeshes " + AZStd::to_string(loadActorSettings.m_loadMeshes); + loadActorCommand += " -loadTangents " + AZStd::to_string(loadActorSettings.m_loadTangents); + loadActorCommand += " -autoGenTangents " + AZStd::to_string(loadActorSettings.m_autoGenerateTangents); + loadActorCommand += " -loadLimits " + AZStd::to_string(loadActorSettings.m_loadLimits); + loadActorCommand += " -loadGeomLods " + AZStd::to_string(loadActorSettings.m_loadGeometryLoDs); + loadActorCommand += " -loadMorphTargets " + AZStd::to_string(loadActorSettings.m_loadMorphTargets); + loadActorCommand += " -loadCollisionMeshes " + AZStd::to_string(loadActorSettings.m_loadCollisionMeshes); + loadActorCommand += " -loadMaterialLayers " + AZStd::to_string(loadActorSettings.m_loadStandardMaterialLayers); + loadActorCommand += " -loadSkinningInfo " + AZStd::to_string(loadActorSettings.m_loadSkinningInfo); + loadActorCommand += " -loadSkeletalLODs " + AZStd::to_string(loadActorSettings.m_loadSkeletalLoDs); + loadActorCommand += " -dualQuatSkinning " + AZStd::to_string(loadActorSettings.m_dualQuaternionSkinning); // add the load and the create instance commands commandGroup.AddCommandString(loadActorCommand.c_str()); @@ -1345,14 +1346,14 @@ namespace EMStudio // add the actor in the recent actor list // if the same actor is already in the list, the duplicate is removed - mRecentActors.AddRecentFile(fileName); + m_recentActors.AddRecentFile(fileName); } void MainWindow::LoadCharacter(const AZ::Data::AssetId& actorAssetId, const AZ::Data::AssetId& animgraphId, const AZ::Data::AssetId& motionSetId) { - mCharacterFiles.clear(); + m_characterFiles.clear(); AZStd::string cachePath = gEnv->pFileIO->GetAlias("@assets@"); AZStd::string filename; AzFramework::StringFunc::AssetDatabasePath::Normalize(cachePath); @@ -1395,10 +1396,10 @@ namespace EMStudio AZStd::vector objects; AZStd::vector dirtyObjects; - const size_t numDirtyFilesCallbacks = mDirtyFileManager->GetNumCallbacks(); + const size_t numDirtyFilesCallbacks = m_dirtyFileManager->GetNumCallbacks(); for (size_t i = 0; i < numDirtyFilesCallbacks; ++i) { - SaveDirtyFilesCallback* callback = mDirtyFileManager->GetCallback(i); + SaveDirtyFilesCallback* callback = m_dirtyFileManager->GetCallback(i); callback->GetDirtyFileNames(&filenames, &objects); const size_t numFileNames = filenames.size(); for (size_t j = 0; j < numFileNames; ++j) @@ -1428,18 +1429,18 @@ namespace EMStudio // Dont reload dirty files that are already open. if (!foundActor) { - mCharacterFiles.push_back(actorFilename); + m_characterFiles.push_back(actorFilename); } if (!foundAnimgraph) { - mCharacterFiles.push_back(animgraphFilename); + m_characterFiles.push_back(animgraphFilename); } if (!foundMotionSet) { - mCharacterFiles.push_back(motionSetFilename); + m_characterFiles.push_back(motionSetFilename); } - if (isVisible() && mLayoutLoaded) + if (isVisible() && m_layoutLoaded) { LoadCharacterFiles(); } @@ -1448,7 +1449,7 @@ namespace EMStudio void MainWindow::OnFileNewWorkspace() { // save all files that have been changed - if (mDirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) { return; } @@ -1490,7 +1491,7 @@ namespace EMStudio void MainWindow::OnFileOpenWorkspace() { - const AZStd::string filename = mFileManager->LoadWorkspaceFileDialog(this); + const AZStd::string filename = m_fileManager->LoadWorkspaceFileDialog(this); if (filename.empty()) { return; @@ -1502,14 +1503,14 @@ namespace EMStudio void MainWindow::OnSaveAll() { - mDirtyFileManager->SaveDirtyFiles(MCORE_INVALIDINDEX32, MCORE_INVALIDINDEX32, QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + m_dirtyFileManager->SaveDirtyFiles(MCORE_INVALIDINDEX32, MCORE_INVALIDINDEX32, QDialogButtonBox::Ok | QDialogButtonBox::Cancel); } void MainWindow::OnFileSaveWorkspace() { // save all files that have been changed, filter to not show the workspace files - if (mDirtyFileManager->SaveDirtyFiles(MCORE_INVALIDINDEX32, SaveDirtyWorkspaceCallback::TYPE_ID) == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles(MCORE_INVALIDINDEX32, SaveDirtyWorkspaceCallback::TYPE_ID) == DirtyFileManager::CANCELED) { return; } @@ -1551,7 +1552,7 @@ namespace EMStudio void MainWindow::OnFileSaveWorkspaceAs() { // save all files that have been changed, filter to not show the workspace files - if (mDirtyFileManager->SaveDirtyFiles(MCORE_INVALIDINDEX32, SaveDirtyWorkspaceCallback::TYPE_ID) == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles(MCORE_INVALIDINDEX32, SaveDirtyWorkspaceCallback::TYPE_ID) == DirtyFileManager::CANCELED) { return; } @@ -1642,7 +1643,7 @@ namespace EMStudio void MainWindow::OnReset() { - if (mDirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) { return; } @@ -1672,52 +1673,52 @@ namespace EMStudio if (optionChanged == GUIOptions::s_maxRecentFilesOptionName) { // Set the maximum number of recent files - mRecentActors.SetMaxRecentFiles(mOptions.GetMaxRecentFiles()); - mRecentWorkspaces.SetMaxRecentFiles(mOptions.GetMaxRecentFiles()); + m_recentActors.SetMaxRecentFiles(m_options.GetMaxRecentFiles()); + m_recentWorkspaces.SetMaxRecentFiles(m_options.GetMaxRecentFiles()); } else if (optionChanged == GUIOptions::s_maxHistoryItemsOptionName) { // Set the maximum number of history items in the command manager - GetCommandManager()->SetMaxHistoryItems(mOptions.GetMaxHistoryItems()); + GetCommandManager()->SetMaxHistoryItems(m_options.GetMaxHistoryItems()); } else if (optionChanged == GUIOptions::s_notificationVisibleTimeOptionName) { // Set the notification visible time - GetNotificationWindowManager()->SetVisibleTime(mOptions.GetNotificationInvisibleTime()); + GetNotificationWindowManager()->SetVisibleTime(m_options.GetNotificationInvisibleTime()); } else if (optionChanged == GUIOptions::s_enableAutosaveOptionName) { // Enable or disable the autosave timer - if (mOptions.GetEnableAutoSave()) + if (m_options.GetEnableAutoSave()) { - mAutosaveTimer->setInterval(mOptions.GetAutoSaveInterval() * 60 * 1000); - mAutosaveTimer->start(); + m_autosaveTimer->setInterval(m_options.GetAutoSaveInterval() * 60 * 1000); + m_autosaveTimer->start(); } else { - mAutosaveTimer->stop(); + m_autosaveTimer->stop(); } } else if (optionChanged == GUIOptions::s_autosaveIntervalOptionName) { // Set the autosave interval - mAutosaveTimer->stop(); - mAutosaveTimer->setInterval(mOptions.GetAutoSaveInterval() * 60 * 1000); - mAutosaveTimer->start(); + m_autosaveTimer->stop(); + m_autosaveTimer->setInterval(m_options.GetAutoSaveInterval() * 60 * 1000); + m_autosaveTimer->start(); } else if (optionChanged == GUIOptions::s_importerLogDetailsEnabledOptionName) { // Set if the detail logging of the importer is enabled or not - EMotionFX::GetImporter().SetLogDetails(mOptions.GetImporterLogDetailsEnabled()); + EMotionFX::GetImporter().SetLogDetails(m_options.GetImporterLogDetailsEnabled()); } else if (optionChanged == GUIOptions::s_autoLoadLastWorkspaceOptionName) { // Set if auto loading the last workspace is enabled or not - GetManager()->SetAutoLoadLastWorkspace(mOptions.GetAutoLoadLastWorkspace()); + GetManager()->SetAutoLoadLastWorkspace(m_options.GetAutoLoadLastWorkspace()); } // Save preferences - if (!mLoadingOptions) + if (!m_loadingOptions) { SavePreferences(); } @@ -1726,12 +1727,12 @@ namespace EMStudio // open an actor void MainWindow::OnFileOpenActor() { - if (mDirtyFileManager->SaveDirtyFiles({azrtti_typeid()}) == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles({azrtti_typeid()}) == DirtyFileManager::CANCELED) { return; } - AZStd::vector filenames = mFileManager->LoadActorsFileDialog(this); + AZStd::vector filenames = m_fileManager->LoadActorsFileDialog(this); activateWindow(); if (filenames.empty()) { @@ -1749,7 +1750,7 @@ namespace EMStudio // merge an actor void MainWindow::OnFileMergeActor() { - AZStd::vector filenames = mFileManager->LoadActorsFileDialog(this); + AZStd::vector filenames = m_fileManager->LoadActorsFileDialog(this); activateWindow(); if (filenames.empty()) { @@ -1768,21 +1769,21 @@ namespace EMStudio { // get the current selection list const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedActors = selectionList.GetNumSelectedActors(); - const uint32 numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numSelectedActors = selectionList.GetNumSelectedActors(); + const size_t numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); // create the saving actor array AZStd::vector savingActors; savingActors.reserve(numSelectedActors + numSelectedActorInstances); // add all selected actors to the list - for (uint32 i = 0; i < numSelectedActors; ++i) + for (size_t i = 0; i < numSelectedActors; ++i) { savingActors.push_back(selectionList.GetActor(i)); } // check all actors of all selected actor instances and put them in the list if they are not in yet - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { EMotionFX::Actor* actor = selectionList.GetActorInstance(i)->GetActor(); @@ -1828,7 +1829,7 @@ namespace EMStudio void MainWindow::UpdateLayoutsMenu() { // clear the current menu - mLayoutsMenu->clear(); + m_layoutsMenu->clear(); // generate the layouts path QDir layoutsPath = QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Layouts"); @@ -1839,7 +1840,7 @@ namespace EMStudio dir.setSorting(QDir::Name); // add each layout - mLayoutNames.Clear(); + m_layoutNames.clear(); AZStd::string filename; const QFileInfoList list = dir.entryInfoList(); const int listSize = list.size(); @@ -1856,70 +1857,69 @@ namespace EMStudio if (extension == "layout") { AzFramework::StringFunc::Path::GetFileName(filename.c_str(), filename); - mLayoutNames.Add(filename); + m_layoutNames.emplace_back(filename); } } // add each menu - const uint32 numLayoutNames = mLayoutNames.GetLength(); - for (uint32 i = 0; i < numLayoutNames; ++i) + for (const AZStd::string& layoutName : m_layoutNames) { - QAction* action = mLayoutsMenu->addAction(mLayoutNames[i].c_str()); + QAction* action = m_layoutsMenu->addAction(layoutName.c_str()); connect(action, &QAction::triggered, this, &MainWindow::OnLoadLayout); } // add the separator only if at least one layout - if (numLayoutNames > 0) + if (!m_layoutNames.empty()) { - mLayoutsMenu->addSeparator(); + m_layoutsMenu->addSeparator(); } // add the save current menu - QAction* saveCurrentAction = mLayoutsMenu->addAction("Save Current"); + QAction* saveCurrentAction = m_layoutsMenu->addAction("Save Current"); connect(saveCurrentAction, &QAction::triggered, this, &MainWindow::OnLayoutSaveAs); // remove menu is needed only if at least one layout - if (numLayoutNames > 0) + if (!m_layoutNames.empty()) { // add the remove menu - QMenu* removeMenu = mLayoutsMenu->addMenu("Remove"); + QMenu* removeMenu = m_layoutsMenu->addMenu("Remove"); removeMenu->setObjectName("RemoveMenu"); // add each layout in the remove menu - for (uint32 i = 0; i < numLayoutNames; ++i) + for (const AZStd::string& layoutName : m_layoutNames) { // User cannot remove the default layout. This layout is referenced in the qrc file, removing it will // cause compiling issue too. - if (mLayoutNames[i] == "AnimGraph") + if (layoutName == "AnimGraph") { continue; } - QAction* action = removeMenu->addAction(mLayoutNames[i].c_str()); + QAction* action = removeMenu->addAction(layoutName.c_str()); connect(action, &QAction::triggered, this, &MainWindow::OnRemoveLayout); } } // disable signals to avoid to switch of layout - mApplicationMode->blockSignals(true); + m_applicationMode->blockSignals(true); // update the combo box - mApplicationMode->clear(); - for (uint32 i = 0; i < numLayoutNames; ++i) + m_applicationMode->clear(); + for (const AZStd::string& layoutName : m_layoutNames) { - mApplicationMode->addItem(mLayoutNames[i].c_str()); + m_applicationMode->addItem(layoutName.c_str()); } // update the current selection of combo box - const int layoutIndex = mApplicationMode->findText(QString(mOptions.GetApplicationMode().c_str())); - mApplicationMode->setCurrentIndex(layoutIndex); + const int layoutIndex = m_applicationMode->findText(QString(m_options.GetApplicationMode().c_str())); + m_applicationMode->setCurrentIndex(layoutIndex); // enable signals - mApplicationMode->blockSignals(false); + m_applicationMode->blockSignals(false); } void MainWindow::ApplicationModeChanged(int index) { - QString text = mApplicationMode->itemText(index); + QString text = m_applicationMode->itemText(index); ApplicationModeChanged(text); } @@ -1935,7 +1935,7 @@ namespace EMStudio } // update the last used layout and save it in the preferences file - mOptions.SetApplicationMode(text.toUtf8().data()); + m_options.SetApplicationMode(text.toUtf8().data()); SavePreferences(); // generate the filename @@ -1972,16 +1972,16 @@ namespace EMStudio } // check if the layout removed is the current used - if (QString(mOptions.GetApplicationMode().c_str()) == m_removeLayoutNameText) + if (QString(m_options.GetApplicationMode().c_str()) == m_removeLayoutNameText) { // find the layout index on the application mode combo box - const int layoutIndex = mApplicationMode->findText(m_removeLayoutNameText); + const int layoutIndex = m_applicationMode->findText(m_removeLayoutNameText); // set the new layout index, take the previous if the last layout is removed, the next is taken otherwise - const int newLayoutIndex = (layoutIndex == (mApplicationMode->count() - 1)) ? layoutIndex - 1 : layoutIndex + 1; + const int newLayoutIndex = (layoutIndex == (m_applicationMode->count() - 1)) ? layoutIndex - 1 : layoutIndex + 1; // select the layout, it also keeps it and saves to config - mApplicationMode->setCurrentIndex(newLayoutIndex); + m_applicationMode->setCurrentIndex(newLayoutIndex); } // update the layouts menu @@ -2021,7 +2021,7 @@ namespace EMStudio QAction* action = qobject_cast(sender()); // update the last used layout and save it in the preferences file - mOptions.SetApplicationMode(action->text().toUtf8().data()); + m_options.SetApplicationMode(action->text().toUtf8().data()); SavePreferences(); // generate the filename @@ -2031,10 +2031,10 @@ namespace EMStudio if (GetLayoutManager()->LoadLayout(filename.c_str())) { // update the combo box - mApplicationMode->blockSignals(true); - const int layoutIndex = mApplicationMode->findText(action->text()); - mApplicationMode->setCurrentIndex(layoutIndex); - mApplicationMode->blockSignals(false); + m_applicationMode->blockSignals(true); + const int layoutIndex = m_applicationMode->findText(action->text()); + m_applicationMode->setCurrentIndex(layoutIndex); + m_applicationMode->blockSignals(false); } else { @@ -2054,7 +2054,7 @@ namespace EMStudio const bool result = GetCommandManager()->Undo(outResult); // log the results if there are any - if (outResult.size() > 0) + if (!outResult.empty()) { if (result == false) { @@ -2079,7 +2079,7 @@ namespace EMStudio const bool result = GetCommandManager()->Redo(outResult); // log the results if there are any - if (outResult.size() > 0) + if (!outResult.empty()) { if (result == false) { @@ -2195,8 +2195,8 @@ namespace EMStudio const size_t actorCount = actorFilenames.size(); if (actorCount == 1) { - mDroppedActorFileName = actorFilenames[0].c_str(); - mRecentActors.AddRecentFile(mDroppedActorFileName.c_str()); + m_droppedActorFileName = actorFilenames[0].c_str(); + m_recentActors.AddRecentFile(m_droppedActorFileName.c_str()); if (contextMenuEnabled) { @@ -2252,11 +2252,11 @@ namespace EMStudio if (numWorkspaces > 0) { // make sure we did not cancel load workspace - if (mDirtyFileManager->SaveDirtyFiles() != DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles() != DirtyFileManager::CANCELED) { // add the workspace in the recent workspace list // if the same workspace is already in the list, the duplicate is removed - mRecentWorkspaces.AddRecentFile(workspaceFilenames[0]); + m_recentWorkspaces.AddRecentFile(workspaceFilenames[0]); // create the command group MCore::CommandGroup workspaceCommandGroup("Load workspace", 64); @@ -2278,8 +2278,8 @@ namespace EMStudio // for all registered plugins, call the after load workspace callback PluginManager* pluginManager = GetPluginManager(); - const uint32 numPlugins = pluginManager->GetNumActivePlugins(); - for (uint32 p = 0; p < numPlugins; ++p) + const size_t numPlugins = pluginManager->GetNumActivePlugins(); + for (size_t p = 0; p < numPlugins; ++p) { EMStudioPlugin* plugin = pluginManager->GetActivePlugin(p); plugin->OnAfterLoadProject(); @@ -2319,8 +2319,8 @@ namespace EMStudio MCore::CommandGroup commandGroup("Animgraph and motion set activation"); AZStd::string commandString; - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); if (!actorInstance || actorFilename != actorInstance->GetActor()->GetFileName()) @@ -2344,21 +2344,21 @@ namespace EMStudio void MainWindow::LoadLayoutAfterShow() { - if (!mLayoutLoaded) + if (!m_layoutLoaded) { - mLayoutLoaded = true; + m_layoutLoaded = true; LoadDefaultLayout(); - if (mCharacterFiles.empty() && GetManager()->GetAutoLoadLastWorkspace()) + if (m_characterFiles.empty() && GetManager()->GetAutoLoadLastWorkspace()) { // load last workspace - const AZStd::string lastRecentWorkspace = mRecentWorkspaces.GetLastRecentFileName(); + const AZStd::string lastRecentWorkspace = m_recentWorkspaces.GetLastRecentFileName(); if (!lastRecentWorkspace.empty()) { - mCharacterFiles.push_back(lastRecentWorkspace); + m_characterFiles.push_back(lastRecentWorkspace); } } - if (!mCharacterFiles.empty()) + if (!m_characterFiles.empty()) { // Need to defer loading the character until the layout is ready. We also // need a couple of initializeGL/paintGL to happen before the character @@ -2391,7 +2391,7 @@ namespace EMStudio // Load default layout. void MainWindow::LoadDefaultLayout() { - if (mApplicationMode->count() == 0) + if (m_applicationMode->count() == 0) { // When the combo box is empty, the call to setCurrentIndex will // not cause any slots to be fired, so dispatch the call manually. @@ -2401,23 +2401,23 @@ namespace EMStudio return; } - int layoutIndex = mApplicationMode->findText(mOptions.GetApplicationMode().c_str()); + int layoutIndex = m_applicationMode->findText(m_options.GetApplicationMode().c_str()); // If searching for the last used layout fails load the default or viewer layout if they exist if (layoutIndex == -1) { - layoutIndex = mApplicationMode->findText("AnimGraph"); + layoutIndex = m_applicationMode->findText("AnimGraph"); } if (layoutIndex == -1) { - layoutIndex = mApplicationMode->findText("Character"); + layoutIndex = m_applicationMode->findText("Character"); } if (layoutIndex == -1) { - layoutIndex = mApplicationMode->findText("Animation"); + layoutIndex = m_applicationMode->findText("Animation"); } - mApplicationMode->setCurrentIndex(layoutIndex); + m_applicationMode->setCurrentIndex(layoutIndex); } @@ -2457,15 +2457,15 @@ namespace EMStudio void MainWindow::LoadCharacterFiles() { - if (!mCharacterFiles.empty()) + if (!m_characterFiles.empty()) { - LoadFiles(mCharacterFiles, 0, 0, false, true); - mCharacterFiles.clear(); + LoadFiles(m_characterFiles, 0, 0, false, true); + m_characterFiles.clear(); // for all registered plugins, call the after load actors callback PluginManager* pluginManager = GetPluginManager(); - const uint32 numPlugins = pluginManager->GetNumActivePlugins(); - for (uint32 p = 0; p < numPlugins; ++p) + const size_t numPlugins = pluginManager->GetNumActivePlugins(); + for (size_t p = 0; p < numPlugins; ++p) { EMStudioPlugin* plugin = pluginManager->GetActivePlugin(p); plugin->OnAfterLoadActors(); @@ -2494,18 +2494,18 @@ namespace EMStudio // gets called when the user drag&dropped an actor to the application and then chose to open it in the context menu void MainWindow::OnOpenDroppedActor() { - if (mDirtyFileManager->SaveDirtyFiles({azrtti_typeid()}) == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles({azrtti_typeid()}) == DirtyFileManager::CANCELED) { return; } - LoadActor(mDroppedActorFileName.c_str(), true); + LoadActor(m_droppedActorFileName.c_str(), true); } // gets called when the user drag&dropped an actor to the application and then chose to merge it in the context menu void MainWindow::OnMergeDroppedActor() { - LoadActor(mDroppedActorFileName.c_str(), false); + LoadActor(m_droppedActorFileName.c_str(), false); } @@ -2536,13 +2536,13 @@ namespace EMStudio void MainWindow::closeEvent(QCloseEvent* event) { - if (mDirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) + if (m_dirtyFileManager->SaveDirtyFiles() == DirtyFileManager::CANCELED) { event->ignore(); } else { - mAutosaveTimer->stop(); + m_autosaveTimer->stop(); PluginManager* pluginManager = GetPluginManager(); @@ -2570,22 +2570,22 @@ namespace EMStudio // We mark it as false so next time is shown the layout is re-loaded if // necessary - mLayoutLoaded = false; + m_layoutLoaded = false; } void MainWindow::showEvent(QShowEvent* event) { - if (mOptions.GetEnableAutoSave()) + if (m_options.GetEnableAutoSave()) { - mAutosaveTimer->setInterval(mOptions.GetAutoSaveInterval() * 60 * 1000); - mAutosaveTimer->start(); + m_autosaveTimer->setInterval(m_options.GetAutoSaveInterval() * 60 * 1000); + m_autosaveTimer->start(); } // EMotionFX dock widget is created the first time it's opened, so we need to load layout after that // The singleShot is needed because show event is fired before the dock widget resizes (in the same function dock widget is created) // So we want to load layout after that. It's a bit hacky, but most sensible at the moment. - if (!mLayoutLoaded) + if (!m_layoutLoaded) { QTimer::singleShot(0, this, &MainWindow::LoadLayoutAfterShow); } @@ -2603,7 +2603,7 @@ namespace EMStudio const char* MainWindow::GetCurrentLayoutName() const { // get the selected layout - const int currentLayoutIndex = mApplicationMode->currentIndex(); + const int currentLayoutIndex = m_applicationMode->currentIndex(); // if the index is out of range, return empty name if ((currentLayoutIndex < 0) || (currentLayoutIndex >= (int32)GetNumLayouts())) @@ -2628,10 +2628,10 @@ namespace EMStudio AZStd::vector objects; AZStd::vector dirtyObjects; - const size_t numDirtyFilesCallbacks = mDirtyFileManager->GetNumCallbacks(); + const size_t numDirtyFilesCallbacks = m_dirtyFileManager->GetNumCallbacks(); for (size_t i = 0; i < numDirtyFilesCallbacks; ++i) { - SaveDirtyFilesCallback* callback = mDirtyFileManager->GetCallback(i); + SaveDirtyFilesCallback* callback = m_dirtyFileManager->GetCallback(i); callback->GetDirtyFileNames(&filenames, &objects); const size_t numFileNames = filenames.size(); for (size_t j = 0; j < numFileNames; ++j) @@ -2721,11 +2721,11 @@ namespace EMStudio } // check if the length is upper than the max num files - if (autosaveFileList.length() >= mOptions.GetAutoSaveNumberOfFiles()) + if (autosaveFileList.length() >= m_options.GetAutoSaveNumberOfFiles()) { // number of files to delete // one is added because one space needs to be free for the new file - const int numFilesToDelete = mOptions.GetAutoSaveNumberOfFiles() ? (autosaveFileList.size() - mOptions.GetAutoSaveNumberOfFiles() + 1) : autosaveFileList.size(); + const int numFilesToDelete = m_options.GetAutoSaveNumberOfFiles() ? (autosaveFileList.size() - m_options.GetAutoSaveNumberOfFiles() + 1) : autosaveFileList.size(); // delete each file for (int j = 0; j < numFilesToDelete; ++j) @@ -2749,18 +2749,18 @@ namespace EMStudio AZ_Printf("EMotionFX", "Saving to '%s'\n", newFileFilename.c_str()); // Backing up actors and motions doesn't work anymore as we just update the .assetinfos and the asset processor does the rest. - if (dirtyObjects[i].mMotionSet) + if (dirtyObjects[i].m_motionSet) { - command = AZStd::string::format("SaveMotionSet -motionSetID %i -filename \"%s\" -updateFilename false -updateDirtyFlag false -sourceControl false", dirtyObjects[i].mMotionSet->GetID(), newFileFilename.c_str()); + command = AZStd::string::format("SaveMotionSet -motionSetID %i -filename \"%s\" -updateFilename false -updateDirtyFlag false -sourceControl false", dirtyObjects[i].m_motionSet->GetID(), newFileFilename.c_str()); commandGroup.AddCommandString(command); } - else if (dirtyObjects[i].mAnimGraph) + else if (dirtyObjects[i].m_animGraph) { - const uint32 animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(dirtyObjects[i].mAnimGraph); - command = AZStd::string::format("SaveAnimGraph -index %i -filename \"%s\" -updateFilename false -updateDirtyFlag false -sourceControl false", animGraphIndex, newFileFilename.c_str()); + const size_t animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(dirtyObjects[i].m_animGraph); + command = AZStd::string::format("SaveAnimGraph -index %zu -filename \"%s\" -updateFilename false -updateDirtyFlag false -sourceControl false", animGraphIndex, newFileFilename.c_str()); commandGroup.AddCommandString(command); } - else if (dirtyObjects[i].mWorkspace) + else if (dirtyObjects[i].m_workspace) { Workspace* workspace = GetManager()->GetWorkspace(); workspace->Save(newFileFilename.c_str(), false, false); @@ -2802,8 +2802,8 @@ namespace EMStudio PluginManager* pluginManager = GetPluginManager(); // get the number of active plugins, iterate through them and call the process frame method - const uint32 numPlugins = pluginManager->GetNumActivePlugins(); - for (uint32 p = 0; p < numPlugins; ++p) + const size_t numPlugins = pluginManager->GetNumActivePlugins(); + for (size_t p = 0; p < numPlugins; ++p) { EMStudioPlugin* plugin = pluginManager->GetActivePlugin(p); if (plugin->GetPluginType() == EMStudioPlugin::PLUGINTYPE_RENDERING) 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 a8909380ef..734dd7840d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include #include #include @@ -91,7 +91,7 @@ namespace EMStudio void Init(const AZStd::vector& errors); private: - QTextEdit* mTextEdit = nullptr; + QTextEdit* m_textEdit = nullptr; }; // the main window @@ -114,7 +114,7 @@ namespace EMStudio static void Reflect(AZ::ReflectContext* context); void Init(); - MCORE_INLINE QMenu* GetLayoutsMenu() { return mLayoutsMenu; } + MCORE_INLINE QMenu* GetLayoutsMenu() { return m_layoutsMenu; } void LoadActor(const char* fileName, bool replaceCurrentScene); void LoadCharacter(const AZ::Data::AssetId& actorAssetId, const AZ::Data::AssetId& animgraphId, const AZ::Data::AssetId& motionSetId); @@ -123,9 +123,9 @@ namespace EMStudio void Activate(const AZ::Data::AssetId& actorAssetId, const EMotionFX::AnimGraph* animGraph, const EMotionFX::MotionSet* motionSet); - MysticQt::RecentFiles* GetRecentWorkspaces() { return &mRecentWorkspaces; } + MysticQt::RecentFiles* GetRecentWorkspaces() { return &m_recentWorkspaces; } - GUIOptions& GetOptions() { return mOptions; } + GUIOptions& GetOptions() { return m_options; } void Reset(bool clearActors = true, bool clearMotionSets = true, bool clearMotions = true, bool clearAnimGraphs = true, MCore::CommandGroup* commandGroup = nullptr); @@ -143,17 +143,17 @@ namespace EMStudio void OnWorkspaceSaved(const char* filename); - MCORE_INLINE QComboBox* GetApplicationModeComboBox() { return mApplicationMode; } - DirtyFileManager* GetDirtyFileManager() const { return mDirtyFileManager; } - FileManager* GetFileManager() const { return mFileManager; } - PreferencesWindow* GetPreferencesWindow() const { return mPreferencesWindow; } + MCORE_INLINE QComboBox* GetApplicationModeComboBox() { return m_applicationMode; } + DirtyFileManager* GetDirtyFileManager() const { return m_dirtyFileManager; } + FileManager* GetFileManager() const { return m_fileManager; } + PreferencesWindow* GetPreferencesWindow() const { return m_preferencesWindow; } - uint32 GetNumLayouts() const { return mLayoutNames.GetLength(); } - const char* GetLayoutName(uint32 index) const { return mLayoutNames[index].c_str(); } + size_t GetNumLayouts() const { return m_layoutNames.size(); } + const char* GetLayoutName(uint32 index) const { return m_layoutNames[index].c_str(); } const char* GetCurrentLayoutName() const; static const char* GetEMotionFXPaneName(); - MysticQt::KeyboardShortcutManager* GetShortcutManager() const { return mShortcutManager; } + MysticQt::KeyboardShortcutManager* GetShortcutManager() const { return m_shortcutManager; } AzQtComponents::FancyDocking* GetFancyDockingManager() const { return m_fancyDockingManager; } @@ -186,56 +186,56 @@ namespace EMStudio EMotionFX::Actor* m_prevSelectedActor; EMotionFX::ActorInstance* m_prevSelectedActorInstance; - QMenu* mCreateWindowMenu; - QMenu* mLayoutsMenu; + QMenu* m_createWindowMenu; + QMenu* m_layoutsMenu; QAction* m_undoAction; QAction* m_redoAction; // keyboard shortcut manager - MysticQt::KeyboardShortcutManager* mShortcutManager; + MysticQt::KeyboardShortcutManager* m_shortcutManager; // layouts (application modes) - MCore::Array mLayoutNames; - bool mLayoutLoaded; + AZStd::vector m_layoutNames; + bool m_layoutLoaded; // menu actions - QAction* mResetAction; - QAction* mSaveAllAction; - QAction* mMergeActorAction; - QAction* mSaveSelectedActorsAction; + QAction* m_resetAction; + QAction* m_saveAllAction; + QAction* m_mergeActorAction; + QAction* m_saveSelectedActorsAction; #ifdef EMFX_DEVELOPMENT_BUILD - QAction* mSaveSelectedActorAsAttachmentsAction; + QAction* m_saveSelectedActorAsAttachmentsAction; #endif // application mode - QComboBox* mApplicationMode; + QComboBox* m_applicationMode; - PreferencesWindow* mPreferencesWindow; + PreferencesWindow* m_preferencesWindow; - FileManager* mFileManager; + FileManager* m_fileManager; - MysticQt::RecentFiles mRecentActors; - MysticQt::RecentFiles mRecentWorkspaces; + MysticQt::RecentFiles m_recentActors; + MysticQt::RecentFiles m_recentWorkspaces; // dirty files - DirtyFileManager* mDirtyFileManager; + DirtyFileManager* m_dirtyFileManager; void SetWindowTitleFromFileName(const AZStd::string& fileName); // drag & drop support void dragEnterEvent(QDragEnterEvent* event) override; void dropEvent(QDropEvent* event) override; - AZStd::string mDroppedActorFileName; + AZStd::string m_droppedActorFileName; // General options - GUIOptions mOptions; - bool mLoadingOptions; + GUIOptions m_options; + bool m_loadingOptions; - QTimer* mAutosaveTimer; + QTimer* m_autosaveTimer; - AZStd::vector mCharacterFiles; + AZStd::vector m_characterFiles; - NativeEventFilter* mNativeEventFilter; + NativeEventFilter* m_nativeEventFilter; void closeEvent(QCloseEvent* event) override; void showEvent(QShowEvent* event) override; @@ -266,21 +266,21 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandUnselectCallback); MCORE_DEFINECOMMANDCALLBACK(CommandClearSelectionCallback); MCORE_DEFINECOMMANDCALLBACK(CommandSaveWorkspaceCallback); - CommandImportActorCallback* mImportActorCallback; - CommandRemoveActorCallback* mRemoveActorCallback; - CommandRemoveActorInstanceCallback* mRemoveActorInstanceCallback; - CommandImportMotionCallback* mImportMotionCallback; - CommandRemoveMotionCallback* mRemoveMotionCallback; - CommandCreateMotionSetCallback* mCreateMotionSetCallback; - CommandRemoveMotionSetCallback* mRemoveMotionSetCallback; - CommandLoadMotionSetCallback* mLoadMotionSetCallback; - CommandCreateAnimGraphCallback* mCreateAnimGraphCallback; - CommandRemoveAnimGraphCallback* mRemoveAnimGraphCallback; - CommandLoadAnimGraphCallback* mLoadAnimGraphCallback; - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; + CommandImportActorCallback* m_importActorCallback; + CommandRemoveActorCallback* m_removeActorCallback; + CommandRemoveActorInstanceCallback* m_removeActorInstanceCallback; + CommandImportMotionCallback* m_importMotionCallback; + CommandRemoveMotionCallback* m_removeMotionCallback; + CommandCreateMotionSetCallback* m_createMotionSetCallback; + CommandRemoveMotionSetCallback* m_removeMotionSetCallback; + CommandLoadMotionSetCallback* m_loadMotionSetCallback; + CommandCreateAnimGraphCallback* m_createAnimGraphCallback; + CommandRemoveAnimGraphCallback* m_removeAnimGraphCallback; + CommandLoadAnimGraphCallback* m_loadAnimGraphCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; CommandClearSelectionCallback* m_clearSelectionCallback; - CommandSaveWorkspaceCallback* mSaveWorkspaceCallback; + CommandSaveWorkspaceCallback* m_saveWorkspaceCallback; class MainWindowCommandManagerCallback : public MCore::CommandManagerCallback { @@ -296,9 +296,9 @@ namespace EMStudio void OnPreUndoCommand(MCore::Command* command, const MCore::CommandLine& commandLine); void OnPreExecuteCommandGroup(MCore::CommandGroup* /*group*/, bool /*undo*/) override { } void OnPostExecuteCommandGroup(MCore::CommandGroup* /*group*/, bool /*wasSuccess*/) override { } - void OnAddCommandToHistory(uint32 /*historyIndex*/, MCore::CommandGroup* /*group*/, MCore::Command* /*command*/, const MCore::CommandLine& /*commandLine*/) override { } - void OnRemoveCommand(uint32 /*historyIndex*/) override { } - void OnSetCurrentCommand(uint32 /*index*/) override { } + void OnAddCommandToHistory(size_t /*historyIndex*/, MCore::CommandGroup* /*group*/, MCore::Command* /*command*/, const MCore::CommandLine& /*commandLine*/) override { } + void OnRemoveCommand(size_t /*historyIndex*/) override { } + void OnSetCurrentCommand(size_t /*index*/) override { } void OnShowErrorReport(const AZStd::vector& errors) override; private: AZStd::vector m_skipClearRecorderCommands; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter.h index d6afacf602..c7e82b13e9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter.h @@ -20,13 +20,13 @@ namespace EMStudio public: NativeEventFilter(MainWindow* mainWindow) : QAbstractNativeEventFilter(), - m_MainWindow(mainWindow) + m_mainWindow(mainWindow) { } virtual bool nativeEventFilter(const QByteArray& /*eventType*/, void* message, long* /*result*/) Q_DECL_OVERRIDE; private: - MainWindow* m_MainWindow; + MainWindow* m_mainWindow; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp index 47b282824a..326b1b9902 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.cpp @@ -21,30 +21,30 @@ namespace EMStudio QVBoxLayout* layout = new QVBoxLayout(); - mListWidget = new QListWidget(); - mListWidget->setAlternatingRowColors(true); + m_listWidget = new QListWidget(); + m_listWidget->setAlternatingRowColors(true); if (multiSelect) { - mListWidget->setSelectionMode(QListWidget::ExtendedSelection); + m_listWidget->setSelectionMode(QListWidget::ExtendedSelection); } else { - mListWidget->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); + m_listWidget->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); } QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mCancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); + m_okButton = new QPushButton("OK"); + m_cancelButton = new QPushButton("Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); - layout->addWidget(mListWidget); + layout->addWidget(m_listWidget); layout->addLayout(buttonLayout); setLayout(layout); - connect(mOKButton, &QPushButton::clicked, this, &MorphTargetSelectionWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &MorphTargetSelectionWindow::reject); - connect(mListWidget, &QListWidget::itemSelectionChanged, this, &MorphTargetSelectionWindow::OnSelectionChanged); + connect(m_okButton, &QPushButton::clicked, this, &MorphTargetSelectionWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &MorphTargetSelectionWindow::reject); + connect(m_listWidget, &QListWidget::itemSelectionChanged, this, &MorphTargetSelectionWindow::OnSelectionChanged); } @@ -55,25 +55,25 @@ namespace EMStudio const AZStd::vector& MorphTargetSelectionWindow::GetMorphTargetIDs() const { - return mSelection; + return m_selection; } void MorphTargetSelectionWindow::OnSelectionChanged() { - mSelection.clear(); + m_selection.clear(); - const int numItems = mListWidget->count(); - mSelection.reserve(numItems); + const int numItems = m_listWidget->count(); + m_selection.reserve(numItems); for (int i = 0; i < numItems; ++i) { - QListWidgetItem* item = mListWidget->item(i); + QListWidgetItem* item = m_listWidget->item(i); if (!item->isSelected()) { continue; } - mSelection.emplace_back(item->data(Qt::UserRole).toInt()); + m_selection.emplace_back(item->data(Qt::UserRole).toInt()); } } @@ -85,13 +85,13 @@ namespace EMStudio return; } - mListWidget->blockSignals(true); - mListWidget->clear(); + m_listWidget->blockSignals(true); + m_listWidget->clear(); - mSelection = selection; + m_selection = selection; - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (uint32 i = 0; i < numMorphTargets; ++i) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t i = 0; i < numMorphTargets; ++i) { EMotionFX::MorphTarget* morphTarget = morphSetup->GetMorphTarget(i); const uint32 morphTargetID = morphTarget->GetID(); @@ -100,16 +100,16 @@ namespace EMStudio item->setText(morphTarget->GetName()); item->setData(Qt::UserRole, morphTargetID); - mListWidget->addItem(item); + m_listWidget->addItem(item); - if (AZStd::find(mSelection.begin(), mSelection.end(), morphTargetID) != mSelection.end()) + if (AZStd::find(m_selection.begin(), m_selection.end(), morphTargetID) != m_selection.end()) { item->setSelected(true); } } - mListWidget->blockSignals(false); - mSelection = selection; + m_listWidget->blockSignals(false); + m_selection = selection; } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.h index aee6f38754..c05fa91a3d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MorphTargetSelectionWindow.h @@ -38,9 +38,9 @@ namespace EMStudio void OnSelectionChanged(); private: - AZStd::vector mSelection; - QListWidget* mListWidget; - QPushButton* mOKButton; - QPushButton* mCancelButton; + AZStd::vector m_selection; + QListWidget* m_listWidget; + QPushButton* m_okButton; + QPushButton* m_cancelButton; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.cpp index e6f3fd5ac8..ac5dd80f4f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.cpp @@ -70,12 +70,12 @@ namespace EMStudio //----------------------------------- - const AZ::u32 MotionEventPresetManager::m_unknownEventColor = MCore::RGBA(193, 195, 196, 255); + const AZ::u32 MotionEventPresetManager::s_unknownEventColor = MCore::RGBA(193, 195, 196, 255); MotionEventPresetManager::MotionEventPresetManager() - : mDirtyFlag(false) + : m_dirtyFlag(false) { - mFileName = GetManager()->GetAppDataFolder() + "EMStudioDefaultEventPresets.cfg"; + m_fileName = GetManager()->GetAppDataFolder() + "EMStudioDefaultEventPresets.cfg"; } @@ -96,51 +96,51 @@ namespace EMStudio serializeContext->Class() ->Version(1) - ->Field("eventPresets", &MotionEventPresetManager::mEventPresets) + ->Field("eventPresets", &MotionEventPresetManager::m_eventPresets) ; } void MotionEventPresetManager::Clear() { - for (MotionEventPreset* eventPreset : mEventPresets) + for (MotionEventPreset* eventPreset : m_eventPresets) { delete eventPreset; } - mEventPresets.clear(); + m_eventPresets.clear(); } size_t MotionEventPresetManager::GetNumPresets() const { - return mEventPresets.size(); + return m_eventPresets.size(); } bool MotionEventPresetManager::IsEmpty() const { - return mEventPresets.empty(); + return m_eventPresets.empty(); } void MotionEventPresetManager::AddPreset(MotionEventPreset* preset) { - mEventPresets.emplace_back(preset); - mDirtyFlag = true; + m_eventPresets.emplace_back(preset); + m_dirtyFlag = true; } void MotionEventPresetManager::RemovePreset(size_t index) { - delete mEventPresets[index]; - mEventPresets.erase(mEventPresets.begin() + index); - mDirtyFlag = true; + delete m_eventPresets[index]; + m_eventPresets.erase(m_eventPresets.begin() + index); + m_dirtyFlag = true; } MotionEventPreset* MotionEventPresetManager::GetPreset(size_t index) const { - return mEventPresets[index]; + return m_eventPresets[index]; } @@ -152,14 +152,14 @@ namespace EMStudio MotionEventPreset* rightFootPreset = aznew MotionEventPreset("RightFoot", {AZStd::move(rightFootData)}, AZ::Color(AZ::u8(0), 255, 0, 255)); leftFootPreset->SetIsDefault(true); rightFootPreset->SetIsDefault(true); - mEventPresets.emplace(mEventPresets.begin(), leftFootPreset); - mEventPresets.emplace(AZStd::next(mEventPresets.begin(), 1), rightFootPreset); + m_eventPresets.emplace(m_eventPresets.begin(), leftFootPreset); + m_eventPresets.emplace(AZStd::next(m_eventPresets.begin(), 1), rightFootPreset); } void MotionEventPresetManager::Load(const AZStd::string& filename) { - mFileName = filename; + m_fileName = filename; // Clear the old event presets. Clear(); @@ -169,11 +169,11 @@ namespace EMStudio LoadLegacyQSettingsFormat(); } - // LoadLYSerializedFormat() will clear mEventPresets, so default + // LoadLYSerializedFormat() will clear m_eventPresets, so default // presets have to be made afterwards CreateDefaultPresets(); - mDirtyFlag = false; + m_dirtyFlag = false; // Update the default preset settings filename so that next startup the presets get auto-loaded. SaveToSettings(); @@ -182,7 +182,7 @@ namespace EMStudio bool MotionEventPresetManager::LoadLegacyQSettingsFormat() { - QSettings settings(mFileName.c_str(), QSettings::IniFormat, GetManager()->GetMainWindow()); + QSettings settings(m_fileName.c_str(), QSettings::IniFormat, GetManager()->GetMainWindow()); if (settings.status() != QSettings::Status::NoError) { @@ -221,18 +221,18 @@ namespace EMStudio bool MotionEventPresetManager::LoadLYSerializedFormat() { - return AZ::Utils::LoadObjectFromFileInPlace(mFileName, azrtti_typeid(mEventPresets), &mEventPresets); + return AZ::Utils::LoadObjectFromFileInPlace(m_fileName, azrtti_typeid(m_eventPresets), &m_eventPresets); } void MotionEventPresetManager::SaveAs(const AZStd::string& filename, bool showNotification) { - mFileName = filename; + m_fileName = filename; // Skip saving the built-in presets AZStd::vector presets; - presets.reserve(mEventPresets.size()); - for (MotionEventPreset* preset : mEventPresets) + presets.reserve(m_eventPresets.size()); + for (MotionEventPreset* preset : m_eventPresets) { if (preset->GetIsDefault()) { @@ -251,7 +251,7 @@ namespace EMStudio // Check if the settings correctly saved. if (AZ::Utils::SaveObjectToFile(filename, AZ::DataStream::ST_XML, &presets)) { - mDirtyFlag = false; + m_dirtyFlag = false; // Add file in case it did not exist before (when saving it the first time). if (!SourceControlCommand::CheckOutFile(filename.c_str(), fileExisted, checkoutResultString, /*useSourceControl=*/true, /*add=*/true)) @@ -279,11 +279,11 @@ namespace EMStudio void MotionEventPresetManager::SaveToSettings() { - if (!mFileName.empty()) + if (!m_fileName.empty()) { QSettings settings(GetManager()->GetMainWindow()); settings.beginGroup("EMotionFX"); - settings.setValue("lastEventPresetFile", mFileName.c_str()); + settings.setValue("lastEventPresetFile", m_fileName.c_str()); settings.endGroup(); } } @@ -298,7 +298,7 @@ namespace EMStudio if (!filename.empty()) { - mFileName = AZStd::move(filename); + m_fileName = AZStd::move(filename); } } @@ -306,7 +306,7 @@ namespace EMStudio // Check if motion event with this configuration exists and return color. AZ::u32 MotionEventPresetManager::GetEventColor(const EMotionFX::EventDataSet& eventDatas) const { - for (const MotionEventPreset* preset : mEventPresets) + for (const MotionEventPreset* preset : m_eventPresets) { EMotionFX::EventDataSet commonDatas; const EMotionFX::EventDataSet& presetDatas = preset->GetEventDatas(); @@ -325,6 +325,6 @@ namespace EMStudio } // Use the same color for all events that are not from a preset. - return m_unknownEventColor; + return s_unknownEventColor; } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.h index 89e997a96f..8e5853291c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionEventPresetManager.h @@ -75,16 +75,16 @@ namespace EMStudio void Clear(); void Load(const AZStd::string& filename); - void Load() { Load(mFileName); } + void Load() { Load(m_fileName); } void LoadFromSettings(); void SaveAs(const AZStd::string& filename, bool showNotification=true); - void Save(bool showNotification=true) { SaveAs(mFileName, showNotification); } + void Save(bool showNotification=true) { SaveAs(m_fileName, showNotification); } - bool GetIsDirty() const { return mDirtyFlag; } - void SetDirtyFlag(bool isDirty) { mDirtyFlag = isDirty; } - const char* GetFileName() const { return mFileName.c_str(); } - const AZStd::string& GetFileNameString() const { return mFileName; } - void SetFileName(const char* filename) { mFileName = filename; } + bool GetIsDirty() const { return m_dirtyFlag; } + void SetDirtyFlag(bool isDirty) { m_dirtyFlag = isDirty; } + const char* GetFileName() const { return m_fileName.c_str(); } + const AZStd::string& GetFileNameString() const { return m_fileName; } + void SetFileName(const char* filename) { m_fileName = filename; } AZ::u32 GetEventColor(const EMotionFX::EventDataSet& eventDatas) const; @@ -92,10 +92,10 @@ namespace EMStudio bool LoadLYSerializedFormat(); bool LoadLegacyQSettingsFormat(); - AZStd::vector mEventPresets; - AZStd::string mFileName; - bool mDirtyFlag; - static const AZ::u32 m_unknownEventColor; + AZStd::vector m_eventPresets; + AZStd::string m_fileName; + bool m_dirtyFlag; + static const AZ::u32 s_unknownEventColor; void SaveToSettings(); void CreateDefaultPresets(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.cpp index 7b125e9e63..99180a716c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.cpp @@ -32,10 +32,10 @@ namespace EMStudio MotionSetHierarchyWidget::MotionSetHierarchyWidget(QWidget* parent, bool useSingleSelection, CommandSystem::SelectionList* selectionList) : QWidget(parent) { - mCurrentSelectionList = selectionList; + m_currentSelectionList = selectionList; if (selectionList == nullptr) { - mCurrentSelectionList = &(GetCommandManager()->GetCurrentSelection()); + m_currentSelectionList = &(GetCommandManager()->GetCurrentSelection()); } QVBoxLayout* layout = new QVBoxLayout(); @@ -46,34 +46,34 @@ namespace EMStudio connect(m_searchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, this, &MotionSetHierarchyWidget::OnTextFilterChanged); // create the tree widget - mHierarchy = new QTreeWidget(); + m_hierarchy = new QTreeWidget(); // create header items - mHierarchy->setColumnCount(2); + m_hierarchy->setColumnCount(2); QStringList headerList; headerList.append("ID"); headerList.append("FileName"); - mHierarchy->setHeaderLabels(headerList); + m_hierarchy->setHeaderLabels(headerList); // set optical stuff for the tree - mHierarchy->setColumnWidth(0, 400); - mHierarchy->setSortingEnabled(false); - mHierarchy->setSelectionMode(QAbstractItemView::SingleSelection); - mHierarchy->setMinimumWidth(620); - mHierarchy->setMinimumHeight(500); - mHierarchy->setAlternatingRowColors(true); - mHierarchy->setExpandsOnDoubleClick(true); - mHierarchy->setAnimated(true); + m_hierarchy->setColumnWidth(0, 400); + m_hierarchy->setSortingEnabled(false); + m_hierarchy->setSelectionMode(QAbstractItemView::SingleSelection); + m_hierarchy->setMinimumWidth(620); + m_hierarchy->setMinimumHeight(500); + m_hierarchy->setAlternatingRowColors(true); + m_hierarchy->setExpandsOnDoubleClick(true); + m_hierarchy->setAnimated(true); // disable the move of section to have column order fixed - mHierarchy->header()->setSectionsMovable(false); + m_hierarchy->header()->setSectionsMovable(false); layout->addWidget(m_searchWidget); - layout->addWidget(mHierarchy); + layout->addWidget(m_hierarchy); setLayout(layout); - connect(mHierarchy, &QTreeWidget::itemSelectionChanged, this, &MotionSetHierarchyWidget::UpdateSelection); - connect(mHierarchy, &QTreeWidget::itemDoubleClicked, this, &MotionSetHierarchyWidget::ItemDoubleClicked); + connect(m_hierarchy, &QTreeWidget::itemSelectionChanged, this, &MotionSetHierarchyWidget::UpdateSelection); + connect(m_hierarchy, &QTreeWidget::itemDoubleClicked, this, &MotionSetHierarchyWidget::ItemDoubleClicked); // connect the window activation signal to refresh if reactivated //connect( this, SIGNAL(visibilityChanged(bool)), this, SLOT(OnVisibilityChanged(bool)) ); @@ -91,12 +91,12 @@ namespace EMStudio // update from a motion set and selection list void MotionSetHierarchyWidget::Update(EMotionFX::MotionSet* motionSet, CommandSystem::SelectionList* selectionList) { - mMotionSet = motionSet; - mCurrentSelectionList = selectionList; + m_motionSet = motionSet; + m_currentSelectionList = selectionList; if (selectionList == nullptr) { - mCurrentSelectionList = &(GetCommandManager()->GetCurrentSelection()); + m_currentSelectionList = &(GetCommandManager()->GetCurrentSelection()); } Update(); @@ -106,18 +106,18 @@ namespace EMStudio // update the widget void MotionSetHierarchyWidget::Update() { - mHierarchy->clear(); + m_hierarchy->clear(); - mHierarchy->blockSignals(true); - if (mMotionSet) + m_hierarchy->blockSignals(true); + if (m_motionSet) { - AddMotionSetWithParents(mMotionSet); + AddMotionSetWithParents(m_motionSet); } else { // add all root motion sets - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -128,12 +128,12 @@ namespace EMStudio if (motionSet->GetParentSet() == nullptr) { - RecursiveAddMotionSet(nullptr, EMotionFX::GetMotionManager().GetMotionSet(i), mCurrentSelectionList); + RecursiveAddMotionSet(nullptr, EMotionFX::GetMotionManager().GetMotionSet(i), m_currentSelectionList); } } } - mHierarchy->blockSignals(false); + m_hierarchy->blockSignals(false); UpdateSelection(); } @@ -144,8 +144,8 @@ namespace EMStudio QTreeWidgetItem* motionSetItem; if (parent == nullptr) { - motionSetItem = new QTreeWidgetItem(mHierarchy); - mHierarchy->addTopLevelItem(motionSetItem); + motionSetItem = new QTreeWidgetItem(m_hierarchy); + m_hierarchy->addTopLevelItem(motionSetItem); } else { @@ -185,8 +185,8 @@ namespace EMStudio } // add all child sets - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { RecursiveAddMotionSet(motionSetItem, motionSet->GetChildSet(i), selectionList); } @@ -196,7 +196,7 @@ namespace EMStudio void MotionSetHierarchyWidget::AddMotionSetWithParents(EMotionFX::MotionSet* motionSet) { // create the motion set item - QTreeWidgetItem* motionSetItem = new QTreeWidgetItem(mHierarchy); + QTreeWidgetItem* motionSetItem = new QTreeWidgetItem(m_hierarchy); // set the name motionSetItem->setText(0, motionSet->GetName()); @@ -232,7 +232,7 @@ namespace EMStudio while (parentMotionSet) { // create the motion set item - QTreeWidgetItem* parentMotionSetItem = new QTreeWidgetItem(mHierarchy); + QTreeWidgetItem* parentMotionSetItem = new QTreeWidgetItem(m_hierarchy); // set the name parentMotionSetItem->setText(0, parentMotionSet->GetName()); @@ -264,7 +264,7 @@ namespace EMStudio } // add the last motion set item as child and set this parent as last motion set item - parentMotionSetItem->addChild(mHierarchy->takeTopLevelItem(mHierarchy->indexOfTopLevelItem(motionSetItem))); + parentMotionSetItem->addChild(m_hierarchy->takeTopLevelItem(m_hierarchy->indexOfTopLevelItem(motionSetItem))); motionSetItem = parentMotionSetItem; // set the next parent motion set @@ -272,19 +272,19 @@ namespace EMStudio } // expand all to show all items - mHierarchy->expandAll(); + m_hierarchy->expandAll(); } void MotionSetHierarchyWidget::Select(const AZStd::vector& selectedItems) { - mSelected = selectedItems; + m_selected = selectedItems; for (const MotionSetSelectionItem& selectionItem : selectedItems) { - const AZStd::string& motionId = selectionItem.mMotionId; + const AZStd::string& motionId = selectionItem.m_motionId; - QTreeWidgetItemIterator itemIterator(mHierarchy); + QTreeWidgetItemIterator itemIterator(m_hierarchy); while (*itemIterator) { QTreeWidgetItem* item = *itemIterator; @@ -302,22 +302,20 @@ namespace EMStudio void MotionSetHierarchyWidget::UpdateSelection() { // Get the selected items in the tree widget. - QList selectedItems = mHierarchy->selectedItems(); - const uint32 numSelectedItems = selectedItems.count(); + QList selectedItems = m_hierarchy->selectedItems(); // Reset the selection. - mSelected.clear(); - mSelected.reserve(numSelectedItems); + m_selected.clear(); + m_selected.reserve(selectedItems.size()); AZStd::string motionId; - for (uint32 i = 0; i < numSelectedItems; ++i) + for (const QTreeWidgetItem* item : selectedItems) { - QTreeWidgetItem* item = selectedItems[i]; - motionId = item->text(0).toUtf8().data(); + motionId = item->text(0).toUtf8().data(); // Extract the motion set id. QString motionSetIdAsString = item->whatsThis(0); - const AZ::u32 motionSetId = AzFramework::StringFunc::ToInt(motionSetIdAsString.toUtf8().data()); + const uint32 motionSetId = AzFramework::StringFunc::ToInt(motionSetIdAsString.toUtf8().data()); // Find the motion set based on the id. EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetId); @@ -327,7 +325,7 @@ namespace EMStudio } MotionSetSelectionItem selectionItem(motionId, motionSet); - mSelected.push_back(selectionItem); + m_selected.push_back(selectionItem); } } @@ -336,14 +334,14 @@ namespace EMStudio { if (useSingleSelection) { - mHierarchy->setSelectionMode(QAbstractItemView::SingleSelection); + m_hierarchy->setSelectionMode(QAbstractItemView::SingleSelection); } else { - mHierarchy->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_hierarchy->setSelectionMode(QAbstractItemView::ExtendedSelection); } - mUseSingleSelection = useSingleSelection; + m_useSingleSelection = useSingleSelection; } @@ -366,14 +364,14 @@ namespace EMStudio void MotionSetHierarchyWidget::FireSelectionDoneSignal() { - emit SelectionChanged(mSelected); + emit SelectionChanged(m_selected); } AZStd::vector& MotionSetHierarchyWidget::GetSelectedItems() { UpdateSelection(); - return mSelected; + return m_selected; } @@ -386,9 +384,9 @@ namespace EMStudio for (const MotionSetSelectionItem& selectedItem : selectedItems) { - if (selectedItem.mMotionSet == motionSet) + if (selectedItem.m_motionSet == motionSet) { - result.push_back(selectedItem.mMotionId); + result.push_back(selectedItem.m_motionId); } } @@ -397,9 +395,9 @@ namespace EMStudio void MotionSetHierarchyWidget::SelectItemsWithText(QString text) { - QList items = mHierarchy->findItems(text, Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); + QList items = m_hierarchy->findItems(text, Qt::MatchWrap | Qt::MatchWildcard | Qt::MatchRecursive); - mHierarchy->clearSelection(); + m_hierarchy->clearSelection(); for (QTreeWidgetItem* item : items) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.h index 838044c010..50e86cf8ba 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetHierarchyWidget.h @@ -33,12 +33,12 @@ namespace EMStudio { struct EMSTUDIO_API MotionSetSelectionItem { - AZStd::string mMotionId; - EMotionFX::MotionSet* mMotionSet; + AZStd::string m_motionId; + EMotionFX::MotionSet* m_motionSet; MotionSetSelectionItem(const AZStd::string& motionId, EMotionFX::MotionSet* motionSet) - : mMotionId(motionId) - , mMotionSet(motionSet) + : m_motionId(motionId) + , m_motionSet(motionSet) { } }; @@ -58,7 +58,7 @@ namespace EMStudio void Update(EMotionFX::MotionSet* motionSet, CommandSystem::SelectionList* selectionList = nullptr); void FireSelectionDoneSignal(); - MCORE_INLINE QTreeWidget* GetTreeWidget() { return mHierarchy; } + MCORE_INLINE QTreeWidget* GetTreeWidget() { return m_hierarchy; } MCORE_INLINE AzQtComponents::FilteredSearchWidget* GetSearchWidget() { return m_searchWidget; } void Select(const AZStd::vector& selectedItems); @@ -84,12 +84,12 @@ namespace EMStudio void RecursiveAddMotionSet(QTreeWidgetItem* parent, EMotionFX::MotionSet* motionSet, CommandSystem::SelectionList* selectionList); void AddMotionSetWithParents(EMotionFX::MotionSet* motionSet); - EMotionFX::MotionSet* mMotionSet; - QTreeWidget* mHierarchy; + EMotionFX::MotionSet* m_motionSet; + QTreeWidget* m_hierarchy; AzQtComponents::FilteredSearchWidget* m_searchWidget; AZStd::string m_searchWidgetText; - AZStd::vector mSelected; - CommandSystem::SelectionList* mCurrentSelectionList; - bool mUseSingleSelection; + AZStd::vector m_selected; + CommandSystem::SelectionList* m_currentSelectionList; + bool m_useSingleSelection; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.cpp index 79b53da0f9..23c2000754 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.cpp @@ -26,29 +26,29 @@ namespace EMStudio QVBoxLayout* layout = new QVBoxLayout(); - mHierarchyWidget = new MotionSetHierarchyWidget(this, useSingleSelection, selectionList); + m_hierarchyWidget = new MotionSetHierarchyWidget(this, useSingleSelection, selectionList); // create the ok and cancel buttons QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mOKButton->setObjectName("EMFX.MotionSetSelectionWindow.Ok"); - mCancelButton = new QPushButton("Cancel"); - mCancelButton->setObjectName("EMFX.MotionSetSelectionWindow.Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); - - layout->addWidget(mHierarchyWidget); + m_okButton = new QPushButton("OK"); + m_okButton->setObjectName("EMFX.MotionSetSelectionWindow.Ok"); + m_cancelButton = new QPushButton("Cancel"); + m_cancelButton->setObjectName("EMFX.MotionSetSelectionWindow.Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); + + layout->addWidget(m_hierarchyWidget); layout->addLayout(buttonLayout); setLayout(layout); - connect(mOKButton, &QPushButton::clicked, this, &MotionSetSelectionWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &MotionSetSelectionWindow::reject); + connect(m_okButton, &QPushButton::clicked, this, &MotionSetSelectionWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &MotionSetSelectionWindow::reject); connect(this, &MotionSetSelectionWindow::accepted, this, &MotionSetSelectionWindow::OnAccept); - connect(mHierarchyWidget, &MotionSetHierarchyWidget::SelectionChanged, this, &MotionSetSelectionWindow::OnSelectionChanged); + connect(m_hierarchyWidget, &MotionSetHierarchyWidget::SelectionChanged, this, &MotionSetSelectionWindow::OnSelectionChanged); // set the selection mode - mHierarchyWidget->SetSelectionMode(useSingleSelection); - mUseSingleSelection = useSingleSelection; + m_hierarchyWidget->SetSelectionMode(useSingleSelection); + m_useSingleSelection = useSingleSelection; } @@ -59,7 +59,7 @@ namespace EMStudio void MotionSetSelectionWindow::Select(const AZStd::vector& selectedItems) { - mHierarchyWidget->Select(selectedItems); + m_hierarchyWidget->Select(selectedItems); } @@ -85,9 +85,9 @@ namespace EMStudio void MotionSetSelectionWindow::OnAccept() { - if (mUseSingleSelection == false) + if (m_useSingleSelection == false) { - mHierarchyWidget->FireSelectionDoneSignal(); + m_hierarchyWidget->FireSelectionDoneSignal(); } } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.h index 552b45d249..c35e46fc54 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MotionSetSelectionWindow.h @@ -29,8 +29,8 @@ namespace EMStudio MotionSetSelectionWindow(QWidget* parent, bool useSingleSelection = true, CommandSystem::SelectionList* selectionList = nullptr); virtual ~MotionSetSelectionWindow(); - MCORE_INLINE MotionSetHierarchyWidget* GetHierarchyWidget() { return mHierarchyWidget; } - void Update(EMotionFX::MotionSet* motionSet, CommandSystem::SelectionList* selectionList = nullptr) { mHierarchyWidget->Update(motionSet, selectionList); } + MCORE_INLINE MotionSetHierarchyWidget* GetHierarchyWidget() { return m_hierarchyWidget; } + void Update(EMotionFX::MotionSet* motionSet, CommandSystem::SelectionList* selectionList = nullptr) { m_hierarchyWidget->Update(motionSet, selectionList); } void Select(const AZStd::vector& selectedItems); void Select(const AZStd::vector& selectedMotionIds, EMotionFX::MotionSet* motionSet); @@ -40,9 +40,9 @@ namespace EMStudio void OnSelectionChanged(AZStd::vector selection); private: - MotionSetHierarchyWidget* mHierarchyWidget; - QPushButton* mOKButton; - QPushButton* mCancelButton; - bool mUseSingleSelection; + MotionSetHierarchyWidget* m_hierarchyWidget; + QPushButton* m_okButton; + QPushButton* m_cancelButton; + bool m_useSingleSelection; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp index 6d0355ead0..63934a380c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.cpp @@ -25,7 +25,7 @@ EMotionFX::Node* SelectionItem::GetNode() const { - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceID); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(m_actorInstanceId); if (!actorInstance) { return nullptr; @@ -46,12 +46,10 @@ namespace EMStudio const auto boneIconFilename = iconFilename("Bone.svg"); const auto nodeIconFilename = iconFilename("Node.svg"); const auto meshIconFilename = iconFilename("Mesh.svg"); - mBoneIcon = new QIcon(boneIconFilename); - mNodeIcon = new QIcon(nodeIconFilename); - mMeshIcon = new QIcon(meshIconFilename); - mCharacterIcon = new QIcon(iconFilename("Character.svg")); - - mActorInstanceIDs.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK); + m_boneIcon = new QIcon(boneIconFilename); + m_nodeIcon = new QIcon(nodeIconFilename); + m_meshIcon = new QIcon(meshIconFilename); + m_characterIcon = new QIcon(iconFilename("Character.svg")); QVBoxLayout* layout = new QVBoxLayout(); layout->setMargin(0); @@ -69,7 +67,7 @@ namespace EMStudio addFilter(tr("Meshes"), meshIconFilename, FilterType::Meshes); addFilter(tr("Nodes"), nodeIconFilename, FilterType::Nodes); addFilter(tr("Bones"), boneIconFilename, FilterType::Bones); - mFilterState = {FilterType::Meshes, FilterType::Nodes, FilterType::Bones}; + m_filterState = {FilterType::Meshes, FilterType::Nodes, FilterType::Bones}; connect(m_searchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, this, &NodeHierarchyWidget::OnTextFilterChanged); connect(m_searchWidget, &AzQtComponents::FilteredSearchWidget::TypeFilterChanged, this, [this](const auto& filters) { FilterTypes filterState; @@ -77,52 +75,52 @@ namespace EMStudio { filterState.setFlag(static_cast(filter.metadata.toInt())); } - if (filterState == mFilterState) + if (filterState == m_filterState) { return; } - mFilterState = filterState; + m_filterState = filterState; Update(); emit FilterStateChanged(filterState); }); layout->addWidget(m_searchWidget); // create the tree widget - mHierarchy = new QTreeWidget(); + m_hierarchy = new QTreeWidget(); // create header items - mHierarchy->setColumnCount(1); + m_hierarchy->setColumnCount(1); // set optical stuff for the tree - mHierarchy->header()->setVisible(false); - mHierarchy->header()->setStretchLastSection(true); - mHierarchy->setSortingEnabled(false); - mHierarchy->setSelectionMode(QAbstractItemView::SingleSelection); + m_hierarchy->header()->setVisible(false); + m_hierarchy->header()->setStretchLastSection(true); + m_hierarchy->setSortingEnabled(false); + m_hierarchy->setSelectionMode(QAbstractItemView::SingleSelection); if (useDefaultMinWidth) { - mHierarchy->setMinimumWidth(500); + m_hierarchy->setMinimumWidth(500); } - mHierarchy->setMinimumHeight(400); - mHierarchy->setExpandsOnDoubleClick(true); - mHierarchy->setAnimated(true); + m_hierarchy->setMinimumHeight(400); + m_hierarchy->setExpandsOnDoubleClick(true); + m_hierarchy->setAnimated(true); // disable the move of section to have column order fixed - mHierarchy->header()->setSectionsMovable(false); + m_hierarchy->header()->setSectionsMovable(false); if (useSingleSelection == false) { - mHierarchy->setContextMenuPolicy(Qt::CustomContextMenu); - connect(mHierarchy, &QTreeWidget::customContextMenuRequested, this, &NodeHierarchyWidget::TreeContextMenu); + m_hierarchy->setContextMenuPolicy(Qt::CustomContextMenu); + connect(m_hierarchy, &QTreeWidget::customContextMenuRequested, this, &NodeHierarchyWidget::TreeContextMenu); } - layout->addWidget(mHierarchy); + layout->addWidget(m_hierarchy); setLayout(layout); - connect(mHierarchy, &QTreeWidget::itemSelectionChanged, this, &NodeHierarchyWidget::UpdateSelection); - connect(mHierarchy, &QTreeWidget::itemDoubleClicked, this, &NodeHierarchyWidget::ItemDoubleClicked); - connect(mHierarchy, &QTreeWidget::itemSelectionChanged, this, &NodeHierarchyWidget::OnSelectionChanged); + connect(m_hierarchy, &QTreeWidget::itemSelectionChanged, this, &NodeHierarchyWidget::UpdateSelection); + connect(m_hierarchy, &QTreeWidget::itemDoubleClicked, this, &NodeHierarchyWidget::ItemDoubleClicked); + connect(m_hierarchy, &QTreeWidget::itemSelectionChanged, this, &NodeHierarchyWidget::OnSelectionChanged); // connect the window activation signal to refresh if reactivated //connect( this, SIGNAL(visibilityChanged(bool)), this, SLOT(OnVisibilityChanged(bool)) ); @@ -135,16 +133,16 @@ namespace EMStudio // destructor NodeHierarchyWidget::~NodeHierarchyWidget() { - delete mBoneIcon; - delete mMeshIcon; - delete mNodeIcon; - delete mCharacterIcon; + delete m_boneIcon; + delete m_meshIcon; + delete m_nodeIcon; + delete m_characterIcon; } - void NodeHierarchyWidget::Update(const MCore::Array& actorInstanceIDs, CommandSystem::SelectionList* selectionList) + void NodeHierarchyWidget::Update(const AZStd::vector& actorInstanceIDs, CommandSystem::SelectionList* selectionList) { - mActorInstanceIDs = actorInstanceIDs; + m_actorInstanceIDs = actorInstanceIDs; ConvertFromSelectionList(selectionList); Update(); @@ -153,13 +151,13 @@ namespace EMStudio void NodeHierarchyWidget::Update(uint32 actorInstanceID, CommandSystem::SelectionList* selectionList) { - mActorInstanceIDs.Clear(); + m_actorInstanceIDs.clear(); if (actorInstanceID == MCORE_INVALIDINDEX32) { // get the number actor instances and iterate over them - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { // add the actor to the node hierarchy widget EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -169,38 +167,37 @@ namespace EMStudio continue; } - mActorInstanceIDs.Add(actorInstance->GetID()); + m_actorInstanceIDs.emplace_back(actorInstance->GetID()); } } else { - mActorInstanceIDs.Add(actorInstanceID); + m_actorInstanceIDs.emplace_back(actorInstanceID); } - Update(mActorInstanceIDs, selectionList); + Update(m_actorInstanceIDs, selectionList); } void NodeHierarchyWidget::Update() { - mHierarchy->blockSignals(true); + m_hierarchy->blockSignals(true); // clear the whole thing (don't put this before blockSignals() else we have a bug in the skeletal LOD choosing, before also doesn't make any sense cause the OnNodesChanged() gets called and resets the selection!) - mHierarchy->clear(); + m_hierarchy->clear(); // get the number actor instances and iterate over them - const uint32 numActorInstances = mActorInstanceIDs.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) + for (const uint32 actorInstanceID : m_actorInstanceIDs) { // get the actor instance by its id - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(mActorInstanceIDs[i]); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); if (actorInstance) { AddActorInstance(actorInstance); } } - mHierarchy->blockSignals(false); + m_hierarchy->blockSignals(false); // after we refilled everything, update the selection UpdateSelection(); @@ -212,16 +209,16 @@ namespace EMStudio EMotionFX::Actor* actor = actorInstance->GetActor(); AZStd::string actorName; AzFramework::StringFunc::Path::GetFileName(actor->GetFileNameString().c_str(), actorName); - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); // extract the bones from the actor - actor->ExtractBoneList(actorInstance->GetLODLevel(), &mBoneList); + actor->ExtractBoneList(actorInstance->GetLODLevel(), &m_boneList); // calculate the number of polygons and indices uint32 numPolygons, numVertices, numIndices; actor->CalcMeshTotals(actorInstance->GetLODLevel(), &numPolygons, &numVertices, &numIndices); - QTreeWidgetItem* rootItem = new QTreeWidgetItem(mHierarchy); + QTreeWidgetItem* rootItem = new QTreeWidgetItem(m_hierarchy); // select the item in case the actor if (CheckIfActorInstanceSelected(actorInstance->GetID())) @@ -235,18 +232,18 @@ namespace EMStudio rootItem->setText(3, AZStd::to_string(numIndices / 3).c_str()); rootItem->setText(4, ""); rootItem->setExpanded(true); - rootItem->setIcon(0, *mCharacterIcon); + rootItem->setIcon(0, *m_characterIcon); QString whatsthis = AZStd::to_string(actorInstance->GetID()).c_str(); rootItem->setWhatsThis(0, whatsthis); - mHierarchy->addTopLevelItem(rootItem); + m_hierarchy->addTopLevelItem(rootItem); // get the number of root nodes and iterate through them - const uint32 numRootNodes = actor->GetSkeleton()->GetNumRootNodes(); - for (uint32 i = 0; i < numRootNodes; ++i) + const size_t numRootNodes = actor->GetSkeleton()->GetNumRootNodes(); + for (size_t i = 0; i < numRootNodes; ++i) { // get the root node index and the corresponding node - const uint32 rootNodeIndex = actor->GetSkeleton()->GetRootNodeIndex(i); + const size_t rootNodeIndex = actor->GetSkeleton()->GetRootNodeIndex(i); EMotionFX::Node* rootNode = actor->GetSkeleton()->GetNode(rootNodeIndex); // recursively add all the nodes to the hierarchy @@ -262,12 +259,12 @@ namespace EMStudio return false; } - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); AZStd::string nodeName = node->GetNameString(); AZStd::to_lower(nodeName.begin(), nodeName.end()); EMotionFX::Mesh* mesh = actorInstance->GetActor()->GetMesh(actorInstance->GetLODLevel(), nodeIndex); const bool isMeshNode = (mesh); - const bool isBone = (mBoneList.Find(nodeIndex) != MCORE_INVALIDINDEX32); + const bool isBone = (AZStd::find(begin(m_boneList), end(m_boneList), nodeIndex) != end(m_boneList)); const bool isNode = (isMeshNode == false && isBone == false); return CheckIfNodeVisible(nodeName, isMeshNode, isBone, isNode); @@ -290,13 +287,13 @@ namespace EMStudio void NodeHierarchyWidget::RecursivelyAddChilds(QTreeWidgetItem* parent, EMotionFX::Actor* actor, EMotionFX::ActorInstance* actorInstance, EMotionFX::Node* node) { - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); AZStd::string nodeName = node->GetNameString(); AZStd::to_lower(nodeName.begin(), nodeName.end()); - const uint32 numChildren = node->GetNumChildNodes(); + const size_t numChildren = node->GetNumChildNodes(); EMotionFX::Mesh* mesh = actor->GetMesh(actorInstance->GetLODLevel(), nodeIndex); const bool isMeshNode = (mesh); - const bool isBone = (mBoneList.Find(nodeIndex) != MCORE_INVALIDINDEX32); + const bool isBone = (AZStd::find(begin(m_boneList), end(m_boneList), nodeIndex) != end(m_boneList)); const bool isNode = (isMeshNode == false && isBone == false); if (CheckIfNodeVisible(nodeName, isMeshNode, isBone, isNode)) @@ -317,18 +314,18 @@ namespace EMStudio // set the correct icon and the type if (isMeshNode) { - item->setIcon(0, *mMeshIcon); + item->setIcon(0, *m_meshIcon); item->setText(1, "Mesh"); item->setText(3, QString::number(mesh->GetNumIndices() / 3)); } else if (isBone) { - item->setIcon(0, *mBoneIcon); + item->setIcon(0, *m_boneIcon); item->setText(1, "Bone"); } else if (isNode) { - item->setIcon(0, *mNodeIcon); + item->setIcon(0, *m_nodeIcon); item->setText(1, "Node"); } else @@ -339,22 +336,22 @@ namespace EMStudio // the mirrored node const bool hasMirrorInfo = actor->GetHasMirrorInfo(); - if (hasMirrorInfo == false || actor->GetNodeMirrorInfo(nodeIndex).mSourceNode == MCORE_INVALIDINDEX16 || actor->GetNodeMirrorInfo(nodeIndex).mSourceNode == nodeIndex) + if (hasMirrorInfo == false || actor->GetNodeMirrorInfo(nodeIndex).m_sourceNode == MCORE_INVALIDINDEX16 || actor->GetNodeMirrorInfo(nodeIndex).m_sourceNode == nodeIndex) { item->setText(4, ""); } else { - item->setText(4, actor->GetSkeleton()->GetNode(actor->GetNodeMirrorInfo(nodeIndex).mSourceNode)->GetName()); + item->setText(4, actor->GetSkeleton()->GetNode(actor->GetNodeMirrorInfo(nodeIndex).m_sourceNode)->GetName()); } parent->addChild(item); // iterate through all children - for (uint32 i = 0; i < numChildren; ++i) + for (size_t i = 0; i < numChildren; ++i) { // get the node index and the corresponding node - const uint32 childIndex = node->GetChildIndex(i); + const size_t childIndex = node->GetChildIndex(i); EMotionFX::Node* child = actor->GetSkeleton()->GetNode(childIndex); // recursively add all the nodes to the hierarchy @@ -364,10 +361,10 @@ namespace EMStudio else { // iterate through all children - for (uint32 i = 0; i < numChildren; ++i) + for (size_t i = 0; i < numChildren; ++i) { // get the node index and the corresponding node - const uint32 childIndex = node->GetChildIndex(i); + const size_t childIndex = node->GetChildIndex(i); EMotionFX::Node* child = actor->GetSkeleton()->GetNode(childIndex); // recursively add all the nodes to the hierarchy @@ -387,7 +384,7 @@ namespace EMStudio for (size_t i = 0; i < m_selectedNodes.size(); ) { // check if this is our node, if yes remove it - if (nodeNameID == m_selectedNodes[i].mNodeNameID && actorInstanceID == m_selectedNodes[i].mActorInstanceID) + if (nodeNameID == m_selectedNodes[i].m_nodeNameId && actorInstanceID == m_selectedNodes[i].m_actorInstanceId) { m_selectedNodes.erase(m_selectedNodes.begin() + i); //LOG("Removing: %s", nodeName); @@ -408,7 +405,7 @@ namespace EMStudio for (size_t i = 0; i < m_selectedNodes.size(); ) { // check if this is our node, if yes remove it - if (emptyStringID == m_selectedNodes[i].mNodeNameID && actorInstanceID == m_selectedNodes[i].mActorInstanceID) + if (emptyStringID == m_selectedNodes[i].m_nodeNameId && actorInstanceID == m_selectedNodes[i].m_actorInstanceId) { m_selectedNodes.erase(m_selectedNodes.begin() + i); //LOG("Removing: %s", nodeName); @@ -433,13 +430,13 @@ namespace EMStudio // Make sure this node is not already in our selection list for (const SelectionItem& selectedItem : m_selectedNodes) { - if (item.mNodeNameID == selectedItem.mNodeNameID && item.mActorInstanceID == selectedItem.mActorInstanceID) + if (item.m_nodeNameId == selectedItem.m_nodeNameId && item.m_actorInstanceId == selectedItem.m_actorInstanceId) { return; } } - if (mUseSingleSelection) + if (m_useSingleSelection) { m_selectedNodes.clear(); } @@ -455,9 +452,9 @@ namespace EMStudio if (item->isSelected() == false) { // get the actor instance id to which this item belongs to - mActorInstanceIDString = FromQtString(item->whatsThis(0)); + m_actorInstanceIdString = FromQtString(item->whatsThis(0)); int actorInstanceID; - const bool validConversion = AzFramework::StringFunc::LooksLikeInt(mActorInstanceIDString.c_str(), &actorInstanceID); + const bool validConversion = AzFramework::StringFunc::LooksLikeInt(m_actorInstanceIdString.c_str(), &actorInstanceID); MCORE_ASSERT(validConversion); // remove the node from the selected nodes @@ -472,8 +469,8 @@ namespace EMStudio } // get the number of children and iterate through them - const uint32 numChilds = item->childCount(); - for (uint32 i = 0; i < numChilds; ++i) + const int numChilds = item->childCount(); + for (int i = 0; i < numChilds; ++i) { RecursiveRemoveUnselectedItems(item->child(i)); } @@ -482,38 +479,25 @@ namespace EMStudio void NodeHierarchyWidget::UpdateSelection() { - uint32 i; - - //LOG("================================Update Selection!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); - //LOG("NumSelectedNodes=%i", mSelectedNodes.GetLength()); - //String debugString; - //debugString.Reserve(10000); - //for (uint32 s=0; s selectedItems = mHierarchy->selectedItems(); - const uint32 numSelectedItems = selectedItems.count(); + QList selectedItems = m_hierarchy->selectedItems(); // remove the unselected tree widget items from the selected nodes - const uint32 numTopLevelItems = mHierarchy->topLevelItemCount(); - for (i = 0; i < numTopLevelItems; ++i) + const int numTopLevelItems = m_hierarchy->topLevelItemCount(); + for (int i = 0; i < numTopLevelItems; ++i) { - RecursiveRemoveUnselectedItems(mHierarchy->topLevelItem(i)); + RecursiveRemoveUnselectedItems(m_hierarchy->topLevelItem(i)); } // iterate through all selected items - for (i = 0; i < numSelectedItems; ++i) + for (const QTreeWidgetItem* item : selectedItems) { - QTreeWidgetItem* item = selectedItems[i]; - - // get the item name - FromQtString(item->text(0), &mItemName); - FromQtString(item->whatsThis(0), &mActorInstanceIDString); + // get the item name + FromQtString(item->text(0), &m_itemName); + FromQtString(item->whatsThis(0), &m_actorInstanceIdString); int actorInstanceID; - const bool validConversion = AzFramework::StringFunc::LooksLikeInt(mActorInstanceIDString.c_str(), &actorInstanceID); + const bool validConversion = AzFramework::StringFunc::LooksLikeInt(m_actorInstanceIdString.c_str(), &actorInstanceID); MCORE_ASSERT(validConversion); EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); @@ -525,9 +509,9 @@ namespace EMStudio // check if the item name is actually a valid node EMotionFX::Actor* actor = actorInstance->GetActor(); - if (actor->GetSkeleton()->FindNodeByName(mItemName.c_str())) + if (actor->GetSkeleton()->FindNodeByName(m_itemName.c_str())) { - AddNodeToSelectedNodes(mItemName.c_str(), actorInstanceID); + AddNodeToSelectedNodes(m_itemName.c_str(), actorInstanceID); } // check if we are dealing with an actor instance @@ -544,14 +528,14 @@ namespace EMStudio { if (useSingleSelection) { - mHierarchy->setSelectionMode(QAbstractItemView::SingleSelection); + m_hierarchy->setSelectionMode(QAbstractItemView::SingleSelection); } else { - mHierarchy->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_hierarchy->setSelectionMode(QAbstractItemView::ExtendedSelection); } - mUseSingleSelection = useSingleSelection; + m_useSingleSelection = useSingleSelection; } @@ -563,7 +547,6 @@ namespace EMStudio UpdateSelection(); emit OnDoubleClicked(m_selectedNodes); - emit OnDoubleClicked(GetSelectedItemsAsMCoreArray()); } @@ -588,7 +571,7 @@ namespace EMStudio menu.addAction("Add all towards root to selection"); AZStd::vector itemsToAdd; - if (menu.exec(mHierarchy->mapToGlobal(pos))) + if (menu.exec(m_hierarchy->mapToGlobal(pos))) { // Collect the list of items to select. Actual adding to the // selection has to happen in a separate loop so that the iterators @@ -598,7 +581,7 @@ namespace EMStudio // Ensure the actor instance is still valid before looking at // its skeleton const EMotionFX::ActorInstance* actorInstance = - EMotionFX::GetActorManager().FindActorInstanceByID(selectedItem.mActorInstanceID); + EMotionFX::GetActorManager().FindActorInstanceByID(selectedItem.m_actorInstanceId); if (!actorInstance) { continue; @@ -609,7 +592,7 @@ namespace EMStudio actorInstance->GetActor()->GetSkeleton()->FindNodeByName(selectedItem.GetNodeName()); for(; parentNode; parentNode = parentNode->GetParentNode()) { - itemsToAdd.emplace_back(selectedItem.mActorInstanceID, parentNode->GetName()); + itemsToAdd.emplace_back(selectedItem.m_actorInstanceId, parentNode->GetName()); } } @@ -624,7 +607,6 @@ namespace EMStudio void NodeHierarchyWidget::OnTextFilterChanged(const QString& text) { - //mFindString = String(text.toAscii().data()).Lowered(); FromQtString(text, &m_searchWidgetText); AZStd::to_lower(m_searchWidgetText.begin(), m_searchWidgetText.end()); Update(); @@ -634,7 +616,6 @@ namespace EMStudio void NodeHierarchyWidget::FireSelectionDoneSignal() { emit OnSelectionDone(m_selectedNodes); - emit OnSelectionDone(GetSelectedItemsAsMCoreArray()); } @@ -645,52 +626,23 @@ namespace EMStudio } - MCore::Array NodeHierarchyWidget::GetSelectedItemsAsMCoreArray() - { - AZStd::vector& selectedItems = GetSelectedItems(); - MCore::Array result; - - const AZ::u32 numSelectedItems = static_cast(selectedItems.size()); - result.Resize(numSelectedItems); - - for (AZ::u32 i = 0; i < numSelectedItems; ++i) - { - result[i] = selectedItems[i]; - } - - return result; - } - - // check if the node with the given name is selected in the window bool NodeHierarchyWidget::CheckIfNodeSelected(const char* nodeName, uint32 actorInstanceID) { - for (const SelectionItem& selectedItem : m_selectedNodes) + return AZStd::any_of(begin(m_selectedNodes), end(m_selectedNodes), [nodeName, actorInstanceID](const SelectionItem& selectedItem) { - if (selectedItem.mActorInstanceID == actorInstanceID && selectedItem.GetNodeNameString() == nodeName) - { - return true; - } - } - - // failure, not found in the selected nodes array - return false; + return selectedItem.m_actorInstanceId == actorInstanceID && selectedItem.GetNodeNameString() == nodeName; + }); } // check if the actor instance with the given id is selected in the window bool NodeHierarchyWidget::CheckIfActorInstanceSelected(uint32 actorInstanceID) { - for (const SelectionItem& selectedItem : m_selectedNodes) + return AZStd::any_of(begin(m_selectedNodes), end(m_selectedNodes), [actorInstanceID](const SelectionItem& selectedItem) { - if (selectedItem.mActorInstanceID == actorInstanceID && selectedItem.GetNodeNameString().empty()) - { - return true; - } - } - - // failure, not found in the selected nodes array - return false; + return selectedItem.m_actorInstanceId == actorInstanceID && selectedItem.GetNodeNameString().empty(); + }); } @@ -706,21 +658,18 @@ namespace EMStudio m_selectedNodes.clear(); // get the number actor instances and iterate over them - const uint32 numActorInstances = mActorInstanceIDs.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) + for (const uint32 actorInstanceID : m_actorInstanceIDs) { // add the actor to the node hierarchy widget - const uint32 actorInstanceID = mActorInstanceIDs[i]; - // get the number of selected nodes and iterate through them - const uint32 numSelectedNodes = selectionList->GetNumSelectedNodes(); - for (uint32 n = 0; n < numSelectedNodes; ++n) + const size_t numSelectedNodes = selectionList->GetNumSelectedNodes(); + for (size_t n = 0; n < numSelectedNodes; ++n) { const EMotionFX::Node* joint = selectionList->GetNode(n); if (joint) { SelectionItem selectionItem; - selectionItem.mActorInstanceID = actorInstanceID; + selectionItem.m_actorInstanceId = actorInstanceID; selectionItem.SetNodeName(joint->GetName()); m_selectedNodes.emplace_back(selectionItem); } @@ -731,27 +680,21 @@ namespace EMStudio bool NodeHierarchyWidget::GetDisplayMeshes() const { - return mFilterState.testFlag(FilterType::Meshes); + return m_filterState.testFlag(FilterType::Meshes); } bool NodeHierarchyWidget::GetDisplayNodes() const { - return mFilterState.testFlag(FilterType::Nodes); + return m_filterState.testFlag(FilterType::Nodes); } bool NodeHierarchyWidget::GetDisplayBones() const { - return mFilterState.testFlag(FilterType::Bones); + return m_filterState.testFlag(FilterType::Bones); } - /* - void NodeHierarchyWidget::OnVisibilityChanged(bool isVisible) - { - if (isVisible) - Update(); - }*/ } // namespace EMStudio #include diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h index 3f0ca1a639..c566be6005 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeHierarchyWidget.h @@ -30,26 +30,26 @@ namespace AzQtComponents struct EMSTUDIO_API SelectionItem { - uint32 mActorInstanceID; - uint32 mNodeNameID; - uint32 mMorphTargetID; + uint32 m_actorInstanceId; + uint32 m_nodeNameId; + uint32 m_morphTargetId; SelectionItem() { - mActorInstanceID = MCORE_INVALIDINDEX32; - mNodeNameID = MCORE_INVALIDINDEX32; - mMorphTargetID = MCORE_INVALIDINDEX32; + m_actorInstanceId = MCORE_INVALIDINDEX32; + m_nodeNameId = MCORE_INVALIDINDEX32; + m_morphTargetId = MCORE_INVALIDINDEX32; } SelectionItem(const uint32 actorInstanceID, const char* nodeName, const uint32 morphTargetID = MCORE_INVALIDINDEX32) - : mActorInstanceID(actorInstanceID), mMorphTargetID(morphTargetID) + : m_actorInstanceId(actorInstanceID), m_morphTargetId(morphTargetID) { SetNodeName(nodeName); } - void SetNodeName(const char* nodeName) { mNodeNameID = MCore::GetStringIdPool().GenerateIdForString(nodeName); } - const char* GetNodeName() const { return MCore::GetStringIdPool().GetName(mNodeNameID).c_str(); } - const AZStd::string& GetNodeNameString() const { return MCore::GetStringIdPool().GetName(mNodeNameID); } + void SetNodeName(const char* nodeName) { m_nodeNameId = MCore::GetStringIdPool().GenerateIdForString(nodeName); } + const char* GetNodeName() const { return MCore::GetStringIdPool().GetName(m_nodeNameId).c_str(); } + const AZStd::string& GetNodeNameString() const { return MCore::GetStringIdPool().GetName(m_nodeNameId); } EMotionFX::Node* GetNode() const; }; @@ -68,9 +68,9 @@ namespace EMStudio void SetSelectionMode(bool useSingleSelection); void Update(uint32 actorInstanceID, CommandSystem::SelectionList* selectionList = nullptr); - void Update(const MCore::Array& actorInstanceIDs, CommandSystem::SelectionList* selectionList = nullptr); + void Update(const AZStd::vector& actorInstanceIDs, CommandSystem::SelectionList* selectionList = nullptr); void FireSelectionDoneSignal(); - MCORE_INLINE QTreeWidget* GetTreeWidget() { return mHierarchy; } + MCORE_INLINE QTreeWidget* GetTreeWidget() { return m_hierarchy; } MCORE_INLINE AzQtComponents::FilteredSearchWidget* GetSearchWidget() { return m_searchWidget; } // is node shown in the hierarchy widget? @@ -78,7 +78,6 @@ namespace EMStudio bool CheckIfNodeVisible(const AZStd::string& nodeName, bool isMeshNode, bool isBone, bool isNode); // this calls UpdateSelection() and then returns the member array containing the selected items - MCore::Array GetSelectedItemsAsMCoreArray(); AZStd::vector& GetSelectedItems(); const AZStd::string& GetSearchWidgetText() const { return m_searchWidgetText; } @@ -98,10 +97,6 @@ namespace EMStudio Q_DECLARE_FLAGS(FilterTypes, FilterType) signals: - // Deprecated - void OnSelectionDone(MCore::Array selectedNodes); - void OnDoubleClicked(MCore::Array selectedNodes); - void OnSelectionDone(AZStd::vector selectedNodes); void OnDoubleClicked(AZStd::vector selectedNodes); @@ -131,18 +126,18 @@ namespace EMStudio void RecursiveRemoveUnselectedItems(QTreeWidgetItem* item); AZStd::vector m_selectedNodes; - QTreeWidget* mHierarchy; + QTreeWidget* m_hierarchy; AzQtComponents::FilteredSearchWidget* m_searchWidget; AZStd::string m_searchWidgetText; - QIcon* mBoneIcon; - QIcon* mNodeIcon; - QIcon* mMeshIcon; - QIcon* mCharacterIcon; - MCore::Array mBoneList; - MCore::Array mActorInstanceIDs; - AZStd::string mItemName; - AZStd::string mActorInstanceIDString; - bool mUseSingleSelection; - FilterTypes mFilterState; + QIcon* m_boneIcon; + QIcon* m_nodeIcon; + QIcon* m_meshIcon; + QIcon* m_characterIcon; + AZStd::vector m_boneList; + AZStd::vector m_actorInstanceIDs; + AZStd::string m_itemName; + AZStd::string m_actorInstanceIdString; + bool m_useSingleSelection; + FilterTypes m_filterState; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.cpp index 4033ae55a8..3458a44de1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.cpp @@ -28,42 +28,42 @@ namespace EMStudio NodeSelectionWindow::NodeSelectionWindow(QWidget* parent, bool useSingleSelection) : QDialog(parent) { - mAccepted = false; + m_accepted = false; setWindowTitle("Node Selection Window"); QVBoxLayout* layout = new QVBoxLayout(); - mHierarchyWidget = new NodeHierarchyWidget(this, useSingleSelection); + m_hierarchyWidget = new NodeHierarchyWidget(this, useSingleSelection); // create the ok and cancel buttons QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mCancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); + m_okButton = new QPushButton("OK"); + m_cancelButton = new QPushButton("Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); - layout->addWidget(mHierarchyWidget); + layout->addWidget(m_hierarchyWidget); layout->addLayout(buttonLayout); setLayout(layout); - connect(mOKButton, &QPushButton::clicked, this, &NodeSelectionWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &NodeSelectionWindow::reject); + connect(m_okButton, &QPushButton::clicked, this, &NodeSelectionWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &NodeSelectionWindow::reject); connect(this, &NodeSelectionWindow::accepted, this, &NodeSelectionWindow::OnAccept); - connect(mHierarchyWidget, static_cast)>(&NodeHierarchyWidget::OnDoubleClicked), this, &NodeSelectionWindow::OnDoubleClicked); + connect(m_hierarchyWidget, static_cast)>(&NodeHierarchyWidget::OnDoubleClicked), this, &NodeSelectionWindow::OnDoubleClicked); // connect the window activation signal to refresh if reactivated //connect( this, SIGNAL(visibilityChanged(bool)), this, SLOT(OnVisibilityChanged(bool)) ); // set the selection mode - mHierarchyWidget->SetSelectionMode(useSingleSelection); - mUseSingleSelection = useSingleSelection; + m_hierarchyWidget->SetSelectionMode(useSingleSelection); + m_useSingleSelection = useSingleSelection; setMinimumSize(QSize(500, 400)); resize(700, 800); } - void NodeSelectionWindow::OnDoubleClicked(MCore::Array selection) + void NodeSelectionWindow::OnDoubleClicked(AZStd::vector selection) { MCORE_UNUSED(selection); accept(); @@ -72,7 +72,7 @@ namespace EMStudio void NodeSelectionWindow::OnAccept() { - mHierarchyWidget->FireSelectionDoneSignal(); + m_hierarchyWidget->FireSelectionDoneSignal(); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.h index af106c50ce..df6f0195bc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NodeSelectionWindow.h @@ -28,9 +28,9 @@ namespace EMStudio * 2. Use the itemSelectionChanged() signal of the GetNodeHierarchyWidget()->GetTreeWidget() to detect when the user adjusts the selection in the node hierarchy widget. * 3. Use the OnSelectionDone() in the GetNodeHierarchyWidget() to detect when the user finished selecting and pressed the OK button. * Example: - * connect( mNodeSelectionWindow, SIGNAL(rejected()), this, SLOT(UserWantsToCancel_1()) ); - * connect( mNodeSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged_2()) ); - * connect( mNodeSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(MCore::Array)), this, SLOT(FinishedSelectionAndPressedOK_3(MCore::Array)) ); + * connect( m_nodeSelectionWindow, SIGNAL(rejected()), this, SLOT(UserWantsToCancel_1()) ); + * connect( m_nodeSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged_2()) ); + * connect( m_nodeSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); */ class EMSTUDIO_API NodeSelectionWindow : public QDialog @@ -41,20 +41,20 @@ namespace EMStudio public: NodeSelectionWindow(QWidget* parent, bool useSingleSelection); - MCORE_INLINE NodeHierarchyWidget* GetNodeHierarchyWidget() { return mHierarchyWidget; } - void Update(uint32 actorInstanceID, CommandSystem::SelectionList* selectionList = nullptr) { mHierarchyWidget->Update(actorInstanceID, selectionList); } - void Update(const MCore::Array& actorInstanceIDs, CommandSystem::SelectionList* selectionList = nullptr) { mHierarchyWidget->Update(actorInstanceIDs, selectionList); } + MCORE_INLINE NodeHierarchyWidget* GetNodeHierarchyWidget() { return m_hierarchyWidget; } + void Update(uint32 actorInstanceID, CommandSystem::SelectionList* selectionList = nullptr) { m_hierarchyWidget->Update(actorInstanceID, selectionList); } + void Update(const AZStd::vector& actorInstanceIDs, CommandSystem::SelectionList* selectionList = nullptr) { m_hierarchyWidget->Update(actorInstanceIDs, selectionList); } public slots: void OnAccept(); - void OnDoubleClicked(MCore::Array selection); + void OnDoubleClicked(AZStd::vector selection); private: - NodeHierarchyWidget* mHierarchyWidget; - QPushButton* mOKButton; - QPushButton* mCancelButton; - bool mUseSingleSelection; - bool mAccepted; + NodeHierarchyWidget* m_hierarchyWidget; + QPushButton* m_okButton; + QPushButton* m_cancelButton; + bool m_useSingleSelection; + bool m_accepted; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp index c1316878c8..0b277c6195 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.cpp @@ -22,7 +22,7 @@ namespace EMStudio : QWidget(parent) { // set the opacity - mOpacity = 210; + m_opacity = 210; // set the window title setWindowTitle("Notification"); @@ -40,42 +40,42 @@ namespace EMStudio setFixedWidth(300); // create the icon - mIcon = new QToolButton(); - mIcon->setObjectName("NotificationIcon"); - mIcon->setStyleSheet("#NotificationIcon{ background-color: transparent; border: none; }"); - mIcon->setIconSize(QSize(22, 22)); - mIcon->setFocusPolicy(Qt::NoFocus); + m_icon = new QToolButton(); + m_icon->setObjectName("NotificationIcon"); + m_icon->setStyleSheet("#NotificationIcon{ background-color: transparent; border: none; }"); + m_icon->setIconSize(QSize(22, 22)); + m_icon->setFocusPolicy(Qt::NoFocus); if (type == TYPE_ERROR) { - mIcon->setIcon(MysticQt::GetMysticQt()->FindIcon("Images/Icons/ExclamationMark.svg")); + m_icon->setIcon(MysticQt::GetMysticQt()->FindIcon("Images/Icons/ExclamationMark.svg")); } else if (type == TYPE_WARNING) { - mIcon->setIcon(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Warning.svg")); + m_icon->setIcon(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Warning.svg")); } else if (type == TYPE_SUCCESS) { - mIcon->setIcon(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Confirm.svg")); + m_icon->setIcon(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Confirm.svg")); } - connect(mIcon, &QToolButton::pressed, this, &NotificationWindow::IconPressed); + connect(m_icon, &QToolButton::pressed, this, &NotificationWindow::IconPressed); // create the message label - mMessageLabel = new QLabel(Message); - mMessageLabel->setWordWrap(true); + m_messageLabel = new QLabel(Message); + m_messageLabel->setWordWrap(true); // create the layout QHBoxLayout* layout = new QHBoxLayout(); - layout->addWidget(mIcon); - layout->addWidget(mMessageLabel); + layout->addWidget(m_icon); + layout->addWidget(m_messageLabel); // set the layout setLayout(layout); // start the timer - mTimer = new QTimer(this); - mTimer->setSingleShot(true); - connect(mTimer, &QTimer::timeout, this, &NotificationWindow::TimerTimeOut); - mTimer->start(GetNotificationWindowManager()->GetVisibleTime() * 1000); + m_timer = new QTimer(this); + m_timer->setSingleShot(true); + connect(m_timer, &QTimer::timeout, this, &NotificationWindow::TimerTimeOut); + m_timer->start(GetNotificationWindowManager()->GetVisibleTime() * 1000); } NotificationWindow::~NotificationWindow() @@ -91,7 +91,7 @@ namespace EMStudio MCORE_UNUSED(event); QPainter p(this); p.setPen(Qt::transparent); - p.setBrush(QColor(0, 0, 0, mOpacity)); + p.setBrush(QColor(0, 0, 0, m_opacity)); p.setRenderHint(QPainter::Antialiasing); p.drawRoundedRect(rect(), 10, 10); } @@ -109,13 +109,13 @@ namespace EMStudio void NotificationWindow::mousePressEvent(QMouseEvent* event) { // we only want the left button, stop here if the timer is not active too - if ((mTimer->isActive() == false) || (event->button() != Qt::LeftButton)) + if ((m_timer->isActive() == false) || (event->button() != Qt::LeftButton)) { return; } // stop the timer because the event will be called before - mTimer->stop(); + m_timer->stop(); // call the timer time out function TimerTimeOut(); @@ -126,13 +126,13 @@ namespace EMStudio void NotificationWindow::IconPressed() { // stop here if the timer is not active - if (mTimer->isActive() == false) + if (m_timer->isActive() == false) { return; } // stop the timer because the event will be called before - mTimer->stop(); + m_timer->stop(); // call the timer time out function TimerTimeOut(); @@ -144,24 +144,24 @@ namespace EMStudio { // create the opacity effect and set it on the icon QGraphicsOpacityEffect* iconOpacityEffect = new QGraphicsOpacityEffect(this); - mIcon->setGraphicsEffect(iconOpacityEffect); + m_icon->setGraphicsEffect(iconOpacityEffect); // create the property animation to control the property value QPropertyAnimation* iconPropertyAnimation = new QPropertyAnimation(iconOpacityEffect, "opacity"); iconPropertyAnimation->setDuration(500); - iconPropertyAnimation->setStartValue((double)mOpacity / 255.0); + iconPropertyAnimation->setStartValue((double)m_opacity / 255.0); iconPropertyAnimation->setEndValue(0.0); iconPropertyAnimation->setEasingCurve(QEasingCurve::Linear); iconPropertyAnimation->start(QPropertyAnimation::DeleteWhenStopped); // create the opacity effect and set it on the label QGraphicsOpacityEffect* labelOpacityEffect = new QGraphicsOpacityEffect(this); - mMessageLabel->setGraphicsEffect(labelOpacityEffect); + m_messageLabel->setGraphicsEffect(labelOpacityEffect); // create the property animation to control the property value QPropertyAnimation* labelPropertyAnimation = new QPropertyAnimation(labelOpacityEffect, "opacity"); labelPropertyAnimation->setDuration(500); - labelPropertyAnimation->setStartValue((double)mOpacity / 255.0); + labelPropertyAnimation->setStartValue((double)m_opacity / 255.0); labelPropertyAnimation->setEndValue(0.0); labelPropertyAnimation->setEasingCurve(QEasingCurve::Linear); labelPropertyAnimation->start(QPropertyAnimation::DeleteWhenStopped); @@ -176,7 +176,7 @@ namespace EMStudio void NotificationWindow::OpacityChanged(qreal opacity) { // set the new opacity for the paint of the window - mOpacity = aznumeric_cast(opacity * 255); + m_opacity = aznumeric_cast(opacity * 255); // update the window update(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.h index b4dfb70ef1..72a53cafdf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindow.h @@ -50,9 +50,9 @@ namespace EMStudio void FadeOutFinished(); private: - QLabel* mMessageLabel; - QToolButton* mIcon; - QTimer* mTimer; - int mOpacity; + QLabel* m_messageLabel; + QToolButton* m_icon; + QTimer* m_timer; + int m_opacity; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp index a42bc1d54b..8b651314ca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.cpp @@ -33,10 +33,9 @@ namespace EMStudio // compute the height of all notification windows with the spacing int allNotificationWindowsHeight = 0; - const uint32 numNotificationWindows = mNotificationWindows.GetLength(); - for (uint32 i = 0; i < numNotificationWindows; ++i) + for (const NotificationWindow* currentNotificationWindow : m_notificationWindows) { - allNotificationWindowsHeight += mNotificationWindows[i]->geometry().height() + notificationWindowSpacing; + allNotificationWindowsHeight += currentNotificationWindow->geometry().height() + notificationWindowSpacing; } // move the notification window @@ -45,7 +44,7 @@ namespace EMStudio notificationWindow->move(mainWindowBottomRight.x() - notificationWindowGeometry.width() - notificationWindowMainWindowPadding, mainWindowBottomRight.y() - allNotificationWindowsHeight - notificationWindowGeometry.height() - notificationWindowMainWindowPadding); // add the notification window in the array - mNotificationWindows.Add(notificationWindow); + m_notificationWindows.emplace_back(notificationWindow); } @@ -53,25 +52,24 @@ namespace EMStudio void NotificationWindowManager::RemoveNotificationWindow(NotificationWindow* notificationWindow) { // find the notification window - const uint32 index = mNotificationWindows.Find(notificationWindow); + auto windowIt = AZStd::find(begin(m_notificationWindows), end(m_notificationWindows), notificationWindow); // if not found, stop here - if (index == MCORE_INVALIDINDEX32) + if (windowIt == end(m_notificationWindows)) { return; } // move down each notification window after this one, spacing is added on the height const int notificationWindowHeight = notificationWindow->geometry().height() + notificationWindowSpacing; - const uint32 numNotificationWindows = mNotificationWindows.GetLength(); - for (uint32 i = index + 1; i < numNotificationWindows; ++i) + for (auto it = windowIt + 1; it != end(m_notificationWindows); ++it) { - const QPoint pos = mNotificationWindows[i]->pos(); - mNotificationWindows[i]->move(pos.x(), pos.y() + notificationWindowHeight); + const QPoint pos = (*it)->pos(); + (*it)->move(pos.x(), pos.y() + notificationWindowHeight); } // remove the notification window - mNotificationWindows.Remove(index); + m_notificationWindows.erase(windowIt); } @@ -83,16 +81,15 @@ namespace EMStudio // move each notification window int currentNotificationWindowHeight = notificationWindowMainWindowPadding; - const uint32 numNotificationWindows = mNotificationWindows.GetLength(); - for (uint32 i = 0; i < numNotificationWindows; ++i) + for (NotificationWindow* notificationWindow : m_notificationWindows) { // add the height of the notification window - currentNotificationWindowHeight += mNotificationWindows[i]->geometry().height(); + currentNotificationWindowHeight += notificationWindow->geometry().height(); // move the notification window const QPoint mainWindowBottomRight = mainWindow->geometry().bottomRight(); - const QRect& notificationWindowGeometry = mNotificationWindows[i]->geometry(); - mNotificationWindows[i]->move(mainWindowBottomRight.x() - notificationWindowGeometry.width() - notificationWindowMainWindowPadding, mainWindowBottomRight.y() - currentNotificationWindowHeight); + const QRect& notificationWindowGeometry = notificationWindow->geometry(); + notificationWindow->move(mainWindowBottomRight.x() - notificationWindowGeometry.width() - notificationWindowMainWindowPadding, mainWindowBottomRight.y() - currentNotificationWindowHeight); // spacing is added after to avoid spacing on the bottom of the first notification window currentNotificationWindowHeight += notificationWindowSpacing; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.h index f71f60fde6..4724b4ba54 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/NotificationWindowManager.h @@ -11,7 +11,7 @@ #if !defined(Q_MOC_RUN) #include "EMStudioConfig.h" #include "NotificationWindow.h" -#include +#include #endif @@ -24,7 +24,7 @@ namespace EMStudio public: MCORE_INLINE NotificationWindowManager() { - mVisibleTime = 5; + m_visibleTime = 5; } void CreateNotificationWindow(NotificationWindow::EType type, const QString& message); @@ -32,28 +32,28 @@ namespace EMStudio MCORE_INLINE NotificationWindow* GetNotificationWindow(uint32 index) const { - return mNotificationWindows[index]; + return m_notificationWindows[index]; } - MCORE_INLINE uint32 GetNumNotificationWindow() const + MCORE_INLINE size_t GetNumNotificationWindow() const { - return mNotificationWindows.GetLength(); + return m_notificationWindows.size(); } void OnMovedOrResized(); MCORE_INLINE void SetVisibleTime(int32 timeSeconds) { - mVisibleTime = timeSeconds; + m_visibleTime = timeSeconds; } MCORE_INLINE int32 GetVisibleTime() const { - return mVisibleTime; + return m_visibleTime; } private: - MCore::Array mNotificationWindows; - int32 mVisibleTime; + AZStd::vector m_notificationWindows; + int32 m_visibleTime; }; } // namespace EMStudio 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 7a90e4d979..fde4336a49 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp @@ -8,6 +8,7 @@ // include required headers #include +#include #include "EMStudioManager.h" #include #include "PluginManager.h" @@ -33,8 +34,8 @@ namespace EMStudio // constructor PluginManager::PluginManager() { - mActivePlugins.reserve(50); - mPlugins.reserve(50); + m_activePlugins.reserve(50); + m_plugins.reserve(50); } @@ -49,19 +50,19 @@ namespace EMStudio // remove a given active plugin void PluginManager::RemoveActivePlugin(EMStudioPlugin* plugin) { - PluginVector::const_iterator itPlugin = AZStd::find(mActivePlugins.begin(), mActivePlugins.end(), plugin); - if (itPlugin == mActivePlugins.end()) + PluginVector::const_iterator itPlugin = AZStd::find(m_activePlugins.begin(), m_activePlugins.end(), plugin); + if (itPlugin == m_activePlugins.end()) { MCore::LogWarning("Failed to remove plugin '%s'", plugin->GetName()); return; } - for (EMStudioPlugin* activePlugin : mActivePlugins) + for (EMStudioPlugin* activePlugin : m_activePlugins) { activePlugin->OnBeforeRemovePlugin(plugin->GetClassID()); } - mActivePlugins.erase(itPlugin); + m_activePlugins.erase(itPlugin); delete plugin; } @@ -73,32 +74,22 @@ namespace EMStudio QApplication::processEvents(); // delete all plugins - for (EMStudioPlugin* plugin : mPlugins) + for (EMStudioPlugin* plugin : m_plugins) { delete plugin; } - mPlugins.clear(); + m_plugins.clear(); // delete all active plugins - const int32 numActivePlugins = static_cast(mActivePlugins.size()); - if (numActivePlugins > 0) + for (auto plugin = m_activePlugins.rbegin(); plugin != m_activePlugins.rend(); ++plugin) { - // iterate from back to front, destructing the plugins and removing them directly from the array of active plugins - for (int32 a = numActivePlugins - 1; a >= 0; a--) + for (EMStudioPlugin* pluginToNotify : m_activePlugins) { - EMStudioPlugin* plugin = mActivePlugins[a]; - - const int32 currentNumPlugins = static_cast(mActivePlugins.size()); - for (int32 p = 0; p < currentNumPlugins; ++p) - { - mActivePlugins[p]->OnBeforeRemovePlugin(plugin->GetClassID()); - } - - mActivePlugins.erase(mActivePlugins.begin() + a); - delete plugin; + pluginToNotify->OnBeforeRemovePlugin((*plugin)->GetClassID()); } - MCORE_ASSERT(mActivePlugins.empty()); + delete *plugin; + m_activePlugins.pop_back(); } } @@ -106,7 +97,7 @@ namespace EMStudio // register the plugin void PluginManager::RegisterPlugin(EMStudioPlugin* plugin) { - mPlugins.push_back(plugin); + m_plugins.push_back(plugin); } @@ -114,14 +105,14 @@ namespace EMStudio EMStudioPlugin* PluginManager::CreateWindowOfType(const char* pluginType, const char* objectName) { // try to locate the plugin type - const uint32 pluginIndex = FindPluginByTypeString(pluginType); - if (pluginIndex == MCORE_INVALIDINDEX32) + const size_t pluginIndex = FindPluginByTypeString(pluginType); + if (pluginIndex == InvalidIndex) { return nullptr; } // create the new plugin of this type - EMStudioPlugin* newPlugin = mPlugins[ pluginIndex ]->Clone(); + EMStudioPlugin* newPlugin = m_plugins[ pluginIndex ]->Clone(); // init the plugin newPlugin->CreateBaseInterface(objectName); @@ -129,7 +120,7 @@ namespace EMStudio // register as active plugin. This has to be done at this point since // the initialization could try to access the plugin and assume that // is active. - mActivePlugins.push_back(newPlugin); + m_activePlugins.push_back(newPlugin); newPlugin->Init(); @@ -138,32 +129,22 @@ namespace EMStudio // find a given plugin by its name (type string) - uint32 PluginManager::FindPluginByTypeString(const char* pluginType) const + size_t PluginManager::FindPluginByTypeString(const char* pluginType) const { - const size_t numPlugins = mPlugins.size(); - for (size_t i = 0; i < numPlugins; ++i) + const auto foundPlugin = AZStd::find_if(begin(m_plugins), end(m_plugins), [pluginType](const EMStudioPlugin* plugin) { - if (AzFramework::StringFunc::Equal(pluginType, mPlugins[i]->GetName())) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return AzFramework::StringFunc::Equal(pluginType, plugin->GetName()); + }); + return foundPlugin != end(m_plugins) ? AZStd::distance(begin(m_plugins), foundPlugin) : InvalidIndex; } EMStudioPlugin* PluginManager::GetActivePluginByTypeString(const char* pluginType) const { - const size_t numPlugins = mActivePlugins.size(); - for (size_t i = 0; i < numPlugins; ++i) + const auto foundPlugin = AZStd::find_if(begin(m_activePlugins), end(m_activePlugins), [pluginType](const EMStudioPlugin* plugin) { - if (AzFramework::StringFunc::Equal(pluginType, mActivePlugins[i]->GetName())) - { - return mActivePlugins[i]; - } - } - - return nullptr; + return AzFramework::StringFunc::Equal(pluginType, plugin->GetName()); + }); + return foundPlugin != end(m_activePlugins) ? *foundPlugin : nullptr; } // generate a unique object name @@ -185,81 +166,47 @@ namespace EMStudio ); // check if we have a conflict with a current plugin - bool hasConflict = false; - const size_t numActivePlugins = mActivePlugins.size(); - for (size_t i = 0; i < numActivePlugins; ++i) + const bool hasConflict = AZStd::any_of(begin(m_activePlugins), end(m_activePlugins), [&randomString](EMStudioPlugin* plugin) { - EMStudioPlugin* plugin = mActivePlugins[i]; - - // if the object name of a current plugin is equal to the one - if (plugin->GetHasWindowWithObjectName(randomString)) - { - hasConflict = true; - break; - } - } + return plugin->GetHasWindowWithObjectName(randomString); + }); if (hasConflict == false) { return randomString.c_str(); } } - - //return QString("INVALID"); } // find the number of active plugins of a given type - uint32 PluginManager::GetNumActivePluginsOfType(const char* pluginType) const + size_t PluginManager::GetNumActivePluginsOfType(const char* pluginType) const { - uint32 total = 0; - - // check all active plugins to see if they are from the given type - const size_t numActivePlugins = mActivePlugins.size(); - for (size_t i = 0; i < numActivePlugins; ++i) + return AZStd::accumulate(m_activePlugins.begin(), m_activePlugins.end(), size_t{0}, [pluginType](size_t total, const EMStudioPlugin* plugin) { - if (AzFramework::StringFunc::Equal(pluginType, mActivePlugins[i]->GetName())) - { - total++; - } - } - - return total; + return total + AzFramework::StringFunc::Equal(pluginType, plugin->GetName()); + }); } // find the first active plugin of a given type EMStudioPlugin* PluginManager::FindActivePlugin(uint32 classID) const { - const size_t numActivePlugins = mActivePlugins.size(); - for (size_t i = 0; i < numActivePlugins; ++i) + const auto foundPlugin = AZStd::find_if(begin(m_activePlugins), end(m_activePlugins), [classID](const EMStudioPlugin* plugin) { - if (mActivePlugins[i]->GetClassID() == classID) - { - return mActivePlugins[i]; - } - } - - return nullptr; + return plugin->GetClassID() == classID; + }); + return foundPlugin != end(m_activePlugins) ? *foundPlugin : nullptr; } // find the number of active plugins of a given type - uint32 PluginManager::GetNumActivePluginsOfType(uint32 classID) const + size_t PluginManager::GetNumActivePluginsOfType(uint32 classID) const { - uint32 total = 0; - - // check all active plugins to see if they are from the given type - const size_t numActivePlugins = mActivePlugins.size(); - for (size_t i = 0; i < numActivePlugins; ++i) + return AZStd::accumulate(m_activePlugins.begin(), m_activePlugins.end(), size_t{0}, [classID](size_t total, const EMStudioPlugin* plugin) { - if (mActivePlugins[i]->GetClassID() == classID) - { - total++; - } - } - - return total; + return total + (plugin->GetClassID() == classID); + }); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.h index 6b511e2a04..e3a5f9627a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.h @@ -36,7 +36,7 @@ namespace EMStudio void RegisterPlugin(EMStudioPlugin* plugin); EMStudioPlugin* CreateWindowOfType(const char* pluginType, const char* objectName = nullptr); - uint32 FindPluginByTypeString(const char* pluginType) const; + size_t FindPluginByTypeString(const char* pluginType) const; EMStudioPlugin* GetActivePluginByTypeString(const char* pluginType) const; // Reqire that PluginType is a subclass of EMStudioPlugin @@ -47,23 +47,23 @@ namespace EMStudio } EMStudioPlugin* FindActivePlugin(uint32 classID) const; // find first active plugin, or nullptr when not found - MCORE_INLINE uint32 GetNumPlugins() const { return static_cast(mPlugins.size()); } - MCORE_INLINE EMStudioPlugin* GetPlugin(const uint32 index) { return mPlugins[index]; } + MCORE_INLINE size_t GetNumPlugins() const { return m_plugins.size(); } + MCORE_INLINE EMStudioPlugin* GetPlugin(const size_t index) { return m_plugins[index]; } - MCORE_INLINE uint32 GetNumActivePlugins() const { return static_cast(mActivePlugins.size()); } - MCORE_INLINE EMStudioPlugin* GetActivePlugin(const uint32 index) { return mActivePlugins[index]; } - MCORE_INLINE const PluginVector& GetActivePlugins() { return mActivePlugins; } + MCORE_INLINE size_t GetNumActivePlugins() const { return m_activePlugins.size(); } + MCORE_INLINE EMStudioPlugin* GetActivePlugin(const size_t index) { return m_activePlugins[index]; } + MCORE_INLINE const PluginVector& GetActivePlugins() { return m_activePlugins; } - uint32 GetNumActivePluginsOfType(const char* pluginType) const; - uint32 GetNumActivePluginsOfType(uint32 classID) const; + size_t GetNumActivePluginsOfType(const char* pluginType) const; + size_t GetNumActivePluginsOfType(uint32 classID) const; void RemoveActivePlugin(EMStudioPlugin* plugin); QString GenerateObjectName() const; private: - PluginVector mPlugins; + PluginVector m_plugins; - PluginVector mActivePlugins; + PluginVector m_activePlugins; void UnloadPlugins(); }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.cpp index 3c2fe98e06..04104e4acd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.cpp @@ -25,7 +25,7 @@ namespace EMStudio RecoverFilesWindow::RecoverFilesWindow(QWidget* parent, const AZStd::vector& files) : QDialog(parent) { - mFiles = files; + m_files = files; // Update title of the dialog. setWindowTitle("Recover Files"); @@ -39,43 +39,43 @@ namespace EMStudio layout->addWidget(new QLabel("Some files have been corrupted but can be restored. The following files can be recovered:")); // Create the table widget. - mTableWidget = new QTableWidget(); - mTableWidget->setAlternatingRowColors(true); - mTableWidget->setSelectionMode(QAbstractItemView::NoSelection); - mTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); - mTableWidget->setMinimumHeight(250); - mTableWidget->setMinimumWidth(600); - mTableWidget->horizontalHeader()->setStretchLastSection(true); - mTableWidget->setCornerButtonEnabled(false); - mTableWidget->setSortingEnabled(false); - - mTableWidget->setColumnCount(3); + m_tableWidget = new QTableWidget(); + m_tableWidget->setAlternatingRowColors(true); + m_tableWidget->setSelectionMode(QAbstractItemView::NoSelection); + m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_tableWidget->setMinimumHeight(250); + m_tableWidget->setMinimumWidth(600); + m_tableWidget->horizontalHeader()->setStretchLastSection(true); + m_tableWidget->setCornerButtonEnabled(false); + m_tableWidget->setSortingEnabled(false); + + m_tableWidget->setColumnCount(3); // Set the header items. QTableWidgetItem* headerItem = new QTableWidgetItem(""); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(0, headerItem); + m_tableWidget->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem("Filename"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(1, headerItem); + m_tableWidget->setHorizontalHeaderItem(1, headerItem); headerItem = new QTableWidgetItem("Type"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(2, headerItem); + m_tableWidget->setHorizontalHeaderItem(2, headerItem); // Set the horizontal header params. - QHeaderView* horizontalHeader = mTableWidget->horizontalHeader(); + QHeaderView* horizontalHeader = m_tableWidget->horizontalHeader(); horizontalHeader->setSectionResizeMode(0, QHeaderView::Fixed); horizontalHeader->setStretchLastSection(true); - mTableWidget->verticalHeader()->hide(); + m_tableWidget->verticalHeader()->hide(); // Set the left column smaller to only fits the checkbox. - mTableWidget->horizontalHeader()->resizeSection(0, 19); + m_tableWidget->horizontalHeader()->resizeSection(0, 19); // Set the row count. const size_t numFiles = files.size(); const int rowCount = static_cast(numFiles); - mTableWidget->setRowCount(rowCount); + m_tableWidget->setRowCount(rowCount); // For each file that might be recovered. AZStd::string backupFilename; @@ -170,22 +170,22 @@ namespace EMStudio itemType->setData(Qt::UserRole, row); // Add table items to the current row. - mTableWidget->setCellWidget(row, 0, checkbox); - mTableWidget->setCellWidget(row, 1, filenameLabel); - mTableWidget->setItem(row, 2, itemType); + m_tableWidget->setCellWidget(row, 0, checkbox); + m_tableWidget->setCellWidget(row, 1, filenameLabel); + m_tableWidget->setItem(row, 2, itemType); - mTableWidget->setRowHeight(row, 21); + m_tableWidget->setRowHeight(row, 21); } - mTableWidget->setSortingEnabled(true); + m_tableWidget->setSortingEnabled(true); // Set the size of the filename column to take the whole space. - mTableWidget->setColumnWidth(1, 894); + m_tableWidget->setColumnWidth(1, 894); // Needed to have the last column stretching correctly. - mTableWidget->setColumnWidth(2, 0); + m_tableWidget->setColumnWidth(2, 0); - layout->addWidget(mTableWidget); + layout->addWidget(m_tableWidget); // Create the warning message. QLabel* warningLabel = new QLabel("Warning: Files that will not be recovered will be deleted"); @@ -265,16 +265,16 @@ namespace EMStudio AZStd::string backupFilename; AZStd::string originalFilename; - const int numRows = mTableWidget->rowCount(); + const int numRows = m_tableWidget->rowCount(); for (int i = 0; i < numRows; ++i) { - QWidget* widget = mTableWidget->cellWidget(i, 0); + QWidget* widget = m_tableWidget->cellWidget(i, 0); QCheckBox* checkbox = static_cast(widget); - QTableWidgetItem* item = mTableWidget->item(i, 2); + QTableWidgetItem* item = m_tableWidget->item(i, 2); const int32 filesIndex = item->data(Qt::UserRole).toInt(); // Get the recover and the backup filenames - const AZStd::string& recoverFilename = mFiles[filesIndex]; + const AZStd::string& recoverFilename = m_files[filesIndex]; backupFilename = recoverFilename; AzFramework::StringFunc::Path::StripExtension(backupFilename); @@ -359,17 +359,17 @@ namespace EMStudio using namespace AZ::IO; FileIOBase* fileIo = FileIOBase::GetInstance(); - const size_t numFiles = mFiles.size(); + const size_t numFiles = m_files.size(); AZStd::string backupFilename; for (size_t i = 0; i < numFiles; ++i) { - backupFilename = mFiles[i]; + backupFilename = m_files[i]; AzFramework::StringFunc::Path::StripExtension(backupFilename); // Remove the recover file. - if (fileIo->Remove(mFiles[i].c_str()) == ResultCode::Error) + if (fileIo->Remove(m_files[i].c_str()) == ResultCode::Error) { - const AZStd::string errorMessage = AZStd::string::format("Cannot delete file '%s'.", mFiles[i].c_str()); + const AZStd::string errorMessage = AZStd::string::format("Cannot delete file '%s'.", m_files[i].c_str()); CommandSystem::GetCommandManager()->AddError(errorMessage); AZ_Error("EMotionFX", false, errorMessage.c_str()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.h index f6e25e8ca5..5804db1aa1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RecoverFilesWindow.h @@ -35,7 +35,7 @@ namespace EMStudio private: AZStd::string GetOriginalFilenameFromRecoverFile(const char* recoverFilename); - QTableWidget* mTableWidget; - AZStd::vector mFiles; + QTableWidget* m_tableWidget; + AZStd::vector m_files; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.cpp index 1f703b8cfb..8d37c933a4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.cpp @@ -15,13 +15,13 @@ namespace EMStudio { RemovePluginOnCloseDockWidget::RemovePluginOnCloseDockWidget(QWidget* parent, const QString& name, EMStudio::EMStudioPlugin* plugin) : AzQtComponents::StyledDockWidget(name, parent) - , mPlugin(plugin) + , m_plugin(plugin) {} void RemovePluginOnCloseDockWidget::closeEvent(QCloseEvent* event) { MCORE_UNUSED(event); - GetPluginManager()->RemoveActivePlugin(mPlugin); + GetPluginManager()->RemoveActivePlugin(m_plugin); GetMainWindow()->UpdateCreateWindowMenu(); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.h index 21db2524cc..5a08cd7981 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RemovePluginOnCloseDockWidget.h @@ -28,6 +28,6 @@ namespace EMStudio void closeEvent(QCloseEvent* event) override; private: - EMStudio::EMStudioPlugin* mPlugin; + EMStudio::EMStudioPlugin* m_plugin; }; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/ManipulatorCallbacks.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/ManipulatorCallbacks.cpp index df54968f0c..7758ba9163 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/ManipulatorCallbacks.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/ManipulatorCallbacks.cpp @@ -21,20 +21,20 @@ namespace EMStudio ManipulatorCallback::Update(value); // update the position, if actorinstance is still valid - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { - mActorInstance->SetLocalSpacePosition(value); + m_actorInstance->SetLocalSpacePosition(value); } } void TranslateManipulatorCallback::UpdateOldValues() { // update the rotation, if actorinstance is still valid - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { - mOldValueVec = mActorInstance->GetLocalSpaceTransform().mPosition; + m_oldValueVec = m_actorInstance->GetLocalSpaceTransform().m_position; } } @@ -43,10 +43,10 @@ namespace EMStudio EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); if (actorInstance) { - const AZ::Vector3 newPos = actorInstance->GetLocalSpaceTransform().mPosition; - actorInstance->SetLocalSpacePosition(mOldValueVec); + const AZ::Vector3 newPos = actorInstance->GetLocalSpaceTransform().m_position; + actorInstance->SetLocalSpacePosition(m_oldValueVec); - if ((mOldValueVec - newPos).GetLength() >= MCore::Math::epsilon) + if ((m_oldValueVec - newPos).GetLength() >= MCore::Math::epsilon) { AZStd::string outResult; if (GetCommandManager()->ExecuteCommand( @@ -66,24 +66,24 @@ namespace EMStudio void RotateManipulatorCallback::Update(const AZ::Quaternion& value) { // update the rotation, if actorinstance is still valid - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { // temporarily update the actor instance - mActorInstance->SetLocalSpaceRotation(value * mActorInstance->GetLocalSpaceTransform().mRotation.GetNormalized()); + m_actorInstance->SetLocalSpaceRotation(value * m_actorInstance->GetLocalSpaceTransform().m_rotation.GetNormalized()); // update the callback parent - ManipulatorCallback::Update(mActorInstance->GetLocalSpaceTransform().mRotation); + ManipulatorCallback::Update(m_actorInstance->GetLocalSpaceTransform().m_rotation); } } void RotateManipulatorCallback::UpdateOldValues() { // update the rotation, if actorinstance is still valid - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { - mOldValueQuat = mActorInstance->GetLocalSpaceTransform().mRotation; + m_oldValueQuat = m_actorInstance->GetLocalSpaceTransform().m_rotation; } } @@ -92,10 +92,10 @@ namespace EMStudio EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); if (actorInstance) { - const AZ::Quaternion newRot = actorInstance->GetLocalSpaceTransform().mRotation; - actorInstance->SetLocalSpaceRotation(mOldValueQuat); + const AZ::Quaternion newRot = actorInstance->GetLocalSpaceTransform().m_rotation; + actorInstance->SetLocalSpaceRotation(m_oldValueQuat); - const float dot = newRot.Dot(mOldValueQuat); + const float dot = newRot.Dot(m_oldValueQuat); if (dot < 1.0f - MCore::Math::epsilon && dot > -1.0f + MCore::Math::epsilon) { AZStd::string outResult; @@ -117,11 +117,11 @@ namespace EMStudio AZ::Vector3 ScaleManipulatorCallback::GetCurrValueVec() { - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { #ifndef EMFX_SCALE_DISABLED - return mActorInstance->GetLocalSpaceTransform().mScale; + return m_actorInstance->GetLocalSpaceTransform().m_scale; #else return AZ::Vector3::CreateOne(); #endif @@ -137,16 +137,16 @@ namespace EMStudio EMFX_SCALECODE ( // update the position, if actorinstance is still valid - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { float minScale = 0.001f; const AZ::Vector3 scale = AZ::Vector3( - MCore::Max(float(mOldValueVec.GetX() * value.GetX()), minScale), - MCore::Max(float(mOldValueVec.GetY() * value.GetY()), minScale), - MCore::Max(float(mOldValueVec.GetZ() * value.GetZ()), minScale)); + MCore::Max(float(m_oldValueVec.GetX() * value.GetX()), minScale), + MCore::Max(float(m_oldValueVec.GetY() * value.GetY()), minScale), + MCore::Max(float(m_oldValueVec.GetZ() * value.GetZ()), minScale)); - mActorInstance->SetLocalSpaceScale(scale); + m_actorInstance->SetLocalSpaceScale(scale); // update the callback ManipulatorCallback::Update(scale); @@ -159,10 +159,10 @@ namespace EMStudio EMFX_SCALECODE ( // update the rotation, if actorinstance is still valid - uint32 actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(mActorInstance); - if (actorInstanceID != MCORE_INVALIDINDEX32) + size_t actorInstanceID = EMotionFX::GetActorManager().FindActorInstanceIndex(m_actorInstance); + if (actorInstanceID != InvalidIndex) { - mOldValueVec = mActorInstance->GetLocalSpaceTransform().mScale; + m_oldValueVec = m_actorInstance->GetLocalSpaceTransform().m_scale; } ) } @@ -174,10 +174,10 @@ namespace EMStudio EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); if (actorInstance) { - AZ::Vector3 newScale = actorInstance->GetLocalSpaceTransform().mScale; - actorInstance->SetLocalSpaceScale(mOldValueVec); + AZ::Vector3 newScale = actorInstance->GetLocalSpaceTransform().m_scale; + actorInstance->SetLocalSpaceScale(m_oldValueVec); - if ((mOldValueVec - newScale).GetLength() >= MCore::Math::epsilon) + if ((m_oldValueVec - newScale).GetLength() >= MCore::Math::epsilon) { AZStd::string outResult; if (GetCommandManager()->ExecuteCommand( diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.cpp index ef74cf466f..af2cb2c8e8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.cpp @@ -55,8 +55,6 @@ namespace EMStudio const char* RenderOptions::s_nodeAABBColorOptionName = "nodeAABBColor"; const char* RenderOptions::s_staticAABBColorOptionName = "staticAABBColor"; const char* RenderOptions::s_meshAABBColorOptionName = "meshAABBColor"; - const char* RenderOptions::s_collisionMeshAABBColorOptionName = "collisionMeshAABBColor"; - const char* RenderOptions::s_OBBsColorOptionName = "OBBsColor"; const char* RenderOptions::s_lineSkeletonColorOptionName = "lineSkeletonColor_v2"; const char* RenderOptions::s_skeletonColorOptionName = "skeletonColor"; const char* RenderOptions::s_selectionColorOptionName = "selectionColor"; @@ -108,8 +106,6 @@ namespace EMStudio , m_nodeAABBColor(1.0f, 0.0f, 0.0f, 1.0f) , m_staticAABBColor(0.0f, 0.7f, 0.7f, 1.0f) , m_meshAABBColor(0.0f, 0.0f, 0.7f, 1.0f) - , m_collisionMeshAABBColor(0.0f, 0.7f, 0.0f, 1.0f) - , m_OBBsColor(1.0f, 1.0f, 0.0f, 1.0f) , m_lineSkeletonColor(0.33333f, 1.0f, 0.0f, 1.0f) , m_skeletonColor(0.19f, 0.58f, 0.19f, 1.0f) , m_selectionColor(1.0f, 1.0f, 1.0f, 1.0f) @@ -134,7 +130,7 @@ namespace EMStudio MCommon::OrbitCamera tempCam; m_nearClipPlaneDistance = tempCam.GetNearClipDistance(); m_farClipPlaneDistance = tempCam.GetFarClipDistance(); - m_FOV = tempCam.GetFOV(); + m_fov = tempCam.GetFOV(); } RenderOptions& RenderOptions::operator=(const RenderOptions& other) @@ -169,8 +165,6 @@ namespace EMStudio SetNodeAABBColor(other.GetNodeAABBColor()); SetStaticAABBColor(other.GetStaticAABBColor()); SetMeshAABBColor(other.GetMeshAABBColor()); - SetCollisionMeshAABBColor(other.GetCollisionMeshAABBColor()); - SetOBBsColor(other.GetOBBsColor()); SetLineSkeletonColor(other.GetLineSkeletonColor()); SetSkeletonColor(other.GetSkeletonColor()); SetSelectionColor(other.GetSelectionColor()); @@ -206,9 +200,7 @@ namespace EMStudio settings->setValue(s_nodeAABBColorOptionName, ColorToString(m_nodeAABBColor)); settings->setValue(s_staticAABBColorOptionName, ColorToString(m_staticAABBColor)); settings->setValue(s_meshAABBColorOptionName, ColorToString(m_meshAABBColor)); - settings->setValue(s_collisionMeshAABBColorOptionName, ColorToString(m_collisionMeshAABBColor)); settings->setValue(s_collisionMeshColorOptionName, ColorToString(m_collisionMeshColor)); - settings->setValue(s_OBBsColorOptionName, ColorToString(m_OBBsColor)); settings->setValue(s_lineSkeletonColorOptionName, ColorToString(m_lineSkeletonColor)); settings->setValue(s_skeletonColorOptionName, ColorToString(m_skeletonColor)); settings->setValue(s_selectionColorOptionName, ColorToString(m_selectionColor)); @@ -237,7 +229,7 @@ namespace EMStudio settings->setValue(s_tangentsScaleOptionName, (double)m_tangentsScale); settings->setValue(s_nearClipPlaneDistanceOptionName, (double)m_nearClipPlaneDistance); settings->setValue(s_farClipPlaneDistanceOptionName, (double)m_farClipPlaneDistance); - settings->setValue(s_FOVOptionName, (double)m_FOV); + settings->setValue(s_FOVOptionName, (double)m_fov); settings->setValue(s_showFPSOptionName, m_showFPS); settings->setValue(s_lastUsedLayoutOptionName, m_lastUsedLayout.c_str()); @@ -275,9 +267,7 @@ namespace EMStudio options.m_nodeAABBColor = StringToColor(settings->value(s_nodeAABBColorOptionName, ColorToString(options.m_nodeAABBColor)).toString()); options.m_staticAABBColor = StringToColor(settings->value(s_staticAABBColorOptionName, ColorToString(options.m_staticAABBColor)).toString()); options.m_meshAABBColor = StringToColor(settings->value(s_meshAABBColorOptionName, ColorToString(options.m_meshAABBColor)).toString()); - options.m_collisionMeshAABBColor = StringToColor(settings->value(s_collisionMeshAABBColorOptionName, ColorToString(options.m_collisionMeshAABBColor)).toString()); options.m_collisionMeshColor = StringToColor(settings->value(s_collisionMeshColorOptionName, ColorToString(options.m_collisionMeshColor)).toString()); - options.m_OBBsColor = StringToColor(settings->value(s_OBBsColorOptionName, ColorToString(options.m_OBBsColor)).toString()); options.m_lineSkeletonColor = StringToColor(settings->value(s_lineSkeletonColorOptionName, ColorToString(options.m_lineSkeletonColor)).toString()); options.m_skeletonColor = StringToColor(settings->value(s_skeletonColorOptionName, ColorToString(options.m_skeletonColor)).toString()); options.m_selectionColor = StringToColor(settings->value(s_selectionColorOptionName, ColorToString(options.m_selectionColor)).toString()); @@ -310,7 +300,7 @@ namespace EMStudio options.m_nearClipPlaneDistance = (float)settings->value(s_nearClipPlaneDistanceOptionName, (double)options.m_nearClipPlaneDistance).toDouble(); options.m_farClipPlaneDistance = (float)settings->value(s_farClipPlaneDistanceOptionName, (double)options.m_farClipPlaneDistance).toDouble(); - options.m_FOV = (float)settings->value(s_FOVOptionName, (double)options.m_FOV).toDouble(); + options.m_fov = (float)settings->value(s_FOVOptionName, (double)options.m_fov).toDouble(); options.m_mainLightIntensity = (float)settings->value(s_mainLightIntensityOptionName, (double)options.m_mainLightIntensity).toDouble(); options.m_mainLightAngleA = (float)settings->value(s_mainLightAngleAOptionName, (double)options.m_mainLightAngleA).toDouble(); @@ -368,7 +358,7 @@ namespace EMStudio ->Field(s_scaleBonesOnLengthOptionName, &RenderOptions::m_scaleBonesOnLength) ->Field(s_nearClipPlaneDistanceOptionName, &RenderOptions::m_nearClipPlaneDistance) ->Field(s_farClipPlaneDistanceOptionName, &RenderOptions::m_farClipPlaneDistance) - ->Field(s_FOVOptionName, &RenderOptions::m_FOV) + ->Field(s_FOVOptionName, &RenderOptions::m_fov) ->Field(s_mainLightIntensityOptionName, &RenderOptions::m_mainLightIntensity) ->Field(s_mainLightAngleAOptionName, &RenderOptions::m_mainLightAngleA) ->Field(s_mainLightAngleBOptionName, &RenderOptions::m_mainLightAngleB) @@ -393,8 +383,6 @@ namespace EMStudio ->Field(s_nodeAABBColorOptionName, &RenderOptions::m_nodeAABBColor) ->Field(s_staticAABBColorOptionName, &RenderOptions::m_staticAABBColor) ->Field(s_meshAABBColorOptionName, &RenderOptions::m_meshAABBColor) - ->Field(s_collisionMeshAABBColorOptionName, &RenderOptions::m_collisionMeshAABBColor) - ->Field(s_OBBsColorOptionName, &RenderOptions::m_OBBsColor) ->Field(s_lineSkeletonColorOptionName, &RenderOptions::m_lineSkeletonColor) ->Field(s_skeletonColorOptionName, &RenderOptions::m_skeletonColor) ->Field(s_selectionColorOptionName, &RenderOptions::m_selectionColor) @@ -461,7 +449,7 @@ namespace EMStudio ->Attribute(AZ::Edit::Attributes::ChangeNotify, &RenderOptions::OnFarClipPlaneDistanceChangedCallback) ->Attribute(AZ::Edit::Attributes::Min, 1.0f) ->Attribute(AZ::Edit::Attributes::Max, 100000.0f) - ->DataElement(AZ::Edit::UIHandlers::Default, &RenderOptions::m_FOV, "Field of view", + ->DataElement(AZ::Edit::UIHandlers::Default, &RenderOptions::m_fov, "Field of view", "Angle in degrees of the field of view.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &RenderOptions::OnFOVChangedCallback) ->Attribute(AZ::Edit::Attributes::Min, 1.0f) @@ -552,12 +540,6 @@ namespace EMStudio ->DataElement(AZ::Edit::UIHandlers::Default, &RenderOptions::m_meshAABBColor, "Mesh based AABB color", "Color for the runtime-updated AABB calculated based on the deformed meshes.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &RenderOptions::OnMeshAABBColorChangedCallback) - ->DataElement(AZ::Edit::UIHandlers::Default, &RenderOptions::m_collisionMeshAABBColor, "CollisionMesh based AABB color", - "Color for the runtime-updated AABB calculated based on the deformed collision meshes.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &RenderOptions::OnCollisionMeshAABBColorChangedCallback) - ->DataElement(AZ::Edit::UIHandlers::Default, &RenderOptions::m_OBBsColor, "Joint OBB color", - "Color used for the pre-calculated joint oriented bounding boxes.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &RenderOptions::OnOBBsColorChangedCallback) ->DataElement(AZ::Edit::UIHandlers::Default, &RenderOptions::m_lineSkeletonColor, "Line based skeleton color", "Line-based skeleton color.") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &RenderOptions::OnLineSkeletonColorChangedCallback) @@ -680,9 +662,9 @@ namespace EMStudio void RenderOptions::SetFOV(float FOV) { - if (!AZ::IsClose(FOV, m_FOV, std::numeric_limits::epsilon())) + if (!AZ::IsClose(FOV, m_fov, std::numeric_limits::epsilon())) { - m_FOV = FOV; + m_fov = FOV; OnFOVChangedCallback(); } } @@ -903,24 +885,6 @@ namespace EMStudio } } - void RenderOptions::SetCollisionMeshAABBColor(const AZ::Color& collisionMeshAABBColor) - { - if (!collisionMeshAABBColor.IsClose(m_collisionMeshAABBColor)) - { - m_collisionMeshAABBColor = collisionMeshAABBColor; - OnCollisionMeshAABBColorChangedCallback(); - } - } - - void RenderOptions::SetOBBsColor(const AZ::Color& OBBsColor) - { - if (!OBBsColor.IsClose(m_OBBsColor)) - { - m_OBBsColor = OBBsColor; - OnOBBsColorChangedCallback(); - } - } - void RenderOptions::SetLineSkeletonColor(const AZ::Color& lineSkeletonColor) { if (!lineSkeletonColor.IsClose(m_lineSkeletonColor)) @@ -1258,16 +1222,6 @@ namespace EMStudio PluginOptionsNotificationsBus::Event(s_meshAABBColorOptionName, &PluginOptionsNotificationsBus::Events::OnOptionChanged, s_meshAABBColorOptionName); } - void RenderOptions::OnCollisionMeshAABBColorChangedCallback() const - { - PluginOptionsNotificationsBus::Event(s_collisionMeshAABBColorOptionName, &PluginOptionsNotificationsBus::Events::OnOptionChanged, s_collisionMeshAABBColorOptionName); - } - - void RenderOptions::OnOBBsColorChangedCallback() const - { - PluginOptionsNotificationsBus::Event(s_OBBsColorOptionName, &PluginOptionsNotificationsBus::Events::OnOptionChanged, s_OBBsColorOptionName); - } - void RenderOptions::OnLineSkeletonColorChangedCallback() const { PluginOptionsNotificationsBus::Event(s_lineSkeletonColorOptionName, &PluginOptionsNotificationsBus::Events::OnOptionChanged, s_lineSkeletonColorOptionName); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.h index 1df1a023c8..f146f62215 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderOptions.h @@ -59,8 +59,6 @@ namespace EMStudio static const char* s_nodeAABBColorOptionName; static const char* s_staticAABBColorOptionName; static const char* s_meshAABBColorOptionName; - static const char* s_collisionMeshAABBColorOptionName; - static const char* s_OBBsColorOptionName; static const char* s_lineSkeletonColorOptionName; static const char* s_skeletonColorOptionName; static const char* s_selectionColorOptionName; @@ -116,7 +114,7 @@ namespace EMStudio float GetFarClipPlaneDistance() const { return m_farClipPlaneDistance; } void SetFarClipPlaneDistance(float farClipPlaneDistance); - float GetFOV() const { return m_FOV; } + float GetFOV() const { return m_fov; } void SetFOV(float FOV); float GetMainLightIntensity() const { return m_mainLightIntensity; } @@ -191,12 +189,6 @@ namespace EMStudio AZ::Color GetMeshAABBColor() const { return m_meshAABBColor; } void SetMeshAABBColor(const AZ::Color& meshAABBColor); - AZ::Color GetCollisionMeshAABBColor() const { return m_collisionMeshAABBColor; } - void SetCollisionMeshAABBColor(const AZ::Color& collisionMeshAABBColor); - - AZ::Color GetOBBsColor() const { return m_OBBsColor; } - void SetOBBsColor(const AZ::Color& OBBsColor); - AZ::Color GetLineSkeletonColor() const { return m_lineSkeletonColor; } void SetLineSkeletonColor(const AZ::Color& lineSkeletonColor); @@ -303,8 +295,6 @@ namespace EMStudio void OnNodeAABBColorChangedCallback() const; void OnStaticAABBColorChangedCallback() const; void OnMeshAABBColorChangedCallback() const; - void OnCollisionMeshAABBColorChangedCallback() const; - void OnOBBsColorChangedCallback() const; void OnLineSkeletonColorChangedCallback() const; void OnSkeletonColorChangedCallback() const; void OnSelectionColorChangedCallback() const; @@ -334,7 +324,7 @@ namespace EMStudio bool m_scaleBonesOnLength; float m_nearClipPlaneDistance; float m_farClipPlaneDistance; - float m_FOV; + float m_fov; float m_mainLightIntensity; float m_mainLightAngleA; float m_mainLightAngleB; @@ -361,8 +351,6 @@ namespace EMStudio AZ::Color m_nodeAABBColor; AZ::Color m_staticAABBColor; AZ::Color m_meshAABBColor; - AZ::Color m_collisionMeshAABBColor; - AZ::Color m_OBBsColor; AZ::Color m_lineSkeletonColor; AZ::Color m_skeletonColor; AZ::Color m_selectionColor; 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 182314f2a6..db0c355002 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 @@ -27,36 +27,34 @@ namespace EMStudio RenderPlugin::RenderPlugin() : DockWidgetPlugin() { - mActors.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); - - mIsVisible = true; - mRenderUtil = nullptr; - mUpdateCallback = nullptr; - - mUpdateRenderActorsCallback = nullptr; - mReInitRenderActorsCallback = nullptr; - mCreateActorInstanceCallback = nullptr; - mRemoveActorInstanceCallback = nullptr; - mSelectCallback = nullptr; - mUnselectCallback = nullptr; - mClearSelectionCallback = nullptr; - mResetToBindPoseCallback = nullptr; - mAdjustActorInstanceCallback = nullptr; - - mZoomInCursor = nullptr; - mZoomOutCursor = nullptr; - - mBaseLayout = nullptr; - mRenderLayoutWidget = nullptr; - mActiveViewWidget = nullptr; - mCurrentSelection = nullptr; + m_isVisible = true; + m_renderUtil = nullptr; + m_updateCallback = nullptr; + + m_updateRenderActorsCallback = nullptr; + m_reInitRenderActorsCallback = nullptr; + m_createActorInstanceCallback = nullptr; + m_removeActorInstanceCallback = nullptr; + m_selectCallback = nullptr; + m_unselectCallback = nullptr; + m_clearSelectionCallback = nullptr; + m_resetToBindPoseCallback = nullptr; + m_adjustActorInstanceCallback = nullptr; + + m_zoomInCursor = nullptr; + m_zoomOutCursor = nullptr; + + m_baseLayout = nullptr; + m_renderLayoutWidget = nullptr; + m_activeViewWidget = nullptr; + m_currentSelection = nullptr; m_currentLayout = nullptr; - mFocusViewWidget = nullptr; - mFirstFrameAfterReInit = false; + m_focusViewWidget = nullptr; + m_firstFrameAfterReInit = false; - mTranslateManipulator = nullptr; - mRotateManipulator = nullptr; - mScaleManipulator = nullptr; + m_translateManipulator = nullptr; + m_rotateManipulator = nullptr; + m_scaleManipulator = nullptr; EMotionFX::ActorNotificationBus::Handler::BusConnect(); } @@ -85,38 +83,38 @@ namespace EMStudio m_layouts.clear(); // delete the gizmos - GetManager()->RemoveTransformationManipulator(mTranslateManipulator); - GetManager()->RemoveTransformationManipulator(mRotateManipulator); - GetManager()->RemoveTransformationManipulator(mScaleManipulator); + GetManager()->RemoveTransformationManipulator(m_translateManipulator); + GetManager()->RemoveTransformationManipulator(m_rotateManipulator); + GetManager()->RemoveTransformationManipulator(m_scaleManipulator); - delete mTranslateManipulator; - delete mRotateManipulator; - delete mScaleManipulator; + delete m_translateManipulator; + delete m_rotateManipulator; + delete m_scaleManipulator; // get rid of the cursors - delete mZoomInCursor; - delete mZoomOutCursor; + delete m_zoomInCursor; + delete m_zoomOutCursor; // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mUpdateRenderActorsCallback, false); - GetCommandManager()->RemoveCommandCallback(mReInitRenderActorsCallback, false); - GetCommandManager()->RemoveCommandCallback(mCreateActorInstanceCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveActorInstanceCallback, false); - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - GetCommandManager()->RemoveCommandCallback(mResetToBindPoseCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustActorInstanceCallback, false); - - delete mUpdateRenderActorsCallback; - delete mReInitRenderActorsCallback; - delete mCreateActorInstanceCallback; - delete mRemoveActorInstanceCallback; - delete mSelectCallback; - delete mUnselectCallback; - delete mClearSelectionCallback; - delete mResetToBindPoseCallback; - delete mAdjustActorInstanceCallback; + GetCommandManager()->RemoveCommandCallback(m_updateRenderActorsCallback, false); + GetCommandManager()->RemoveCommandCallback(m_reInitRenderActorsCallback, false); + GetCommandManager()->RemoveCommandCallback(m_createActorInstanceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeActorInstanceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_resetToBindPoseCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustActorInstanceCallback, false); + + delete m_updateRenderActorsCallback; + delete m_reInitRenderActorsCallback; + delete m_createActorInstanceCallback; + delete m_removeActorInstanceCallback; + delete m_selectCallback; + delete m_unselectCallback; + delete m_clearSelectionCallback; + delete m_resetToBindPoseCallback; + delete m_adjustActorInstanceCallback; for (MCommon::RenderUtil::TrajectoryTracePath* trajectoryPath : m_trajectoryTracePaths) { @@ -130,15 +128,14 @@ namespace EMStudio void RenderPlugin::CleanEMStudioActors() { // get rid of the actors - const uint32 numActors = mActors.GetLength(); - for (uint32 i = 0; i < numActors; ++i) + for (EMStudioRenderActor* actor : m_actors) { - if (mActors[i]) + if (actor) { - delete mActors[i]; + delete actor; } } - mActors.Clear(); + m_actors.clear(); } @@ -154,12 +151,12 @@ namespace EMStudio } // get the index of the emstudio actor, we can be sure it is valid as else the emstudioActor pointer would be nullptr already - const uint32 index = FindEMStudioActorIndex(emstudioActor); - MCORE_ASSERT(index != MCORE_INVALIDINDEX32); + const size_t index = FindEMStudioActorIndex(emstudioActor); + MCORE_ASSERT(index != InvalidIndex); // get rid of the emstudio actor delete emstudioActor; - mActors.Remove(index); + m_actors.erase(AZStd::next(begin(m_actors), index)); return true; } @@ -168,8 +165,7 @@ namespace EMStudio MCommon::TransformationManipulator* RenderPlugin::GetActiveManipulator(MCommon::Camera* camera, int32 mousePosX, int32 mousePosY) { // get the current manipulator - MCore::Array* transformationManipulators = GetManager()->GetTransformationManipulators(); - const uint32 numGizmos = transformationManipulators->GetLength(); + AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); // init the active manipulator to nullptr MCommon::TransformationManipulator* activeManipulator = nullptr; @@ -177,10 +173,9 @@ namespace EMStudio bool activeManipulatorFound = false; // iterate over all gizmos and search for the hit one that is closest to the camera - for (uint32 i = 0; i < numGizmos; ++i) + for (MCommon::TransformationManipulator* currentManipulator : *transformationManipulators) { // get the current manipulator and check if it exists - MCommon::TransformationManipulator* currentManipulator = transformationManipulators->GetItem(i); if (currentManipulator == nullptr || currentManipulator->GetIsVisible() == false) { continue; @@ -221,40 +216,40 @@ namespace EMStudio void RenderPlugin::ReInitTransformationManipulators() { EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); - const RenderOptions::ManipulatorMode mode = mRenderOptions.GetManipulatorMode(); + const RenderOptions::ManipulatorMode mode = m_renderOptions.GetManipulatorMode(); - if (mTranslateManipulator) + if (m_translateManipulator) { if (actorInstance) { - mTranslateManipulator->Init(actorInstance->GetLocalSpaceTransform().mPosition); - mTranslateManipulator->SetCallback(new TranslateManipulatorCallback(actorInstance, actorInstance->GetLocalSpaceTransform().mPosition)); + m_translateManipulator->Init(actorInstance->GetLocalSpaceTransform().m_position); + m_translateManipulator->SetCallback(new TranslateManipulatorCallback(actorInstance, actorInstance->GetLocalSpaceTransform().m_position)); } - mTranslateManipulator->SetIsVisible(actorInstance && mode == RenderOptions::ManipulatorMode::TRANSLATE); + m_translateManipulator->SetIsVisible(actorInstance && mode == RenderOptions::ManipulatorMode::TRANSLATE); } - if (mRotateManipulator) + if (m_rotateManipulator) { if (actorInstance) { - mRotateManipulator->Init(actorInstance->GetLocalSpaceTransform().mPosition); - mRotateManipulator->SetCallback(new RotateManipulatorCallback(actorInstance, actorInstance->GetLocalSpaceTransform().mRotation)); + m_rotateManipulator->Init(actorInstance->GetLocalSpaceTransform().m_position); + m_rotateManipulator->SetCallback(new RotateManipulatorCallback(actorInstance, actorInstance->GetLocalSpaceTransform().m_rotation)); } - mRotateManipulator->SetIsVisible(actorInstance && mode == RenderOptions::ManipulatorMode::ROTATE); + m_rotateManipulator->SetIsVisible(actorInstance && mode == RenderOptions::ManipulatorMode::ROTATE); } - if (mScaleManipulator) + if (m_scaleManipulator) { if (actorInstance) { - mScaleManipulator->Init(actorInstance->GetLocalSpaceTransform().mPosition); + m_scaleManipulator->Init(actorInstance->GetLocalSpaceTransform().m_position); #ifndef EMFX_SCALE_DISABLED - mScaleManipulator->SetCallback(new ScaleManipulatorCallback(actorInstance, actorInstance->GetLocalSpaceTransform().mScale)); + m_scaleManipulator->SetCallback(new ScaleManipulatorCallback(actorInstance, actorInstance->GetLocalSpaceTransform().m_scale)); #else - mScaleManipulator->SetCallback(new ScaleManipulatorCallback(actorInstance, AZ::Vector3::CreateOne())); + m_scaleManipulator->SetCallback(new ScaleManipulatorCallback(actorInstance, AZ::Vector3::CreateOne())); #endif } - mScaleManipulator->SetIsVisible(actorInstance && mode == RenderOptions::ManipulatorMode::SCALE); + m_scaleManipulator->SetIsVisible(actorInstance && mode == RenderOptions::ManipulatorMode::SCALE); } } @@ -266,8 +261,7 @@ namespace EMStudio return; } - MCore::AABB aabb; - aabb.Init(); + AZ::Aabb aabb = AZ::Aabb::CreateNull(); const EMotionFX::Actor* actor = actorInstance->GetActor(); const EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); @@ -275,22 +269,21 @@ namespace EMStudio for (const EMotionFX::Node* joint : joints) { - const AZ::Vector3 jointPosition = pose->GetWorldSpaceTransform(joint->GetNodeIndex()).mPosition; + const AZ::Vector3 jointPosition = pose->GetWorldSpaceTransform(joint->GetNodeIndex()).m_position; + aabb.AddPoint(jointPosition); - aabb.Encapsulate(jointPosition); - - const AZ::u32 childCount = joint->GetNumChildNodes(); - for (AZ::u32 i = 0; i < childCount; ++i) + const size_t childCount = joint->GetNumChildNodes(); + for (size_t i = 0; i < childCount; ++i) { EMotionFX::Node* childJoint = skeleton->GetNode(joint->GetChildIndex(i)); - const AZ::Vector3 childPosition = pose->GetWorldSpaceTransform(childJoint->GetNodeIndex()).mPosition; - aabb.Encapsulate(childPosition); + const AZ::Vector3 childPosition = pose->GetWorldSpaceTransform(childJoint->GetNodeIndex()).m_position; + aabb.AddPoint(childPosition); } } - if (aabb.CheckIfIsValid()) + if (aabb.IsValid()) { - aabb.Widen(aabb.CalcRadius()); + aabb.Expand(AZ::Vector3(aabb.GetExtents().GetLength() * 0.5f)); bool isFollowModeActive = false; for (const RenderViewWidget* viewWidget : m_viewWidgets) @@ -307,7 +300,7 @@ namespace EMStudio if (isFollowModeActive) { - QMessageBox::warning(mDock, "Please disable character follow mode", "Zoom to joints is only working in case character follow mode is disabled.\nPlease disable character follow mode in the render view menu: Camera -> Follow Mode", QMessageBox::Ok); + QMessageBox::warning(m_dock, "Please disable character follow mode", "Zoom to joints is only working in case character follow mode is disabled.\nPlease disable character follow mode in the render view menu: Camera -> Follow Mode", QMessageBox::Ok); } } } @@ -318,80 +311,49 @@ namespace EMStudio } // try to locate the helper actor for a given instance - RenderPlugin::EMStudioRenderActor* RenderPlugin::FindEMStudioActor(EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance) + RenderPlugin::EMStudioRenderActor* RenderPlugin::FindEMStudioActor(const EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance) const { - // get the number of emstudio actors and iterate through them - const uint32 numEMStudioRenderActors = mActors.GetLength(); - for (uint32 i = 0; i < numEMStudioRenderActors; ++i) + const auto foundActor = AZStd::find_if(begin(m_actors), end(m_actors), [actorInstance, doubleCheckInstance](const EMStudioRenderActor* renderActor) { - EMStudioRenderActor* EMStudioRenderActor = mActors[i]; - // is the parent actor of the instance the same as the one in the emstudio actor? - if (EMStudioRenderActor->mActor == actorInstance->GetActor()) + if (renderActor->m_actor == actorInstance->GetActor()) { // double check if the actor instance is in the actor instance array inside the emstudio actor if (doubleCheckInstance) { // now double check if the actor instance really is in the array of instances of this emstudio actor - const uint32 numActorInstances = EMStudioRenderActor->mActorInstances.GetLength(); - for (uint32 a = 0; a < numActorInstances; ++a) - { - if (EMStudioRenderActor->mActorInstances[a] == actorInstance) - { - return EMStudioRenderActor; - } - } - } - else - { - return EMStudioRenderActor; + const auto foundActorInstance = AZStd::find(begin(renderActor->m_actorInstances), end(renderActor->m_actorInstances), actorInstance); + return foundActorInstance != end(renderActor->m_actorInstances); } + return true; } - } - - return nullptr; + return false; + }); + return foundActor != end(m_actors) ? *foundActor : nullptr; } // try to locate the helper actor for a given one - RenderPlugin::EMStudioRenderActor* RenderPlugin::FindEMStudioActor(EMotionFX::Actor* actor) + RenderPlugin::EMStudioRenderActor* RenderPlugin::FindEMStudioActor(const EMotionFX::Actor* actor) const { if (!actor) { return nullptr; } - const uint32 numEMStudioRenderActors = mActors.GetLength(); - for (uint32 i = 0; i < numEMStudioRenderActors; ++i) + const auto foundActor = AZStd::find_if(begin(m_actors), end(m_actors), [match = actor](const EMStudioRenderActor* actor) { - EMStudioRenderActor* EMStudioRenderActor = mActors[i]; - - if (EMStudioRenderActor->mActor == actor) - { - return EMStudioRenderActor; - } - } - - return nullptr; + return actor->m_actor == match; + }); + return foundActor != end(m_actors) ? *foundActor : nullptr; } // get the index of the given emstudio actor - uint32 RenderPlugin::FindEMStudioActorIndex(EMStudioRenderActor* EMStudioRenderActor) + size_t RenderPlugin::FindEMStudioActorIndex(const EMStudioRenderActor* EMStudioRenderActor) const { - // get the number of emstudio actors and iterate through them - const uint32 numEMStudioRenderActors = mActors.GetLength(); - for (uint32 i = 0; i < numEMStudioRenderActors; ++i) - { - // compare the two emstudio actors and return the current index in case of success - if (EMStudioRenderActor == mActors[i]) - { - return i; - } - } - - // the emstudio actor has not been found - return MCORE_INVALIDINDEX32; + const auto foundActor = AZStd::find(begin(m_actors), end(m_actors), EMStudioRenderActor); + return foundActor != end(m_actors) ? AZStd::distance(begin(m_actors), foundActor) : InvalidIndex; } @@ -409,20 +371,20 @@ namespace EMStudio void RenderPlugin::AddEMStudioActor(EMStudioRenderActor* emstudioActor) { // add the actor to the list and return success - mActors.Add(emstudioActor); + m_actors.emplace_back(emstudioActor); } void RenderPlugin::ReInit(bool resetViewCloseup) { - if (!mRenderUtil) + if (!m_renderUtil) { return; } // 1. Create new emstudio actors - uint32 numActors = EMotionFX::GetActorManager().GetNumActors(); - for (uint32 i = 0; i < numActors; ++i) + size_t numActors = EMotionFX::GetActorManager().GetNumActors(); + for (size_t i = 0; i < numActors; ++i) { // get the current actor and the number of clones EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); @@ -442,14 +404,13 @@ namespace EMStudio } } - // 2. Remove invalid, not ready or unused emstudio actors - for (uint32 i = 0; i < mActors.GetLength(); ++i) + for (size_t i = 0; i < m_actors.size(); ++i) { - EMStudioRenderActor* emstudioActor = mActors[i]; - EMotionFX::Actor* actor = emstudioActor->mActor; + EMStudioRenderActor* emstudioActor = m_actors[i]; + EMotionFX::Actor* actor = emstudioActor->m_actor; bool found = false; - for (uint32 j = 0; j < numActors; ++j) + for (size_t j = 0; j < numActors; ++j) { EMotionFX::Actor* curActor = EMotionFX::GetActorManager().GetActor(j); if (actor == curActor) @@ -467,8 +428,8 @@ namespace EMStudio } // 3. Relink the actor instances with the emstudio actors - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); EMotionFX::Actor* actor = actorInstance->GetActor(); @@ -481,10 +442,9 @@ namespace EMStudio if (!emstudioActor) { - for (uint32 j = 0; j < mActors.GetLength(); ++j) + for (EMStudioRenderActor* currentEMStudioActor : m_actors) { - EMStudioRenderActor* currentEMStudioActor = mActors[j]; - if (actor == currentEMStudioActor->mActor) + if (actor == currentEMStudioActor->m_actor) { emstudioActor = currentEMStudioActor; break; @@ -495,27 +455,25 @@ namespace EMStudio if (emstudioActor) { // set the GL actor - actorInstance->SetCustomData(emstudioActor->mRenderActor); + actorInstance->SetCustomData(emstudioActor->m_renderActor); // add the actor instance to the emstudio actor instances in case it is not in yet - if (emstudioActor->mActorInstances.Find(actorInstance) == MCORE_INVALIDINDEX32) + if (AZStd::find(begin(emstudioActor->m_actorInstances), end(emstudioActor->m_actorInstances), actorInstance) == end(emstudioActor->m_actorInstances)) { - emstudioActor->mActorInstances.Add(actorInstance); + emstudioActor->m_actorInstances.emplace_back(actorInstance); } } } // 4. Unlink invalid actor instances from the emstudio actors - for (uint32 i = 0; i < mActors.GetLength(); ++i) + for (EMStudioRenderActor* emstudioActor : m_actors) { - EMStudioRenderActor* emstudioActor = mActors[i]; - - for (uint32 j = 0; j < emstudioActor->mActorInstances.GetLength();) + for (size_t j = 0; j < emstudioActor->m_actorInstances.size();) { - EMotionFX::ActorInstance* emstudioActorInstance = emstudioActor->mActorInstances[j]; + EMotionFX::ActorInstance* emstudioActorInstance = emstudioActor->m_actorInstances[j]; bool found = false; - for (uint32 k = 0; k < numActorInstances; ++k) + for (size_t k = 0; k < numActorInstances; ++k) { if (emstudioActorInstance == EMotionFX::GetActorManager().GetActorInstance(k)) { @@ -526,7 +484,7 @@ namespace EMStudio if (found == false) { - emstudioActor->mActorInstances.Remove(j); + emstudioActor->m_actorInstances.erase(AZStd::next(begin(emstudioActor->m_actorInstances), j)); } else { @@ -535,7 +493,7 @@ namespace EMStudio } } - mFirstFrameAfterReInit = true; + m_firstFrameAfterReInit = true; m_reinitRequested = false; // zoom the camera to the available character only in case we're dealing with a single instance @@ -555,15 +513,15 @@ namespace EMStudio // constructor RenderPlugin::EMStudioRenderActor::EMStudioRenderActor(EMotionFX::Actor* actor, RenderGL::GLActor* renderActor) { - mRenderActor = renderActor; - mActor = actor; - mNormalsScaleMultiplier = 1.0f; - mCharacterHeight = 0.0f; - mOffsetFromTrajectoryNode = 0.0f; - mMustCalcNormalScale = true; + m_renderActor = renderActor; + m_actor = actor; + m_normalsScaleMultiplier = 1.0f; + m_characterHeight = 0.0f; + m_offsetFromTrajectoryNode = 0.0f; + m_mustCalcNormalScale = true; // extract the bones from the actor and add it to the array - actor->ExtractBoneList(0, &mBoneList); + actor->ExtractBoneList(0, &m_boneList); CalculateNormalScaleMultiplier(); } @@ -573,14 +531,11 @@ namespace EMStudio RenderPlugin::EMStudioRenderActor::~EMStudioRenderActor() { // get the number of actor instances and iterate through them - const uint32 numActorInstances = mActorInstances.GetLength(); - for (uint32 i = 0; i < numActorInstances; ++i) + for (EMotionFX::ActorInstance* actorInstance : m_actorInstances) { - EMotionFX::ActorInstance* actorInstance = mActorInstances[i]; - // only delete the actor instance in case it is still inside the actor manager // in case it is not present there anymore this means an undo command has already deleted it - if (EMotionFX::GetActorManager().FindActorInstanceIndex(actorInstance) != MCORE_INVALIDINDEX32) + if (EMotionFX::GetActorManager().FindActorInstanceIndex(actorInstance) != InvalidIndex) { //actorInstance->Destroy(); } @@ -594,21 +549,17 @@ namespace EMStudio // only delete the actor in case it is still inside the actor manager // in case it is not present there anymore this means an undo command has already deleted it - if (EMotionFX::GetActorManager().FindActorIndex(mActor) != MCORE_INVALIDINDEX32) - { - //mActor->Destroy(); - } - // in case the actor is not valid anymore make sure to unselect it to avoid bad pointers - else + if (EMotionFX::GetActorManager().FindActorIndex(m_actor) == InvalidIndex) { + // in case the actor is not valid anymore make sure to unselect it to avoid bad pointers CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - selection.RemoveActor(mActor); + selection.RemoveActor(m_actor); } // get rid of the OpenGL actor - if (mRenderActor) + if (m_renderActor) { - mRenderActor->Destroy(); + m_renderActor->Destroy(); } } @@ -616,38 +567,33 @@ namespace EMStudio void RenderPlugin::EMStudioRenderActor::CalculateNormalScaleMultiplier() { // calculate the max extent of the character - EMotionFX::ActorInstance* actorInstance = EMotionFX::ActorInstance::Create(mActor); + EMotionFX::ActorInstance* actorInstance = EMotionFX::ActorInstance::Create(m_actor); actorInstance->UpdateMeshDeformers(0.0f, true); - MCore::AABB aabb; - actorInstance->CalcMeshBasedAABB(0, &aabb); - - if (aabb.CheckIfIsValid() == false) - { - actorInstance->CalcNodeOBBBasedAABB(&aabb); - } + AZ::Aabb aabb; + actorInstance->CalcMeshBasedAabb(0, &aabb); - if (aabb.CheckIfIsValid() == false) + if (!aabb.IsValid()) { - actorInstance->CalcNodeBasedAABB(&aabb); + actorInstance->CalcNodeBasedAabb(&aabb); } - mCharacterHeight = aabb.CalcHeight(); - mOffsetFromTrajectoryNode = aabb.GetMin().GetY() + (mCharacterHeight * 0.5f); + m_characterHeight = aabb.GetExtents().GetZ(); + m_offsetFromTrajectoryNode = aabb.GetMin().GetY() + (m_characterHeight * 0.5f); actorInstance->Destroy(); // scale the normals down to 1% of the character size, that looks pretty nice on all models - mNormalsScaleMultiplier = aabb.CalcRadius() * 0.01f; + const float radius = AZ::Vector3(aabb.GetMax() - aabb.GetMin()).GetLength() * 0.5f; + m_normalsScaleMultiplier = radius * 0.01f; } // zoom to characters void RenderPlugin::ViewCloseup(bool selectedInstancesOnly, RenderWidget* renderWidget, float flightTime) { - const MCore::AABB sceneAABB = GetSceneAABB(selectedInstancesOnly); - - if (sceneAABB.CheckIfIsValid()) + const AZ::Aabb sceneAabb = GetSceneAabb(selectedInstancesOnly); + if (sceneAabb.IsValid()) { // in case the given view widget parameter is nullptr apply it on all view widgets if (!renderWidget) @@ -655,13 +601,13 @@ namespace EMStudio for (RenderViewWidget* viewWidget : m_viewWidgets) { RenderWidget* current = viewWidget->GetRenderWidget(); - current->ViewCloseup(sceneAABB, flightTime); + current->ViewCloseup(sceneAabb, flightTime); } } // only apply it to the given view widget else { - renderWidget->ViewCloseup(sceneAABB, flightTime); + renderWidget->ViewCloseup(sceneAabb, flightTime); } } } @@ -694,55 +640,55 @@ namespace EMStudio { // load the cursors QDir dataDir{ QString(MysticQt::GetDataDir().c_str()) }; - mZoomInCursor = new QCursor(QPixmap(dataDir.filePath("Images/Rendering/ZoomInCursor.png")).scaled(32, 32)); - mZoomOutCursor = new QCursor(QPixmap(dataDir.filePath("Images/Rendering/ZoomOutCursor.png")).scaled(32, 32)); + m_zoomInCursor = new QCursor(QPixmap(dataDir.filePath("Images/Rendering/ZoomInCursor.png")).scaled(32, 32)); + m_zoomOutCursor = new QCursor(QPixmap(dataDir.filePath("Images/Rendering/ZoomOutCursor.png")).scaled(32, 32)); - mCurrentSelection = &GetCommandManager()->GetCurrentSelection(); + m_currentSelection = &GetCommandManager()->GetCurrentSelection(); - connect(mDock, &QDockWidget::visibilityChanged, this, &RenderPlugin::VisibilityChanged); + connect(m_dock, &QDockWidget::visibilityChanged, this, &RenderPlugin::VisibilityChanged); // add the available render template layouts RegisterRenderPluginLayouts(this); // create the inner widget which contains the base layout - mInnerWidget = new QWidget(); - mDock->setWidget(mInnerWidget); + m_innerWidget = new QWidget(); + m_dock->setWidget(m_innerWidget); // the base layout contains the render layout templates on the left and the render views on the right - mBaseLayout = new QHBoxLayout(mInnerWidget); - mBaseLayout->setContentsMargins(0, 2, 2, 2); - mBaseLayout->setSpacing(0); + m_baseLayout = new QHBoxLayout(m_innerWidget); + m_baseLayout->setContentsMargins(0, 2, 2, 2); + m_baseLayout->setSpacing(0); SetSelectionMode(); // create and register the command callbacks only (only execute this code once for all plugins) - mUpdateRenderActorsCallback = new UpdateRenderActorsCallback(false); - mReInitRenderActorsCallback = new ReInitRenderActorsCallback(false); - mCreateActorInstanceCallback = new CreateActorInstanceCallback(false); - mRemoveActorInstanceCallback = new RemoveActorInstanceCallback(false); - mSelectCallback = new SelectCallback(false); - mUnselectCallback = new UnselectCallback(false); - mClearSelectionCallback = new ClearSelectionCallback(false); - mResetToBindPoseCallback = new CommandResetToBindPoseCallback(false); - mAdjustActorInstanceCallback = new AdjustActorInstanceCallback(false); - GetCommandManager()->RegisterCommandCallback("UpdateRenderActors", mUpdateRenderActorsCallback); - GetCommandManager()->RegisterCommandCallback("ReInitRenderActors", mReInitRenderActorsCallback); - GetCommandManager()->RegisterCommandCallback("CreateActorInstance", mCreateActorInstanceCallback); - GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", mRemoveActorInstanceCallback); - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); - GetCommandManager()->RegisterCommandCallback("ResetToBindPose", mResetToBindPoseCallback); - GetCommandManager()->RegisterCommandCallback("AdjustActorInstance", mAdjustActorInstanceCallback); + m_updateRenderActorsCallback = new UpdateRenderActorsCallback(false); + m_reInitRenderActorsCallback = new ReInitRenderActorsCallback(false); + m_createActorInstanceCallback = new CreateActorInstanceCallback(false); + m_removeActorInstanceCallback = new RemoveActorInstanceCallback(false); + m_selectCallback = new SelectCallback(false); + m_unselectCallback = new UnselectCallback(false); + m_clearSelectionCallback = new ClearSelectionCallback(false); + m_resetToBindPoseCallback = new CommandResetToBindPoseCallback(false); + m_adjustActorInstanceCallback = new AdjustActorInstanceCallback(false); + GetCommandManager()->RegisterCommandCallback("UpdateRenderActors", m_updateRenderActorsCallback); + GetCommandManager()->RegisterCommandCallback("ReInitRenderActors", m_reInitRenderActorsCallback); + GetCommandManager()->RegisterCommandCallback("CreateActorInstance", m_createActorInstanceCallback); + GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", m_removeActorInstanceCallback); + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); + GetCommandManager()->RegisterCommandCallback("ResetToBindPose", m_resetToBindPoseCallback); + GetCommandManager()->RegisterCommandCallback("AdjustActorInstance", m_adjustActorInstanceCallback); // initialize the gizmos - mTranslateManipulator = (MCommon::TranslateManipulator*)GetManager()->AddTransformationManipulator(new MCommon::TranslateManipulator(70.0f, false)); - mScaleManipulator = (MCommon::ScaleManipulator*)GetManager()->AddTransformationManipulator(new MCommon::ScaleManipulator(70.0f, false)); - mRotateManipulator = (MCommon::RotateManipulator*)GetManager()->AddTransformationManipulator(new MCommon::RotateManipulator(70.0f, false)); + m_translateManipulator = (MCommon::TranslateManipulator*)GetManager()->AddTransformationManipulator(new MCommon::TranslateManipulator(70.0f, false)); + m_scaleManipulator = (MCommon::ScaleManipulator*)GetManager()->AddTransformationManipulator(new MCommon::ScaleManipulator(70.0f, false)); + m_rotateManipulator = (MCommon::RotateManipulator*)GetManager()->AddTransformationManipulator(new MCommon::RotateManipulator(70.0f, false)); // Load the render options and set the last used layout. LoadRenderOptions(); - LayoutButtonPressed(mRenderOptions.GetLastUsedLayout().c_str()); + LayoutButtonPressed(m_renderOptions.GetLastUsedLayout().c_str()); EMotionFX::SkeletonOutlinerNotificationBus::Handler::BusConnect(); return true; @@ -756,7 +702,7 @@ namespace EMStudio QSettings settings(renderOptionsFilename.c_str(), QSettings::IniFormat, this); // save the general render options - mRenderOptions.Save(&settings); + m_renderOptions.Save(&settings); AZStd::string groupName; if (m_currentLayout) @@ -781,7 +727,7 @@ namespace EMStudio AZStd::string renderOptionsFilename(GetManager()->GetAppDataFolder()); renderOptionsFilename += "EMStudioRenderOptions.cfg"; QSettings settings(renderOptionsFilename.c_str(), QSettings::IniFormat, this); - mRenderOptions = RenderOptions::Load(&settings); + m_renderOptions = RenderOptions::Load(&settings); AZStd::string groupName; if (m_currentLayout) @@ -799,13 +745,12 @@ namespace EMStudio } } - //SetAspiredRenderingFPS(mRenderOptions.mAspiredRenderFPS); - SetManipulatorMode(mRenderOptions.GetManipulatorMode()); + SetManipulatorMode(m_renderOptions.GetManipulatorMode()); } void RenderPlugin::SetManipulatorMode(RenderOptions::ManipulatorMode mode) { - mRenderOptions.SetManipulatorMode(mode); + m_renderOptions.SetManipulatorMode(mode); for (RenderViewWidget* viewWidget : m_viewWidgets) { @@ -817,13 +762,13 @@ namespace EMStudio void RenderPlugin::VisibilityChanged(bool visible) { - mIsVisible = visible; + m_isVisible = visible; } void RenderPlugin::UpdateActorInstances(float timePassedInSeconds) { - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -848,7 +793,7 @@ namespace EMStudio void RenderPlugin::ProcessFrame(float timePassedInSeconds) { // skip rendering in case we want to avoid updating any 3d views - if (GetManager()->GetAvoidRendering() || mIsVisible == false) + if (GetManager()->GetAvoidRendering() || m_isVisible == false) { return; } @@ -865,14 +810,14 @@ namespace EMStudio { RenderWidget* renderWidget = viewWidget->GetRenderWidget(); - if (!mFirstFrameAfterReInit) + if (!m_firstFrameAfterReInit) { renderWidget->GetCamera()->Update(timePassedInSeconds); } - if (mFirstFrameAfterReInit) + if (m_firstFrameAfterReInit) { - mFirstFrameAfterReInit = false; + m_firstFrameAfterReInit = false; } // redraw @@ -882,27 +827,27 @@ namespace EMStudio // get the AABB containing all actor instances in the scene - MCore::AABB RenderPlugin::GetSceneAABB(bool selectedInstancesOnly) + AZ::Aabb RenderPlugin::GetSceneAabb(bool selectedInstancesOnly) { - MCore::AABB finalAABB; + AZ::Aabb finalAabb = AZ::Aabb::CreateNull(); CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - if (mUpdateCallback) + if (m_updateCallback) { - mUpdateCallback->SetEnableRendering(false); + m_updateCallback->SetEnableRendering(false); } // update EMotion FX, but don't render EMotionFX::GetEMotionFX().Update(0.0f); - if (mUpdateCallback) + if (m_updateCallback) { - mUpdateCallback->SetEnableRendering(true); + m_updateCallback->SetEnableRendering(true); } // get the number of actor instances and iterate through them - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { // get the actor instance and update its transformations and meshes EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -922,20 +867,28 @@ namespace EMStudio } // get the mesh based AABB - MCore::AABB aabb; - actorInstance->CalcMeshBasedAABB(0, &aabb); + AZ::Aabb aabb = AZ::Aabb::CreateNull(); + actorInstance->CalcMeshBasedAabb(0, &aabb); // get the node based AABB - if (aabb.CheckIfIsValid() == false) + if (!aabb.IsValid()) { - actorInstance->CalcNodeBasedAABB(&aabb); + actorInstance->CalcNodeBasedAabb(&aabb); } // make sure the actor instance is covered in our global bounding box - finalAABB.Encapsulate(aabb); + if (aabb.IsValid()) + { + finalAabb.AddAabb(aabb); + } } - return finalAABB; + if (!finalAabb.IsValid()) + { + finalAabb.Set(AZ::Vector3(-1.0f, -1.0f, 0.0f), AZ::Vector3(1.0f, 1.0f, 0.0f)); + } + + return finalAabb; } @@ -979,26 +932,26 @@ namespace EMStudio } // save the current settings and disable rendering - mRenderOptions.SetLastUsedLayout(layout->GetName()); + m_renderOptions.SetLastUsedLayout(layout->GetName()); ClearViewWidgets(); VisibilityChanged(false); m_currentLayout = layout; - QWidget* oldLayoutWidget = mRenderLayoutWidget; - QWidget* newLayoutWidget = layout->Create(this, mInnerWidget); + QWidget* oldLayoutWidget = m_renderLayoutWidget; + QWidget* newLayoutWidget = layout->Create(this, m_innerWidget); // delete the old render layout after we created the new one, so we can keep the old resources // this only removes it from the layout - mBaseLayout->removeWidget(oldLayoutWidget); + m_baseLayout->removeWidget(oldLayoutWidget); - mRenderLayoutWidget = newLayoutWidget; + m_renderLayoutWidget = newLayoutWidget; // create thw new one and add it to the base layout - mBaseLayout->addWidget(mRenderLayoutWidget); - mRenderLayoutWidget->update(); - mBaseLayout->update(); - mRenderLayoutWidget->show(); + m_baseLayout->addWidget(m_renderLayoutWidget); + m_renderLayoutWidget->update(); + m_baseLayout->update(); + m_renderLayoutWidget->show(); LoadRenderOptions(); ViewCloseup(false, nullptr, 0.0f); @@ -1027,7 +980,7 @@ namespace EMStudio { for (MCommon::RenderUtil::TrajectoryTracePath* trajectoryPath : m_trajectoryTracePaths) { - if (trajectoryPath->mActorInstance == actorInstance) + if (trajectoryPath->m_actorInstance == actorInstance) { return trajectoryPath; } @@ -1036,8 +989,8 @@ namespace EMStudio // we haven't created a path for the given actor instance yet, do so MCommon::RenderUtil::TrajectoryTracePath* tracePath = new MCommon::RenderUtil::TrajectoryTracePath(); - tracePath->mActorInstance = actorInstance; - tracePath->mTraceParticles.Reserve(512); + tracePath->m_actorInstance = actorInstance; + tracePath->m_traceParticles.reserve(512); m_trajectoryTracePaths.emplace_back(tracePath); return tracePath; @@ -1049,10 +1002,10 @@ namespace EMStudio { // get the current selection CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); // iterate through the actor instances and reset their trajectory path - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { // get the actor instance and find the corresponding trajectory path EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); @@ -1078,20 +1031,20 @@ namespace EMStudio const EMotionFX::Transform& worldTM = actorInstance->GetWorldSpaceTransform(); bool distanceTraveledEnough = false; - if (trajectoryPath->mTraceParticles.GetIsEmpty()) + if (trajectoryPath->m_traceParticles.empty()) { distanceTraveledEnough = true; } else { - const uint32 numParticles = trajectoryPath->mTraceParticles.GetLength(); - const EMotionFX::Transform& oldWorldTM = trajectoryPath->mTraceParticles[numParticles - 1].mWorldTM; + const size_t numParticles = trajectoryPath->m_traceParticles.size(); + const EMotionFX::Transform& oldWorldTM = trajectoryPath->m_traceParticles[numParticles - 1].m_worldTm; - const AZ::Vector3& oldPos = oldWorldTM.mPosition; - const AZ::Quaternion oldRot = oldWorldTM.mRotation.GetNormalized(); - const AZ::Quaternion rotation = worldTM.mRotation.GetNormalized(); + const AZ::Vector3& oldPos = oldWorldTM.m_position; + const AZ::Quaternion oldRot = oldWorldTM.m_rotation.GetNormalized(); + const AZ::Quaternion rotation = worldTM.m_rotation.GetNormalized(); - const AZ::Vector3 deltaPos = worldTM.mPosition - oldPos; + const AZ::Vector3 deltaPos = worldTM.m_position - oldPos; const float deltaRot = MCore::Math::Abs(rotation.Dot(oldRot)); if (MCore::SafeLength(deltaPos) > 0.0001f || deltaRot < 0.99f) { @@ -1100,25 +1053,25 @@ namespace EMStudio } // add the time delta to the time passed since the last add - trajectoryPath->mTimePassed += timePassedInSeconds; + trajectoryPath->m_timePassed += timePassedInSeconds; const uint32 particleSampleRate = 30; - if (trajectoryPath->mTimePassed >= (1.0f / particleSampleRate) && distanceTraveledEnough) + if (trajectoryPath->m_timePassed >= (1.0f / particleSampleRate) && distanceTraveledEnough) { // create the particle, fill its data and add it to the trajectory trace path MCommon::RenderUtil::TrajectoryPathParticle trajectoryParticle; - trajectoryParticle.mWorldTM = worldTM; - trajectoryPath->mTraceParticles.Add(trajectoryParticle); + trajectoryParticle.m_worldTm = worldTM; + trajectoryPath->m_traceParticles.emplace_back(trajectoryParticle); // reset the time passed as we just added a new particle - trajectoryPath->mTimePassed = 0.0f; + trajectoryPath->m_timePassed = 0.0f; } } // make sure we don't have too many items in our array - if (trajectoryPath->mTraceParticles.GetLength() > 50) + if (trajectoryPath->m_traceParticles.size() > 50) { - trajectoryPath->mTraceParticles.RemoveFirst(); + trajectoryPath->m_traceParticles.erase(begin(trajectoryPath->m_traceParticles)); } } } @@ -1145,34 +1098,29 @@ namespace EMStudio RenderViewWidget* widget = GetActiveViewWidget(); RenderOptions* renderOptions = GetRenderOptions(); - const AZStd::unordered_set& visibleJointIndices = GetManager()->GetVisibleJointIndices(); - const AZStd::unordered_set& selectedJointIndices = GetManager()->GetSelectedJointIndices(); + const AZStd::unordered_set& visibleJointIndices = GetManager()->GetVisibleJointIndices(); + const AZStd::unordered_set& selectedJointIndices = GetManager()->GetSelectedJointIndices(); // render the AABBs if (widget->GetRenderFlag(RenderViewWidget::RENDER_AABB)) { MCommon::RenderUtil::AABBRenderSettings settings; - settings.mNodeBasedColor = renderOptions->GetNodeAABBColor(); - settings.mStaticBasedColor = renderOptions->GetStaticAABBColor(); - settings.mMeshBasedColor = renderOptions->GetMeshAABBColor(); - settings.mCollisionMeshBasedColor = renderOptions->GetCollisionMeshAABBColor(); + settings.m_nodeBasedColor = renderOptions->GetNodeAABBColor(); + settings.m_staticBasedColor = renderOptions->GetStaticAABBColor(); + settings.m_meshBasedColor = renderOptions->GetMeshAABBColor(); - renderUtil->RenderAABBs(actorInstance, settings); + renderUtil->RenderAabbs(actorInstance, settings); } - if (widget->GetRenderFlag(RenderViewWidget::RENDER_OBB)) - { - renderUtil->RenderOBBs(actorInstance, &visibleJointIndices, &selectedJointIndices, renderOptions->GetOBBsColor(), renderOptions->GetSelectedObjectColor()); - } if (widget->GetRenderFlag(RenderViewWidget::RENDER_LINESKELETON)) { const MCommon::Camera* camera = widget->GetRenderWidget()->GetCamera(); const AZ::Vector3& cameraPos = camera->GetPosition(); - MCore::AABB aabb; - actorInstance->CalcNodeBasedAABB(&aabb); - const AZ::Vector3 aabbMid = aabb.CalcMiddle(); - const float aabbRadius = aabb.CalcRadius(); + AZ::Aabb aabb; + actorInstance->CalcNodeBasedAabb(&aabb); + const AZ::Vector3 aabbMid = aabb.GetCenter(); + const float aabbRadius = AZ::Vector3(aabb.GetMax() - aabb.GetMin()).GetLength() * 0.5f; const float camDistance = fabs((cameraPos - aabbMid).GetLength()); // Avoid rendering too big joint spheres when zooming in onto a joint. @@ -1185,7 +1133,7 @@ namespace EMStudio // Scale the joint spheres based on the character's extents, to avoid really large joint spheres // on small characters and too small spheres on large characters. static const float baseRadius = 0.005f; - const float jointSphereRadius = aabb.CalcRadius() * scaleMultiplier * baseRadius; + const float jointSphereRadius = aabbRadius * scaleMultiplier * baseRadius; renderUtil->RenderSimpleSkeleton(actorInstance, &visibleJointIndices, &selectedJointIndices, renderOptions->GetLineSkeletonColor(), renderOptions->GetSelectedObjectColor(), jointSphereRadius); @@ -1197,11 +1145,11 @@ namespace EMStudio renderUtil->EnableLighting(false); // disable lighting if (widget->GetRenderFlag(RenderViewWidget::RENDER_SKELETON)) { - renderUtil->RenderSkeleton(actorInstance, emstudioActor->mBoneList, &visibleJointIndices, &selectedJointIndices, renderOptions->GetSkeletonColor(), renderOptions->GetSelectedObjectColor()); + renderUtil->RenderSkeleton(actorInstance, emstudioActor->m_boneList, &visibleJointIndices, &selectedJointIndices, renderOptions->GetSkeletonColor(), renderOptions->GetSelectedObjectColor()); } if (widget->GetRenderFlag(RenderViewWidget::RENDER_NODEORIENTATION)) { - renderUtil->RenderNodeOrientations(actorInstance, emstudioActor->mBoneList, &visibleJointIndices, &selectedJointIndices, emstudioActor->mNormalsScaleMultiplier * renderOptions->GetNodeOrientationScale(), renderOptions->GetScaleBonesOnLength()); + renderUtil->RenderNodeOrientations(actorInstance, emstudioActor->m_boneList, &visibleJointIndices, &selectedJointIndices, emstudioActor->m_normalsScaleMultiplier * renderOptions->GetNodeOrientationScale(), renderOptions->GetScaleBonesOnLength()); } if (widget->GetRenderFlag(RenderViewWidget::RENDER_ACTORBINDPOSE)) { @@ -1212,7 +1160,7 @@ namespace EMStudio if (widget->GetRenderFlag(RenderViewWidget::RENDER_MOTIONEXTRACTION)) { // render an arrow for the trajectory - renderUtil->RenderTrajectoryPath(FindTracePath(actorInstance), renderOptions->GetTrajectoryArrowInnerColor(), emstudioActor->mCharacterHeight * 0.05f); + renderUtil->RenderTrajectoryPath(FindTracePath(actorInstance), renderOptions->GetTrajectoryArrowInnerColor(), emstudioActor->m_characterHeight * 0.05f); } renderUtil->EnableCulling(cullingEnabled); // reset to the old state renderUtil->EnableLighting(lightingEnabled); @@ -1228,13 +1176,13 @@ namespace EMStudio // iterate through all enabled nodes const EMotionFX::Pose* pose = actorInstance->GetTransformData()->GetCurrentPose(); - const uint32 geomLODLevel = actorInstance->GetLODLevel(); - const uint32 numEnabled = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabled; ++i) + const size_t geomLODLevel = actorInstance->GetLODLevel(); + const size_t numEnabled = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numEnabled; ++i) { - EMotionFX::Node* node = emstudioActor->mActor->GetSkeleton()->GetNode(actorInstance->GetEnabledNode(i)); - const AZ::u32 nodeIndex = node->GetNodeIndex(); - EMotionFX::Mesh* mesh = emstudioActor->mActor->GetMesh(geomLODLevel, nodeIndex); + EMotionFX::Node* node = emstudioActor->m_actor->GetSkeleton()->GetNode(actorInstance->GetEnabledNode(i)); + const size_t nodeIndex = node->GetNodeIndex(); + EMotionFX::Mesh* mesh = emstudioActor->m_actor->GetMesh(geomLODLevel, nodeIndex); renderUtil->ResetCurrentMesh(); @@ -1247,20 +1195,20 @@ namespace EMStudio if (!mesh->GetIsCollisionMesh()) { - renderUtil->RenderNormals(mesh, worldTM, renderVertexNormals, renderFaceNormals, renderOptions->GetVertexNormalsScale() * emstudioActor->mNormalsScaleMultiplier, renderOptions->GetFaceNormalsScale() * emstudioActor->mNormalsScaleMultiplier, renderOptions->GetVertexNormalsColor(), renderOptions->GetFaceNormalsColor()); + renderUtil->RenderNormals(mesh, worldTM, renderVertexNormals, renderFaceNormals, renderOptions->GetVertexNormalsScale() * emstudioActor->m_normalsScaleMultiplier, renderOptions->GetFaceNormalsScale() * emstudioActor->m_normalsScaleMultiplier, renderOptions->GetVertexNormalsColor(), renderOptions->GetFaceNormalsColor()); if (renderTangents) { - renderUtil->RenderTangents(mesh, worldTM, renderOptions->GetTangentsScale() * emstudioActor->mNormalsScaleMultiplier, renderOptions->GetTangentsColor(), renderOptions->GetMirroredBitangentsColor(), renderOptions->GetBitangentsColor()); + renderUtil->RenderTangents(mesh, worldTM, renderOptions->GetTangentsScale() * emstudioActor->m_normalsScaleMultiplier, renderOptions->GetTangentsColor(), renderOptions->GetMirroredBitangentsColor(), renderOptions->GetBitangentsColor()); } if (renderWireframe) { - renderUtil->RenderWireframe(mesh, worldTM, renderOptions->GetWireframeColor(), false, emstudioActor->mNormalsScaleMultiplier); + renderUtil->RenderWireframe(mesh, worldTM, renderOptions->GetWireframeColor(), false, emstudioActor->m_normalsScaleMultiplier); } } else if (renderCollisionMeshes) { - renderUtil->RenderWireframe(mesh, worldTM, renderOptions->GetCollisionMeshColor(), false, emstudioActor->mNormalsScaleMultiplier); + renderUtil->RenderWireframe(mesh, worldTM, renderOptions->GetCollisionMeshColor(), false, emstudioActor->m_normalsScaleMultiplier); } } } @@ -1268,8 +1216,8 @@ namespace EMStudio // render the selection if (renderOptions->GetRenderSelectionBox() && EMotionFX::GetActorManager().GetNumActorInstances() != 1 && GetCurrentSelection()->CheckIfHasActorInstance(actorInstance)) { - MCore::AABB aabb = actorInstance->GetAABB(); - aabb.Widen(aabb.CalcRadius() * 0.005f); + AZ::Aabb aabb = actorInstance->GetAabb(); + aabb.Expand(AZ::Vector3(0.005f)); renderUtil->RenderSelection(aabb, renderOptions->GetSelectionColor()); } 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 68cabbefa3..01678e024d 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 @@ -52,14 +52,14 @@ namespace EMStudio { MCORE_MEMORYOBJECTCATEGORY(RenderPlugin::EMStudioRenderActor, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); - EMotionFX::Actor* mActor; - MCore::Array mBoneList; - RenderGL::GLActor* mRenderActor; - MCore::Array mActorInstances; - float mNormalsScaleMultiplier; - float mCharacterHeight; - float mOffsetFromTrajectoryNode; - bool mMustCalcNormalScale; + EMotionFX::Actor* m_actor; + AZStd::vector m_boneList; + RenderGL::GLActor* m_renderActor; + AZStd::vector m_actorInstances; + float m_normalsScaleMultiplier; + float m_characterHeight; + float m_offsetFromTrajectoryNode; + bool m_mustCalcNormalScale; EMStudioRenderActor(EMotionFX::Actor* actor, RenderGL::GLActor* renderActor); virtual ~EMStudioRenderActor(); @@ -72,14 +72,14 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(RenderPlugin::Layout, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); public: - Layout() { mRenderPlugin = nullptr; } + Layout() { m_renderPlugin = nullptr; } virtual ~Layout() { } virtual QWidget* Create(RenderPlugin* renderPlugin, QWidget* parent) = 0; virtual const char* GetName() = 0; virtual const char* GetImageFileName() = 0; private: - RenderPlugin* mRenderPlugin; + RenderPlugin* m_renderPlugin; }; RenderPlugin(); @@ -103,12 +103,12 @@ namespace EMStudio EMStudioPlugin::EPluginType GetPluginType() const override { return EMStudioPlugin::PLUGINTYPE_RENDERING; } uint32 GetProcessFramePriority() const override { return 100; } - PluginOptions* GetOptions() override { return &mRenderOptions; } + PluginOptions* GetOptions() override { return &m_renderOptions; } // render actors - EMStudioRenderActor* FindEMStudioActor(EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance = true); - EMStudioRenderActor* FindEMStudioActor(EMotionFX::Actor* actor); - uint32 FindEMStudioActorIndex(EMStudioRenderActor* EMStudioRenderActor); + EMStudioRenderActor* FindEMStudioActor(const EMotionFX::ActorInstance* actorInstance, bool doubleCheckInstance = true) const; + EMStudioRenderActor* FindEMStudioActor(const EMotionFX::Actor* actor) const; + size_t FindEMStudioActorIndex(const EMStudioRenderActor* EMStudioRenderActor) const; void AddEMStudioActor(EMStudioRenderActor* emstudioActor); bool DestroyEMStudioActor(EMotionFX::Actor* actor); @@ -123,16 +123,16 @@ namespace EMStudio // manipulators void ReInitTransformationManipulators(); MCommon::TransformationManipulator* GetActiveManipulator(MCommon::Camera* camera, int32 mousePosX, int32 mousePosY); - MCORE_INLINE MCommon::TranslateManipulator* GetTranslateManipulator() { return mTranslateManipulator; } - MCORE_INLINE MCommon::RotateManipulator* GetRotateManipulator() { return mRotateManipulator; } - MCORE_INLINE MCommon::ScaleManipulator* GetScaleManipulator() { return mScaleManipulator; } + MCORE_INLINE MCommon::TranslateManipulator* GetTranslateManipulator() { return m_translateManipulator; } + MCORE_INLINE MCommon::RotateManipulator* GetRotateManipulator() { return m_rotateManipulator; } + MCORE_INLINE MCommon::ScaleManipulator* GetScaleManipulator() { return m_scaleManipulator; } // other helpers - MCORE_INLINE RenderOptions* GetRenderOptions() { return &mRenderOptions; } + MCORE_INLINE RenderOptions* GetRenderOptions() { return &m_renderOptions; } // view widget helpers - MCORE_INLINE RenderViewWidget* GetFocusViewWidget() { return mFocusViewWidget; } - MCORE_INLINE void SetFocusViewWidget(RenderViewWidget* focusViewWidget) { mFocusViewWidget = focusViewWidget; } + MCORE_INLINE RenderViewWidget* GetFocusViewWidget() { return m_focusViewWidget; } + MCORE_INLINE void SetFocusViewWidget(RenderViewWidget* focusViewWidget) { m_focusViewWidget = focusViewWidget; } RenderViewWidget* GetViewWidget(size_t index) { return m_viewWidgets[index]; } size_t GetNumViewWidgets() const { return m_viewWidgets.size(); } @@ -140,21 +140,21 @@ namespace EMStudio void RemoveViewWidget(RenderViewWidget* viewWidget); void ClearViewWidgets(); - MCORE_INLINE RenderViewWidget* GetActiveViewWidget() { return mActiveViewWidget; } - MCORE_INLINE void SetActiveViewWidget(RenderViewWidget* viewWidget) { mActiveViewWidget = viewWidget; } + MCORE_INLINE RenderViewWidget* GetActiveViewWidget() { return m_activeViewWidget; } + MCORE_INLINE void SetActiveViewWidget(RenderViewWidget* viewWidget) { m_activeViewWidget = viewWidget; } void AddLayout(Layout* layout) { m_layouts.emplace_back(layout); } Layout* FindLayoutByName(const AZStd::string& layoutName) const; Layout* GetCurrentLayout() const { return m_currentLayout; } const AZStd::vector& GetLayouts() { return m_layouts; } - MCORE_INLINE QCursor& GetZoomInCursor() { assert(mZoomInCursor); return *mZoomInCursor; } - MCORE_INLINE QCursor& GetZoomOutCursor() { assert(mZoomOutCursor); return *mZoomOutCursor; } + MCORE_INLINE QCursor& GetZoomInCursor() { assert(m_zoomInCursor); return *m_zoomInCursor; } + MCORE_INLINE QCursor& GetZoomOutCursor() { assert(m_zoomOutCursor); return *m_zoomOutCursor; } - MCORE_INLINE CommandSystem::SelectionList* GetCurrentSelection() const { return mCurrentSelection; } - MCORE_INLINE MCommon::RenderUtil* GetRenderUtil() const { return mRenderUtil; } + MCORE_INLINE CommandSystem::SelectionList* GetCurrentSelection() const { return m_currentSelection; } + MCORE_INLINE MCommon::RenderUtil* GetRenderUtil() const { return m_renderUtil; } - MCore::AABB GetSceneAABB(bool selectedInstancesOnly); + AZ::Aabb GetSceneAabb(bool selectedInstancesOnly); MCommon::RenderUtil::TrajectoryTracePath* FindTracePath(EMotionFX::ActorInstance* actorInstance); void ResetSelectedTrajectoryPaths(); @@ -195,38 +195,38 @@ namespace EMStudio AZStd::vector m_trajectoryTracePaths; // the transformation manipulators - MCommon::TranslateManipulator* mTranslateManipulator; - MCommon::RotateManipulator* mRotateManipulator; - MCommon::ScaleManipulator* mScaleManipulator; + MCommon::TranslateManipulator* m_translateManipulator; + MCommon::RotateManipulator* m_rotateManipulator; + MCommon::ScaleManipulator* m_scaleManipulator; - MCommon::RenderUtil* mRenderUtil; - RenderUpdateCallback* mUpdateCallback; + MCommon::RenderUtil* m_renderUtil; + RenderUpdateCallback* m_updateCallback; - RenderOptions mRenderOptions; - MCore::Array mActors; + RenderOptions m_renderOptions; + AZStd::vector m_actors; // view widgets AZStd::vector m_viewWidgets; - RenderViewWidget* mActiveViewWidget; - RenderViewWidget* mFocusViewWidget; + RenderViewWidget* m_activeViewWidget; + RenderViewWidget* m_focusViewWidget; // render view layouts AZStd::vector m_layouts; Layout* m_currentLayout; // cursor image files - QCursor* mZoomInCursor; - QCursor* mZoomOutCursor; + QCursor* m_zoomInCursor; + QCursor* m_zoomOutCursor; // window visibility - bool mIsVisible; + bool m_isVisible; // base layout and interface functionality - QHBoxLayout* mBaseLayout; - QWidget* mRenderLayoutWidget; - QWidget* mInnerWidget; - CommandSystem::SelectionList* mCurrentSelection; - bool mFirstFrameAfterReInit; + QHBoxLayout* m_baseLayout; + QWidget* m_renderLayoutWidget; + QWidget* m_innerWidget; + CommandSystem::SelectionList* m_currentSelection; + bool m_firstFrameAfterReInit; bool m_reinitRequested = false; // command callbacks @@ -239,14 +239,14 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(ClearSelectionCallback); MCORE_DEFINECOMMANDCALLBACK(CommandResetToBindPoseCallback); MCORE_DEFINECOMMANDCALLBACK(AdjustActorInstanceCallback); - UpdateRenderActorsCallback* mUpdateRenderActorsCallback; - ReInitRenderActorsCallback* mReInitRenderActorsCallback; - CreateActorInstanceCallback* mCreateActorInstanceCallback; - RemoveActorInstanceCallback* mRemoveActorInstanceCallback; - SelectCallback* mSelectCallback; - UnselectCallback* mUnselectCallback; - ClearSelectionCallback* mClearSelectionCallback; - CommandResetToBindPoseCallback* mResetToBindPoseCallback; - AdjustActorInstanceCallback* mAdjustActorInstanceCallback; + UpdateRenderActorsCallback* m_updateRenderActorsCallback; + ReInitRenderActorsCallback* m_reInitRenderActorsCallback; + CreateActorInstanceCallback* m_createActorInstanceCallback; + RemoveActorInstanceCallback* m_removeActorInstanceCallback; + SelectCallback* m_selectCallback; + UnselectCallback* m_unselectCallback; + ClearSelectionCallback* m_clearSelectionCallback; + CommandResetToBindPoseCallback* m_resetToBindPoseCallback; + AdjustActorInstanceCallback* m_adjustActorInstanceCallback; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.cpp index 4c032cb2ea..5cc88db0b0 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.cpp @@ -21,15 +21,15 @@ namespace EMStudio // constructor RenderUpdateCallback::RenderUpdateCallback(RenderPlugin* plugin) { - mEnableRendering = true; - mPlugin = plugin; + m_enableRendering = true; + m_plugin = plugin; } // enable or disable rendering void RenderUpdateCallback::SetEnableRendering(bool renderingEnabled) { - mEnableRendering = renderingEnabled; + m_enableRendering = renderingEnabled; } @@ -41,7 +41,7 @@ namespace EMStudio // set to visible for the cases the active view widget is nullptr // this happens when call the Process() function from the render plugin before we update our view - RenderViewWidget* widget = mPlugin->GetActiveViewWidget(); + RenderViewWidget* widget = m_plugin->GetActiveViewWidget(); if (widget == nullptr) { actorInstance->SetIsVisible(true); @@ -72,7 +72,7 @@ namespace EMStudio //actorInstance->UpdateTransformations( timePassedInSeconds, true); // find the corresponding trajectory trace path for the given actor instance - MCommon::RenderUtil::TrajectoryTracePath* trajectoryPath = mPlugin->FindTracePath(actorInstance); + MCommon::RenderUtil::TrajectoryTracePath* trajectoryPath = m_plugin->FindTracePath(actorInstance); if (trajectoryPath) { EMotionFX::Actor* actor = actorInstance->GetActor(); @@ -84,20 +84,20 @@ namespace EMStudio const EMotionFX::Transform globalTM = transformData->GetCurrentPose()->GetWorldSpaceTransform(motionExtractionNode->GetNodeIndex()).ProjectedToGroundPlane(); bool distanceTraveledEnough = false; - if (trajectoryPath->mTraceParticles.GetIsEmpty()) + if (trajectoryPath->m_traceParticles.empty()) { distanceTraveledEnough = true; } else { - const uint32 numParticles = trajectoryPath->mTraceParticles.GetLength(); - const EMotionFX::Transform& oldGlobalTM = trajectoryPath->mTraceParticles[numParticles - 1].mWorldTM; + const size_t numParticles = trajectoryPath->m_traceParticles.size(); + const EMotionFX::Transform& oldGlobalTM = trajectoryPath->m_traceParticles[numParticles - 1].m_worldTm; - const AZ::Vector3& oldPos = oldGlobalTM.mPosition; - const AZ::Quaternion& oldRot = oldGlobalTM.mRotation; - const AZ::Quaternion rotation = globalTM.mRotation.GetNormalized(); + const AZ::Vector3& oldPos = oldGlobalTM.m_position; + const AZ::Quaternion& oldRot = oldGlobalTM.m_rotation; + const AZ::Quaternion rotation = globalTM.m_rotation.GetNormalized(); - const AZ::Vector3 deltaPos = globalTM.mPosition - oldPos; + const AZ::Vector3 deltaPos = globalTM.m_position - oldPos; float deltaRot = MCore::Math::Abs(rotation.Dot(oldRot)); if (MCore::SafeLength(deltaPos) > 0.0001f || deltaRot < 0.99f) @@ -107,25 +107,25 @@ namespace EMStudio } // add the time delta to the time passed since the last add - trajectoryPath->mTimePassed += timePassedInSeconds; + trajectoryPath->m_timePassed += timePassedInSeconds; const uint32 particleSampleRate = 30; - if (trajectoryPath->mTimePassed >= (1.0f / particleSampleRate) && distanceTraveledEnough) + if (trajectoryPath->m_timePassed >= (1.0f / particleSampleRate) && distanceTraveledEnough) { // create the particle, fill its data and add it to the trajectory trace path MCommon::RenderUtil::TrajectoryPathParticle trajectoryParticle; - trajectoryParticle.mWorldTM = globalTM; - trajectoryPath->mTraceParticles.Add(trajectoryParticle); + trajectoryParticle.m_worldTm = globalTM; + trajectoryPath->m_traceParticles.emplace_back(trajectoryParticle); // reset the time passed as we just added a new particle - trajectoryPath->mTimePassed = 0.0f; + trajectoryPath->m_timePassed = 0.0f; } } // make sure we don't have too many items in our array - if (trajectoryPath->mTraceParticles.GetLength() > 50) + if (trajectoryPath->m_traceParticles.size() > 50) { - trajectoryPath->mTraceParticles.RemoveFirst(); + trajectoryPath->m_traceParticles.erase(begin(trajectoryPath->m_traceParticles)); } } } @@ -136,19 +136,19 @@ namespace EMStudio { MCORE_UNUSED(timePassedInSeconds); - if (mEnableRendering == false) + if (m_enableRendering == false) { return; } - RenderPlugin::EMStudioRenderActor* emstudioActor = mPlugin->FindEMStudioActor(actorInstance); + RenderPlugin::EMStudioRenderActor* emstudioActor = m_plugin->FindEMStudioActor(actorInstance); if (emstudioActor == nullptr) { return; } // renderUtil options - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; @@ -157,28 +157,23 @@ namespace EMStudio actorInstance->UpdateMeshDeformers(timePassedInSeconds); // get the active widget & it's rendering options - RenderViewWidget* widget = mPlugin->GetActiveViewWidget(); - RenderOptions* renderOptions = mPlugin->GetRenderOptions(); + RenderViewWidget* widget = m_plugin->GetActiveViewWidget(); + RenderOptions* renderOptions = m_plugin->GetRenderOptions(); - const AZStd::unordered_set& visibleJointIndices = GetManager()->GetVisibleJointIndices(); - const AZStd::unordered_set& selectedJointIndices = GetManager()->GetSelectedJointIndices(); + const AZStd::unordered_set& visibleJointIndices = GetManager()->GetVisibleJointIndices(); + const AZStd::unordered_set& selectedJointIndices = GetManager()->GetSelectedJointIndices(); // render the AABBs if (widget->GetRenderFlag(RenderViewWidget::RENDER_AABB)) { MCommon::RenderUtil::AABBRenderSettings settings; - settings.mNodeBasedColor = renderOptions->GetNodeAABBColor(); - settings.mStaticBasedColor = renderOptions->GetStaticAABBColor(); - settings.mMeshBasedColor = renderOptions->GetMeshAABBColor(); - settings.mCollisionMeshBasedColor = renderOptions->GetCollisionMeshAABBColor(); + settings.m_nodeBasedColor = renderOptions->GetNodeAABBColor(); + settings.m_staticBasedColor = renderOptions->GetStaticAABBColor(); + settings.m_meshBasedColor = renderOptions->GetMeshAABBColor(); - renderUtil->RenderAABBs(actorInstance, settings); + renderUtil->RenderAabbs(actorInstance, settings); } - if (widget->GetRenderFlag(RenderViewWidget::RENDER_OBB)) - { - renderUtil->RenderOBBs(actorInstance, &visibleJointIndices, &selectedJointIndices, renderOptions->GetOBBsColor(), renderOptions->GetSelectedObjectColor()); - } if (widget->GetRenderFlag(RenderViewWidget::RENDER_LINESKELETON)) { renderUtil->RenderSimpleSkeleton(actorInstance, &visibleJointIndices, &selectedJointIndices, renderOptions->GetLineSkeletonColor(), renderOptions->GetSelectedObjectColor()); @@ -190,11 +185,11 @@ namespace EMStudio renderUtil->EnableLighting(false); // disable lighting if (widget->GetRenderFlag(RenderViewWidget::RENDER_SKELETON)) { - renderUtil->RenderSkeleton(actorInstance, emstudioActor->mBoneList, &visibleJointIndices, &selectedJointIndices, renderOptions->GetSkeletonColor(), renderOptions->GetSelectedObjectColor()); + renderUtil->RenderSkeleton(actorInstance, emstudioActor->m_boneList, &visibleJointIndices, &selectedJointIndices, renderOptions->GetSkeletonColor(), renderOptions->GetSelectedObjectColor()); } if (widget->GetRenderFlag(RenderViewWidget::RENDER_NODEORIENTATION)) { - renderUtil->RenderNodeOrientations(actorInstance, emstudioActor->mBoneList, &visibleJointIndices, &selectedJointIndices, renderOptions->GetNodeOrientationScale(), renderOptions->GetScaleBonesOnLength()); + renderUtil->RenderNodeOrientations(actorInstance, emstudioActor->m_boneList, &visibleJointIndices, &selectedJointIndices, renderOptions->GetNodeOrientationScale(), renderOptions->GetScaleBonesOnLength()); } if (widget->GetRenderFlag(RenderViewWidget::RENDER_ACTORBINDPOSE)) { @@ -205,8 +200,7 @@ namespace EMStudio if (widget->GetRenderFlag(RenderViewWidget::RENDER_MOTIONEXTRACTION)) { // render an arrow for the trajectory node - //renderUtil->RenderTrajectoryNode(actorInstance, renderOptions->mTrajectoryArrowInnerColor, renderOptions->mTrajectoryArrowBorderColor, emstudioActor->mCharacterHeight*0.05f); - renderUtil->RenderTrajectoryPath(mPlugin->FindTracePath(actorInstance), renderOptions->GetTrajectoryArrowInnerColor(), emstudioActor->mCharacterHeight * 0.05f); + renderUtil->RenderTrajectoryPath(m_plugin->FindTracePath(actorInstance), renderOptions->GetTrajectoryArrowInnerColor(), emstudioActor->m_characterHeight * 0.05f); } renderUtil->EnableCulling(cullingEnabled); // reset to the old state renderUtil->EnableLighting(lightingEnabled); @@ -221,13 +215,12 @@ namespace EMStudio { // iterate through all enabled nodes const EMotionFX::Pose* pose = actorInstance->GetTransformData()->GetCurrentPose(); - const uint32 geomLODLevel = actorInstance->GetLODLevel(); - const uint32 numEnabled = actorInstance->GetNumEnabledNodes(); - for (uint32 i = 0; i < numEnabled; ++i) + const size_t geomLODLevel = actorInstance->GetLODLevel(); + const size_t numEnabled = actorInstance->GetNumEnabledNodes(); + for (size_t i = 0; i < numEnabled; ++i) { - EMotionFX::Node* node = emstudioActor->mActor->GetSkeleton()->GetNode(actorInstance->GetEnabledNode(i)); - EMotionFX::Mesh* mesh = emstudioActor->mActor->GetMesh(geomLODLevel, node->GetNodeIndex()); - //EMotionFX::Mesh* collisionMesh = emstudioActor->mActor->GetCollisionMesh( geomLODLevel, node->GetNodeIndex() ); + EMotionFX::Node* node = emstudioActor->m_actor->GetSkeleton()->GetNode(actorInstance->GetEnabledNode(i)); + EMotionFX::Mesh* mesh = emstudioActor->m_actor->GetMesh(geomLODLevel, node->GetNodeIndex()); const AZ::Transform globalTM = pose->GetWorldSpaceTransform(node->GetNodeIndex()).ToAZTransform(); renderUtil->ResetCurrentMesh(); @@ -239,10 +232,10 @@ namespace EMStudio if (mesh->GetIsCollisionMesh() == false) { - renderUtil->RenderNormals(mesh, globalTM, renderVertexNormals, renderFaceNormals, renderOptions->GetVertexNormalsScale() * emstudioActor->mNormalsScaleMultiplier, renderOptions->GetFaceNormalsScale() * emstudioActor->mNormalsScaleMultiplier, renderOptions->GetVertexNormalsColor(), renderOptions->GetFaceNormalsColor()); + renderUtil->RenderNormals(mesh, globalTM, renderVertexNormals, renderFaceNormals, renderOptions->GetVertexNormalsScale() * emstudioActor->m_normalsScaleMultiplier, renderOptions->GetFaceNormalsScale() * emstudioActor->m_normalsScaleMultiplier, renderOptions->GetVertexNormalsColor(), renderOptions->GetFaceNormalsColor()); if (renderTangents) { - renderUtil->RenderTangents(mesh, globalTM, renderOptions->GetTangentsScale() * emstudioActor->mNormalsScaleMultiplier, renderOptions->GetTangentsColor(), renderOptions->GetMirroredBitangentsColor(), renderOptions->GetBitangentsColor()); + renderUtil->RenderTangents(mesh, globalTM, renderOptions->GetTangentsScale() * emstudioActor->m_normalsScaleMultiplier, renderOptions->GetTangentsColor(), renderOptions->GetMirroredBitangentsColor(), renderOptions->GetBitangentsColor()); } if (renderWireframe) { @@ -258,10 +251,10 @@ namespace EMStudio } // render the selection - if (renderOptions->GetRenderSelectionBox() && EMotionFX::GetActorManager().GetNumActorInstances() != 1 && mPlugin->GetCurrentSelection()->CheckIfHasActorInstance(actorInstance)) + if (renderOptions->GetRenderSelectionBox() && EMotionFX::GetActorManager().GetNumActorInstances() != 1 && m_plugin->GetCurrentSelection()->CheckIfHasActorInstance(actorInstance)) { - MCore::AABB aabb = actorInstance->GetAABB(); - aabb.Widen(aabb.CalcRadius() * 0.005f); + AZ::Aabb aabb = actorInstance->GetAabb(); + aabb.Expand(aabb.GetExtents() * 0.005f); renderUtil->RenderSelection(aabb, renderOptions->GetSelectionColor()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.h index fed8d5feec..a9bc26ae22 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderUpdateCallback.h @@ -34,8 +34,8 @@ namespace EMStudio void SetEnableRendering(bool renderingEnabled); protected: - bool mEnableRendering; - RenderPlugin* mPlugin; + bool m_enableRendering; + RenderPlugin* m_plugin; }; } // namespace EMStudio 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 76e1a1e7f3..93a6dd3019 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 @@ -26,12 +26,12 @@ namespace EMStudio { for (uint32 i = 0; i < NUM_RENDER_OPTIONS; ++i) { - mToolbarButtons[i] = nullptr; - mActions[i] = nullptr; + m_toolbarButtons[i] = nullptr; + m_actions[i] = nullptr; } - mRenderOptionsWindow = nullptr; - mPlugin = parentPlugin; + m_renderOptionsWindow = nullptr; + m_plugin = parentPlugin; // create the vertical layout with the menu and the gl widget as entries QVBoxLayout* verticalLayout = new QVBoxLayout(this); @@ -40,14 +40,14 @@ namespace EMStudio verticalLayout->setMargin(0); // create toolbar - mToolBar = new QToolBar(this); - mToolBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + m_toolBar = new QToolBar(this); + m_toolBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); // add the toolbar to the vertical layout - verticalLayout->addWidget(mToolBar); + verticalLayout->addWidget(m_toolBar); QWidget* renderWidget = nullptr; - mPlugin->CreateRenderWidget(this, &mRenderWidget, &renderWidget); + m_plugin->CreateRenderWidget(this, &m_renderWidget, &renderWidget); verticalLayout->addWidget(renderWidget); new QActionGroup(this); @@ -65,14 +65,14 @@ namespace EMStudio group->addAction(action); } - mToolBar->addSeparator(); + m_toolBar->addSeparator(); QAction* layoutsAction = AddToolBarAction("Layouts", "Layout_category.svg"); { QMenu* contextMenu = new QMenu(this); - const AZStd::vector& layouts = mPlugin->GetLayouts(); - const RenderPlugin::Layout* currentLayout = mPlugin->GetCurrentLayout(); + const AZStd::vector& layouts = m_plugin->GetLayouts(); + const RenderPlugin::Layout* currentLayout = m_plugin->GetCurrentLayout(); for (RenderPlugin::Layout* layout : layouts) { QAction* layoutAction = contextMenu->addAction(layout->GetName()); @@ -80,15 +80,15 @@ namespace EMStudio layoutAction->setCheckable(true); layoutAction->setChecked(layout == currentLayout); - connect(layoutAction, &QAction::triggered, mPlugin, [this, layout](){ - mPlugin->LayoutButtonPressed(layout->GetName()); + connect(layoutAction, &QAction::triggered, m_plugin, [this, layout](){ + m_plugin->LayoutButtonPressed(layout->GetName()); }); } connect(layoutsAction, &QAction::toggled, contextMenu, &QMenu::show); layoutsAction->setMenu(contextMenu); - auto widgetForAction = qobject_cast(mToolBar->widgetForAction(layoutsAction)); + auto widgetForAction = qobject_cast(m_toolBar->widgetForAction(layoutsAction)); if (widgetForAction) { connect(layoutsAction, &QAction::triggered, widgetForAction, &QToolButton::showMenu); @@ -108,7 +108,6 @@ namespace EMStudio CreateViewOptionEntry(contextMenu, "Face Normals", RENDER_FACENORMALS); CreateViewOptionEntry(contextMenu, "Tangents", RENDER_TANGENTS); CreateViewOptionEntry(contextMenu, "Actor Bounding Boxes", RENDER_AABB); - CreateViewOptionEntry(contextMenu, "Joint OBBs", RENDER_OBB, false); CreateViewOptionEntry(contextMenu, "Collision Meshes", RENDER_COLLISIONMESHES, false); contextMenu->addSeparator(); CreateViewOptionEntry(contextMenu, "Line Skeleton", RENDER_LINESKELETON); @@ -132,7 +131,7 @@ namespace EMStudio viewOptionsAction->setMenu(contextMenu); - auto widgetForAction = qobject_cast(mToolBar->widgetForAction(viewOptionsAction)); + auto widgetForAction = qobject_cast(m_toolBar->widgetForAction(viewOptionsAction)); if (widgetForAction) { connect(viewOptionsAction, &QAction::triggered, widgetForAction, &QToolButton::showMenu); @@ -167,26 +166,26 @@ namespace EMStudio cameraMenu->addSeparator(); - mFollowCharacterAction = cameraMenu->addAction(tr("Follow Character")); - mFollowCharacterAction->setCheckable(true); - mFollowCharacterAction->setChecked(true); - connect(mFollowCharacterAction, &QAction::triggered, this, &RenderViewWidget::OnFollowCharacter); + m_followCharacterAction = cameraMenu->addAction(tr("Follow Character")); + m_followCharacterAction->setCheckable(true); + m_followCharacterAction->setChecked(true); + connect(m_followCharacterAction, &QAction::triggered, this, &RenderViewWidget::OnFollowCharacter); cameraOptionsAction->setMenu(cameraMenu); - mCameraMenu = cameraMenu; + m_cameraMenu = cameraMenu; - auto widgetForAction = qobject_cast(mToolBar->widgetForAction(cameraOptionsAction)); + auto widgetForAction = qobject_cast(m_toolBar->widgetForAction(cameraOptionsAction)); if (widgetForAction) { connect(cameraOptionsAction, &QAction::triggered, widgetForAction, &QToolButton::showMenu); } } - connect(m_manipulatorModes[RenderOptions::SELECT], &QAction::triggered, mPlugin, &RenderPlugin::SetSelectionMode); - connect(m_manipulatorModes[RenderOptions::TRANSLATE], &QAction::triggered, mPlugin, &RenderPlugin::SetTranslationMode); - connect(m_manipulatorModes[RenderOptions::ROTATE], &QAction::triggered, mPlugin, &RenderPlugin::SetRotationMode); - connect(m_manipulatorModes[RenderOptions::SCALE], &QAction::triggered, mPlugin, &RenderPlugin::SetScaleMode); + connect(m_manipulatorModes[RenderOptions::SELECT], &QAction::triggered, m_plugin, &RenderPlugin::SetSelectionMode); + connect(m_manipulatorModes[RenderOptions::TRANSLATE], &QAction::triggered, m_plugin, &RenderPlugin::SetTranslationMode); + connect(m_manipulatorModes[RenderOptions::ROTATE], &QAction::triggered, m_plugin, &RenderPlugin::SetRotationMode); + connect(m_manipulatorModes[RenderOptions::SCALE], &QAction::triggered, m_plugin, &RenderPlugin::SetScaleMode); QAction* toggleSelectionBoxRendering = new QAction( "Toggle Selection Box Rendering", @@ -196,7 +195,7 @@ namespace EMStudio GetMainWindow()->GetShortcutManager()->RegisterKeyboardShortcut(toggleSelectionBoxRendering, RenderPlugin::s_renderWindowShortcutGroupName, true); connect(toggleSelectionBoxRendering, &QAction::triggered, this, [this] { - mPlugin->GetRenderOptions()->SetRenderSelectionBox(mPlugin->GetRenderOptions()->GetRenderSelectionBox() ^ true); + m_plugin->GetRenderOptions()->SetRenderSelectionBox(m_plugin->GetRenderOptions()->GetRenderSelectionBox() ^ true); }); addAction(toggleSelectionBoxRendering); @@ -233,7 +232,6 @@ namespace EMStudio SetRenderFlag(RENDER_TANGENTS, false); SetRenderFlag(RENDER_AABB, false); - SetRenderFlag(RENDER_OBB, false); SetRenderFlag(RENDER_COLLISIONMESHES, false); SetRenderFlag(RENDER_RAGDOLL_COLLIDERS, true); SetRenderFlag(RENDER_RAGDOLL_JOINTLIMITS, true); @@ -259,13 +257,13 @@ namespace EMStudio { const uint32 optionIndex = (uint32)option; - if (mToolbarButtons[optionIndex]) + if (m_toolbarButtons[optionIndex]) { - mToolbarButtons[optionIndex]->setChecked(isEnabled); + m_toolbarButtons[optionIndex]->setChecked(isEnabled); } - if (mActions[optionIndex]) + if (m_actions[optionIndex]) { - mActions[optionIndex]->setChecked(isEnabled); + m_actions[optionIndex]->setChecked(isEnabled); } } @@ -282,7 +280,7 @@ namespace EMStudio if (actionIndex >= 0) { - mActions[actionIndex] = action; + m_actions[actionIndex] = action; } } @@ -292,7 +290,7 @@ namespace EMStudio iconFileName += iconName; const QIcon& icon = MysticQt::GetMysticQt()->FindIcon(iconFileName.c_str()); - QAction* action = mToolBar->addAction(icon, entryName); + QAction* action = m_toolBar->addAction(icon, entryName); return action; } @@ -301,22 +299,22 @@ namespace EMStudio // destructor RenderViewWidget::~RenderViewWidget() { - mPlugin->RemoveViewWidget(this); + m_plugin->RemoveViewWidget(this); } // show the global rendering options dialog void RenderViewWidget::OnOptions() { - if (mRenderOptionsWindow == nullptr) + if (m_renderOptionsWindow == nullptr) { - mRenderOptionsWindow = new PreferencesWindow(this); - mRenderOptionsWindow->Init(); + m_renderOptionsWindow = new PreferencesWindow(this); + m_renderOptionsWindow->Init(); - AzToolsFramework::ReflectedPropertyEditor* generalPropertyWidget = mRenderOptionsWindow->FindPropertyWidgetByName("General"); + AzToolsFramework::ReflectedPropertyEditor* generalPropertyWidget = m_renderOptionsWindow->FindPropertyWidgetByName("General"); if (!generalPropertyWidget) { - generalPropertyWidget = mRenderOptionsWindow->AddCategory("General"); + generalPropertyWidget = m_renderOptionsWindow->AddCategory("General"); generalPropertyWidget->ClearInstances(); generalPropertyWidget->InvalidateAll(); } @@ -329,7 +327,7 @@ namespace EMStudio return; } - PluginOptions* pluginOptions = mPlugin->GetOptions(); + PluginOptions* pluginOptions = m_plugin->GetOptions(); AZ_Assert(pluginOptions, "Expected options in render plugin"); generalPropertyWidget->AddInstance(pluginOptions, azrtti_typeid(pluginOptions)); @@ -341,25 +339,25 @@ namespace EMStudio generalPropertyWidget->InvalidateAll(); } - mRenderOptionsWindow->show(); + m_renderOptionsWindow->show(); } void RenderViewWidget::OnShowSelected() { - mRenderWidget->ViewCloseup(true, DEFAULT_FLIGHT_TIME); + m_renderWidget->ViewCloseup(true, DEFAULT_FLIGHT_TIME); } void RenderViewWidget::OnShowEntireScene() { - mRenderWidget->ViewCloseup(false, DEFAULT_FLIGHT_TIME); + m_renderWidget->ViewCloseup(false, DEFAULT_FLIGHT_TIME); } void RenderViewWidget::SetCharacterFollowModeActive(bool active) { - mFollowCharacterAction->setChecked(active); + m_followCharacterAction->setChecked(active); } @@ -368,9 +366,9 @@ namespace EMStudio CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); EMotionFX::ActorInstance* followInstance = selectionList.GetFirstActorInstance(); - if (followInstance && GetIsCharacterFollowModeActive() && mRenderWidget) + if (followInstance && GetIsCharacterFollowModeActive() && m_renderWidget) { - mRenderWidget->ViewCloseup(true, DEFAULT_FLIGHT_TIME, 1); + m_renderWidget->ViewCloseup(true, DEFAULT_FLIGHT_TIME, 1); } } @@ -381,7 +379,7 @@ namespace EMStudio { QAction* action = actionModePair.first; action->setCheckable(true); - action->setChecked(mRenderWidget->GetCameraMode() == actionModePair.second); + action->setChecked(m_renderWidget->GetCameraMode() == actionModePair.second); } } @@ -391,10 +389,10 @@ namespace EMStudio for (uint32 i = 0; i < numRenderOptions; ++i) { QString name = QString(i); - settings->setValue(name, mActions[i] ? mActions[i]->isChecked() : false); + settings->setValue(name, m_actions[i] ? m_actions[i]->isChecked() : false); } - settings->setValue("CameraMode", (int32)mRenderWidget->GetCameraMode()); + settings->setValue("CameraMode", (int32)m_renderWidget->GetCameraMode()); settings->setValue("CharacterFollowMode", GetIsCharacterFollowModeActive()); } @@ -405,17 +403,16 @@ namespace EMStudio for (uint32 i = 0; i < numRenderOptions; ++i) { QString name = QString(i); - const bool isEnabled = settings->value(name, mActions[i] ? mActions[i]->isChecked() : false).toBool(); + const bool isEnabled = settings->value(name, m_actions[i] ? m_actions[i]->isChecked() : false).toBool(); SetRenderFlag((ERenderFlag)i, isEnabled); } // Override some settings as we removed those from the menu. - SetRenderFlag(RENDER_OBB, false); SetRenderFlag(RENDER_COLLISIONMESHES, false); SetRenderFlag(RENDER_TEXTURING, false); - RenderWidget::CameraMode cameraMode = (RenderWidget::CameraMode)settings->value("CameraMode", (int32)mRenderWidget->GetCameraMode()).toInt(); - mRenderWidget->SwitchCamera(cameraMode); + RenderWidget::CameraMode cameraMode = (RenderWidget::CameraMode)settings->value("CameraMode", (int32)m_renderWidget->GetCameraMode()).toInt(); + m_renderWidget->SwitchCamera(cameraMode); const bool followMode = settings->value("CharacterFollowMode", GetIsCharacterFollowModeActive()).toBool(); SetCharacterFollowModeActive(followMode); @@ -429,7 +426,7 @@ namespace EMStudio const uint32 numRenderOptions = NUM_RENDER_OPTIONS; for (uint32 i = 0; i < numRenderOptions; ++i) { - if (mActions[i] == action) + if (m_actions[i] == action) { return i; } 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 74e5e0ce72..aed4f0c133 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 @@ -52,7 +52,6 @@ namespace EMStudio RENDER_VERTEXNORMALS = 6, RENDER_TANGENTS = 7, RENDER_AABB = 8, - RENDER_OBB = 9, RENDER_COLLISIONMESHES = 10, RENDER_SKELETON = 11, RENDER_LINESKELETON = 12, @@ -72,16 +71,16 @@ namespace EMStudio NUM_RENDER_OPTIONS = 26 }; - MCORE_INLINE bool GetRenderFlag(ERenderFlag option) { return mActions[(uint32)option] ? mActions[(uint32)option]->isChecked() : false; } + MCORE_INLINE bool GetRenderFlag(ERenderFlag option) { return m_actions[(uint32)option] ? m_actions[(uint32)option]->isChecked() : false; } void SetRenderFlag(ERenderFlag option, bool isEnabled); uint32 FindActionIndex(QAction* action); - RenderWidget* GetRenderWidget() const { return mRenderWidget; } - QMenu* GetCameraMenu() const { return mCameraMenu; } + RenderWidget* GetRenderWidget() const { return m_renderWidget; } + QMenu* GetCameraMenu() const { return m_cameraMenu; } void SaveOptions(QSettings* settings); void LoadOptions(QSettings* settings); - bool GetIsCharacterFollowModeActive() const { return mFollowCharacterAction->isChecked(); } + bool GetIsCharacterFollowModeActive() const { return m_followCharacterAction->isChecked(); } void SetCharacterFollowModeActive(bool active); void OnContextMenuEvent(QWidget* renderWidget, bool ctrlPressed, int32 localMouseX, int32 localMouseY, QPoint globalMousePos, RenderPlugin* plugin, MCommon::Camera* camera); @@ -90,17 +89,17 @@ namespace EMStudio public slots: void OnOptions(); - void OnOrbitCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_ORBIT); UpdateInterface(); } - void OnFirstPersonCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_FIRSTPERSON); UpdateInterface(); } - void OnOrthoFrontCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_FRONT); UpdateInterface(); } - void OnOrthoBackCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_BACK); UpdateInterface(); } - void OnOrthoLeftCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_LEFT); UpdateInterface(); } - void OnOrthoRightCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_RIGHT); UpdateInterface(); } - void OnOrthoTopCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_TOP); UpdateInterface(); } - void OnOrthoBottomCamera() { mRenderWidget->SwitchCamera(RenderWidget::CAMMODE_BOTTOM); UpdateInterface(); } + void OnOrbitCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_ORBIT); UpdateInterface(); } + void OnFirstPersonCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_FIRSTPERSON); UpdateInterface(); } + void OnOrthoFrontCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_FRONT); UpdateInterface(); } + void OnOrthoBackCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_BACK); UpdateInterface(); } + void OnOrthoLeftCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_LEFT); UpdateInterface(); } + void OnOrthoRightCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_RIGHT); UpdateInterface(); } + void OnOrthoTopCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_TOP); UpdateInterface(); } + void OnOrthoBottomCamera() { m_renderWidget->SwitchCamera(RenderWidget::CAMMODE_BOTTOM); UpdateInterface(); } void OnResetCamera(float flightTime = 1.0f) { - MCommon::Camera* camera = mRenderWidget->GetCamera(); + MCommon::Camera* camera = m_renderWidget->GetCamera(); if (camera) { camera->Reset(flightTime); @@ -118,15 +117,15 @@ namespace EMStudio QAction* AddToolBarAction(const char* entryName, const char* iconName); void Reset(); - QToolBar* mToolBar; - QMenu* mCameraMenu; - RenderWidget* mRenderWidget; - QAction* mActions[NUM_RENDER_OPTIONS]; - QAction* mFollowCharacterAction; + QToolBar* m_toolBar; + QMenu* m_cameraMenu; + RenderWidget* m_renderWidget; + QAction* m_actions[NUM_RENDER_OPTIONS]; + QAction* m_followCharacterAction; AZStd::vector> m_cameraModeActions; - QPushButton* mToolbarButtons[NUM_RENDER_OPTIONS]; + QPushButton* m_toolbarButtons[NUM_RENDER_OPTIONS]; AZStd::array m_manipulatorModes; - RenderPlugin* mPlugin; - PreferencesWindow* mRenderOptionsWindow; + RenderPlugin* m_plugin; + PreferencesWindow* m_renderOptionsWindow; }; } // namespace EMStudio 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 c74f693765..429a0bffae 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 @@ -6,7 +6,6 @@ * */ -// include the required headers #include "RenderWidget.h" #include "RenderPlugin.h" #include @@ -21,6 +20,7 @@ #include "../EMStudioManager.h" #include "../MainWindow.h" #include +#include namespace EMStudio @@ -30,33 +30,28 @@ namespace EMStudio // constructor RenderWidget::RenderWidget(RenderPlugin* renderPlugin, RenderViewWidget* viewWidget) - : mEventHandler(this) + : m_eventHandler(this) { // create our event handler - EMotionFX::GetEventManager().AddEventHandler(&mEventHandler); - - //mLines.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); - //mLines.Reserve(2048); - - mSelectedActorInstances.SetMemoryCategory(MEMCATEGORY_EMSTUDIOSDK_RENDERPLUGINBASE); + EMotionFX::GetEventManager().AddEventHandler(&m_eventHandler); // camera used to render the little axis on the bottom left - mAxisFakeCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_FRONT); - - mPlugin = renderPlugin; - mViewWidget = viewWidget; - mWidth = 0; - mHeight = 0; - mViewCloseupWaiting = 0; - mPrevMouseX = 0; - mPrevMouseY = 0; - mPrevLocalMouseX = 0; - mPrevLocalMouseY = 0; - mOldActorInstancePos = AZ::Vector3::CreateZero(); - mCamera = nullptr; - mActiveTransformManip = nullptr; - mSkipFollowCalcs = false; - mNeedDisableFollowMode = true; + m_axisFakeCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_FRONT); + + m_plugin = renderPlugin; + m_viewWidget = viewWidget; + m_width = 0; + m_height = 0; + m_viewCloseupWaiting = 0; + m_prevMouseX = 0; + m_prevMouseY = 0; + m_prevLocalMouseX = 0; + m_prevLocalMouseY = 0; + m_oldActorInstancePos = AZ::Vector3::CreateZero(); + m_camera = nullptr; + m_activeTransformManip = nullptr; + m_skipFollowCalcs = false; + m_needDisableFollowMode = true; } @@ -64,83 +59,81 @@ namespace EMStudio RenderWidget::~RenderWidget() { // get rid of the event handler - EMotionFX::GetEventManager().RemoveEventHandler(&mEventHandler); + EMotionFX::GetEventManager().RemoveEventHandler(&m_eventHandler); // get rid of the camera objects - delete mCamera; - delete mAxisFakeCamera; + delete m_camera; + delete m_axisFakeCamera; } // start view closeup flight - void RenderWidget::ViewCloseup(const MCore::AABB& aabb, float flightTime, uint32 viewCloseupWaiting) + void RenderWidget::ViewCloseup(const AZ::Aabb& aabb, float flightTime, uint32 viewCloseupWaiting) { - //LogError("ViewCloseup: AABB: Pos=(%.3f, %.3f, %.3f), Width=%.3f, Height=%.3f, Depth=%.3f", aabb.CalcMiddle().x, aabb.CalcMiddle().y, aabb.CalcMiddle().z, aabb.CalcWidth(), aabb.CalcHeight(), aabb.CalcDepth()); - mViewCloseupWaiting = viewCloseupWaiting; - mViewCloseupAABB = aabb; - mViewCloseupFlightTime = flightTime; + m_viewCloseupWaiting = viewCloseupWaiting; + m_viewCloseupAabb = aabb; + m_viewCloseupFlightTime = flightTime; } void RenderWidget::ViewCloseup(bool selectedInstancesOnly, float flightTime, uint32 viewCloseupWaiting) { - //LogError("ViewCloseup: AABB: Pos=(%.3f, %.3f, %.3f), Width=%.3f, Height=%.3f, Depth=%.3f", aabb.CalcMiddle().x, aabb.CalcMiddle().y, aabb.CalcMiddle().z, aabb.CalcWidth(), aabb.CalcHeight(), aabb.CalcDepth()); - mViewCloseupWaiting = viewCloseupWaiting; - mViewCloseupAABB = mPlugin->GetSceneAABB(selectedInstancesOnly); - mViewCloseupFlightTime = flightTime; + m_viewCloseupWaiting = viewCloseupWaiting; + m_viewCloseupAabb = m_plugin->GetSceneAabb(selectedInstancesOnly); + m_viewCloseupFlightTime = flightTime; } // switch the active camera void RenderWidget::SwitchCamera(CameraMode mode) { - delete mCamera; - mCameraMode = mode; + delete m_camera; + m_cameraMode = mode; switch (mode) { case CAMMODE_ORBIT: { - mCamera = new MCommon::OrbitCamera(); + m_camera = new MCommon::OrbitCamera(); break; } case CAMMODE_FIRSTPERSON: { - mCamera = new MCommon::FirstPersonCamera(); + m_camera = new MCommon::FirstPersonCamera(); break; } case CAMMODE_FRONT: { - mCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_FRONT); + m_camera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_FRONT); break; } case CAMMODE_BACK: { - mCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_BACK); + m_camera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_BACK); break; } case CAMMODE_LEFT: { - mCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_LEFT); + m_camera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_LEFT); break; } case CAMMODE_RIGHT: { - mCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_RIGHT); + m_camera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_RIGHT); break; } case CAMMODE_TOP: { - mCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_TOP); + m_camera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_TOP); break; } case CAMMODE_BOTTOM: { - mCamera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_BOTTOM); + m_camera = new MCommon::OrthographicCamera(MCommon::OrthographicCamera::VIEWMODE_BOTTOM); break; } } // show the entire scene - mPlugin->ViewCloseup(false, this, 0.0f); + m_plugin->ViewCloseup(false, this, 0.0f); } @@ -164,7 +157,7 @@ namespace EMStudio float camDist = 0.0f; // calculate cam distance for the orthographic cam mode - if (mCamera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC) + if (m_camera->GetProjectionMode() == MCommon::Camera::PROJMODE_ORTHOGRAPHIC) { camDist = 0.75f; switch (GetCameraMode()) @@ -172,20 +165,20 @@ namespace EMStudio case CAMMODE_FRONT: case CAMMODE_BOTTOM: // -(scale.x) - camDist *= -2.0f / static_cast(mCamera->GetViewProjMatrix().GetElement(0, 0)); + camDist *= -2.0f / static_cast(m_camera->GetViewProjMatrix().GetElement(0, 0)); break; case CAMMODE_BACK: case CAMMODE_TOP: // scale.x - camDist *= 2.0f / static_cast(mCamera->GetViewProjMatrix().GetElement(0, 0)); + camDist *= 2.0f / static_cast(m_camera->GetViewProjMatrix().GetElement(0, 0)); break; case CAMMODE_LEFT: // -(scale.y) - camDist *= -2.0f / static_cast(mCamera->GetViewProjMatrix().GetElement(0, 1)); + camDist *= -2.0f / static_cast(m_camera->GetViewProjMatrix().GetElement(0, 1)); break; case CAMMODE_RIGHT: // scale.y - camDist *= 2.0f / static_cast(mCamera->GetViewProjMatrix().GetElement(0, 1)); + camDist *= 2.0f / static_cast(m_camera->GetViewProjMatrix().GetElement(0, 1)); break; default: break; @@ -195,14 +188,14 @@ namespace EMStudio else { if (activeManipulator->GetSelectionLocked() && - mViewWidget->GetIsCharacterFollowModeActive() == false && + m_viewWidget->GetIsCharacterFollowModeActive() == false && activeManipulator->GetType() == MCommon::TransformationManipulator::GIZMOTYPE_TRANSLATION) { - camDist = (callback->GetOldValueVec() - mCamera->GetPosition()).GetLength(); + camDist = (callback->GetOldValueVec() - m_camera->GetPosition()).GetLength(); } else { - camDist = (activeManipulator->GetPosition() - mCamera->GetPosition()).GetLength(); + camDist = (activeManipulator->GetPosition() - m_camera->GetPosition()).GetLength(); } } @@ -217,14 +210,14 @@ namespace EMStudio } else if (activeManipulator->GetType() == MCommon::TransformationManipulator::GIZMOTYPE_SCALE) { - activeManipulator->SetScale(aznumeric_cast(camDist * 0.15), mCamera); + activeManipulator->SetScale(aznumeric_cast(camDist * 0.15), m_camera); } // update position of the actor instance (needed for camera follow mode) EMotionFX::ActorInstance* actorInstance = callback->GetActorInstance(); if (actorInstance) { - activeManipulator->Init(actorInstance->GetLocalSpaceTransform().mPosition); + activeManipulator->Init(actorInstance->GetLocalSpaceTransform().m_position); } } @@ -233,14 +226,14 @@ namespace EMStudio void RenderWidget::OnMouseMoveEvent(QWidget* renderWidget, QMouseEvent* event) { // calculate the delta mouse movement - int32 deltaX = event->globalX() - mPrevMouseX; - int32 deltaY = event->globalY() - mPrevMouseY; + int32 deltaX = event->globalX() - m_prevMouseX; + int32 deltaY = event->globalY() - m_prevMouseY; // store the current value as previous value - mPrevMouseX = event->globalX(); - mPrevMouseY = event->globalY(); - mPrevLocalMouseX = event->x(); - mPrevLocalMouseY = event->y(); + m_prevMouseX = event->globalX(); + m_prevMouseY = event->globalY(); + m_prevLocalMouseX = event->x(); + m_prevLocalMouseY = event->y(); // get the button states const bool leftButtonPressed = event->buttons() & Qt::LeftButton; @@ -253,17 +246,15 @@ namespace EMStudio // accumulate the number of pixels moved since the last right click if (leftButtonPressed == false && middleButtonPressed == false && rightButtonPressed && altPressed == false) { - mPixelsMovedSinceRightClick += (int32)MCore::Math::Abs(aznumeric_cast(deltaX)) + (int32)MCore::Math::Abs(aznumeric_cast(deltaY)); + m_pixelsMovedSinceRightClick += (int32)MCore::Math::Abs(aznumeric_cast(deltaX)) + (int32)MCore::Math::Abs(aznumeric_cast(deltaY)); } // update size/bounding volumes volumes of all existing gizmos - const MCore::Array* transformationManipulators = GetManager()->GetTransformationManipulators(); + const AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); // render all visible gizmos - const uint32 numGizmos = transformationManipulators->GetLength(); - for (uint32 i = 0; i < numGizmos; ++i) + for (MCommon::TransformationManipulator* activeManipulator : *transformationManipulators) { - MCommon::TransformationManipulator* activeManipulator = transformationManipulators->GetItem(i); if (activeManipulator == nullptr) { continue; @@ -274,16 +265,16 @@ namespace EMStudio } // get the translate manipulator - MCommon::TransformationManipulator* mouseOveredManip = mPlugin->GetActiveManipulator(mCamera, event->x(), event->y()); + MCommon::TransformationManipulator* mouseOveredManip = m_plugin->GetActiveManipulator(m_camera, event->x(), event->y()); // check if the current manipulator is hit if (mouseOveredManip) { - gizmoHit = mouseOveredManip->Hit(mCamera, event->x(), event->y()); + gizmoHit = mouseOveredManip->Hit(m_camera, event->x(), event->y()); } else { - mouseOveredManip = mActiveTransformManip; + mouseOveredManip = m_activeTransformManip; } // flag to check if mouse wrapping occured @@ -293,34 +284,34 @@ namespace EMStudio //if (activeManipulator != (MCommon::TransformationManipulator*)translateManipulator || (translateManipulator && translateManipulator->GetMode() == MCommon::TranslateManipulator::TRANSLATE_NONE)) if (mouseOveredManip == nullptr || (mouseOveredManip && mouseOveredManip->GetType() != MCommon::TransformationManipulator::GIZMOTYPE_TRANSLATION)) { - const int32 width = mCamera->GetScreenWidth(); - const int32 height = mCamera->GetScreenHeight(); + const int32 width = m_camera->GetScreenWidth(); + const int32 height = m_camera->GetScreenHeight(); // handle mouse wrapping, to enable smoother panning if (event->x() > (int32)width) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX() - width, event->globalY())); - mPrevMouseX = event->globalX() - width; + m_prevMouseX = event->globalX() - width; } else if (event->x() < 0) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX() + width, event->globalY())); - mPrevMouseX = event->globalX() + width; + m_prevMouseX = event->globalX() + width; } if (event->y() > (int32)height) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX(), event->globalY() - height)); - mPrevMouseY = event->globalY() - height; + m_prevMouseY = event->globalY() - height; } else if (event->y() < 0) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX(), event->globalY() + height)); - mPrevMouseY = event->globalY() + height; + m_prevMouseY = event->globalY() + height; } // don't apply the delta, if mouse has been wrapped @@ -341,16 +332,16 @@ namespace EMStudio } else if (mouseOveredManip->GetSelectionLocked()) { - if (mNeedDisableFollowMode) + if (m_needDisableFollowMode) { MCommon::ManipulatorCallback* callback = mouseOveredManip->GetCallback(); if (callback) { if (callback->GetResetFollowMode()) { - mIsCharacterFollowModeActive = mViewWidget->GetIsCharacterFollowModeActive(); - mViewWidget->SetCharacterFollowModeActive(false); - mNeedDisableFollowMode = false; + m_isCharacterFollowModeActive = m_viewWidget->GetIsCharacterFollowModeActive(); + m_viewWidget->SetCharacterFollowModeActive(false); + m_needDisableFollowMode = false; } } } @@ -369,7 +360,7 @@ namespace EMStudio */ // send mouse movement to the manipulators - mouseOveredManip->ProcessMouseInput(mCamera, event->x(), event->y(), deltaX, deltaY, leftButtonPressed && !altPressed, middleButtonPressed, rightButtonPressed); + mouseOveredManip->ProcessMouseInput(m_camera, event->x(), event->y(), deltaX, deltaY, leftButtonPressed && !altPressed, middleButtonPressed, rightButtonPressed); } else { @@ -385,9 +376,9 @@ namespace EMStudio else { // adjust the camera based on keyboard and mouse input - if (mCamera) + if (m_camera) { - switch (mCameraMode) + switch (m_cameraMode) { case CAMMODE_ORBIT: { @@ -401,11 +392,11 @@ namespace EMStudio { if (deltaY < 0) { - renderWidget->setCursor(mPlugin->GetZoomOutCursor()); + renderWidget->setCursor(m_plugin->GetZoomOutCursor()); } else { - renderWidget->setCursor(mPlugin->GetZoomInCursor()); + renderWidget->setCursor(m_plugin->GetZoomInCursor()); } } // move camera forward, backward, left or right @@ -430,11 +421,11 @@ namespace EMStudio { if (deltaY < 0) { - renderWidget->setCursor(mPlugin->GetZoomOutCursor()); + renderWidget->setCursor(m_plugin->GetZoomOutCursor()); } else { - renderWidget->setCursor(mPlugin->GetZoomInCursor()); + renderWidget->setCursor(m_plugin->GetZoomInCursor()); } } // move camera forward, backward, left or right @@ -448,8 +439,8 @@ namespace EMStudio } } - mCamera->ProcessMouseInput(deltaX, deltaY, leftButtonPressed, middleButtonPressed, rightButtonPressed); - mCamera->Update(); + m_camera->ProcessMouseInput(deltaX, deltaY, leftButtonPressed, middleButtonPressed, rightButtonPressed); + m_camera->Update(); } } @@ -461,13 +452,11 @@ namespace EMStudio void RenderWidget::OnMousePressEvent(QWidget* renderWidget, QMouseEvent* event) { // reset the number of pixels moved since the last right click - mPixelsMovedSinceRightClick = 0; + m_pixelsMovedSinceRightClick = 0; // calculate the delta mouse movement and set old mouse position - //const int32 deltaX = event->globalX() - mPrevMouseX; - //const int32 deltaY = event->globalY() - mPrevMouseY; - mPrevMouseX = event->globalX(); - mPrevMouseY = event->globalY(); + m_prevMouseX = event->globalX(); + m_prevMouseY = event->globalY(); // get the button states const bool leftButtonPressed = event->buttons() & Qt::LeftButton; @@ -479,8 +468,8 @@ namespace EMStudio // set the click position if right click was done if (rightButtonPressed) { - mRightClickPosX = QCursor::pos().x(); - mRightClickPosY = QCursor::pos().y(); + m_rightClickPosX = QCursor::pos().x(); + m_rightClickPosY = QCursor::pos().y(); } // get the current selection @@ -491,7 +480,7 @@ namespace EMStudio MCommon::TransformationManipulator* activeManipulator = nullptr; if (leftButtonPressed && middleButtonPressed == false && rightButtonPressed == false) { - activeManipulator = mPlugin->GetActiveManipulator(mCamera, event->x(), event->y()); + activeManipulator = m_plugin->GetActiveManipulator(m_camera, event->x(), event->y()); } if (activeManipulator) @@ -503,12 +492,12 @@ namespace EMStudio { if (gizmoHit && callback->GetResetFollowMode()) { - mIsCharacterFollowModeActive = mViewWidget->GetIsCharacterFollowModeActive(); - mViewWidget->SetCharacterFollowModeActive(false); - mNeedDisableFollowMode = false; + m_isCharacterFollowModeActive = m_viewWidget->GetIsCharacterFollowModeActive(); + m_viewWidget->SetCharacterFollowModeActive(false); + m_needDisableFollowMode = false; - mActiveTransformManip = activeManipulator; - mActiveTransformManip->ProcessMouseInput(mCamera, event->x(), event->y(), 0, 0, leftButtonPressed && !altPressed, middleButtonPressed, rightButtonPressed); + m_activeTransformManip = activeManipulator; + m_activeTransformManip->ProcessMouseInput(m_camera, event->x(), event->y(), 0, 0, leftButtonPressed && !altPressed, middleButtonPressed, rightButtonPressed); } } @@ -531,10 +520,10 @@ namespace EMStudio // handle visual mouse selection if (EMStudio::GetCommandManager()->GetLockSelection() == false && gizmoHit == false) // avoid selection operations when there is only one actor instance { - AZ::u32 editorActorInstanceCount = 0; + size_t editorActorInstanceCount = 0; const EMotionFX::ActorManager& actorManager = EMotionFX::GetActorManager(); - const AZ::u32 totalActorInstanceCount = actorManager.GetNumActorInstances(); - for (AZ::u32 i = 0; i < totalActorInstanceCount; ++i) + const size_t totalActorInstanceCount = actorManager.GetNumActorInstances(); + for (size_t i = 0; i < totalActorInstanceCount; ++i) { const EMotionFX::ActorInstance* actorInstance = actorManager.GetActorInstance(i); if (!actorInstance->GetIsOwnedByRuntime()) @@ -558,11 +547,11 @@ namespace EMStudio EMotionFX::ActorInstance* selectedActorInstance = nullptr; AZ::Vector3 oldIntersectionPoint; - const MCore::Ray ray = mCamera->Unproject(mousePosX, mousePosY); + const MCore::Ray ray = m_camera->Unproject(mousePosX, mousePosY); // get the number of actor instances and iterate through them - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); if (actorInstance->GetIsVisible() == false || actorInstance->GetRender() == false || actorInstance->GetIsUsedForVisualization() || actorInstance->GetIsOwnedByRuntime()) @@ -587,8 +576,8 @@ namespace EMStudio else { // find the actor instance closer to the camera - const float distOld = (mCamera->GetPosition() - oldIntersectionPoint).GetLength(); - const float distNew = (mCamera->GetPosition() - intersect).GetLength(); + const float distOld = (m_camera->GetPosition() - oldIntersectionPoint).GetLength(); + const float distNew = (m_camera->GetPosition() - intersect).GetLength(); if (distNew < distOld) { selectedActorInstance = actorInstance; @@ -603,14 +592,15 @@ namespace EMStudio if (actor->CheckIfHasMeshes(actorInstance->GetLODLevel()) == false) { // calculate the node based AABB - MCore::AABB box; - actorInstance->CalcNodeBasedAABB(&box); + AZ::Aabb box; + actorInstance->CalcNodeBasedAabb(&box); // render the aabb - if (box.CheckIfIsValid()) + if (box.IsValid()) { + const MCore::AABB mcoreAabb(box.GetMin(), box.GetMax()); AZ::Vector3 ii, n; - if (ray.Intersects(box, &ii, &n)) + if (ray.Intersects(mcoreAabb, &ii, &n)) { selectedActorInstance = actorInstance; oldIntersectionPoint = ii; @@ -620,24 +610,24 @@ namespace EMStudio } } - mSelectedActorInstances.Clear(false); + m_selectedActorInstances.clear(); if (ctrlPressed) { // add the old selection to the selected actor instances (selection mode = add) - const uint32 numSelectedActorInstances = selection.GetNumSelectedActorInstances(); - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + const size_t numSelectedActorInstances = selection.GetNumSelectedActorInstances(); + for (size_t i = 0; i < numSelectedActorInstances; ++i) { - mSelectedActorInstances.Add(selection.GetActorInstance(i)); + m_selectedActorInstances.emplace_back(selection.GetActorInstance(i)); } } if (selectedActorInstance) { - mSelectedActorInstances.Add(selectedActorInstance); + m_selectedActorInstances.emplace_back(selectedActorInstance); } - CommandSystem::SelectActorInstancesUsingCommands(mSelectedActorInstances); + CommandSystem::SelectActorInstancesUsingCommands(m_selectedActorInstances); } } } @@ -652,10 +642,10 @@ namespace EMStudio if (altPressed == false) { // check which manipulator is currently mouse-overed and use the active one in case we're not hoving any - MCommon::TransformationManipulator* mouseOveredManip = mPlugin->GetActiveManipulator(mCamera, event->x(), event->y()); + MCommon::TransformationManipulator* mouseOveredManip = m_plugin->GetActiveManipulator(m_camera, event->x(), event->y()); if (mouseOveredManip == nullptr) { - mouseOveredManip = mActiveTransformManip; + mouseOveredManip = m_activeTransformManip; } // only do in case a manipulator got hovered or is active @@ -669,35 +659,28 @@ namespace EMStudio } // the manipulator - mouseOveredManip->ProcessMouseInput(mCamera, 0, 0, 0, 0, false, false, false); + mouseOveredManip->ProcessMouseInput(m_camera, 0, 0, 0, 0, false, false, false); // reset the camera follow mode state - if (callback && callback->GetResetFollowMode() && mIsCharacterFollowModeActive) + if (callback && callback->GetResetFollowMode() && m_isCharacterFollowModeActive) { - mViewWidget->SetCharacterFollowModeActive(mIsCharacterFollowModeActive); - mSkipFollowCalcs = true; - - /* CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - ActorInstance* followInstance = selectionList.GetFirstActorInstance(); - if (followInstance) - mOldActorInstancePos = followInstance->GetLocalPos();*/ - - //mViewWidget->OnFollowCharacter(); + m_viewWidget->SetCharacterFollowModeActive(m_isCharacterFollowModeActive); + m_skipFollowCalcs = true; } } } // reset the active manipulator - mActiveTransformManip = nullptr; + m_activeTransformManip = nullptr; // reset the disable follow flag - mNeedDisableFollowMode = true; + m_needDisableFollowMode = true; // set the arrow cursor renderWidget->setCursor(Qt::ArrowCursor); // context menu handling - if (mPixelsMovedSinceRightClick < 5) + if (m_pixelsMovedSinceRightClick < 5) { OnContextMenuEvent(renderWidget, event->modifiers() & Qt::ControlModifier, event->modifiers() & Qt::AltModifier, event->x(), event->y(), event->globalPos()); } @@ -709,14 +692,14 @@ namespace EMStudio { MCORE_UNUSED(renderWidget); - mCamera->ProcessMouseInput(0, + m_camera->ProcessMouseInput(0, event->angleDelta().y(), false, false, true ); - mCamera->Update(); + m_camera->Update(); } @@ -725,29 +708,29 @@ namespace EMStudio { // stop context menu execution, if mouse position changed or alt is pressed // so block it if zooming, moving etc. is enabled - if (QCursor::pos().x() != mRightClickPosX || QCursor::pos().y() != mRightClickPosY || altPressed) + if (QCursor::pos().x() != m_rightClickPosX || QCursor::pos().y() != m_rightClickPosY || altPressed) { return; } // call the context menu handler - mViewWidget->OnContextMenuEvent(renderWidget, shiftPressed, localMouseX, localMouseY, globalMousePos, mPlugin, mCamera); + m_viewWidget->OnContextMenuEvent(renderWidget, shiftPressed, localMouseX, localMouseY, globalMousePos, m_plugin, m_camera); } void RenderWidget::RenderAxis() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; } // set the camera used to render the axis - MCommon::Camera* camera = mCamera; - if (mCamera->GetType() == MCommon::OrthographicCamera::TYPE_ID) + MCommon::Camera* camera = m_camera; + if (m_camera->GetType() == MCommon::OrthographicCamera::TYPE_ID) { - camera = mAxisFakeCamera; + camera = m_axisFakeCamera; } // store the old projection mode so that we can set it back later on @@ -761,103 +744,103 @@ namespace EMStudio // fake zoom the camera so that we draw the axis in a nice size and remember the old distance int32 distanceFromBorder = 40; float size = 25; - if (mCamera->GetType() == MCommon::OrthographicCamera::TYPE_ID) + if (m_camera->GetType() == MCommon::OrthographicCamera::TYPE_ID) { - MCommon::OrthographicCamera* orgCamera = (MCommon::OrthographicCamera*)mCamera; + MCommon::OrthographicCamera* orgCamera = (MCommon::OrthographicCamera*)m_camera; MCommon::OrthographicCamera* orthoCamera = (MCommon::OrthographicCamera*)camera; orthoCamera->SetCurrentDistance(1.0f); orthoCamera->SetPosition(orgCamera->GetPosition()); orthoCamera->SetMode(orgCamera->GetMode()); - orthoCamera->SetScreenDimensions(mWidth, mHeight); + orthoCamera->SetScreenDimensions(m_width, m_height); size *= 0.001f; } // update the camera - camera->SetOrthoClipDimensions(AZ::Vector2(aznumeric_cast(mWidth), aznumeric_cast(mHeight))); + camera->SetOrthoClipDimensions(AZ::Vector2(aznumeric_cast(m_width), aznumeric_cast(m_height))); camera->Update(); MCommon::RenderUtil::AxisRenderingSettings axisRenderingSettings; int32 originScreenX = 0; int32 originScreenY = 0; - switch (mCameraMode) + switch (m_cameraMode) { case CAMMODE_ORBIT: { originScreenX = distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = true; - axisRenderingSettings.mRenderYAxis = true; - axisRenderingSettings.mRenderZAxis = true; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = true; + axisRenderingSettings.m_renderYAxis = true; + axisRenderingSettings.m_renderZAxis = true; break; } case CAMMODE_FIRSTPERSON: { originScreenX = distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = true; - axisRenderingSettings.mRenderYAxis = true; - axisRenderingSettings.mRenderZAxis = true; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = true; + axisRenderingSettings.m_renderYAxis = true; + axisRenderingSettings.m_renderZAxis = true; break; } case CAMMODE_FRONT: { originScreenX = distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = true; - axisRenderingSettings.mRenderYAxis = true; - axisRenderingSettings.mRenderZAxis = false; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = true; + axisRenderingSettings.m_renderYAxis = true; + axisRenderingSettings.m_renderZAxis = false; break; } case CAMMODE_BACK: { originScreenX = 2 * distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = true; - axisRenderingSettings.mRenderYAxis = true; - axisRenderingSettings.mRenderZAxis = false; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = true; + axisRenderingSettings.m_renderYAxis = true; + axisRenderingSettings.m_renderZAxis = false; break; } case CAMMODE_LEFT: { originScreenX = distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = false; - axisRenderingSettings.mRenderYAxis = true; - axisRenderingSettings.mRenderZAxis = true; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = false; + axisRenderingSettings.m_renderYAxis = true; + axisRenderingSettings.m_renderZAxis = true; break; } case CAMMODE_RIGHT: { originScreenX = 2 * distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = false; - axisRenderingSettings.mRenderYAxis = true; - axisRenderingSettings.mRenderZAxis = true; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = false; + axisRenderingSettings.m_renderYAxis = true; + axisRenderingSettings.m_renderZAxis = true; break; } case CAMMODE_TOP: { originScreenX = distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = true; - axisRenderingSettings.mRenderYAxis = false; - axisRenderingSettings.mRenderZAxis = true; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = true; + axisRenderingSettings.m_renderYAxis = false; + axisRenderingSettings.m_renderZAxis = true; break; } case CAMMODE_BOTTOM: { originScreenX = 2 * distanceFromBorder; - originScreenY = mHeight - distanceFromBorder; - axisRenderingSettings.mRenderXAxis = true; - axisRenderingSettings.mRenderYAxis = false; - axisRenderingSettings.mRenderZAxis = true; + originScreenY = m_height - distanceFromBorder; + axisRenderingSettings.m_renderXAxis = true; + axisRenderingSettings.m_renderYAxis = false; + axisRenderingSettings.m_renderZAxis = true; break; } default: MCORE_ASSERT(false); } - const AZ::Vector3 axisPosition = MCore::UnprojectOrtho(aznumeric_cast(originScreenX), aznumeric_cast(originScreenY), aznumeric_cast(mWidth), aznumeric_cast(mHeight), 0.0f, camera->GetProjectionMatrix(), camera->GetViewMatrix()); + const AZ::Vector3 axisPosition = MCore::UnprojectOrtho(aznumeric_cast(originScreenX), aznumeric_cast(originScreenY), aznumeric_cast(m_width), aznumeric_cast(m_height), 0.0f, camera->GetProjectionMatrix(), camera->GetViewMatrix()); AZ::Matrix4x4 inverseCameraMatrix = camera->GetViewMatrix(); inverseCameraMatrix.InvertFull(); @@ -865,13 +848,13 @@ namespace EMStudio AZ::Transform worldTM = AZ::Transform::CreateIdentity(); worldTM.SetTranslation(axisPosition); - axisRenderingSettings.mSize = size; - axisRenderingSettings.mWorldTM = worldTM; - axisRenderingSettings.mCameraRight = MCore::GetRight(inverseCameraMatrix).GetNormalized(); - axisRenderingSettings.mCameraUp = MCore::GetUp(inverseCameraMatrix).GetNormalized(); - axisRenderingSettings.mRenderXAxisName = true; - axisRenderingSettings.mRenderYAxisName = true; - axisRenderingSettings.mRenderZAxisName = true; + axisRenderingSettings.m_size = size; + axisRenderingSettings.m_worldTm = worldTM; + axisRenderingSettings.m_cameraRight = MCore::GetRight(inverseCameraMatrix).GetNormalized(); + axisRenderingSettings.m_cameraUp = MCore::GetUp(inverseCameraMatrix).GetNormalized(); + axisRenderingSettings.m_renderXAxisName = true; + axisRenderingSettings.m_renderYAxisName = true; + axisRenderingSettings.m_renderZAxisName = true; // render directly as we have to disable the depth test, hope the additional render call won't slow down so much renderUtil->RenderLineAxis(axisRenderingSettings); @@ -886,18 +869,18 @@ namespace EMStudio void RenderWidget::RenderNodeFilterString() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; } // render the camera mode name at the bottom of the gl widget - const char* text = mCamera->GetTypeString(); + const char* text = m_camera->GetTypeString(); const uint32 textSize = 10; const uint32 cameraNameColor = MCore::RGBAColor(1.0f, 1.0f, 1.0f, 1.0f).ToInt(); - const uint32 cameraNameX = aznumeric_cast(mWidth * 0.5f); - const uint32 cameraNameY = mHeight - 20; + const uint32 cameraNameX = aznumeric_cast(m_width * 0.5f); + const uint32 cameraNameY = m_height - 20; renderUtil->RenderText(aznumeric_cast(cameraNameX), aznumeric_cast(cameraNameY), text, cameraNameColor, textSize, true); //glColor4f(1.0f, 1.0f, 1.0f, 1.0f); @@ -910,30 +893,30 @@ namespace EMStudio void RenderWidget::UpdateCharacterFollowModeData() { - if (mViewWidget->GetIsCharacterFollowModeActive()) + if (m_viewWidget->GetIsCharacterFollowModeActive()) { const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); EMotionFX::ActorInstance* followInstance = selectionList.GetFirstActorInstance(); - if (followInstance && mCamera) + if (followInstance && m_camera) { - const AZ::Vector3& localPos = followInstance->GetLocalSpaceTransform().mPosition; - mPlugin->GetTranslateManipulator()->Init(localPos); - mPlugin->GetRotateManipulator()->Init(localPos); - mPlugin->GetScaleManipulator()->Init(localPos); + const AZ::Vector3& localPos = followInstance->GetLocalSpaceTransform().m_position; + m_plugin->GetTranslateManipulator()->Init(localPos); + m_plugin->GetRotateManipulator()->Init(localPos); + m_plugin->GetScaleManipulator()->Init(localPos); AZ::Vector3 actorInstancePos; EMotionFX::Actor* followActor = followInstance->GetActor(); - const uint32 motionExtractionNodeIndex = followActor->GetMotionExtractionNodeIndex(); - if (motionExtractionNodeIndex != MCORE_INVALIDINDEX32) + const size_t motionExtractionNodeIndex = followActor->GetMotionExtractionNodeIndex(); + if (motionExtractionNodeIndex != InvalidIndex) { - actorInstancePos = followInstance->GetWorldSpaceTransform().mPosition; - RenderPlugin::EMStudioRenderActor* emstudioActor = mPlugin->FindEMStudioActor(followActor); + actorInstancePos = followInstance->GetWorldSpaceTransform().m_position; + RenderPlugin::EMStudioRenderActor* emstudioActor = m_plugin->FindEMStudioActor(followActor); if (emstudioActor) { #ifndef EMFX_SCALE_DISABLED - const float scaledOffsetFromTrajectoryNode = followInstance->GetWorldSpaceTransform().mScale.GetZ() * emstudioActor->mOffsetFromTrajectoryNode; + const float scaledOffsetFromTrajectoryNode = followInstance->GetWorldSpaceTransform().m_scale.GetZ() * emstudioActor->m_offsetFromTrajectoryNode; #else const float scaledOffsetFromTrajectoryNode = 1.0f; #endif @@ -942,25 +925,25 @@ namespace EMStudio } else { - actorInstancePos = followInstance->GetWorldSpaceTransform().mPosition; + actorInstancePos = followInstance->GetWorldSpaceTransform().m_position; } // Calculate movement since last frame. - AZ::Vector3 deltaPos = actorInstancePos - mOldActorInstancePos; + AZ::Vector3 deltaPos = actorInstancePos - m_oldActorInstancePos; - if (mSkipFollowCalcs) + if (m_skipFollowCalcs) { deltaPos = AZ::Vector3::CreateZero(); - mSkipFollowCalcs = false; + m_skipFollowCalcs = false; } - mOldActorInstancePos = actorInstancePos; + m_oldActorInstancePos = actorInstancePos; - switch (mCamera->GetType()) + switch (m_camera->GetType()) { case MCommon::OrbitCamera::TYPE_ID: { - MCommon::OrbitCamera* orbitCamera = static_cast(mCamera); + MCommon::OrbitCamera* orbitCamera = static_cast(m_camera); if (orbitCamera->GetIsFlightActive()) { @@ -977,7 +960,7 @@ namespace EMStudio case MCommon::OrthographicCamera::TYPE_ID: { - MCommon::OrthographicCamera* orthoCamera = static_cast(mCamera); + MCommon::OrthographicCamera* orthoCamera = static_cast(m_camera); if (orthoCamera->GetIsFlightActive()) { @@ -995,7 +978,7 @@ namespace EMStudio } else { - mOldActorInstancePos.Set(0.0f, 0.0f, 0.0f); + m_oldActorInstancePos.Set(0.0f, 0.0f, 0.0f); } } @@ -1003,21 +986,17 @@ namespace EMStudio // render the manipulator gizmos void RenderWidget::RenderManipulators() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; } - MCore::Array* transformationManipulators = GetManager()->GetTransformationManipulators(); - const uint32 numGizmos = transformationManipulators->GetLength(); + AZStd::vector* transformationManipulators = GetManager()->GetTransformationManipulators(); // render all visible gizmos - for (uint32 i = 0; i < numGizmos; ++i) + for (MCommon::TransformationManipulator* activeManipulator : *transformationManipulators) { - // update the gizmos - MCommon::TransformationManipulator* activeManipulator = transformationManipulators->GetItem(i); - // update the gizmos if there is an active manipulator if (activeManipulator == nullptr) { @@ -1028,7 +1007,7 @@ namespace EMStudio UpdateActiveTransformationManipulator(activeManipulator); // render the current actor - activeManipulator->Render(mCamera, renderUtil); + activeManipulator->Render(m_camera, renderUtil); } // render any remaining lines @@ -1042,18 +1021,16 @@ namespace EMStudio // render all triangles that got added to the render util void RenderWidget::RenderTriangles() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; } // render custom triangles - const uint32 numTriangles = mTriangles.GetLength(); - for (uint32 i = 0; i < numTriangles; ++i) + for (const Triangle& curTri : m_triangles) { - const Triangle& curTri = mTriangles[i]; - renderUtil->AddTriangle(curTri.mPosA, curTri.mPosB, curTri.mPosC, curTri.mNormalA, curTri.mNormalB, curTri.mNormalC, curTri.mColor); // TODO: make renderutil use uint32 colors instead + renderUtil->AddTriangle(curTri.m_posA, curTri.m_posB, curTri.m_posC, curTri.m_normalA, curTri.m_normalB, curTri.m_normalC, curTri.m_color); // TODO: make renderutil use uint32 colors instead } ClearTriangles(); @@ -1064,20 +1041,20 @@ namespace EMStudio // iterate through all plugins and render their helper data void RenderWidget::RenderCustomPluginData() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; } // render all custom plugin visuals - const uint32 numPlugins = GetPluginManager()->GetNumActivePlugins(); - for (uint32 i = 0; i < numPlugins; ++i) + const size_t numPlugins = GetPluginManager()->GetNumActivePlugins(); + for (size_t i = 0; i < numPlugins; ++i) { EMStudioPlugin* plugin = GetPluginManager()->GetActivePlugin(i); - EMStudioPlugin::RenderInfo renderInfo(renderUtil, mCamera, mWidth, mHeight); + EMStudioPlugin::RenderInfo renderInfo(renderUtil, m_camera, m_width, m_height); - plugin->Render(mPlugin, &renderInfo); + plugin->Render(m_plugin, &renderInfo); } RenderDebugDraw(); @@ -1089,7 +1066,7 @@ namespace EMStudio void RenderWidget::RenderDebugDraw() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (!renderUtil) { return; @@ -1118,14 +1095,14 @@ namespace EMStudio // render solid characters void RenderWidget::RenderActorInstances() { - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); if (renderUtil == nullptr) { return; } // backface culling - const bool backfaceCullingEnabled = mViewWidget->GetRenderFlag(RenderViewWidget::RENDER_BACKFACECULLING); + const bool backfaceCullingEnabled = m_viewWidget->GetRenderFlag(RenderViewWidget::RENDER_BACKFACECULLING); renderUtil->EnableCulling(backfaceCullingEnabled); EMotionFX::GetAnimGraphManager().SetAnimGraphVisualizationEnabled(true); @@ -1134,13 +1111,13 @@ namespace EMStudio ///// EMotionFX::GetEMotionFX().Update(0.0f); // render - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); if (actorInstance->GetRender() && actorInstance->GetIsVisible() && actorInstance->GetIsOwnedByRuntime() == false) { - mPlugin->RenderActorInstance(actorInstance, 0.0f); + m_plugin->RenderActorInstance(actorInstance, 0.0f); } } } @@ -1149,35 +1126,34 @@ namespace EMStudio // prepare the camera void RenderWidget::UpdateCamera() { - if (mCamera == nullptr) + if (m_camera == nullptr) { return; } - RenderOptions* renderOptions = mPlugin->GetRenderOptions(); + RenderOptions* renderOptions = m_plugin->GetRenderOptions(); // update the camera - mCamera->SetNearClipDistance(renderOptions->GetNearClipPlaneDistance()); - mCamera->SetFarClipDistance(renderOptions->GetFarClipPlaneDistance()); - mCamera->SetFOV(renderOptions->GetFOV()); - mCamera->SetAspectRatio(mWidth / (float)mHeight); - mCamera->SetScreenDimensions(mWidth, mHeight); - mCamera->AutoUpdateLimits(); + m_camera->SetNearClipDistance(renderOptions->GetNearClipPlaneDistance()); + m_camera->SetFarClipDistance(renderOptions->GetFarClipPlaneDistance()); + m_camera->SetFOV(renderOptions->GetFOV()); + m_camera->SetAspectRatio(m_width / (float)m_height); + m_camera->SetScreenDimensions(m_width, m_height); + m_camera->AutoUpdateLimits(); - if (mViewCloseupWaiting != 0 && mHeight != 0 && mWidth != 0) + if (m_viewCloseupWaiting != 0 && m_height != 0 && m_width != 0) { - mViewCloseupWaiting--; - if (mViewCloseupWaiting == 0) + m_viewCloseupWaiting--; + if (m_viewCloseupWaiting == 0) { - mCamera->ViewCloseup(mViewCloseupAABB, mViewCloseupFlightTime); - //mViewCloseupWaiting = 0; + m_camera->ViewCloseup(MCore::AABB(m_viewCloseupAabb.GetMin(), m_viewCloseupAabb.GetMax()), m_viewCloseupFlightTime); } } // update the manipulators, camera, old actor instance position etc. when using the character follow mode UpdateCharacterFollowModeData(); - mCamera->Update(); + m_camera->Update(); } @@ -1185,14 +1161,14 @@ namespace EMStudio void RenderWidget::RenderGrid() { // directly return in case we do not want to render any type of grid - if (mViewWidget->GetRenderFlag(RenderViewWidget::RENDER_GRID) == false) + if (m_viewWidget->GetRenderFlag(RenderViewWidget::RENDER_GRID) == false) { return; } // get access to the render utility and render options - MCommon::RenderUtil* renderUtil = mPlugin->GetRenderUtil(); - RenderOptions* renderOptions = mPlugin->GetRenderOptions(); + MCommon::RenderUtil* renderUtil = m_plugin->GetRenderUtil(); + RenderOptions* renderOptions = m_plugin->GetRenderOptions(); if (renderUtil == nullptr || renderOptions == nullptr) { return; @@ -1201,20 +1177,20 @@ namespace EMStudio const float unitSize = renderOptions->GetGridUnitSize(); AZ::Vector3 gridNormal = AZ::Vector3(0.0f, 0.0f, 1.0f); - if (mCamera->GetType() == MCommon::OrthographicCamera::TYPE_ID) + if (m_camera->GetType() == MCommon::OrthographicCamera::TYPE_ID) { // disable depth writing for ortho views renderUtil->SetDepthMaskWrite(false); - switch (mCameraMode) + switch (m_cameraMode) { case CAMMODE_LEFT: case CAMMODE_RIGHT: - gridNormal = MCore::GetForward(mCamera->GetViewMatrix()); + gridNormal = MCore::GetForward(m_camera->GetViewMatrix()); break; default: - gridNormal = MCore::GetUp(mCamera->GetViewMatrix()); + gridNormal = MCore::GetUp(m_camera->GetViewMatrix()); } gridNormal.Normalize(); } @@ -1222,8 +1198,8 @@ namespace EMStudio // render the grid AZ::Vector2 gridStart, gridEnd; - renderUtil->CalcVisibleGridArea(mCamera, mWidth, mHeight, unitSize, &gridStart, &gridEnd); - if (mViewWidget->GetRenderFlag(RenderViewWidget::RENDER_GRID)) + renderUtil->CalcVisibleGridArea(m_camera, m_width, m_height, unitSize, &gridStart, &gridEnd); + if (m_viewWidget->GetRenderFlag(RenderViewWidget::RENDER_GRID)) { renderUtil->RenderGrid(gridStart, gridEnd, gridNormal, unitSize, renderOptions->GetMainAxisColor(), renderOptions->GetGridColor(), renderOptions->GetSubStepColor(), true); } @@ -1234,9 +1210,9 @@ namespace EMStudio void RenderWidget::closeEvent([[maybe_unused]] QCloseEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->SaveRenderOptions(); + m_plugin->SaveRenderOptions(); } } } // namespace EMStudio 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 b6776d43a4..d4906355da 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 @@ -6,11 +6,10 @@ * */ -#ifndef __EMSTUDIO_RENDERWIDGET_H -#define __EMSTUDIO_RENDERWIDGET_H +#pragma once -// #if !defined(Q_MOC_RUN) +#include #include #include "../EMStudioConfig.h" #include @@ -48,25 +47,25 @@ namespace EMStudio struct Triangle { - AZ::Vector3 mPosA; - AZ::Vector3 mPosB; - AZ::Vector3 mPosC; + AZ::Vector3 m_posA; + AZ::Vector3 m_posB; + AZ::Vector3 m_posC; - AZ::Vector3 mNormalA; - AZ::Vector3 mNormalB; - AZ::Vector3 mNormalC; + AZ::Vector3 m_normalA; + AZ::Vector3 m_normalB; + AZ::Vector3 m_normalC; - uint32 mColor; + uint32 m_color; Triangle() {} Triangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) - : mPosA(posA) - , mPosB(posB) - , mPosC(posC) - , mNormalA(normalA) - , mNormalB(normalB) - , mNormalC(normalC) - , mColor(color) {} + : m_posA(posA) + , m_posB(posB) + , m_posC(posC) + , m_normalA(normalA) + , m_normalB(normalB) + , m_normalC(normalC) + , m_color(color) {} }; @@ -77,16 +76,16 @@ namespace EMStudio AZ_CLASS_ALLOCATOR_DECL EventHandler(RenderWidget* widget) - : EMotionFX::EventHandler() { mWidget = widget; } + : EMotionFX::EventHandler() { m_widget = widget; } ~EventHandler() {} // overloaded const AZStd::vector GetHandledEventTypes() const override { return { EMotionFX::EVENT_TYPE_ON_DRAW_LINE, EMotionFX::EVENT_TYPE_ON_DRAW_TRIANGLE, EMotionFX::EVENT_TYPE_ON_DRAW_TRIANGLES }; } - MCORE_INLINE void OnDrawTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) { mWidget->AddTriangle(posA, posB, posC, normalA, normalB, normalC, color); } - MCORE_INLINE void OnDrawTriangles() { mWidget->RenderTriangles(); } + MCORE_INLINE void OnDrawTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) { m_widget->AddTriangle(posA, posB, posC, normalA, normalB, normalC, color); } + MCORE_INLINE void OnDrawTriangles() { m_widget->RenderTriangles(); } private: - RenderWidget* mWidget; + RenderWidget* m_widget; }; RenderWidget(RenderPlugin* renderPlugin, RenderViewWidget* viewWidget); @@ -99,8 +98,8 @@ namespace EMStudio virtual void Update() = 0; // line rendering helper functions - MCORE_INLINE void AddTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) { mTriangles.Add(Triangle(posA, posB, posC, normalA, normalB, normalC, color)); } - MCORE_INLINE void ClearTriangles() { mTriangles.Clear(false); } + MCORE_INLINE void AddTriangle(const AZ::Vector3& posA, const AZ::Vector3& posB, const AZ::Vector3& posC, const AZ::Vector3& normalA, const AZ::Vector3& normalB, const AZ::Vector3& normalC, uint32 color) { m_triangles.emplace_back(Triangle(posA, posB, posC, normalA, normalB, normalC, color)); } + MCORE_INLINE void ClearTriangles() { m_triangles.clear(); } void RenderTriangles(); // helper rendering functions @@ -114,16 +113,16 @@ namespace EMStudio void UpdateCamera(); // camera helper functions - MCORE_INLINE MCommon::Camera* GetCamera() const { return mCamera; } - MCORE_INLINE CameraMode GetCameraMode() const { return mCameraMode; } - MCORE_INLINE void SetSkipFollowCalcs(bool skipFollowCalcs) { mSkipFollowCalcs = skipFollowCalcs; } - void ViewCloseup(const MCore::AABB& aabb, float flightTime, uint32 viewCloseupWaiting = 5); + MCORE_INLINE MCommon::Camera* GetCamera() const { return m_camera; } + MCORE_INLINE CameraMode GetCameraMode() const { return m_cameraMode; } + MCORE_INLINE void SetSkipFollowCalcs(bool skipFollowCalcs) { m_skipFollowCalcs = skipFollowCalcs; } + void ViewCloseup(const AZ::Aabb& aabb, float flightTime, uint32 viewCloseupWaiting = 5); void ViewCloseup(bool selectedInstancesOnly, float flightTime, uint32 viewCloseupWaiting = 5); void SwitchCamera(CameraMode mode); // render bugger dimensions - MCORE_INLINE uint32 GetScreenWidth() const { return mWidth; } - MCORE_INLINE uint32 GetScreenHeight() const { return mHeight; } + MCORE_INLINE uint32 GetScreenWidth() const { return m_width; } + MCORE_INLINE uint32 GetScreenHeight() const { return m_height; } // helper functions for easy calling void OnMouseMoveEvent(QWidget* renderWidget, QMouseEvent* event); @@ -138,43 +137,40 @@ namespace EMStudio void closeEvent(QCloseEvent* event); - RenderPlugin* mPlugin; - RenderViewWidget* mViewWidget; - MCore::Array mTriangles; - EventHandler mEventHandler; + RenderPlugin* m_plugin; + RenderViewWidget* m_viewWidget; + AZStd::vector m_triangles; + EventHandler m_eventHandler; - MCore::Array mSelectedActorInstances; + AZStd::vector m_selectedActorInstances; - MCommon::TransformationManipulator* mActiveTransformManip; + MCommon::TransformationManipulator* m_activeTransformManip; // camera helper data - CameraMode mCameraMode; - MCommon::Camera* mCamera; - MCommon::Camera* mAxisFakeCamera; - bool mIsCharacterFollowModeActive; - bool mSkipFollowCalcs; - bool mNeedDisableFollowMode; + CameraMode m_cameraMode; + MCommon::Camera* m_camera; + MCommon::Camera* m_axisFakeCamera; + bool m_isCharacterFollowModeActive; + bool m_skipFollowCalcs; + bool m_needDisableFollowMode; // render buffer dimensions - uint32 mWidth; - uint32 mHeight; + uint32 m_width; + uint32 m_height; // used for closeup camera flights - uint32 mViewCloseupWaiting; - MCore::AABB mViewCloseupAABB; - float mViewCloseupFlightTime; + uint32 m_viewCloseupWaiting; + AZ::Aabb m_viewCloseupAabb; + float m_viewCloseupFlightTime; // manipulator helper data - AZ::Vector3 mOldActorInstancePos; - int32 mPrevMouseX; - int32 mPrevMouseY; - int32 mPrevLocalMouseX; - int32 mPrevLocalMouseY; - int32 mRightClickPosX; - int32 mRightClickPosY; - int32 mPixelsMovedSinceRightClick; + AZ::Vector3 m_oldActorInstancePos; + int32 m_prevMouseX; + int32 m_prevMouseY; + int32 m_prevLocalMouseX; + int32 m_prevLocalMouseY; + int32 m_rightClickPosX; + int32 m_rightClickPosY; + int32 m_pixelsMovedSinceRightClick; }; } // namespace EMStudio - - -#endif diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp index 94b5fadd79..2f45a89ea2 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ResetSettingsDialog.cpp @@ -29,8 +29,8 @@ namespace EMStudio template bool HasEntityInEditor(const ManagerType& manager, const GetNumFunc& getNumEntitiesFunc, const GetEntityFunc& getEntityFunc) { - const uint32 numEntities = (manager.*getNumEntitiesFunc)(); - for (uint32 i = 0; i < numEntities; ++i) + const size_t numEntities = (manager.*getNumEntitiesFunc)(); + for (size_t i = 0; i < numEntities; ++i) { const auto& entity = (manager.*getEntityFunc)(i); if (!entity->GetIsOwnedByRuntime()) 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 5e624fd75e..6919877170 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.cpp @@ -30,11 +30,11 @@ namespace EMStudio { SaveDirtyFilesCallback::ObjectPointer::ObjectPointer() : - mActor(nullptr), - mMotion(nullptr), - mMotionSet(nullptr), - mAnimGraph(nullptr), - mWorkspace(nullptr) + m_actor(nullptr), + m_motion(nullptr), + m_motionSet(nullptr), + m_animGraph(nullptr), + m_workspace(nullptr) { } @@ -52,7 +52,7 @@ namespace EMStudio return; } - mSaveDirtyFilesCallbacks.erase(AZStd::remove(mSaveDirtyFilesCallbacks.begin(), mSaveDirtyFilesCallbacks.end(), callback), mSaveDirtyFilesCallbacks.end()); + m_saveDirtyFilesCallbacks.erase(AZStd::remove(m_saveDirtyFilesCallbacks.begin(), m_saveDirtyFilesCallbacks.end(), callback), m_saveDirtyFilesCallbacks.end()); if (delFromMem) { @@ -63,21 +63,18 @@ namespace EMStudio void DirtyFileManager::SaveSettings() { - const size_t numDirtyFilesCallbacks = mSaveDirtyFilesCallbacks.size(); + const size_t numDirtyFilesCallbacks = m_saveDirtyFilesCallbacks.size(); // save the callback settings to the config file QSettings settings; settings.beginGroup("EMotionFX"); settings.beginGroup("DirtyFileManager"); - //settings.setValue("ShowSettingsWindow", mShowDirtyFileSettingsWindow); for (size_t i = 0; i < numDirtyFilesCallbacks; ++i) { - settings.beginGroup(mSaveDirtyFilesCallbacks[i]->GetFileType()); - settings.setValue("FileExtension", mSaveDirtyFilesCallbacks[i]->GetExtension()); - //settings.setValue( "AskIndividually", mSaveDirtyFilesCallbacks[i]->AskIndividually()); - //settings.setValue( "SkipSaving", mSaveDirtyFilesCallbacks[i]->SkipSaving()); + settings.beginGroup(m_saveDirtyFilesCallbacks[i]->GetFileType()); + settings.setValue("FileExtension", m_saveDirtyFilesCallbacks[i]->GetExtension()); settings.endGroup(); } @@ -89,12 +86,12 @@ namespace EMStudio // destructor DirtyFileManager::~DirtyFileManager() { - const size_t numDirtyFilesCallbacks = mSaveDirtyFilesCallbacks.size(); + const size_t numDirtyFilesCallbacks = m_saveDirtyFilesCallbacks.size(); for (size_t i = 0; i < numDirtyFilesCallbacks; ++i) { - delete mSaveDirtyFilesCallbacks[i]; + delete m_saveDirtyFilesCallbacks[i]; } - mSaveDirtyFilesCallbacks.clear(); + m_saveDirtyFilesCallbacks.clear(); } @@ -134,10 +131,10 @@ namespace EMStudio size_t insertIndex = MCORE_INVALIDINDEX32; // get the number of callbacks and iterate through them - const size_t numCallbacks = mSaveDirtyFilesCallbacks.size(); + const size_t numCallbacks = m_saveDirtyFilesCallbacks.size(); for (size_t i = 0; i < numCallbacks; ++i) { - const uint32 currentPriority = mSaveDirtyFilesCallbacks[i]->GetPriority(); + const uint32 currentPriority = m_saveDirtyFilesCallbacks[i]->GetPriority(); if (newPriority > currentPriority) { @@ -149,11 +146,11 @@ namespace EMStudio // add the new callback if (insertIndex == MCORE_INVALIDINDEX32) { - mSaveDirtyFilesCallbacks.push_back(callback); + m_saveDirtyFilesCallbacks.push_back(callback); } else { - mSaveDirtyFilesCallbacks.insert(mSaveDirtyFilesCallbacks.begin()+insertIndex, callback); + m_saveDirtyFilesCallbacks.insert(m_saveDirtyFilesCallbacks.begin()+insertIndex, callback); } } @@ -162,12 +159,12 @@ namespace EMStudio { AZStd::vector neededCallbacks; - const size_t numDirtyFilesCallbacks = mSaveDirtyFilesCallbacks.size(); + const size_t numDirtyFilesCallbacks = m_saveDirtyFilesCallbacks.size(); // check if there are any dirty files for (size_t i = 0; i < numDirtyFilesCallbacks; ++i) { - SaveDirtyFilesCallback* callback = mSaveDirtyFilesCallbacks[i]; + SaveDirtyFilesCallback* callback = m_saveDirtyFilesCallbacks[i]; // make sure we want to handle the given save dirty files callback if ((type != MCORE_INVALIDINDEX32 && callback->GetType() != type) || (filter != MCORE_INVALIDINDEX32 && callback->GetType() == filter)) @@ -184,11 +181,11 @@ namespace EMStudio { AZStd::vector neededCallbacks; - const size_t numDirtyFilesCallbacks = mSaveDirtyFilesCallbacks.size(); + const size_t numDirtyFilesCallbacks = m_saveDirtyFilesCallbacks.size(); for (size_t i = 0; i < numDirtyFilesCallbacks; ++i) { - SaveDirtyFilesCallback* callback = mSaveDirtyFilesCallbacks[i]; + SaveDirtyFilesCallback* callback = m_saveDirtyFilesCallbacks[i]; // make sure we want to handle the given save dirty files callback if (AZStd::find(typeIds.begin(), typeIds.end(), callback->GetFileRttiType()) != typeIds.end()) @@ -333,9 +330,9 @@ namespace EMStudio MCORE_ASSERT(dirtyFileNames.size() == objects.size()); // store values - mFileNames = dirtyFileNames; - mObjects = objects; - mSaveDirtyFiles = true; + m_fileNames = dirtyFileNames; + m_objects = objects; + m_saveDirtyFiles = true; // update title of the dialog setWindowTitle("Save Changes To Files"); @@ -350,54 +347,54 @@ namespace EMStudio vLayout->addWidget(new QLabel("Do you want to save changes? The following files have been changed but have not been saved yet:")); // create the lod information table - mTableWidget = new QTableWidget(); - mTableWidget->setAlternatingRowColors(true); - mTableWidget->setSelectionMode(QAbstractItemView::NoSelection); - mTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); - mTableWidget->setMinimumHeight(250); - mTableWidget->setMinimumWidth(600); - mTableWidget->verticalHeader()->hide(); + m_tableWidget = new QTableWidget(); + m_tableWidget->setAlternatingRowColors(true); + m_tableWidget->setSelectionMode(QAbstractItemView::NoSelection); + m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_tableWidget->setMinimumHeight(250); + m_tableWidget->setMinimumWidth(600); + m_tableWidget->verticalHeader()->hide(); // disable the corner button between the row and column selection thingies - mTableWidget->setCornerButtonEnabled(false); + m_tableWidget->setCornerButtonEnabled(false); // enable the custom context menu for the motion table - mTableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); + m_tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); // disable sorting when adding the items - mTableWidget->setSortingEnabled(false); + m_tableWidget->setSortingEnabled(false); // clear the table widget - mTableWidget->clear(); - mTableWidget->setColumnCount(3); + m_tableWidget->clear(); + m_tableWidget->setColumnCount(3); // set header items for the table QTableWidgetItem* headerItem = new QTableWidgetItem(""); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(0, headerItem); + m_tableWidget->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem("FileName"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(1, headerItem); + m_tableWidget->setHorizontalHeaderItem(1, headerItem); headerItem = new QTableWidgetItem("Type"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(2, headerItem); + m_tableWidget->setHorizontalHeaderItem(2, headerItem); // set column resize modes. The main filename is in column 1, and // stretches to fill any remaining space. The other columns are // informational only, and not very wide, so setting them to always // resize to their contents means we don't have to manage their column // widths. - QHeaderView* horizontalHeader = mTableWidget->horizontalHeader(); + QHeaderView* horizontalHeader = m_tableWidget->horizontalHeader(); horizontalHeader->setSectionResizeMode(0, QHeaderView::ResizeToContents); horizontalHeader->setSectionResizeMode(1, QHeaderView::Stretch); horizontalHeader->setSectionResizeMode(2, QHeaderView::ResizeToContents); const size_t numDirtyFiles = dirtyFileNames.size(); - mTableWidget->setRowCount(static_cast(numDirtyFiles)); + m_tableWidget->setRowCount(static_cast(numDirtyFiles)); for (size_t i = 0; i < numDirtyFiles; ++i) { - SaveDirtyFilesCallback::ObjectPointer object = mObjects[i]; + SaveDirtyFilesCallback::ObjectPointer object = m_objects[i]; QString labelText; if (dirtyFileNames[i].empty()) @@ -438,23 +435,23 @@ namespace EMStudio filenameLabel->setText(labelText); QString typeString; - if (object.mMotion) + if (object.m_motion) { typeString = "Motion"; } - else if (object.mActor) + else if (object.m_actor) { typeString = "Actor"; } - else if (object.mMotionSet) + else if (object.m_motionSet) { typeString = "Motion Set"; } - else if (object.mAnimGraph) + else if (object.m_animGraph) { typeString = "Anim Graph"; } - else if (object.mWorkspace) + else if (object.m_workspace) { typeString = "Workspace"; } @@ -464,19 +461,19 @@ namespace EMStudio itemType->setData(Qt::UserRole, row); // add table items to the current row - mTableWidget->setCellWidget(row, 0, checkbox); - mTableWidget->setCellWidget(row, 1, filenameLabel); - mTableWidget->setItem(row, 2, itemType); + m_tableWidget->setCellWidget(row, 0, checkbox); + m_tableWidget->setCellWidget(row, 1, filenameLabel); + m_tableWidget->setItem(row, 2, itemType); // set the row height - mTableWidget->setRowHeight(row, 21); + m_tableWidget->setRowHeight(row, 21); } // enable sorting - mTableWidget->setSortingEnabled(true); + m_tableWidget->setSortingEnabled(true); // add the table in the layout - vLayout->addWidget(mTableWidget); + vLayout->addWidget(m_tableWidget); // the buttons at the bottom of the dialog QDialogButtonBox* buttonBox = new QDialogButtonBox(buttons); @@ -525,26 +522,26 @@ namespace EMStudio outFileNames->clear(); outObjects->clear(); - const uint32 numRows = mTableWidget->rowCount(); + const uint32 numRows = m_tableWidget->rowCount(); // iteration for motions, motion sets, actors and anim graphs for (uint32 i = 0; i < numRows; ++i) { // get the checkbox - QWidget* widget = mTableWidget->cellWidget(i, 0); + QWidget* widget = m_tableWidget->cellWidget(i, 0); QCheckBox* checkbox = static_cast(widget); // get the type item - QTableWidgetItem* item = mTableWidget->item(i, 2); + QTableWidgetItem* item = m_tableWidget->item(i, 2); const int32 filenameIndex = item->data(Qt::UserRole).toInt(); // get the object pointer - SaveDirtyFilesCallback::ObjectPointer objPointer = mObjects[filenameIndex]; + SaveDirtyFilesCallback::ObjectPointer objPointer = m_objects[filenameIndex]; // add the filename to the list of selected filenames in case the checkbox in the same row is checked if (checkbox->isChecked()) { - outFileNames->push_back(mFileNames[filenameIndex]); + outFileNames->push_back(m_fileNames[filenameIndex]); outObjects->push_back(objPointer); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.h index aabfddd687..48c47ef2ec 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.h @@ -40,11 +40,11 @@ namespace EMStudio ObjectPointer(); - EMotionFX::Actor * mActor; - EMotionFX::Motion* mMotion; - EMotionFX::MotionSet* mMotionSet; - EMotionFX::AnimGraph* mAnimGraph; - Workspace* mWorkspace; + EMotionFX::Actor * m_actor; + EMotionFX::Motion* m_motion; + EMotionFX::MotionSet* m_motionSet; + EMotionFX::AnimGraph* m_animGraph; + Workspace* m_workspace; }; SaveDirtyFilesCallback(); @@ -80,8 +80,8 @@ namespace EMStudio // dirty files callbacks void AddCallback(SaveDirtyFilesCallback* callback); void RemoveCallback(SaveDirtyFilesCallback* callback, bool delFromMem = true); - SaveDirtyFilesCallback* GetCallback(size_t index) const { return mSaveDirtyFilesCallbacks[index]; } - size_t GetNumCallbacks() const { return mSaveDirtyFilesCallbacks.size(); } + SaveDirtyFilesCallback* GetCallback(size_t index) const { return m_saveDirtyFilesCallbacks[index]; } + size_t GetNumCallbacks() const { return m_saveDirtyFilesCallbacks.size(); } int SaveDirtyFiles(uint32 type = MCORE_INVALIDINDEX32, uint32 filter = MCORE_INVALIDINDEX32, QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Ok | QDialogButtonBox::Discard | QDialogButtonBox::Cancel @@ -94,7 +94,7 @@ namespace EMStudio void SaveSettings(); private: - AZStd::vector mSaveDirtyFilesCallbacks; + AZStd::vector m_saveDirtyFilesCallbacks; int SaveDirtyFiles(const AZStd::vector& neededSaveDirtyFilesCallbacks, QDialogButtonBox::StandardButtons buttons); }; @@ -115,18 +115,18 @@ namespace EMStudio ); virtual ~SaveDirtySettingsWindow(); - bool GetSaveDirtyFiles() { return mSaveDirtyFiles; } + bool GetSaveDirtyFiles() { return m_saveDirtyFiles; } void GetSelectedFileNames(AZStd::vector* outFileNames, AZStd::vector* outObjects); public slots: - void OnSaveButton() { mSaveDirtyFiles = true; emit accept(); } - void OnSkipSavingButton() { mSaveDirtyFiles = false; emit accept(); } - void OnCancelButton() { mSaveDirtyFiles = false; emit reject(); } + void OnSaveButton() { m_saveDirtyFiles = true; emit accept(); } + void OnSkipSavingButton() { m_saveDirtyFiles = false; emit accept(); } + void OnCancelButton() { m_saveDirtyFiles = false; emit reject(); } private: - QTableWidget* mTableWidget; - bool mSaveDirtyFiles; - AZStd::vector mFileNames; - AZStd::vector mObjects; + QTableWidget* m_tableWidget; + bool m_saveDirtyFiles; + AZStd::vector m_fileNames; + AZStd::vector m_objects; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.cpp index f0820b3b5c..87511e19ce 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.cpp @@ -17,7 +17,7 @@ namespace EMStudio // constructor ToolBarPlugin::ToolBarPlugin() : EMStudioPlugin() - , mBar() + , m_bar() { } @@ -25,10 +25,10 @@ namespace EMStudio // destructor ToolBarPlugin::~ToolBarPlugin() { - if (!mBar.isNull()) + if (!m_bar.isNull()) { - EMStudio::GetMainWindow()->removeToolBar(mBar); - delete mBar; + EMStudio::GetMainWindow()->removeToolBar(m_bar); + delete m_bar; } } @@ -40,13 +40,13 @@ namespace EMStudio // check if we have a window that uses this object name bool ToolBarPlugin::GetHasWindowWithObjectName(const AZStd::string& objectName) { - if (mBar.isNull()) + if (m_bar.isNull()) { return false; } // check if the object name is equal to the one of the dock widget - return objectName == FromQtString(mBar->objectName()); + return objectName == FromQtString(m_bar->objectName()); } @@ -68,33 +68,33 @@ namespace EMStudio // set the interface title void ToolBarPlugin::SetInterfaceTitle(const char* name) { - if (!mBar.isNull()) + if (!m_bar.isNull()) { - mBar->setWindowTitle(name); + m_bar->setWindowTitle(name); } } QToolBar* ToolBarPlugin::GetToolBar() { - if (!mBar.isNull()) + if (!m_bar.isNull()) { - return mBar; + return m_bar; } MainWindow* mainWindow = GetMainWindow(); // create the toolbar - mBar = new QToolBar(GetName(), mainWindow); - mBar->setAllowedAreas(GetAllowedAreas()); - mBar->setFloatable(GetIsFloatable()); - mBar->setMovable(GetIsMovable()); - mBar->setOrientation(GetIsVertical() ? Qt::Vertical : Qt::Horizontal); - mBar->setToolButtonStyle(GetToolButtonStyle()); + m_bar = new QToolBar(GetName(), mainWindow); + m_bar->setAllowedAreas(GetAllowedAreas()); + m_bar->setFloatable(GetIsFloatable()); + m_bar->setMovable(GetIsMovable()); + m_bar->setOrientation(GetIsVertical() ? Qt::Vertical : Qt::Horizontal); + m_bar->setToolButtonStyle(GetToolButtonStyle()); // add the toolbar to the main window - mainWindow->addToolBar(GetToolBarCreationArea(), mBar); + mainWindow->addToolBar(GetToolBarCreationArea(), m_bar); - return mBar; + return m_bar; } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.h index 72054ab926..dcda6d2c1f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/ToolBarPlugin.h @@ -46,7 +46,7 @@ namespace EMStudio virtual void SetInterfaceTitle(const char* name); void CreateBaseInterface(const char* objectName) override; - QString GetObjectName() const override { AZ_Assert(!mBar.isNull(), "Unexpected null bar"); return mBar->objectName(); } + QString GetObjectName() const override { AZ_Assert(!m_bar.isNull(), "Unexpected null bar"); return m_bar->objectName(); } void SetObjectName(const QString& name) override { GetToolBar()->setObjectName(name); } bool GetHasWindowWithObjectName(const AZStd::string& objectName) override; @@ -56,7 +56,7 @@ namespace EMStudio QToolBar* GetToolBar(); protected: - QPointer mBar; + QPointer m_bar; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.cpp index a39d24c3d7..f449adf733 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.cpp @@ -23,7 +23,7 @@ namespace EMStudio UnitScaleWindow::UnitScaleWindow(QWidget* parent) : QDialog(parent) { - mScaleFactor = 1.0f; + m_scaleFactor = 1.0f; setModal(true); setWindowTitle("Scale Factor Setup"); @@ -47,27 +47,27 @@ namespace EMStudio scaleLayout->addWidget(new QLabel("Scale Factor:")); - mScaleSpinBox = new AzQtComponents::DoubleSpinBox(); - mScaleSpinBox->setRange(0.00001, 100000.0f); - mScaleSpinBox->setSingleStep(0.01); - mScaleSpinBox->setDecimals(7); - mScaleSpinBox->setValue(1.0f); - scaleLayout->addWidget(mScaleSpinBox); + m_scaleSpinBox = new AzQtComponents::DoubleSpinBox(); + m_scaleSpinBox->setRange(0.00001, 100000.0f); + m_scaleSpinBox->setSingleStep(0.01); + m_scaleSpinBox->setDecimals(7); + m_scaleSpinBox->setValue(1.0f); + scaleLayout->addWidget(m_scaleSpinBox); layout->addLayout(scaleLayout); QHBoxLayout* hLayout = new QHBoxLayout(); hLayout->setContentsMargins(9, 0, 9, 9); - mOK = new QPushButton("OK"); - mCancel = new QPushButton("Cancel"); - hLayout->addWidget(mOK); - hLayout->addWidget(mCancel); + m_ok = new QPushButton("OK"); + m_cancel = new QPushButton("Cancel"); + hLayout->addWidget(m_ok); + hLayout->addWidget(m_cancel); layout->addLayout(hLayout); - connect(mOK, &QPushButton::clicked, this, &UnitScaleWindow::OnOKButton); - connect(mCancel, &QPushButton::clicked, this, &UnitScaleWindow::OnCancelButton); + connect(m_ok, &QPushButton::clicked, this, &UnitScaleWindow::OnOKButton); + connect(m_cancel, &QPushButton::clicked, this, &UnitScaleWindow::OnCancelButton); } @@ -80,7 +80,7 @@ namespace EMStudio // accept void UnitScaleWindow::OnOKButton() { - mScaleFactor = static_cast(mScaleSpinBox->value()); + m_scaleFactor = static_cast(m_scaleSpinBox->value()); emit accept(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.h index c60c66fad1..3de0ed1787 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/UnitScaleWindow.h @@ -30,16 +30,16 @@ namespace EMStudio UnitScaleWindow(QWidget* parent); ~UnitScaleWindow(); - float GetScaleFactor() const { return mScaleFactor; } + float GetScaleFactor() const { return m_scaleFactor; } private slots: void OnOKButton(); void OnCancelButton(); private: - float mScaleFactor; - QPushButton* mOK; - QPushButton* mCancel; - AzQtComponents::DoubleSpinBox* mScaleSpinBox; + float m_scaleFactor; + QPushButton* m_ok; + QPushButton* m_cancel; + AzQtComponents::DoubleSpinBox* m_scaleSpinBox; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp index 9919c4cbb3..4cdf645b16 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.cpp @@ -38,7 +38,7 @@ namespace EMStudio { Workspace::Workspace() { - mDirtyFlag = false; + m_dirtyFlag = false; } @@ -139,15 +139,15 @@ namespace EMStudio ActivationIndicesByActorInstance activationIndicesByActorInstance; int32 commandIndex = 0; - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); // actors - const uint32 numActors = EMotionFX::GetActorManager().GetNumActors(); - for (uint32 i = 0; i < numActors; ++i) + const size_t numActors = EMotionFX::GetActorManager().GetNumActors(); + for (size_t i = 0; i < numActors; ++i) { EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); - for (uint32 j = 0; j < numActorInstances; ++j) + for (size_t j = 0; j < numActorInstances; ++j) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(j); if (actorInstance->GetActor() != actor) @@ -161,11 +161,11 @@ namespace EMStudio } const EMotionFX::Transform& transform = actorInstance->GetLocalSpaceTransform(); - const AZ::Vector3& pos = transform.mPosition; - const AZ::Quaternion& rot = transform.mRotation; + const AZ::Vector3& pos = transform.m_position; + const AZ::Quaternion& rot = transform.m_rotation; #ifndef EMFX_SCALE_DISABLED - const AZ::Vector3& scale = transform.mScale; + const AZ::Vector3& scale = transform.m_scale; #else const AZ::Vector3 scale = AZ::Vector3::CreateOne(); #endif @@ -184,7 +184,7 @@ namespace EMStudio } // attachments - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -197,23 +197,23 @@ namespace EMStudio { EMotionFX::Attachment* attachment = actorInstance->GetSelfAttachment(); EMotionFX::ActorInstance* attachedToActorInstance = attachment->GetAttachToActorInstance(); - const uint32 attachedToInstanceIndex = EMotionFX::GetActorManager().FindActorInstanceIndex(attachedToActorInstance); - const uint32 attachtmentInstanceIndex = EMotionFX::GetActorManager().FindActorInstanceIndex(actorInstance); + const size_t attachedToInstanceIndex = EMotionFX::GetActorManager().FindActorInstanceIndex(attachedToActorInstance); + const size_t attachtmentInstanceIndex = EMotionFX::GetActorManager().FindActorInstanceIndex(actorInstance); if (actorInstance->GetIsSkinAttachment()) { - commandString = AZStd::string::format("AddDeformableAttachment -attachmentIndex %d -attachToIndex %d\n", attachtmentInstanceIndex, attachedToInstanceIndex); + commandString = AZStd::string::format("AddDeformableAttachment -attachmentIndex %zu -attachToIndex %zu\n", attachtmentInstanceIndex, attachedToInstanceIndex); commands += commandString; ++commandIndex; } else { EMotionFX::AttachmentNode* attachmentSingleNode = static_cast(attachment); - const uint32 attachedToNodeIndex = attachmentSingleNode->GetAttachToNodeIndex(); + const size_t attachedToNodeIndex = attachmentSingleNode->GetAttachToNodeIndex(); EMotionFX::Actor* attachedToActor = attachedToActorInstance->GetActor(); EMotionFX::Node* attachedToNode = attachedToActor->GetSkeleton()->GetNode(attachedToNodeIndex); - commandString = AZStd::string::format("AddAttachment -attachmentIndex %d -attachToIndex %d -attachToNode \"%s\"\n", attachtmentInstanceIndex, attachedToInstanceIndex, attachedToNode->GetName()); + commandString = AZStd::string::format("AddAttachment -attachmentIndex %zu -attachToIndex %zu -attachToNode \"%s\"\n", attachtmentInstanceIndex, attachedToInstanceIndex, attachedToNode->GetName()); commands += commandString; ++commandIndex; } @@ -221,9 +221,9 @@ namespace EMStudio } // motion sets - const uint32 numRootMotionSets = EMotionFX::GetMotionManager().CalcNumRootMotionSets(); + const size_t numRootMotionSets = EMotionFX::GetMotionManager().CalcNumRootMotionSets(); AZStd::unordered_set motionsInMotionSets; - for (uint32 i = 0; i < numRootMotionSets; ++i) + for (size_t i = 0; i < numRootMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindRootMotionSet(i); @@ -255,8 +255,8 @@ namespace EMStudio } // motions that are not in the above motion sets - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); - for (uint32 i = 0; i < numMotions; ++i) + const size_t numMotions = EMotionFX::GetMotionManager().GetNumMotions(); + for (size_t i = 0; i < numMotions; ++i) { EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); @@ -277,8 +277,8 @@ namespace EMStudio // We need to avoid storing two times the same anim graph. This could happen if the anim graph was loaded from a reference // node. We need to integrate the asset system into the AnimGraphManager AZStd::unordered_set animGraphFilenames; - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -317,7 +317,7 @@ namespace EMStudio } // activate anim graph for each actor instance - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -371,14 +371,14 @@ namespace EMStudio // update the workspace filename if (updateFileName) { - mFilename = filename; + m_filename = filename; } // update the workspace dirty flag if (updateDirtyFlag) { GetCommandManager()->SetWorkspaceDirtyFlag(false); - mDirtyFlag = false; + m_dirtyFlag = false; } // save succeeded @@ -404,7 +404,7 @@ namespace EMStudio QSettings settings(filename, QSettings::IniFormat, (QWidget*)GetManager()->GetMainWindow()); - mFilename = filename; + m_filename = filename; AZStd::string commandsString = FromQtString(settings.value("startScript", "").toString()); @@ -435,23 +435,23 @@ namespace EMStudio } GetCommandManager()->SetWorkspaceDirtyFlag(false); - mDirtyFlag = false; + m_dirtyFlag = false; return true; } void Workspace::Reset() { - mFilename.clear(); + m_filename.clear(); GetCommandManager()->SetWorkspaceDirtyFlag(false); - mDirtyFlag = false; + m_dirtyFlag = false; } bool Workspace::GetDirtyFlag() const { - if (mDirtyFlag) + if (m_dirtyFlag) { return true; } @@ -467,7 +467,7 @@ namespace EMStudio void Workspace::SetDirtyFlag(bool dirty) { - mDirtyFlag = dirty; + m_dirtyFlag = dirty; GetCommandManager()->SetWorkspaceDirtyFlag(dirty); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.h index 6ef029f131..ad048c6d6b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/Workspace.h @@ -35,9 +35,9 @@ namespace EMStudio void Reset(); - void SetFilename(const char* filename) { mFilename = filename; mDirtyFlag = true; } - const AZStd::string& GetFilenameString() const { return mFilename; } - const char* GetFilename() const { return mFilename.c_str(); } + void SetFilename(const char* filename) { m_filename = filename; m_dirtyFlag = true; } + const AZStd::string& GetFilenameString() const { return m_filename; } + const char* GetFilename() const { return m_filename.c_str(); } /** * Set the dirty flag which indicates whether the user has made changes to the motion. This indicator should be set to true @@ -57,7 +57,7 @@ namespace EMStudio void AddFile(AZStd::string* inOutCommands, const char* command, const AZStd::string& filename, const char* additionalParameters = nullptr) const; bool SaveToFile(const char* filename) const; - AZStd::string mFilename; - bool mDirtyFlag; + AZStd::string m_filename; + bool m_dirtyFlag; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp index 2d3a8b9eda..622dd6b566 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.cpp @@ -26,11 +26,11 @@ namespace EMStudio : QOpenGLWidget(parentWidget) , RenderWidget(parentPlugin, parentWidget) { - mParentRenderPlugin = parentPlugin; + m_parentRenderPlugin = parentPlugin; // construct the font metrics used for overlay text rendering - mFont.setPointSize(10); - mFontMetrics = new QFontMetrics(mFont); + m_font.setPointSize(10); + m_fontMetrics = new QFontMetrics(m_font); // create our default camera SwitchCamera(CAMMODE_ORBIT); @@ -47,27 +47,27 @@ namespace EMStudio GLWidget::~GLWidget() { // destruct the font metrics used for overlay text rendering - delete mFontMetrics; + delete m_fontMetrics; } // initialize the Qt OpenGL widget (overloaded from the widget base class) void GLWidget::initializeGL() { - // initializeOpenGLFunctions() and mParentRenderPlugin->InitializeGraphicsManager must be called first to ensure + // initializeOpenGLFunctions() and m_parentRenderPlugin->InitializeGraphicsManager must be called first to ensure // all OpenGL functions have been resolved before doing anything that could make GL calls (e.g. resizing) initializeOpenGLFunctions(); - mParentRenderPlugin->InitializeGraphicsManager(); - if (mParentRenderPlugin->GetGraphicsManager()) + m_parentRenderPlugin->InitializeGraphicsManager(); + if (m_parentRenderPlugin->GetGraphicsManager()) { - mParentRenderPlugin->GetGraphicsManager()->SetGBuffer(&mGBuffer); + m_parentRenderPlugin->GetGraphicsManager()->SetGBuffer(&m_gBuffer); } // set minimum render view dimensions setMinimumHeight(100); setMinimumWidth(100); - mPerfTimer.StampAndGetDeltaTimeInSeconds(); + m_perfTimer.StampAndGetDeltaTimeInSeconds(); } @@ -80,14 +80,14 @@ namespace EMStudio return; } - mParentRenderPlugin->GetRenderUtil()->Validate(); + m_parentRenderPlugin->GetRenderUtil()->Validate(); - mWidth = width; - mHeight = height; - mGBuffer.Resize(width, height); + m_width = width; + m_height = height; + m_gBuffer.Resize(width, height); - RenderGL::GraphicsManager* graphicsManager = mParentRenderPlugin->GetGraphicsManager(); - if (graphicsManager == nullptr || mCamera == nullptr) + RenderGL::GraphicsManager* graphicsManager = m_parentRenderPlugin->GetGraphicsManager(); + if (graphicsManager == nullptr || m_camera == nullptr) { return; } @@ -115,23 +115,23 @@ namespace EMStudio return; } - mRenderTimer.Stamp(); + m_renderTimer.Stamp(); // render the scene - RenderGL::GraphicsManager* graphicsManager = mParentRenderPlugin->GetGraphicsManager(); - if (graphicsManager == nullptr || mCamera == nullptr) + RenderGL::GraphicsManager* graphicsManager = m_parentRenderPlugin->GetGraphicsManager(); + if (graphicsManager == nullptr || m_camera == nullptr) { return; } painter.beginNativePainting(); - graphicsManager->SetGBuffer(&mGBuffer); + graphicsManager->SetGBuffer(&m_gBuffer); - RenderOptions* renderOptions = mParentRenderPlugin->GetRenderOptions(); + RenderOptions* renderOptions = m_parentRenderPlugin->GetRenderOptions(); // get a pointer to the render utility - RenderGL::GLRenderUtil* renderUtil = mParentRenderPlugin->GetGraphicsManager()->GetRenderUtil(); + RenderGL::GLRenderUtil* renderUtil = m_parentRenderPlugin->GetGraphicsManager()->GetRenderUtil(); if (renderUtil == nullptr) { return; @@ -139,35 +139,23 @@ namespace EMStudio // set this as the active widget // note that this is done in paint() instead of by the plugin because of delay when glwidget::update is called - MCORE_ASSERT(mParentRenderPlugin->GetActiveViewWidget() == nullptr); - mParentRenderPlugin->SetActiveViewWidget(mViewWidget); + MCORE_ASSERT(m_parentRenderPlugin->GetActiveViewWidget() == nullptr); + m_parentRenderPlugin->SetActiveViewWidget(m_viewWidget); // set the background colors graphicsManager->SetClearColor(renderOptions->GetBackgroundColor()); graphicsManager->SetGradientSourceColor(renderOptions->GetGradientSourceColor()); graphicsManager->SetGradientTargetColor(renderOptions->GetGradientTargetColor()); - graphicsManager->SetUseGradientBackground(mViewWidget->GetRenderFlag(RenderViewWidget::RENDER_USE_GRADIENTBACKGROUND)); + graphicsManager->SetUseGradientBackground(m_viewWidget->GetRenderFlag(RenderViewWidget::RENDER_USE_GRADIENTBACKGROUND)); // needed to make multiple viewports working glEnable(GL_DEPTH_TEST); glEnable(GL_MULTISAMPLE); // tell the system about the current viewport - glViewport(0, 0, aznumeric_cast(mWidth * devicePixelRatioF()), aznumeric_cast(mHeight * devicePixelRatioF())); + glViewport(0, 0, aznumeric_cast(m_width * devicePixelRatioF()), aznumeric_cast(m_height * devicePixelRatioF())); renderUtil->SetDevicePixelRatio(aznumeric_cast(devicePixelRatioF())); - // update advanced render settings - /* graphicsManager->SetAdvancedRendering( renderOptions->mEnableAdvancedRendering ); - graphicsManager->SetBloomEnabled ( renderOptions->mBloomEnabled ); - graphicsManager->SetBloomThreshold ( renderOptions->mBloomThreshold ); - graphicsManager->SetBloomIntensity ( renderOptions->mBloomIntensity ); - graphicsManager->SetBloomRadius ( renderOptions->mBloomRadius ); - graphicsManager->SetDOFEnabled ( renderOptions->mDOFEnabled ); - graphicsManager->SetDOFFocalDistance( renderOptions->mDOFFocalPoint ); - graphicsManager->SetDOFNear ( renderOptions->mDOFNear ); - graphicsManager->SetDOFFar ( renderOptions->mDOFFar ); - graphicsManager->SetDOFBlurRadius ( renderOptions->mDOFBlurRadius ); - */ graphicsManager->SetRimAngle (renderOptions->GetRimAngle()); graphicsManager->SetRimIntensity (renderOptions->GetRimIntensity()); graphicsManager->SetRimWidth (renderOptions->GetRimWidth()); @@ -180,7 +168,7 @@ namespace EMStudio // update the camera UpdateCamera(); - graphicsManager->SetCamera(mCamera); + graphicsManager->SetCamera(m_camera); graphicsManager->BeginRender(); @@ -216,16 +204,16 @@ namespace EMStudio glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); - MCommon::Camera* camera = mCamera; - if (mCamera->GetType() == MCommon::OrthographicCamera::TYPE_ID) + MCommon::Camera* camera = m_camera; + if (m_camera->GetType() == MCommon::OrthographicCamera::TYPE_ID) { - camera = mAxisFakeCamera; + camera = m_axisFakeCamera; } graphicsManager->SetCamera(camera); RenderWidget::RenderAxis(); - graphicsManager->SetCamera(mCamera); + graphicsManager->SetCamera(m_camera); glPopAttrib(); @@ -235,7 +223,7 @@ namespace EMStudio // render the border around the render view if (EMotionFX::GetRecorder().GetIsRecording() == false && EMotionFX::GetRecorder().GetIsInPlayMode() == false) { - if (mParentRenderPlugin->GetFocusViewWidget() == mViewWidget) + if (m_parentRenderPlugin->GetFocusViewWidget() == m_viewWidget) { RenderBorder(MCore::RGBAColor(1.0f, 0.647f, 0.0f)); } @@ -261,16 +249,16 @@ namespace EMStudio // makes no GL context the current context, needed in multithreaded environments //doneCurrent(); // Ben: results in a white screen - mParentRenderPlugin->SetActiveViewWidget(nullptr); + m_parentRenderPlugin->SetActiveViewWidget(nullptr); painter.endNativePainting(); if (renderOptions->GetShowFPS()) { - const float renderTime = mRenderTimer.GetDeltaTimeInSeconds() * 1000.0f; + const float renderTime = m_renderTimer.GetDeltaTimeInSeconds() * 1000.0f; // get the time delta between the current time and the last frame - const float perfTimeDelta = mPerfTimer.StampAndGetDeltaTimeInSeconds(); + const float perfTimeDelta = m_perfTimer.StampAndGetDeltaTimeInSeconds(); static float fpsTimeElapsed = 0.0f; static uint32 fpsNumFrames = 0; @@ -288,11 +276,7 @@ namespace EMStudio perfTempString = AZStd::string::format("%d FPS (%.1f ms)", lastFPS, renderTime); // initialize the painter and get the font metrics - //painter.setBrush( Qt::NoBrush ); - //painter.setPen( QColor(130, 130, 130) ); - //painter.setFont( mFont ); - EMStudioManager::RenderText(painter, perfTempString.c_str(), QColor(150, 150, 150), mFont, *mFontMetrics, Qt::AlignRight, QRect(width() - 55, height() - 20, 50, 20)); - //painter.drawText( QPoint(width() - 133, height() - 14), perfTempString.AsChar() ); + EMStudioManager::RenderText(painter, perfTempString.c_str(), QColor(150, 150, 150), m_font, *m_fontMetrics, Qt::AlignRight, QRect(width() - 55, height() - 20, 50, 20)); } } @@ -301,7 +285,7 @@ namespace EMStudio { glMatrixMode(GL_PROJECTION); glLoadIdentity(); - glOrtho(0.0f, mWidth, mHeight, 0.0f, 0.0f, 1.0f); + glOrtho(0.0f, m_width, m_height, 0.0f, 0.0f, 1.0f); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); //glTranslatef(0.375f, 0.375f, 0.0f); @@ -312,20 +296,20 @@ namespace EMStudio glLineWidth(3.0f); - glColor3f(color.r, color.g, color.b); + glColor3f(color.m_r, color.m_g, color.m_b); glBegin(GL_LINES); // left glVertex2f(0.0f, 0.0f); - glVertex2f(0.0f, aznumeric_cast(mHeight)); + glVertex2f(0.0f, aznumeric_cast(m_height)); // bottom - glVertex2f(0.0f, aznumeric_cast(mHeight)); - glVertex2f(aznumeric_cast(mWidth), aznumeric_cast(mHeight)); + glVertex2f(0.0f, aznumeric_cast(m_height)); + glVertex2f(aznumeric_cast(m_width), aznumeric_cast(m_height)); // top glVertex2f(0.0f, 0.0f); - glVertex2f(aznumeric_cast(mWidth), 0); + glVertex2f(aznumeric_cast(m_width), 0); // right - glVertex2f(aznumeric_cast(mWidth), 0.0f); - glVertex2f(aznumeric_cast(mWidth), aznumeric_cast(mHeight)); + glVertex2f(aznumeric_cast(m_width), 0.0f); + glVertex2f(aznumeric_cast(m_width), aznumeric_cast(m_height)); glEnd(); glLineWidth(1.0f); @@ -335,7 +319,7 @@ namespace EMStudio void GLWidget::focusInEvent(QFocusEvent* event) { MCORE_UNUSED(event); - mParentRenderPlugin->SetFocusViewWidget(mViewWidget); + m_parentRenderPlugin->SetFocusViewWidget(m_viewWidget); grabKeyboard(); } @@ -343,7 +327,7 @@ namespace EMStudio void GLWidget::focusOutEvent(QFocusEvent* event) { MCORE_UNUSED(event); - mParentRenderPlugin->SetFocusViewWidget(nullptr); + m_parentRenderPlugin->SetFocusViewWidget(nullptr); releaseKeyboard(); } } // namespace EMStudio 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 2306da0a5f..685ff4ef88 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 @@ -76,12 +76,12 @@ namespace EMStudio void Update() { update(); } void RenderBorder(const MCore::RGBAColor& color); - RenderGL::GBuffer mGBuffer; - OpenGLRenderPlugin* mParentRenderPlugin; - QFont mFont; - QFontMetrics* mFontMetrics; - AZ::Debug::Timer mRenderTimer; - AZ::Debug::Timer mPerfTimer; + RenderGL::GBuffer m_gBuffer; + OpenGLRenderPlugin* m_parentRenderPlugin; + QFont m_font; + QFontMetrics* m_fontMetrics; + AZ::Debug::Timer m_renderTimer; + AZ::Debug::Timer m_perfTimer; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.cpp index 396a7fc906..5626e482eb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.cpp @@ -25,13 +25,13 @@ namespace EMStudio OpenGLRenderPlugin::OpenGLRenderPlugin() : EMStudio::RenderPlugin() { - mGraphicsManager = nullptr; + m_graphicsManager = nullptr; } OpenGLRenderPlugin::~OpenGLRenderPlugin() { // get rid of the OpenGL graphics manager - delete mGraphicsManager; + delete m_graphicsManager; } // init after the parent dock window has been created @@ -48,7 +48,7 @@ namespace EMStudio // initialize the OpenGL engine bool OpenGLRenderPlugin::InitializeGraphicsManager() { - if (mGraphicsManager) + if (m_graphicsManager) { // initialize all already existing actors and actor instances ReInit(); @@ -59,15 +59,15 @@ namespace EMStudio const auto shaderPath = AZ::IO::Path(MysticQt::GetDataDir()) / "Shaders"; // create graphics manager and initialize it - mGraphicsManager = new RenderGL::GraphicsManager(); - if (mGraphicsManager->Init(shaderPath) == false) + m_graphicsManager = new RenderGL::GraphicsManager(); + if (m_graphicsManager->Init(shaderPath) == false) { MCore::LogError("Could not initialize OpenGL graphics manager."); return false; } // set the render util in the base render plugin - mRenderUtil = mGraphicsManager->GetRenderUtil(); + m_renderUtil = m_graphicsManager->GetRenderUtil(); // initialize all already existing actors and actor instances ReInit(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.h index b75a4df24b..1203d7e381 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/OpenGLRenderPlugin.h @@ -51,10 +51,10 @@ namespace EMStudio // OpenGL engine helper functions bool InitializeGraphicsManager(); - MCORE_INLINE RenderGL::GraphicsManager* GetGraphicsManager() { return mGraphicsManager; } + MCORE_INLINE RenderGL::GraphicsManager* GetGraphicsManager() { return m_graphicsManager; } private: - RenderGL::GraphicsManager* mGraphicsManager; // shared OpenGL engine object + RenderGL::GraphicsManager* m_graphicsManager; // shared OpenGL engine object // overloaded emstudio actor create function which creates an OpenGL render actor internally bool CreateEMStudioActor(EMotionFX::Actor* actor); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.cpp index 0d36f19c5a..2715a0a0fe 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.cpp @@ -21,13 +21,13 @@ namespace EMStudio ActionHistoryCallback::ActionHistoryCallback(QListWidget* list) : MCore::CommandManagerCallback() { - mList = list; - mIndex = 0; - mIsRemoving = false; - mGroupExecuting = false; - mExecutedGroup = nullptr; - mNumGroupCommands = 0; - mCurrentCommandIndex = 0; + m_list = list; + m_index = 0; + m_isRemoving = false; + m_groupExecuting = false; + m_executedGroup = nullptr; + m_numGroupCommands = 0; + m_currentCommandIndex = 0; m_darkenedBrush.setColor(QColor(110, 110, 110)); m_brush.setColor(QColor(200, 200, 200)); } @@ -41,16 +41,16 @@ namespace EMStudio { if (MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG) { - mTempString = command->GetName(); - const uint32 numParameters = commandLine.GetNumParameters(); - for (uint32 i = 0; i < numParameters; ++i) + m_tempString = command->GetName(); + const size_t numParameters = commandLine.GetNumParameters(); + for (size_t i = 0; i < numParameters; ++i) { - mTempString += " -"; - mTempString += commandLine.GetParameterName(i); - mTempString += " "; - mTempString += commandLine.GetParameterValue(i); + m_tempString += " -"; + m_tempString += commandLine.GetParameterName(i); + m_tempString += " "; + m_tempString += commandLine.GetParameterValue(i); } - MCore::LogDebugMsg(mTempString.c_str()); + MCore::LogDebugMsg(m_tempString.c_str()); } } } @@ -61,123 +61,123 @@ namespace EMStudio MCORE_UNUSED(group); MCORE_UNUSED(commandLine); MCORE_UNUSED(outResult); - if (mGroupExecuting && mExecutedGroup) + if (m_groupExecuting && m_executedGroup) { - mCurrentCommandIndex++; - if (mCurrentCommandIndex % 32 == 0) + m_currentCommandIndex++; + if (m_currentCommandIndex % 32 == 0) { - EMotionFX::GetEventManager().OnProgressValue(((float)mCurrentCommandIndex / (mNumGroupCommands + 1)) * 100.0f); + EMotionFX::GetEventManager().OnProgressValue(((float)m_currentCommandIndex / (m_numGroupCommands + 1)) * 100.0f); } } if (command && MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG) { - mTempString = AZStd::string::format("%sExecution of command '%s' %s", wasSuccess ? " " : "*** ", command->GetName(), wasSuccess ? "completed successfully" : " FAILED"); - MCore::LogDebugMsg(mTempString.c_str()); + m_tempString = AZStd::string::format("%sExecution of command '%s' %s", wasSuccess ? " " : "*** ", command->GetName(), wasSuccess ? "completed successfully" : " FAILED"); + MCore::LogDebugMsg(m_tempString.c_str()); } } // Before executing a command group. void ActionHistoryCallback::OnPreExecuteCommandGroup(MCore::CommandGroup* group, bool undo) { - if (!mGroupExecuting && group->GetNumCommands() > 64) + if (!m_groupExecuting && group->GetNumCommands() > 64) { - mGroupExecuting = true; - mExecutedGroup = group; - mCurrentCommandIndex = 0; - mNumGroupCommands = group->GetNumCommands(); + m_groupExecuting = true; + m_executedGroup = group; + m_currentCommandIndex = 0; + m_numGroupCommands = group->GetNumCommands(); GetManager()->SetAvoidRendering(true); EMotionFX::GetEventManager().OnProgressStart(); - mTempString = AZStd::string::format("%s%s", undo ? "Undo: " : "", group->GetGroupName()); - EMotionFX::GetEventManager().OnProgressText(mTempString.c_str()); + m_tempString = AZStd::string::format("%s%s", undo ? "Undo: " : "", group->GetGroupName()); + EMotionFX::GetEventManager().OnProgressText(m_tempString.c_str()); } if (group && MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG) { - mTempString = AZStd::string::format("Starting %s of command group '%s'", undo ? "undo" : "execution", group->GetGroupName()); - MCore::LogDebugMsg(mTempString.c_str()); + m_tempString = AZStd::string::format("Starting %s of command group '%s'", undo ? "undo" : "execution", group->GetGroupName()); + MCore::LogDebugMsg(m_tempString.c_str()); } } // After executing a command group. void ActionHistoryCallback::OnPostExecuteCommandGroup(MCore::CommandGroup* group, bool wasSuccess) { - if (mExecutedGroup == group) + if (m_executedGroup == group) { EMotionFX::GetEventManager().OnProgressEnd(); - mGroupExecuting = false; - mExecutedGroup = nullptr; - mNumGroupCommands = 0; - mCurrentCommandIndex = 0; + m_groupExecuting = false; + m_executedGroup = nullptr; + m_numGroupCommands = 0; + m_currentCommandIndex = 0; GetManager()->SetAvoidRendering(false); } if (group && MCore::GetLogManager().GetLogLevels() & MCore::LogCallback::LOGLEVEL_DEBUG) { - mTempString = AZStd::string::format("%sExecution of command group '%s' %s", wasSuccess ? " " : "*** ", group->GetGroupName(), wasSuccess ? "completed successfully" : " FAILED"); - MCore::LogDebugMsg(mTempString.c_str()); + m_tempString = AZStd::string::format("%sExecution of command group '%s' %s", wasSuccess ? " " : "*** ", group->GetGroupName(), wasSuccess ? "completed successfully" : " FAILED"); + MCore::LogDebugMsg(m_tempString.c_str()); } } // Add a new item to the history. - void ActionHistoryCallback::OnAddCommandToHistory(uint32 historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) + void ActionHistoryCallback::OnAddCommandToHistory(size_t historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) { MCORE_UNUSED(commandLine); - mTempString = MCore::CommandManager::CommandHistoryEntry::ToString(group, command, mIndex++).c_str(); + m_tempString = MCore::CommandManager::CommandHistoryEntry::ToString(group, command, m_index++).c_str(); - mList->insertItem(historyIndex, new QListWidgetItem(mTempString.c_str(), mList)); - mList->setCurrentRow(historyIndex); + m_list->insertItem(aznumeric_caster(historyIndex), new QListWidgetItem(m_tempString.c_str(), m_list)); + m_list->setCurrentRow(aznumeric_caster(historyIndex)); } // Remove an item from the history. - void ActionHistoryCallback::OnRemoveCommand(uint32 historyIndex) + void ActionHistoryCallback::OnRemoveCommand(size_t historyIndex) { // Remove the item. - mIsRemoving = true; - delete mList->takeItem(historyIndex); - mIsRemoving = false; + m_isRemoving = true; + delete m_list->takeItem(aznumeric_caster(historyIndex)); + m_isRemoving = false; } // Set the current command. - void ActionHistoryCallback::OnSetCurrentCommand(uint32 index) + void ActionHistoryCallback::OnSetCurrentCommand(size_t index) { - if (mIsRemoving) + if (m_isRemoving) { return; } - if (index == MCORE_INVALIDINDEX32) + if (index == InvalidIndex) { - mList->setCurrentRow(-1); + m_list->setCurrentRow(-1); // Darken all history items. - const int numCommands = static_cast(GetCommandManager()->GetNumHistoryItems()); + const int numCommands = m_list->count(); for (int i = 0; i < numCommands; ++i) { - mList->item(i)->setForeground(m_darkenedBrush); + m_list->item(i)->setForeground(m_darkenedBrush); } return; } // get the list of selected items - mList->setCurrentRow(index); + m_list->setCurrentRow(aznumeric_caster(index)); // Get the current history index. - const uint32 historyIndex = GetCommandManager()->GetHistoryIndex(); - if (historyIndex == MCORE_INVALIDINDEX32) + const size_t historyIndex = GetCommandManager()->GetHistoryIndex(); + if (historyIndex == InvalidIndex) { AZStd::string outResult; - const uint32 numRedos = index + 1; - for (uint32 i = 0; i < numRedos; ++i) + const size_t numRedos = index + 1; + for (size_t i = 0; i < numRedos; ++i) { outResult.clear(); const bool result = GetCommandManager()->Redo(outResult); - if (outResult.size() > 0) + if (!outResult.empty()) { if (!result) { @@ -189,13 +189,13 @@ namespace EMStudio else if (historyIndex > index) // if we need to perform undo's { AZStd::string outResult; - const int32 numUndos = historyIndex - index; - for (int32 i = 0; i < numUndos; ++i) + const ptrdiff_t numUndos = historyIndex - index; + for (ptrdiff_t i = 0; i < numUndos; ++i) { // try to undo outResult.clear(); const bool result = GetCommandManager()->Undo(outResult); - if (outResult.size() > 0) + if (!outResult.empty()) { if (!result) { @@ -207,12 +207,12 @@ namespace EMStudio else if (historyIndex < index) // if we need to redo commands { AZStd::string outResult; - const int32 numRedos = index - historyIndex; - for (int32 i = 0; i < numRedos; ++i) + const ptrdiff_t numRedos = index - historyIndex; + for (ptrdiff_t i = 0; i < numRedos; ++i) { outResult.clear(); const bool result = GetCommandManager()->Redo(outResult); - if (outResult.size() > 0) + if (!outResult.empty()) { if (!result) { @@ -222,26 +222,16 @@ namespace EMStudio } } - // Darken disabled commands. - const uint32 orgIndex = index; - if (index == MCORE_INVALIDINDEX32) - { - index = 0; - } - const int numCommands = static_cast(GetCommandManager()->GetNumHistoryItems()); - for (int i = index; i < numCommands; ++i) + for (int i = aznumeric_caster(index); i < numCommands; ++i) { - mList->item(i)->setForeground(m_darkenedBrush); + m_list->item(i)->setForeground(m_darkenedBrush); } // Color enabled ones. - if (orgIndex != MCORE_INVALIDINDEX32) + for (int i = 0; i <= static_cast(index); ++i) { - for (int i = 0; i <= static_cast(index); ++i) - { - mList->item(index)->setForeground(m_brush); - } + m_list->item(i)->setForeground(m_brush); } } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.h index ba7c5314b1..621ed8ecff 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryCallback.h @@ -37,22 +37,22 @@ namespace EMStudio void OnPreExecuteCommand(MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) override; void OnPostExecuteCommand(MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine, bool wasSuccess, const AZStd::string& outResult) override; - void OnAddCommandToHistory(uint32 historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) override; + void OnAddCommandToHistory(size_t historyIndex, MCore::CommandGroup* group, MCore::Command* command, const MCore::CommandLine& commandLine) override; void OnPreExecuteCommandGroup(MCore::CommandGroup* group, bool undo) override; void OnPostExecuteCommandGroup(MCore::CommandGroup* group, bool wasSuccess) override; - void OnRemoveCommand(uint32 historyIndex) override; - void OnSetCurrentCommand(uint32 index) override; + void OnRemoveCommand(size_t historyIndex) override; + void OnSetCurrentCommand(size_t index) override; private: - QListWidget* mList; - AZStd::string mTempString; - uint32 mIndex; - bool mIsRemoving; - - bool mGroupExecuting; - MCore::CommandGroup* mExecutedGroup; - size_t mNumGroupCommands; - uint32 mCurrentCommandIndex; + QListWidget* m_list; + AZStd::string m_tempString; + uint32 m_index; + bool m_isRemoving; + + bool m_groupExecuting; + MCore::CommandGroup* m_executedGroup; + size_t m_numGroupCommands; + uint32 m_currentCommandIndex; QBrush m_brush; QBrush m_darkenedBrush; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp index 6a80fec548..d84bbebbc6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.cpp @@ -18,20 +18,20 @@ namespace EMStudio ActionHistoryPlugin::ActionHistoryPlugin() : EMStudio::DockWidgetPlugin() { - mCallback = nullptr; - mList = nullptr; + m_callback = nullptr; + m_list = nullptr; } ActionHistoryPlugin::~ActionHistoryPlugin() { - if (mCallback) + if (m_callback) { - EMStudio::GetCommandManager()->RemoveCallback(mCallback, false); - delete mCallback; + EMStudio::GetCommandManager()->RemoveCallback(m_callback, false); + delete m_callback; } - delete mList; + delete m_list; } @@ -75,22 +75,22 @@ namespace EMStudio // Init after the parent dock window has been created. bool ActionHistoryPlugin::Init() { - mList = new QListWidget(mDock); + m_list = new QListWidget(m_dock); - mList->setFlow(QListView::TopToBottom); - mList->setMovement(QListView::Static); - mList->setViewMode(QListView::ListMode); - mList->setSelectionRectVisible(true); - mList->setSelectionBehavior(QAbstractItemView::SelectRows); - mList->setSelectionMode(QAbstractItemView::SingleSelection); - mDock->setWidget(mList); + m_list->setFlow(QListView::TopToBottom); + m_list->setMovement(QListView::Static); + m_list->setViewMode(QListView::ListMode); + m_list->setSelectionRectVisible(true); + m_list->setSelectionBehavior(QAbstractItemView::SelectRows); + m_list->setSelectionMode(QAbstractItemView::SingleSelection); + m_dock->setWidget(m_list); // Detect item selection changes. - connect(mList, &QListWidget::itemSelectionChanged, this, &ActionHistoryPlugin::OnSelectedItemChanged); + connect(m_list, &QListWidget::itemSelectionChanged, this, &ActionHistoryPlugin::OnSelectedItemChanged); // Register the callback. - mCallback = new ActionHistoryCallback(mList); - EMStudio::GetCommandManager()->RegisterCallback(mCallback); + m_callback = new ActionHistoryCallback(m_list); + EMStudio::GetCommandManager()->RegisterCallback(m_callback); // Sync the interface with the actual command history. ReInit(); @@ -109,12 +109,12 @@ namespace EMStudio { const MCore::CommandManager::CommandHistoryEntry& historyItem = commandManager->GetHistoryItem(i); - historyItemString = MCore::CommandManager::CommandHistoryEntry::ToString(historyItem.mCommandGroup, historyItem.mExecutedCommand, historyItem.m_historyItemNr); - mList->addItem(new QListWidgetItem(historyItemString.c_str(), mList)); + historyItemString = MCore::CommandManager::CommandHistoryEntry::ToString(historyItem.m_commandGroup, historyItem.m_executedCommand, historyItem.m_historyItemNr); + m_list->addItem(new QListWidgetItem(historyItemString.c_str(), m_list)); } // Set the current history index in case the user called undo. - mList->setCurrentRow(commandManager->GetHistoryIndex()); + m_list->setCurrentRow(commandManager->GetHistoryIndex()); } @@ -122,17 +122,17 @@ namespace EMStudio void ActionHistoryPlugin::OnSelectedItemChanged() { // Get the list of selected items and make sure exactly one is selected. - QList selected = mList->selectedItems(); + QList selected = m_list->selectedItems(); if (selected.count() != 1) { return; } // Get the selected item and its index (row number in the list). - const uint32 index = mList->row(selected.at(0)); + const uint32 index = m_list->row(selected.at(0)); // Change the command index. - mCallback->OnSetCurrentCommand(index); + m_callback->OnSetCurrentCommand(index); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.h index a9bff7780b..550e6628e3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/ActionHistory/ActionHistoryPlugin.h @@ -51,7 +51,7 @@ namespace EMStudio void OnSelectedItemChanged(); private: - QListWidget* mList; - ActionHistoryCallback* mCallback; + QListWidget* m_list; + ActionHistoryCallback* m_callback; }; } // namespace EMStudio 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 f545873106..5e33659056 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 @@ -206,12 +206,12 @@ namespace EMStudio // If found motion entry, add select and play motion command strings to command group. EMotionFX::Motion* motion = motionEntry->GetMotion(); EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo(); - defaultPlayBackInfo->mBlendInTime = 0.0f; - defaultPlayBackInfo->mBlendOutTime = 0.0f; + defaultPlayBackInfo->m_blendInTime = 0.0f; + defaultPlayBackInfo->m_blendOutTime = 0.0f; commandParameters = CommandSystem::CommandPlayMotion::PlayBackInfoToCommandParameters(defaultPlayBackInfo); - const AZ::u32 motionIndex = EMotionFX::GetMotionManager().FindMotionIndexByName(motion->GetName()); - commandString = AZStd::string::format("Select -motionIndex %d", motionIndex); + const size_t motionIndex = EMotionFX::GetMotionManager().FindMotionIndexByName(motion->GetName()); + commandString = AZStd::string::format("Select -motionIndex %zu", motionIndex); commandGroup.AddCommandString(commandString); commandString = AZStd::string::format("PlayMotion -filename \"%s\" %s", motion->GetFileName(), commandParameters.c_str()); @@ -472,8 +472,8 @@ namespace EMStudio const EMotionFX::MotionManager& motionManager = EMotionFX::GetMotionManager(); // In case no motion set was selected yet, use the first available. The activate graph callback will update the UI. - const AZ::u32 numMotionSets = motionManager.GetNumMotionSets(); - for (AZ::u32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = motionManager.GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* currentMotionSet = motionManager.GetMotionSet(i); if (!currentMotionSet->GetIsOwnedByRuntime()) @@ -494,7 +494,7 @@ namespace EMStudio void AnimGraphActionManager::ActivateGraphForSelectedActors(EMotionFX::AnimGraph* animGraph, EMotionFX::MotionSet* motionSet) { const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); if (numActorInstances == 0) { @@ -507,7 +507,7 @@ namespace EMStudio commandGroup.AddCommandString("RecorderClear -force true"); // Activate the anim graph each selected actor instance. - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); if (actorInstance->GetIsOwnedByRuntime()) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.cpp index f02c8ed0bf..96bc39e29c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.cpp @@ -26,8 +26,8 @@ namespace EMotionFX { - const int AnimGraphEditor::m_propertyLabelWidth = 120; - QString AnimGraphEditor::m_lastMotionSetText = ""; + const int AnimGraphEditor::s_propertyLabelWidth = 120; + QString AnimGraphEditor::s_lastMotionSetText = ""; AnimGraphEditor::AnimGraphEditor(EMotionFX::AnimGraph* animGraph, AZ::SerializeContext* serializeContext, QWidget* parent) : QWidget(parent) @@ -64,7 +64,7 @@ namespace EMotionFX m_propertyEditor = aznew AzToolsFramework::ReflectedPropertyEditor(this); m_propertyEditor->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); m_propertyEditor->setObjectName("PropertyEditor"); - m_propertyEditor->Setup(serializeContext, nullptr, false/*enableScrollbars*/, m_propertyLabelWidth); + m_propertyEditor->Setup(serializeContext, nullptr, false/*enableScrollbars*/, s_propertyLabelWidth); m_propertyEditor->SetSizeHintOffset(QSize(0, 0)); m_propertyEditor->SetAutoResizeLabels(false); m_propertyEditor->SetLeafIndentation(0); @@ -86,9 +86,9 @@ namespace EMotionFX m_motionSetComboBox = new QComboBox(); m_motionSetComboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); //initializes to last selection if it is there - if (!m_lastMotionSetText.isEmpty()) + if (!s_lastMotionSetText.isEmpty()) { - m_motionSetComboBox->addItem(m_lastMotionSetText); + m_motionSetComboBox->addItem(s_lastMotionSetText); m_motionSetComboBox->setCurrentIndex(0); } connect(m_motionSetComboBox, static_cast(&QComboBox::currentIndexChanged), this, &AnimGraphEditor::OnMotionSetChanged); @@ -125,7 +125,7 @@ namespace EMotionFX EMotionFX::MotionSet* AnimGraphEditor::GetSelectedMotionSet() { - const AZ::Outcome motionSetIndex = GetMotionSetIndex(m_motionSetComboBox->currentIndex()); + const AZ::Outcome motionSetIndex = GetMotionSetIndex(m_motionSetComboBox->currentIndex()); if (motionSetIndex.IsSuccess()) { return EMotionFX::GetMotionManager().GetMotionSet(motionSetIndex.GetValue()); @@ -149,8 +149,8 @@ namespace EMotionFX m_motionSetComboBox->clear(); // add each motion set name - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); if (motionSet->GetIsOwnedByRuntime()) @@ -163,7 +163,7 @@ namespace EMotionFX // get the current selection list and the number of actor instances selected const CommandSystem::SelectionList& selectionList = CommandSystem::GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); // if actor instances are selected, set the used motion set if (numActorInstances > 0) @@ -172,7 +172,7 @@ namespace EMotionFX // this is used to check if multiple motion sets are used AZStd::vector usedMotionSets; AZStd::vector usedAnimGraphs; - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); if (actorInstance->GetIsOwnedByRuntime()) @@ -301,16 +301,16 @@ namespace EMotionFX { // get the current selection list and the number of actor instances selected const CommandSystem::SelectionList& selectionList = CommandSystem::GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); - AnimGraphEditor::m_lastMotionSetText = m_motionSetComboBox->itemText(index); + AnimGraphEditor::s_lastMotionSetText = m_motionSetComboBox->itemText(index); // if no one actor instance is selected, the combo box has no effect if (numActorInstances == 0) { return; } - const AZ::Outcome motionSetIndex = GetMotionSetIndex(index); + const AZ::Outcome motionSetIndex = GetMotionSetIndex(index); EMotionFX::MotionSet* motionSet = nullptr; if (motionSetIndex.IsSuccess()) @@ -323,7 +323,7 @@ namespace EMotionFX // update the motion set on each actor instance if one anim graph is activated AZStd::string commandString; - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { // get the actor instance from the selection list and the anim graph instance EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); @@ -401,12 +401,12 @@ namespace EMotionFX } } - AZ::Outcome AnimGraphEditor::GetMotionSetIndex(int comboBoxIndex) const + AZ::Outcome AnimGraphEditor::GetMotionSetIndex(int comboBoxIndex) const { - const uint32 targetEditorMotionSetIndex = comboBoxIndex; - uint32 currentEditorMotionSet = 0; - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t targetEditorMotionSetIndex = comboBoxIndex; + size_t currentEditorMotionSet = 0; + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { const EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.h index be1e3745a9..836bc8f8ad 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphEditor.h @@ -51,16 +51,16 @@ namespace EMotionFX void OnMotionSetChanged(int index); private: - AZ::Outcome GetMotionSetIndex(int comboBoxIndex) const; + AZ::Outcome GetMotionSetIndex(int comboBoxIndex) const; MCORE_DEFINECOMMANDCALLBACK(UpdateMotionSetComboBoxCallback) AnimGraph* m_animGraph; QLabel* m_filenameLabel; AzToolsFramework::ReflectedPropertyEditor* m_propertyEditor; - static const int m_propertyLabelWidth; + static const int s_propertyLabelWidth; QComboBox* m_motionSetComboBox; - static QString m_lastMotionSetText; + static QString s_lastMotionSetText; AZStd::vector m_commandCallbacks; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphHierarchyWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphHierarchyWidget.h index c10320a794..586f419292 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphHierarchyWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphHierarchyWidget.h @@ -34,12 +34,12 @@ namespace CommandSystem struct AnimGraphSelectionItem { AnimGraphSelectionItem(uint32 animGraphID, const AZStd::string& nodeName) - : mAnimGraphID(animGraphID) - , mNodeName(nodeName) + : m_animGraphId(animGraphID) + , m_nodeName(nodeName) {} - uint32 mAnimGraphID; - AZStd::string mNodeName; + uint32 m_animGraphId; + AZStd::string m_nodeName; }; namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp index 36b915a5ce..6e68a761de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModel.cpp @@ -152,8 +152,8 @@ namespace EMStudio // Since the UI could be loaded after anim graphs are added to the manager, we need to pull all the current ones // and add them to the model - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (!animGraph->GetIsOwnedByRuntime() && !animGraph->GetIsOwnedByAsset()) @@ -906,7 +906,7 @@ namespace EMStudio EMotionFX::AnimGraphInstance* animGraphInstance = modelItemData->m_animGraphInstance; EMotionFX::AnimGraphStateMachine* rootStateMachine = referencedAnimGraph->GetRootStateMachine(); - const uint32 rowCount = rootStateMachine->GetNumConnections() + rootStateMachine->GetNumChildNodes() + static_cast(rootStateMachine->GetNumTransitions()); + const int rowCount = aznumeric_caster(rootStateMachine->GetNumConnections() + rootStateMachine->GetNumChildNodes() + rootStateMachine->GetNumTransitions()); if (rowCount > 0) { const QModelIndex referenceNodeModelIndex = createIndex(modelItemData->m_row, 0, modelItemData); @@ -977,15 +977,15 @@ namespace EMStudio } int childRow = 0; - const uint32 connectionCount = node->GetNumConnections(); - for (uint32 i = 0; i < connectionCount; ++i) + const int connectionCount = aznumeric_caster(node->GetNumConnections()); + for (int i = 0; i < connectionCount; ++i) { m_modelItemDataSet.emplace(new ModelItemData(node->GetConnection(i), animGraphInstance, currentModelItemData, childRow + i)); } childRow += connectionCount; - const uint32 childNodeCount = node->GetNumChildNodes(); - for (uint32 i = 0; i < childNodeCount; ++i) + const int childNodeCount = aznumeric_caster(node->GetNumChildNodes()); + for (int i = 0; i < childNodeCount; ++i) { RecursivelyAddNode(animGraphInstance, node->GetChildNode(i), currentModelItemData, childRow + i); } @@ -995,12 +995,12 @@ namespace EMStudio if (nodeTypeId == azrtti_typeid()) { EMotionFX::AnimGraphStateMachine* stateMachine = static_cast(node); - const size_t childTransitionCount = stateMachine->GetNumTransitions(); - for (size_t i = 0; i < childTransitionCount; ++i) + const int childTransitionCount = aznumeric_caster(stateMachine->GetNumTransitions()); + for (int i = 0; i < childTransitionCount; ++i) { - AddTransition(animGraphInstance, stateMachine->GetTransition(i), currentModelItemData, childRow + static_cast(i)); + AddTransition(animGraphInstance, stateMachine->GetTransition(i), currentModelItemData, childRow + i); } - childRow += static_cast(childTransitionCount); + childRow += childTransitionCount; } else if (nodeTypeId == azrtti_typeid()) { @@ -1023,26 +1023,26 @@ namespace EMStudio EMotionFX::AnimGraphStateMachine* rootStateMachine = referencedAnimGraph->GetRootStateMachine(); EMotionFX::AnimGraphInstance* referencedAnimGraphInstance = referenceNode->GetReferencedAnimGraphInstance(animGraphInstance); - const uint32 rootConnectionCount = rootStateMachine->GetNumConnections(); - for (uint32 i = 0; i < rootConnectionCount; ++i) + const int rootConnectionCount = aznumeric_caster(rootStateMachine->GetNumConnections()); + for (int i = 0; i < rootConnectionCount; ++i) { m_modelItemDataSet.emplace(new ModelItemData(rootStateMachine->GetConnection(i), referencedAnimGraphInstance, referenceNodeModelItemData, row + i)); } row += rootConnectionCount; - const uint32 rootChildNodeCount = rootStateMachine->GetNumChildNodes(); - for (uint32 i = 0; i < rootChildNodeCount; ++i) + const int rootChildNodeCount = aznumeric_caster(rootStateMachine->GetNumChildNodes()); + for (int i = 0; i < rootChildNodeCount; ++i) { RecursivelyAddNode(referencedAnimGraphInstance, rootStateMachine->GetChildNode(i), referenceNodeModelItemData, row + i); } row += rootChildNodeCount; - const size_t rootChildTransitionCount = rootStateMachine->GetNumTransitions(); - for (size_t i = 0; i < rootChildTransitionCount; ++i) + const int rootChildTransitionCount = aznumeric_caster(rootStateMachine->GetNumTransitions()); + for (int i = 0; i < rootChildTransitionCount; ++i) { - AddTransition(referencedAnimGraphInstance, rootStateMachine->GetTransition(i), referenceNodeModelItemData, row + static_cast(i)); + AddTransition(referencedAnimGraphInstance, rootStateMachine->GetTransition(i), referenceNodeModelItemData, row + i); } - row += static_cast(rootChildTransitionCount); + row += rootChildTransitionCount; // Now we add the "alias" item ModelItemData* rootStateMachineItem = new ModelItemData(rootStateMachine, referencedAnimGraphInstance, nullptr, referenceNodeModelItemData->m_row); @@ -1424,8 +1424,8 @@ namespace EMStudio { AZStd::vector motionNodes; - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModelCallbacks.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModelCallbacks.cpp index 9ff47bb1fe..c7dc9304d9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModelCallbacks.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphModelCallbacks.cpp @@ -29,7 +29,7 @@ namespace EMStudio { CommandSystem::CommandLoadAnimGraph* commandLoadAnimGraph = static_cast(command); - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandLoadAnimGraph->mOldAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandLoadAnimGraph->m_oldAnimGraphId); if (animGraph) { m_animGraphModel.Add(animGraph); @@ -55,7 +55,7 @@ namespace EMStudio { CommandSystem::CommandCreateAnimGraph* commandCreateAnimGraph = static_cast(command); - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandCreateAnimGraph->mPreviouslyUsedID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandCreateAnimGraph->m_previouslyUsedId); m_animGraphModel.Add(animGraph); EMotionFX::AnimGraphStateMachine* rootStateMachine = animGraph->GetRootStateMachine(); @@ -164,7 +164,7 @@ namespace EMStudio bool AnimGraphModel::CommandDidActivateAnimGraphPostUndoCallback::Undo(MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine) { CommandSystem::CommandActivateAnimGraph* commandActivateAnimGraph = static_cast(command); - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(commandActivateAnimGraph->mActorInstanceID); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(commandActivateAnimGraph->m_actorInstanceId); if (actorInstance) { @@ -181,14 +181,14 @@ namespace EMStudio bool AnimGraphModel::CommandDidActivateAnimGraphCallback::Execute(MCore::Command* command, [[maybe_unused]] const MCore::CommandLine& commandLine) { CommandSystem::CommandActivateAnimGraph* commandActivateAnimGraph = static_cast(command); - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(commandActivateAnimGraph->mActorInstanceID); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(commandActivateAnimGraph->m_actorInstanceId); if (actorInstance) { EMotionFX::AnimGraphInstance* currentAnimGraphInstance = actorInstance->GetAnimGraphInstance(); EMotionFX::AnimGraph* currentAnimGraph = currentAnimGraphInstance->GetAnimGraph(); EMotionFX::AnimGraph* oldAnimGraph = nullptr; - oldAnimGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandActivateAnimGraph->mOldAnimGraphUsed); + oldAnimGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandActivateAnimGraph->m_oldAnimGraphUsed); if (currentAnimGraphInstance) { @@ -209,7 +209,7 @@ namespace EMStudio bool AnimGraphModel::CommandDidActivateAnimGraphCallback::Undo(MCore::Command* command, const MCore::CommandLine& commandLine) { CommandSystem::CommandActivateAnimGraph* commandActivateAnimGraph = static_cast(command); - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(commandActivateAnimGraph->mActorInstanceID); + EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(commandActivateAnimGraph->m_actorInstanceId); // TODO: do this better, we need to find the animgraphinstance that we are undoing after the undo finishes if (actorInstance) @@ -254,7 +254,7 @@ namespace EMStudio } CommandSystem::CommandAnimGraphCreateNode* commandCreateNode = static_cast(command); - EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(commandCreateNode->mNodeId); + EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(commandCreateNode->m_nodeId); return m_animGraphModel.NodeAdded(node); } @@ -393,7 +393,7 @@ namespace EMStudio { // In this case is a BlendTreeConnection, we dont keep items in the model for it. We just // need to mark the target node as changed - EMotionFX::BlendTreeConnection* connection = targetNode->FindConnection(commandCreateConnection->GetTargetPort()); + EMotionFX::BlendTreeConnection* connection = targetNode->FindConnection(aznumeric_caster(commandCreateConnection->GetTargetPort())); return m_animGraphModel.ConnectionAdded(targetNode, connection); } else @@ -656,10 +656,10 @@ namespace EMStudio { CommandSystem::CommandAnimGraphSetEntryState* commandSetEntryState = static_cast(command); - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandSetEntryState->mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(commandSetEntryState->m_animGraphId); if (animGraph) { - EMotionFX::AnimGraphNode* entryNode = animGraph->RecursiveFindNodeById(commandSetEntryState->mOldEntryStateNodeId); + EMotionFX::AnimGraphNode* entryNode = animGraph->RecursiveFindNodeById(commandSetEntryState->m_oldEntryStateNodeId); if (entryNode) { static const QVector entryStateRole = { AnimGraphModel::ROLE_NODE_ENTRY_STATE }; 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 20d4b04acc..4baec366f0 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 @@ -112,8 +112,8 @@ namespace EMStudio void GetDirtyFileNames(AZStd::vector* outFileNames, AZStd::vector* outObjects) override { // get the number of anim graphs and iterate through them - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + for (size_t i = 0; i < numAnimGraphs; ++i) { // return in case we found a dirty file EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); @@ -130,7 +130,7 @@ namespace EMStudio // add the link to the actual object ObjectPointer objPointer; - objPointer.mAnimGraph = animGraph; + objPointer.m_animGraph = animGraph; outObjects->push_back(objPointer); } } @@ -147,17 +147,15 @@ namespace EMStudio return DirtyFileManager::FINISHED; } - const size_t numObjects = objects.size(); - for (size_t i = 0; i < numObjects; ++i) + for (const SaveDirtyFilesCallback::ObjectPointer& objPointer : objects) { // get the current object pointer and skip directly if the type check fails - ObjectPointer objPointer = objects[i]; - if (objPointer.mAnimGraph == nullptr) + if (objPointer.m_animGraph == nullptr) { continue; } - EMotionFX::AnimGraph* animGraph = objPointer.mAnimGraph; + EMotionFX::AnimGraph* animGraph = objPointer.m_animGraph; if (animGraphPlugin->SaveDirtyAnimGraph(animGraph, commandGroup, false) == DirtyFileManager::CANCELED) { return DirtyFileManager::CANCELED; @@ -179,33 +177,32 @@ namespace EMStudio // constructor AnimGraphPlugin::AnimGraphPlugin() : EMStudio::DockWidgetPlugin() - , mEventHandler(this) + , m_eventHandler(this) { - mGraphWidget = nullptr; - mNavigateWidget = nullptr; - mAttributeDock = nullptr; - mNodeGroupDock = nullptr; - mPaletteWidget = nullptr; - mNodePaletteDock = nullptr; - mParameterDock = nullptr; - mParameterWindow = nullptr; - mNodeGroupWindow = nullptr; - mAttributesWindow = nullptr; - mActiveAnimGraph = nullptr; + m_graphWidget = nullptr; + m_navigateWidget = nullptr; + m_attributeDock = nullptr; + m_nodeGroupDock = nullptr; + m_paletteWidget = nullptr; + m_nodePaletteDock = nullptr; + m_parameterDock = nullptr; + m_parameterWindow = nullptr; + m_nodeGroupWindow = nullptr; + m_attributesWindow = nullptr; + m_activeAnimGraph = nullptr; m_animGraphObjectFactory = nullptr; - mGraphNodeFactory = nullptr; - mViewWidget = nullptr; - mDirtyFilesCallback = nullptr; + m_graphNodeFactory = nullptr; + m_viewWidget = nullptr; + m_dirtyFilesCallback = nullptr; m_navigationHistory = nullptr; - mDisplayFlags = 0; - // mShowProcessed = false; - mDisableRendering = false; - mLastPlayTime = -1; - mTotalTime = FLT_MAX; + m_displayFlags = 0; + m_disableRendering = false; + m_lastPlayTime = -1; + m_totalTime = FLT_MAX; #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - mGameControllerWindow = nullptr; - mGameControllerDock = nullptr; + m_gameControllerWindow = nullptr; + m_gameControllerDock = nullptr; #endif m_animGraphModel = nullptr; m_actionManager = nullptr; @@ -216,7 +213,7 @@ namespace EMStudio AnimGraphPlugin::~AnimGraphPlugin() { // destroy the event handler - EMotionFX::GetEventManager().RemoveEventHandler(&mEventHandler); + EMotionFX::GetEventManager().RemoveEventHandler(&m_eventHandler); // unregister the command callbacks and get rid of the memory for (MCore::Command::Callback* callback : m_commandCallbacks) @@ -225,48 +222,48 @@ namespace EMStudio } // remove the dirty file manager callback - GetMainWindow()->GetDirtyFileManager()->RemoveCallback(mDirtyFilesCallback, false); - delete mDirtyFilesCallback; + GetMainWindow()->GetDirtyFileManager()->RemoveCallback(m_dirtyFilesCallback, false); + delete m_dirtyFilesCallback; delete m_animGraphObjectFactory; // delete the graph node factory - delete mGraphNodeFactory; + delete m_graphNodeFactory; // remove the attribute dock widget - if (mParameterDock) + if (m_parameterDock) { - EMStudio::GetMainWindow()->removeDockWidget(mParameterDock); - delete mParameterDock; + EMStudio::GetMainWindow()->removeDockWidget(m_parameterDock); + delete m_parameterDock; } // remove the attribute dock widget - if (mAttributeDock) + if (m_attributeDock) { - EMStudio::GetMainWindow()->removeDockWidget(mAttributeDock); - delete mAttributeDock; + EMStudio::GetMainWindow()->removeDockWidget(m_attributeDock); + delete m_attributeDock; } // remove the node group dock widget - if (mNodeGroupDock) + if (m_nodeGroupDock) { - EMStudio::GetMainWindow()->removeDockWidget(mNodeGroupDock); - delete mNodeGroupDock; + EMStudio::GetMainWindow()->removeDockWidget(m_nodeGroupDock); + delete m_nodeGroupDock; } // remove the blend node palette - if (mNodePaletteDock) + if (m_nodePaletteDock) { - EMStudio::GetMainWindow()->removeDockWidget(mNodePaletteDock); - delete mNodePaletteDock; + EMStudio::GetMainWindow()->removeDockWidget(m_nodePaletteDock); + delete m_nodePaletteDock; } // remove the game controller dock #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (mGameControllerDock) + if (m_gameControllerDock) { - EMStudio::GetMainWindow()->removeDockWidget(mGameControllerDock); - delete mGameControllerDock; + EMStudio::GetMainWindow()->removeDockWidget(m_gameControllerDock); + delete m_gameControllerDock; } #endif if (m_navigationHistory) @@ -324,32 +321,32 @@ namespace EMStudio // During startup, plugins can be constructed more than once, so don't add connections for those items if (GetAttributeDock() != nullptr) { - mDockWindowActions[WINDOWS_PARAMETERWINDOW] = parent->addAction("Parameter Window"); - mDockWindowActions[WINDOWS_PARAMETERWINDOW]->setCheckable(true); - mDockWindowActions[WINDOWS_ATTRIBUTEWINDOW] = parent->addAction("Attribute Window"); - mDockWindowActions[WINDOWS_ATTRIBUTEWINDOW]->setCheckable(true); - mDockWindowActions[WINDOWS_NODEGROUPWINDOW] = parent->addAction("Node Group Window"); - mDockWindowActions[WINDOWS_NODEGROUPWINDOW]->setCheckable(true); - mDockWindowActions[WINDOWS_PALETTEWINDOW] = parent->addAction("Palette Window"); - mDockWindowActions[WINDOWS_PALETTEWINDOW]->setCheckable(true); + m_dockWindowActions[WINDOWS_PARAMETERWINDOW] = parent->addAction("Parameter Window"); + m_dockWindowActions[WINDOWS_PARAMETERWINDOW]->setCheckable(true); + m_dockWindowActions[WINDOWS_ATTRIBUTEWINDOW] = parent->addAction("Attribute Window"); + m_dockWindowActions[WINDOWS_ATTRIBUTEWINDOW]->setCheckable(true); + m_dockWindowActions[WINDOWS_NODEGROUPWINDOW] = parent->addAction("Node Group Window"); + m_dockWindowActions[WINDOWS_NODEGROUPWINDOW]->setCheckable(true); + m_dockWindowActions[WINDOWS_PALETTEWINDOW] = parent->addAction("Palette Window"); + m_dockWindowActions[WINDOWS_PALETTEWINDOW]->setCheckable(true); #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - mDockWindowActions[WINDOWS_GAMECONTROLLERWINDOW] = parent->addAction("Game Controller Window"); - mDockWindowActions[WINDOWS_GAMECONTROLLERWINDOW]->setCheckable(true); + m_dockWindowActions[WINDOWS_GAMECONTROLLERWINDOW] = parent->addAction("Game Controller Window"); + m_dockWindowActions[WINDOWS_GAMECONTROLLERWINDOW]->setCheckable(true); #endif - connect(mDockWindowActions[WINDOWS_PARAMETERWINDOW], &QAction::triggered, this, [this](bool checked) { + connect(m_dockWindowActions[WINDOWS_PARAMETERWINDOW], &QAction::triggered, this, [this](bool checked) { UpdateWindowVisibility(WINDOWS_PARAMETERWINDOW, checked); }); - connect(mDockWindowActions[WINDOWS_ATTRIBUTEWINDOW], &QAction::triggered, this, [this](bool checked) { + connect(m_dockWindowActions[WINDOWS_ATTRIBUTEWINDOW], &QAction::triggered, this, [this](bool checked) { UpdateWindowVisibility(WINDOWS_ATTRIBUTEWINDOW, checked); }); - connect(mDockWindowActions[WINDOWS_NODEGROUPWINDOW], &QAction::triggered, this, [this](bool checked) { + connect(m_dockWindowActions[WINDOWS_NODEGROUPWINDOW], &QAction::triggered, this, [this](bool checked) { UpdateWindowVisibility(WINDOWS_NODEGROUPWINDOW, checked); }); - connect(mDockWindowActions[WINDOWS_PALETTEWINDOW], &QAction::triggered, this, [this](bool checked) { + connect(m_dockWindowActions[WINDOWS_PALETTEWINDOW], &QAction::triggered, this, [this](bool checked) { UpdateWindowVisibility(WINDOWS_PALETTEWINDOW, checked); }); #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - connect(mDockWindowActions[WINDOWS_GAMECONTROLLERWINDOW], &QAction::triggered, this, [this](bool checked) { + connect(m_dockWindowActions[WINDOWS_GAMECONTROLLERWINDOW], &QAction::triggered, this, [this](bool checked) { UpdateWindowVisibility(WINDOWS_GAMECONTROLLERWINDOW, checked); }); #endif @@ -429,19 +426,17 @@ namespace EMStudio void AnimGraphPlugin::SetOptionFlag(EDockWindowOptionFlag option, bool isEnabled) { - const uint32 optionIndex = (uint32)option; - if (mDockWindowActions[optionIndex]) + if (m_dockWindowActions[option]) { - mDockWindowActions[optionIndex]->setChecked(isEnabled); + m_dockWindowActions[option]->setChecked(isEnabled); } } void AnimGraphPlugin::SetOptionEnabled(EDockWindowOptionFlag option, bool isEnabled) { - const uint32 optionIndex = (uint32)option; - if (mDockWindowActions[optionIndex]) + if (m_dockWindowActions[option]) { - mDockWindowActions[optionIndex]->setEnabled(isEnabled); + m_dockWindowActions[option]->setEnabled(isEnabled); } } @@ -478,18 +473,18 @@ namespace EMStudio void AnimGraphPlugin::RegisterPerFrameCallback(AnimGraphPerFrameCallback* callback) { - if (AZStd::find(mPerFrameCallbacks.begin(), mPerFrameCallbacks.end(), callback) == mPerFrameCallbacks.end()) + if (AZStd::find(m_perFrameCallbacks.begin(), m_perFrameCallbacks.end(), callback) == m_perFrameCallbacks.end()) { - mPerFrameCallbacks.push_back(callback); + m_perFrameCallbacks.push_back(callback); } } void AnimGraphPlugin::UnregisterPerFrameCallback(AnimGraphPerFrameCallback* callback) { - auto it = AZStd::find(mPerFrameCallbacks.begin(), mPerFrameCallbacks.end(), callback); - if (it != mPerFrameCallbacks.end()) + auto it = AZStd::find(m_perFrameCallbacks.begin(), m_perFrameCallbacks.end(), callback); + if (it != m_perFrameCallbacks.end()) { - mPerFrameCallbacks.erase(it); + m_perFrameCallbacks.erase(it); } } @@ -541,106 +536,102 @@ namespace EMStudio m_animGraphObjectFactory = aznew EMotionFX::AnimGraphObjectFactory(); // create the graph node factory - mGraphNodeFactory = new GraphNodeFactory(); + m_graphNodeFactory = new GraphNodeFactory(); // create the corresponding widget that holds the menu and the toolbar - mViewWidget = new BlendGraphViewWidget(this, mDock); - mDock->setWidget(mViewWidget); - //mDock->setWidget( mGraphWidget ); // old: without menu and toolbar + m_viewWidget = new BlendGraphViewWidget(this, m_dock); + m_dock->setWidget(m_viewWidget); // create the graph widget - mGraphWidget = new BlendGraphWidget(this, mViewWidget); - //mGraphWidget->resize(1000, 700); - //mGraphWidget->move(0,50); - //mGraphWidget->show(); + m_graphWidget = new BlendGraphWidget(this, m_viewWidget); // get the main window QMainWindow* mainWindow = GetMainWindow(); // create the attribute dock window - mAttributeDock = new AzQtComponents::StyledDockWidget("Attributes", mainWindow); - mainWindow->addDockWidget(Qt::RightDockWidgetArea, mAttributeDock); + m_attributeDock = new AzQtComponents::StyledDockWidget("Attributes", mainWindow); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, m_attributeDock); QDockWidget::DockWidgetFeatures features = QDockWidget::NoDockWidgetFeatures; //features |= QDockWidget::DockWidgetClosable; features |= QDockWidget::DockWidgetFloatable; features |= QDockWidget::DockWidgetMovable; - mAttributeDock->setFeatures(features); - mAttributeDock->setObjectName("AnimGraphPlugin::mAttributeDock"); - mAttributesWindow = new AttributesWindow(this); - mAttributeDock->setWidget(mAttributesWindow); + m_attributeDock->setFeatures(features); + m_attributeDock->setObjectName("AnimGraphPlugin::m_attributeDock"); + m_attributesWindow = new AttributesWindow(this); + m_attributeDock->setWidget(m_attributesWindow); // create the node group dock window - mNodeGroupDock = new AzQtComponents::StyledDockWidget("Node Groups", mainWindow); - mainWindow->addDockWidget(Qt::RightDockWidgetArea, mNodeGroupDock); + m_nodeGroupDock = new AzQtComponents::StyledDockWidget("Node Groups", mainWindow); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, m_nodeGroupDock); features = QDockWidget::NoDockWidgetFeatures; //features |= QDockWidget::DockWidgetClosable; features |= QDockWidget::DockWidgetFloatable; features |= QDockWidget::DockWidgetMovable; - mNodeGroupDock->setFeatures(features); - mNodeGroupDock->setObjectName("AnimGraphPlugin::mNodeGroupDock"); - mNodeGroupWindow = new NodeGroupWindow(this); - mNodeGroupDock->setWidget(mNodeGroupWindow); + m_nodeGroupDock->setFeatures(features); + m_nodeGroupDock->setObjectName("AnimGraphPlugin::m_nodeGroupDock"); + m_nodeGroupWindow = new NodeGroupWindow(this); + m_nodeGroupDock->setWidget(m_nodeGroupWindow); // create the node palette dock - mNodePaletteDock = new AzQtComponents::StyledDockWidget("Anim Graph Palette", mainWindow); - mainWindow->addDockWidget(Qt::RightDockWidgetArea, mNodePaletteDock); + m_nodePaletteDock = new AzQtComponents::StyledDockWidget("Anim Graph Palette", mainWindow); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, m_nodePaletteDock); features = QDockWidget::NoDockWidgetFeatures; //features |= QDockWidget::DockWidgetClosable; features |= QDockWidget::DockWidgetFloatable; features |= QDockWidget::DockWidgetMovable; - mNodePaletteDock->setFeatures(features); - mNodePaletteDock->setObjectName("AnimGraphPlugin::mPaletteDock"); - mPaletteWidget = new NodePaletteWidget(this); - mNodePaletteDock->setWidget(mPaletteWidget); + m_nodePaletteDock->setFeatures(features); + m_nodePaletteDock->setObjectName("AnimGraphPlugin::m_paletteDock"); + m_paletteWidget = new NodePaletteWidget(this); + m_nodePaletteDock->setWidget(m_paletteWidget); // create the parameter dock QScrollArea* scrollArea = new QScrollArea(); - mParameterDock = new AzQtComponents::StyledDockWidget("Parameters", mainWindow); - mainWindow->addDockWidget(Qt::RightDockWidgetArea, mParameterDock); + m_parameterDock = new AzQtComponents::StyledDockWidget("Parameters", mainWindow); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, m_parameterDock); features = QDockWidget::NoDockWidgetFeatures; //features |= QDockWidget::DockWidgetClosable; features |= QDockWidget::DockWidgetFloatable; features |= QDockWidget::DockWidgetMovable; - mParameterDock->setFeatures(features); - mParameterDock->setObjectName("AnimGraphPlugin::mParameterDock"); - mParameterWindow = new ParameterWindow(this); - mParameterDock->setWidget(scrollArea); - scrollArea->setWidget(mParameterWindow); + m_parameterDock->setFeatures(features); + m_parameterDock->setObjectName("AnimGraphPlugin::m_parameterDock"); + m_parameterWindow = new ParameterWindow(this); + m_parameterDock->setWidget(scrollArea); + scrollArea->setWidget(m_parameterWindow); scrollArea->setWidgetResizable(true); // Create Navigation Widget (embedded into BlendGraphViewWidget) - mNavigateWidget = new NavigateWidget(this); + m_navigateWidget = new NavigateWidget(this); // init the display flags - mDisplayFlags = 0; + m_displayFlags = 0; // init the view widget // it must be init after navigate widget is created because actions are linked to it - mViewWidget->Init(mGraphWidget); + m_viewWidget->Init(m_graphWidget); #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER // create the game controller dock - mGameControllerDock = new AzQtComponents::StyledDockWidget("Game Controller", mainWindow); - mainWindow->addDockWidget(Qt::RightDockWidgetArea, mGameControllerDock); + m_gameControllerDock = new AzQtComponents::StyledDockWidget("Game Controller", mainWindow); + mainWindow->addDockWidget(Qt::RightDockWidgetArea, m_gameControllerDock); features = QDockWidget::NoDockWidgetFeatures; //features |= QDockWidget::DockWidgetClosable; features |= QDockWidget::DockWidgetFloatable; features |= QDockWidget::DockWidgetMovable; - mGameControllerDock->setFeatures(features); - mGameControllerDock->setObjectName("AnimGraphPlugin::mGameControllerDock"); - mGameControllerWindow = new GameControllerWindow(this); - mGameControllerDock->setWidget(mGameControllerWindow); + m_gameControllerDock->setFeatures(features); + m_gameControllerDock->setObjectName("AnimGraphPlugin::m_gameControllerDock"); + m_gameControllerWindow = new GameControllerWindow(this); + m_gameControllerDock->setWidget(m_gameControllerWindow); #endif // load options LoadOptions(); // initialize the dirty files callback - mDirtyFilesCallback = new SaveDirtyAnimGraphFilesCallback(); - GetMainWindow()->GetDirtyFileManager()->AddCallback(mDirtyFilesCallback); + m_dirtyFilesCallback = new SaveDirtyAnimGraphFilesCallback(); + GetMainWindow()->GetDirtyFileManager()->AddCallback(m_dirtyFilesCallback); // construct the event handler - EMotionFX::GetEventManager().AddEventHandler(&mEventHandler); + EMotionFX::GetEventManager().AddEventHandler(&m_eventHandler); // connect to the timeline recorder data TimeViewPlugin* timeViewPlugin = FindTimeViewPlugin(); @@ -649,7 +640,7 @@ namespace EMStudio connect(timeViewPlugin, &TimeViewPlugin::DoubleClickedRecorderNodeHistoryItem, this, &AnimGraphPlugin::OnDoubleClickedRecorderNodeHistoryItem); connect(timeViewPlugin, &TimeViewPlugin::ClickedRecorderNodeHistoryItem, this, &AnimGraphPlugin::OnClickedRecorderNodeHistoryItem); // detect changes in the recorder - connect(timeViewPlugin, &TimeViewPlugin::RecorderStateChanged, mParameterWindow, &ParameterWindow::OnRecorderStateChanged); + connect(timeViewPlugin, &TimeViewPlugin::RecorderStateChanged, m_parameterWindow, &ParameterWindow::OnRecorderStateChanged); } EMotionFX::AnimGraph* firstSelectedAnimGraph = CommandSystem::GetCommandManager()->GetCurrentSelection().GetFirstAnimGraph(); @@ -662,14 +653,14 @@ namespace EMStudio void AnimGraphPlugin::LoadOptions() { QSettings settings(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioRenderOptions.cfg").c_str(), QSettings::IniFormat, this); - mOptions = AnimGraphOptions::Load(&settings); + m_options = AnimGraphOptions::Load(&settings); } // save the options void AnimGraphPlugin::SaveOptions() { QSettings settings(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioRenderOptions.cfg").c_str(), QSettings::IniFormat, this); - mOptions.Save(&settings); + m_options.Save(&settings); } @@ -677,9 +668,9 @@ namespace EMStudio void AnimGraphPlugin::OnAfterLoadLayout() { // fit graph on screen - if (mGraphWidget->GetActiveGraph()) + if (m_graphWidget->GetActiveGraph()) { - mGraphWidget->GetActiveGraph()->FitGraphOnScreen(mGraphWidget->geometry().width(), mGraphWidget->geometry().height(), mGraphWidget->GetMousePos(), false); + m_graphWidget->GetActiveGraph()->FitGraphOnScreen(m_graphWidget->geometry().width(), m_graphWidget->geometry().height(), m_graphWidget->GetMousePos(), false); } // connect to the timeline recorder data @@ -704,13 +695,13 @@ namespace EMStudio void AnimGraphPlugin::InitForAnimGraph(EMotionFX::AnimGraph* setup) { AZ_UNUSED(setup); - mAttributesWindow->Unlock(); - mAttributesWindow->Init(QModelIndex(), true); // Force update - mParameterWindow->Reinit(); - mNodeGroupWindow->Init(); - mViewWidget->UpdateAnimGraphOptions(); + m_attributesWindow->Unlock(); + m_attributesWindow->Init(QModelIndex(), true); // Force update + m_parameterWindow->Reinit(); + m_nodeGroupWindow->Init(); + m_viewWidget->UpdateAnimGraphOptions(); #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - mGameControllerWindow->ReInit(); + m_gameControllerWindow->ReInit(); #endif } @@ -719,13 +710,13 @@ namespace EMStudio AnimGraphEventHandler::AnimGraphEventHandler(AnimGraphPlugin* plugin) : EMotionFX::EventHandler() { - mPlugin = plugin; + m_plugin = plugin; } bool AnimGraphEventHandler::OnRayIntersectionTest(const AZ::Vector3& start, const AZ::Vector3& end, EMotionFX::IntersectionInfo* outIntersectInfo) { - outIntersectInfo->mIsValid = true; + outIntersectInfo->m_isValid = true; AZ::Vector3 pos; AZ::Vector3 normal; @@ -739,8 +730,8 @@ namespace EMStudio MCore::Ray ray(start, end); - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -749,7 +740,7 @@ namespace EMStudio continue; } - if (actorInstance == outIntersectInfo->mIgnoreActorInstance) + if (actorInstance == outIntersectInfo->m_ignoreActorInstance) { continue; } @@ -761,11 +752,11 @@ namespace EMStudio if (first) { - outIntersectInfo->mPosition = pos; - outIntersectInfo->mNormal = normal; - outIntersectInfo->mUV = uv; - outIntersectInfo->mBaryCentricU = baryU; - outIntersectInfo->mBaryCentricV = baryU; + outIntersectInfo->m_position = pos; + outIntersectInfo->m_normal = normal; + outIntersectInfo->m_uv = uv; + outIntersectInfo->m_baryCentricU = baryU; + outIntersectInfo->m_baryCentricV = baryU; closestDist = MCore::SafeLength(start - pos); } else @@ -773,11 +764,11 @@ namespace EMStudio float dist = MCore::SafeLength(start - pos); if (dist < closestDist) { - outIntersectInfo->mPosition = pos; - outIntersectInfo->mNormal = normal; - outIntersectInfo->mUV = uv; - outIntersectInfo->mBaryCentricU = baryU; - outIntersectInfo->mBaryCentricV = baryU; + outIntersectInfo->m_position = pos; + outIntersectInfo->m_normal = normal; + outIntersectInfo->m_uv = uv; + outIntersectInfo->m_baryCentricU = baryU; + outIntersectInfo->m_baryCentricV = baryU; closestDist = MCore::SafeLength(start - pos); closestDist = dist; } @@ -787,20 +778,12 @@ namespace EMStudio result = true; } - /* - // collide with ground plane - MCore::Vector3 groundNormal(0.0f, 0.0f, 0.0f); - groundNormal[MCore::GetCoordinateSystem().GetUpIndex()] = 1.0f; - MCore::PlaneEq groundPlane( groundNormal, Vector3(0.0f, 0.0f, 0.0f) ); - bool result = MCore::Ray(start, end).Intersects( groundPlane, &(outIntersectInfo->mPosition) ); - outIntersectInfo->mNormal = groundNormal; - */ return result; } // set the gizmo offsets - void AnimGraphEventHandler::OnSetVisualManipulatorOffset(EMotionFX::AnimGraphInstance* animGraphInstance, uint32 paramIndex, const AZ::Vector3& offset) + void AnimGraphEventHandler::OnSetVisualManipulatorOffset(EMotionFX::AnimGraphInstance* animGraphInstance, size_t paramIndex, const AZ::Vector3& offset) { EMStudioManager* manager = GetManager(); @@ -808,13 +791,10 @@ namespace EMStudio const AZStd::string& paramName = animGraphInstance->GetAnimGraph()->FindParameter(paramIndex)->GetName(); // iterate over all gizmos that are active - MCore::Array* gizmos = manager->GetTransformationManipulators(); - const uint32 numGizmos = gizmos->GetLength(); - for (uint32 i = 0; i < numGizmos; ++i) + const AZStd::vector* gizmos = manager->GetTransformationManipulators(); + for (MCommon::TransformationManipulator* gizmo : *gizmos) { - MCommon::TransformationManipulator* gizmo = gizmos->GetItem(i); - - // check the gizmo name + // check the gizmo name if (paramName == gizmo->GetName()) { gizmo->SetRenderOffset(offset); @@ -835,8 +815,8 @@ namespace EMStudio AZStd::vector > newConnections; // get the number of incoming connections and iterate through them - const uint32 numConnections = node->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = node->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { // get the connection and check if it is plugged into the node EMotionFX::BlendTreeConnection* connection = node->GetConnection(c); @@ -927,8 +907,8 @@ namespace EMStudio AZStd::vector, EMotionFX::AnimGraphNode*> > newConnections; // iterate through all nodes in the parent and check if any of these has a connection from our node - const uint32 numNodes = parentNode->GetNumChildNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = parentNode->GetNumChildNodes(); + for (size_t i = 0; i < numNodes; ++i) { // get the child node and skip it in case it is the parameter node itself EMotionFX::AnimGraphNode* childNode = parentNode->GetChildNode(i); @@ -938,8 +918,8 @@ namespace EMStudio } // get the number of outgoing connections and iterate through them - const uint32 numConnections = childNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = childNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { // get the connection and check if it is plugged into the parameter node EMotionFX::BlendTreeConnection* connection = childNode->GetConnection(c); @@ -1023,24 +1003,24 @@ namespace EMStudio void AnimGraphEventHandler::OnDeleteAnimGraph(EMotionFX::AnimGraph* animGraph) { - if (mPlugin->GetActiveAnimGraph() == animGraph) + if (m_plugin->GetActiveAnimGraph() == animGraph) { - mPlugin->SetActiveAnimGraph(nullptr); + m_plugin->SetActiveAnimGraph(nullptr); } } void AnimGraphEventHandler::OnDeleteAnimGraphInstance(EMotionFX::AnimGraphInstance* animGraphInstance) { - mPlugin->GetAnimGraphModel().SetAnimGraphInstance(animGraphInstance->GetAnimGraph(), animGraphInstance, nullptr); + m_plugin->GetAnimGraphModel().SetAnimGraphInstance(animGraphInstance->GetAnimGraph(), animGraphInstance, nullptr); } // activate a given anim graph void AnimGraphPlugin::SetActiveAnimGraph(EMotionFX::AnimGraph* animGraph) { - if (mActiveAnimGraph != animGraph) + if (m_activeAnimGraph != animGraph) { - mActiveAnimGraph = animGraph; + m_activeAnimGraph = animGraph; InitForAnimGraph(animGraph); // Focus on the newly actived anim graph if it has already been added to the anim graph model. @@ -1059,8 +1039,8 @@ namespace EMStudio bool AnimGraphPlugin::IsAnimGraphActive(EMotionFX::AnimGraph* animGraph) const { const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { const EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); const EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); @@ -1074,9 +1054,9 @@ namespace EMStudio } - void AnimGraphPlugin::SaveAnimGraph(const char* filename, uint32 animGraphIndex, MCore::CommandGroup* commandGroup) + void AnimGraphPlugin::SaveAnimGraph(const char* filename, size_t animGraphIndex, MCore::CommandGroup* commandGroup) { - const AZStd::string command = AZStd::string::format("SaveAnimGraph -index %i -filename \"%s\"", animGraphIndex, filename); + const AZStd::string command = AZStd::string::format("SaveAnimGraph -index %zu -filename \"%s\"", animGraphIndex, filename); if (commandGroup == nullptr) { @@ -1101,8 +1081,8 @@ namespace EMStudio void AnimGraphPlugin::SaveAnimGraph(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup) { - const uint32 animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); - if (animGraphIndex == MCORE_INVALIDINDEX32) + const size_t animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); + if (animGraphIndex == InvalidIndex) { return; } @@ -1123,7 +1103,7 @@ namespace EMStudio void AnimGraphPlugin::SaveAnimGraphAs(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup) { - const AZStd::string filename = GetMainWindow()->GetFileManager()->SaveAnimGraphFileDialog(mViewWidget); + const AZStd::string filename = GetMainWindow()->GetFileManager()->SaveAnimGraphFileDialog(m_viewWidget); if (filename.empty()) { return; @@ -1142,12 +1122,12 @@ namespace EMStudio (sourceAnimGraph || cacheAnimGraph) && (sourceAnimGraph != focusedAnimGraph && cacheAnimGraph != focusedAnimGraph)) { - QMessageBox::warning(mDock, "Cannot overwrite anim graph", "Anim graph is already opened and cannot be overwritten.", QMessageBox::Ok); + QMessageBox::warning(m_dock, "Cannot overwrite anim graph", "Anim graph is already opened and cannot be overwritten.", QMessageBox::Ok); return; } - const uint32 animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); - if (animGraphIndex == MCORE_INVALIDINDEX32) + const size_t animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); + if (animGraphIndex == InvalidIndex) { MCore::LogError("Cannot save anim graph. Anim graph index invalid."); return; @@ -1159,7 +1139,7 @@ namespace EMStudio void AnimGraphPlugin::OnFileOpen() { - AZStd::string filename = GetMainWindow()->GetFileManager()->LoadAnimGraphFileDialog(mViewWidget); + AZStd::string filename = GetMainWindow()->GetFileManager()->LoadAnimGraphFileDialog(m_viewWidget); GetMainWindow()->activateWindow(); if (filename.empty()) { @@ -1176,7 +1156,7 @@ namespace EMStudio } const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); MCore::CommandGroup commandGroup("Load anim graph"); AZStd::string command; @@ -1202,10 +1182,10 @@ namespace EMStudio } else { - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); if (numMotionSets > 0) { - for (uint32 i = 0; i < numMotionSets; ++i) + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* candidate = EMotionFX::GetMotionManager().GetMotionSet(i); if (candidate->GetIsOwnedByRuntime()) @@ -1222,7 +1202,7 @@ namespace EMStudio if (motionSet) { - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); if (actorInstance->GetIsOwnedByRuntime()) @@ -1254,8 +1234,8 @@ namespace EMStudio return; } - const uint32 animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); - assert(animGraphIndex != MCORE_INVALIDINDEX32); + const size_t animGraphIndex = EMotionFX::GetAnimGraphManager().FindAnimGraphIndex(animGraph); + assert(animGraphIndex != InvalidIndex); const AZStd::string filename = animGraph->GetFileName(); if (filename.empty()) @@ -1284,39 +1264,39 @@ namespace EMStudio // timer event void AnimGraphPlugin::ProcessFrame(float timePassedInSeconds) { - if (GetManager()->GetAvoidRendering() || !mGraphWidget || mGraphWidget->visibleRegion().isEmpty()) + if (GetManager()->GetAvoidRendering() || !m_graphWidget || m_graphWidget->visibleRegion().isEmpty()) { return; } - mTotalTime += timePassedInSeconds; + m_totalTime += timePassedInSeconds; - for (AnimGraphPerFrameCallback* callback : mPerFrameCallbacks) + for (AnimGraphPerFrameCallback* callback : m_perFrameCallbacks) { callback->ProcessFrame(timePassedInSeconds); } bool redraw = false; #ifdef MCORE_DEBUG - if (mTotalTime > 1.0f / 30.0f) + if (m_totalTime > 1.0f / 30.0f) #else - if (mTotalTime > 1.0f / 60.0f) + if (m_totalTime > 1.0f / 60.0f) #endif { redraw = true; - mTotalTime = 0.0f; + m_totalTime = 0.0f; } if (EMotionFX::GetRecorder().GetIsInPlayMode()) { - if (MCore::Compare::CheckIfIsClose(EMotionFX::GetRecorder().GetCurrentPlayTime(), mLastPlayTime, 0.001f) == false) + if (MCore::Compare::CheckIfIsClose(EMotionFX::GetRecorder().GetCurrentPlayTime(), m_lastPlayTime, 0.001f) == false) { - mParameterWindow->UpdateParameterValues(); - mLastPlayTime = EMotionFX::GetRecorder().GetCurrentPlayTime(); + m_parameterWindow->UpdateParameterValues(); + m_lastPlayTime = EMotionFX::GetRecorder().GetCurrentPlayTime(); } } - mGraphWidget->ProcessFrame(redraw); + m_graphWidget->ProcessFrame(redraw); } @@ -1407,17 +1387,17 @@ namespace EMStudio MCORE_UNUSED(actorInstanceData); // try to locate the node based on its unique ID - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(historyItem->mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(historyItem->m_animGraphId); if (animGraph == nullptr) { - QMessageBox::warning(mDock, "Cannot Find Anim Graph", "The anim graph used by this node cannot be located anymore, did you delete it?", QMessageBox::Ok); + QMessageBox::warning(m_dock, "Cannot Find Anim Graph", "The anim graph used by this node cannot be located anymore, did you delete it?", QMessageBox::Ok); return; } - EMotionFX::AnimGraphNode* foundNode = animGraph->RecursiveFindNodeById(historyItem->mNodeId); + EMotionFX::AnimGraphNode* foundNode = animGraph->RecursiveFindNodeById(historyItem->m_nodeId); if (foundNode == nullptr) { - QMessageBox::warning(mDock, "Cannot Find Node", "The anim graph node cannot be found. Did you perhaps delete the node or change animgraph?", QMessageBox::Ok); + QMessageBox::warning(m_dock, "Cannot Find Node", "The anim graph node cannot be found. Did you perhaps delete the node or change animgraph?", QMessageBox::Ok); return; } @@ -1437,24 +1417,24 @@ namespace EMStudio MCORE_UNUSED(actorInstanceData); // try to locate the node based on its unique ID - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(historyItem->mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(historyItem->m_animGraphId); if (animGraph == nullptr) { - QMessageBox::warning(mDock, "Cannot Find Anim Graph", "The anim graph used by this node cannot be located anymore, did you delete it?", QMessageBox::Ok); + QMessageBox::warning(m_dock, "Cannot Find Anim Graph", "The anim graph used by this node cannot be located anymore, did you delete it?", QMessageBox::Ok); return; } - EMotionFX::AnimGraphNode* foundNode = animGraph->RecursiveFindNodeById(historyItem->mNodeId); + EMotionFX::AnimGraphNode* foundNode = animGraph->RecursiveFindNodeById(historyItem->m_nodeId); if (foundNode == nullptr) { - QMessageBox::warning(mDock, "Cannot Find Node", "The anim graph node cannot be found. Did you perhaps delete the node or change animgraph?", QMessageBox::Ok); + QMessageBox::warning(m_dock, "Cannot Find Node", "The anim graph node cannot be found. Did you perhaps delete the node or change animgraph?", QMessageBox::Ok); return; } EMotionFX::AnimGraphNode* nodeToShow = foundNode->GetParentNode(); if (nodeToShow) { - const QModelIndex foundNodeIndex = m_animGraphModel->FindModelIndex(nodeToShow, historyItem->mAnimGraphInstance); + const QModelIndex foundNodeIndex = m_animGraphModel->FindModelIndex(nodeToShow, historyItem->m_animGraphInstance); if (foundNodeIndex.isValid()) { m_animGraphModel->Focus(foundNodeIndex); 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 c741b0cc6e..3510920d2c 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 @@ -17,7 +17,7 @@ #include "../../../../EMStudioSDK/Source/EMStudioManager.h" #include -#include +#include #include #include @@ -76,7 +76,7 @@ namespace EMStudio AnimGraphEventHandler(AnimGraphPlugin* plugin); const AZStd::vector GetHandledEventTypes() const override { return { EMotionFX::EVENT_TYPE_ON_SET_VISUAL_MANIPULATOR_OFFSET, EMotionFX::EVENT_TYPE_ON_INPUT_PORTS_CHANGED, EMotionFX::EVENT_TYPE_ON_OUTPUT_PORTS_CHANGED, EMotionFX::EVENT_TYPE_ON_RAY_INTERSECTION_TEST, EMotionFX::EVENT_TYPE_ON_DELETE_ANIM_GRAPH, EMotionFX::EVENT_TYPE_ON_DELETE_ANIM_GRAPH_INSTANCE }; } - void OnSetVisualManipulatorOffset(EMotionFX::AnimGraphInstance* animGraphInstance, uint32 paramIndex, const AZ::Vector3& offset) override; + void OnSetVisualManipulatorOffset(EMotionFX::AnimGraphInstance* animGraphInstance, size_t paramIndex, const AZ::Vector3& offset) override; void OnInputPortsChanged(EMotionFX::AnimGraphNode* node, const AZStd::vector& newInputPorts, const AZStd::string& memberName, const AZStd::vector& memberValue) override; void OnOutputPortsChanged(EMotionFX::AnimGraphNode* node, const AZStd::vector& newOutputPorts, const AZStd::string& memberName, const AZStd::vector& memberValue) override; bool OnRayIntersectionTest(const AZ::Vector3& start, const AZ::Vector3& end, EMotionFX::IntersectionInfo* outIntersectInfo) override; @@ -84,7 +84,7 @@ namespace EMStudio void OnDeleteAnimGraphInstance(EMotionFX::AnimGraphInstance* animGraphInstance) override; private: - AnimGraphPlugin* mPlugin; + AnimGraphPlugin* m_plugin; }; class AnimGraphPerFrameCallback @@ -133,15 +133,15 @@ namespace EMStudio void AddWindowMenuEntries(QMenu* parent) override; void SetActiveAnimGraph(EMotionFX::AnimGraph* animGraph); - EMotionFX::AnimGraph* GetActiveAnimGraph() { return mActiveAnimGraph; } + EMotionFX::AnimGraph* GetActiveAnimGraph() { return m_activeAnimGraph; } - void SaveAnimGraph(const char* filename, uint32 animGraphIndex, MCore::CommandGroup* commandGroup = nullptr); + void SaveAnimGraph(const char* filename, size_t animGraphIndex, MCore::CommandGroup* commandGroup = nullptr); void SaveAnimGraph(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup = nullptr); void SaveAnimGraphAs(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup = nullptr); int SaveDirtyAnimGraph(EMotionFX::AnimGraph* animGraph, MCore::CommandGroup* commandGroup, bool askBeforeSaving, bool showCancelButton = true); int OnSaveDirtyAnimGraphs(); - PluginOptions* GetOptions() override { return &mOptions; } + PluginOptions* GetOptions() override { return &m_options; } void LoadOptions(); void SaveOptions(); @@ -193,41 +193,41 @@ namespace EMStudio void OnClickedRecorderNodeHistoryItem(EMotionFX::Recorder::ActorInstanceData* actorInstanceData, EMotionFX::Recorder::NodeHistoryItem* historyItem); public: - BlendGraphWidget* GetGraphWidget() { return mGraphWidget; } - NavigateWidget* GetNavigateWidget() { return mNavigateWidget; } - NodePaletteWidget* GetPaletteWidget() { return mPaletteWidget; } - AttributesWindow* GetAttributesWindow() { return mAttributesWindow; } - ParameterWindow* GetParameterWindow() { return mParameterWindow; } - NodeGroupWindow* GetNodeGroupWidget() { return mNodeGroupWindow; } - BlendGraphViewWidget* GetViewWidget() { return mViewWidget; } + BlendGraphWidget* GetGraphWidget() { return m_graphWidget; } + NavigateWidget* GetNavigateWidget() { return m_navigateWidget; } + NodePaletteWidget* GetPaletteWidget() { return m_paletteWidget; } + AttributesWindow* GetAttributesWindow() { return m_attributesWindow; } + ParameterWindow* GetParameterWindow() { return m_parameterWindow; } + NodeGroupWindow* GetNodeGroupWidget() { return m_nodeGroupWindow; } + BlendGraphViewWidget* GetViewWidget() { return m_viewWidget; } NavigationHistory* GetNavigationHistory() const { return m_navigationHistory; } - QDockWidget* GetAttributeDock() { return mAttributeDock; } - QDockWidget* GetNodePaletteDock() { return mNodePaletteDock; } - QDockWidget* GetParameterDock() { return mParameterDock; } - QDockWidget* GetNodeGroupDock() { return mNodeGroupDock; } + QDockWidget* GetAttributeDock() { return m_attributeDock; } + QDockWidget* GetNodePaletteDock() { return m_nodePaletteDock; } + QDockWidget* GetParameterDock() { return m_parameterDock; } + QDockWidget* GetNodeGroupDock() { return m_nodeGroupDock; } #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - GameControllerWindow* GetGameControllerWindow() { return mGameControllerWindow; } - QDockWidget* GetGameControllerDock() { return mGameControllerDock; } + GameControllerWindow* GetGameControllerWindow() { return m_gameControllerWindow; } + QDockWidget* GetGameControllerDock() { return m_gameControllerDock; } #endif void SetDisplayFlagEnabled(uint32 flags, bool enabled) { if (enabled) { - mDisplayFlags |= flags; + m_displayFlags |= flags; } else { - mDisplayFlags &= ~flags; + m_displayFlags &= ~flags; } } - bool GetIsDisplayFlagEnabled(uint32 flags) const { return (mDisplayFlags & flags); } - uint32 GetDisplayFlags() const { return mDisplayFlags; } + bool GetIsDisplayFlagEnabled(uint32 flags) const { return (m_displayFlags & flags); } + uint32 GetDisplayFlags() const { return m_displayFlags; } const EMotionFX::AnimGraphObjectFactory* GetAnimGraphObjectFactory() const { return m_animGraphObjectFactory; } - GraphNodeFactory* GetGraphNodeFactory() { return mGraphNodeFactory; } + GraphNodeFactory* GetGraphNodeFactory() { return m_graphNodeFactory; } // overloaded main init function void Reflect(AZ::ReflectContext* serializeContext) override; @@ -235,10 +235,10 @@ namespace EMStudio void OnAfterLoadLayout() override; EMStudioPlugin* Clone() override; - const AnimGraphOptions& GetAnimGraphOptions() const { return mOptions; } + const AnimGraphOptions& GetAnimGraphOptions() const { return m_options; } - void SetDisableRendering(bool flag) { mDisableRendering = flag; } - bool GetDisableRendering() const { return mDisableRendering; } + void SetDisableRendering(bool flag) { m_disableRendering = flag; } + bool GetDisableRendering() const { return m_disableRendering; } void SetActionFilter(const AnimGraphActionFilter& actionFilter); const AnimGraphActionFilter& GetActionFilter() const; @@ -264,44 +264,44 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandPlayMotionCallback); AZStd::vector m_commandCallbacks; - AZStd::vector mPerFrameCallbacks; + AZStd::vector m_perFrameCallbacks; - bool mDisableRendering; + bool m_disableRendering; - AnimGraphEventHandler mEventHandler; + AnimGraphEventHandler m_eventHandler; - BlendGraphWidget* mGraphWidget; - NavigateWidget* mNavigateWidget; - NodePaletteWidget* mPaletteWidget; - AttributesWindow* mAttributesWindow; - ParameterWindow* mParameterWindow; - NodeGroupWindow* mNodeGroupWindow; - BlendGraphViewWidget* mViewWidget; + BlendGraphWidget* m_graphWidget; + NavigateWidget* m_navigateWidget; + NodePaletteWidget* m_paletteWidget; + AttributesWindow* m_attributesWindow; + ParameterWindow* m_parameterWindow; + NodeGroupWindow* m_nodeGroupWindow; + BlendGraphViewWidget* m_viewWidget; NavigationHistory* m_navigationHistory; - SaveDirtyAnimGraphFilesCallback* mDirtyFilesCallback; + SaveDirtyAnimGraphFilesCallback* m_dirtyFilesCallback; - QDockWidget* mAttributeDock; - QDockWidget* mNodePaletteDock; - QDockWidget* mParameterDock; - QDockWidget* mNodeGroupDock; - QAction* mDockWindowActions[NUM_DOCKWINDOW_OPTIONS]; - EMotionFX::AnimGraph* mActiveAnimGraph; + QDockWidget* m_attributeDock; + QDockWidget* m_nodePaletteDock; + QDockWidget* m_parameterDock; + QDockWidget* m_nodeGroupDock; + QAction* m_dockWindowActions[NUM_DOCKWINDOW_OPTIONS]; + EMotionFX::AnimGraph* m_activeAnimGraph; #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - GameControllerWindow* mGameControllerWindow; - QPointer mGameControllerDock; + GameControllerWindow* m_gameControllerWindow; + QPointer m_gameControllerDock; #endif - float mLastPlayTime; - float mTotalTime; + float m_lastPlayTime; + float m_totalTime; - uint32 mDisplayFlags; + uint32 m_displayFlags; - AnimGraphOptions mOptions; + AnimGraphOptions m_options; EMotionFX::AnimGraphObjectFactory* m_animGraphObjectFactory; - GraphNodeFactory* mGraphNodeFactory; + GraphNodeFactory* m_graphNodeFactory; // Model used for the MVC pattern AnimGraphModel* m_animGraphModel; @@ -311,7 +311,7 @@ namespace EMStudio AnimGraphActionFilter m_actionFilter; void InitForAnimGraph(EMotionFX::AnimGraph* setup); - bool GetOptionFlag(EDockWindowOptionFlag option) { return mDockWindowActions[(uint32)option]->isChecked(); } + bool GetOptionFlag(EDockWindowOptionFlag option) { return m_dockWindowActions[(uint32)option]->isChecked(); } void SetOptionFlag(EDockWindowOptionFlag option, bool isEnabled); void SetOptionEnabled(EDockWindowOptionFlag option, bool isEnabled); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.cpp index 91f5e00dd0..8af57e6dee 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.cpp @@ -23,10 +23,10 @@ namespace EMStudio AnimGraphVisualNode::AnimGraphVisualNode(const QModelIndex& modelIndex, AnimGraphPlugin* plugin, EMotionFX::AnimGraphNode* node) : GraphNode(modelIndex, node->GetName(), 0, 0) { - mEMFXNode = node; - mCanHaveChildren = node->GetCanHaveChildren(); - mHasVisualGraph = node->GetHasVisualGraph(); - mPlugin = plugin; + m_emfxNode = node; + m_canHaveChildren = node->GetCanHaveChildren(); + m_hasVisualGraph = node->GetHasVisualGraph(); + m_plugin = plugin; SetSubTitle(node->GetPaletteName(), false); } @@ -45,24 +45,24 @@ namespace EMStudio void AnimGraphVisualNode::Sync() { - SetName(mEMFXNode->GetName()); - SetNodeInfo(mEMFXNode->GetNodeInfo()); + SetName(m_emfxNode->GetName()); + SetNodeInfo(m_emfxNode->GetNodeInfo()); - SetDeletable(mEMFXNode->GetIsDeletable()); - SetBaseColor(AzColorToQColor(mEMFXNode->GetVisualColor())); - SetHasChildIndicatorColor(AzColorToQColor(mEMFXNode->GetHasChildIndicatorColor())); - SetIsCollapsed(mEMFXNode->GetIsCollapsed()); + SetDeletable(m_emfxNode->GetIsDeletable()); + SetBaseColor(AzColorToQColor(m_emfxNode->GetVisualColor())); + SetHasChildIndicatorColor(AzColorToQColor(m_emfxNode->GetHasChildIndicatorColor())); + SetIsCollapsed(m_emfxNode->GetIsCollapsed()); // Update position UpdateRects(); - MoveAbsolute(QPoint(mEMFXNode->GetVisualPosX(), mEMFXNode->GetVisualPosY())); + MoveAbsolute(QPoint(m_emfxNode->GetVisualPosX(), m_emfxNode->GetVisualPosY())); - SetIsVisualized(mEMFXNode->GetIsVisualizationEnabled()); - SetCanVisualize(mEMFXNode->GetSupportsVisualization()); - SetIsEnabled(mEMFXNode->GetIsEnabled()); - SetVisualizeColor(AzColorToQColor(mEMFXNode->GetVisualizeColor())); - SetHasVisualOutputPorts(mEMFXNode->GetHasVisualOutputPorts()); - mHasVisualGraph = mEMFXNode->GetHasVisualGraph(); + SetIsVisualized(m_emfxNode->GetIsVisualizationEnabled()); + SetCanVisualize(m_emfxNode->GetSupportsVisualization()); + SetIsEnabled(m_emfxNode->GetIsEnabled()); + SetVisualizeColor(AzColorToQColor(m_emfxNode->GetVisualizeColor())); + SetHasVisualOutputPorts(m_emfxNode->GetHasVisualOutputPorts()); + m_hasVisualGraph = m_emfxNode->GetHasVisualGraph(); UpdateTextPixmap(); } @@ -72,30 +72,6 @@ namespace EMStudio void AnimGraphVisualNode::RenderDebugInfo(QPainter& painter) { MCORE_UNUSED(painter); - /* // get the selected actor instance - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); - if (actorInstance == nullptr) - return; - - // get the anim graph instance - EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); - if (animGraphInstance == nullptr) - return; - - QRect rect( mRect.left(), mRect.bottom(), mRect.width(), 10 ); - - // draw header text - QTextOption textOptions; - textOptions.setAlignment( Qt::AlignCenter|Qt::AlignTop ); - painter.setPen( QColor(0,255,0) ); - - QString s; - //s.sprintf("%.3f %.3f", mEMFXNode->FindUniqueData(animGraphInstance)->GetInternalPlaySpeed(), mEMFXNode->FindUniqueData(animGraphInstance)->GetPlaySpeed()); - //painter.drawText( rect, s, textOptions ); - - //rect.translate(0, 12); - s.sprintf("%.3f %.3f", mEMFXNode->FindUniqueData(animGraphInstance)->GetGlobalWeight(), mEMFXNode->FindUniqueData(animGraphInstance)->GetLocalWeight()); - painter.drawText( rect, s, textOptions );*/ } @@ -103,7 +79,7 @@ namespace EMStudio void AnimGraphVisualNode::RenderTracks(QPainter& painter, const QColor bgColor, const QColor bgColor2, int32 heightOffset) { // get the sync track - QRect rect(mRect.left() + 5, mRect.bottom() - 13 + heightOffset, mRect.width() - 10, 8); + QRect rect(m_rect.left() + 5, m_rect.bottom() - 13 + heightOffset, m_rect.width() - 10, 8); painter.setPen(bgColor.darker(185)); painter.setBrush(bgColor2); @@ -116,7 +92,7 @@ namespace EMStudio return; } - const float duration = mEMFXNode->GetDuration(animGraphInstance); + const float duration = m_emfxNode->GetDuration(animGraphInstance); if (duration < MCore::Math::epsilon) { return; @@ -124,7 +100,7 @@ namespace EMStudio // draw the background rect QRect playRect = rect; - int32 x = aznumeric_cast(rect.left() + 1 + (rect.width() - 2) * (mEMFXNode->GetCurrentPlayTime(animGraphInstance) / duration)); + int32 x = aznumeric_cast(rect.left() + 1 + (rect.width() - 2) * (m_emfxNode->GetCurrentPlayTime(animGraphInstance) / duration)); playRect.setRight(x); playRect.setLeft(rect.left() + 1); playRect.setTop(rect.top() + 1); @@ -134,7 +110,7 @@ namespace EMStudio painter.drawRect(playRect); // draw the sync keys - const EMotionFX::AnimGraphNodeData* uniqueData = mEMFXNode->FindOrCreateUniqueNodeData(animGraphInstance); + const EMotionFX::AnimGraphNodeData* uniqueData = m_emfxNode->FindOrCreateUniqueNodeData(animGraphInstance); const EMotionFX::AnimGraphSyncTrack* syncTrack = uniqueData->GetSyncTrack(); const size_t numSyncPoints = syncTrack ? syncTrack->GetNumEvents() : 0; @@ -169,7 +145,7 @@ namespace EMStudio // draw the current play time painter.setPen(Qt::yellow); - x = aznumeric_cast(rect.left() + 1 + (rect.width() - 2) * (mEMFXNode->GetCurrentPlayTime(animGraphInstance) / duration)); + x = aznumeric_cast(rect.left() + 1 + (rect.width() - 2) * (m_emfxNode->GetCurrentPlayTime(animGraphInstance) / duration)); painter.drawLine(x, rect.top() + 1, x, rect.bottom()); } @@ -187,7 +163,7 @@ namespace EMStudio // extract anim graph instance EMotionFX::AnimGraphInstance* animGraphInstance = ExtractAnimGraphInstance(); - return (animGraphInstance == nullptr) || (animGraphInstance->GetIsOutputReady(mEMFXNode->GetParentNode()->GetObjectIndex()) == false); + return (animGraphInstance == nullptr) || (animGraphInstance->GetIsOutputReady(m_emfxNode->GetParentNode()->GetObjectIndex()) == false); } @@ -202,7 +178,7 @@ namespace EMStudio } // return the error state of the emfx node - EMotionFX::AnimGraphObjectData* uniqueData = mEMFXNode->FindOrCreateUniqueNodeData(animGraphInstance); - return mEMFXNode->HierarchicalHasError(uniqueData); + EMotionFX::AnimGraphObjectData* uniqueData = m_emfxNode->FindOrCreateUniqueNodeData(animGraphInstance); + return m_emfxNode->HierarchicalHasError(uniqueData); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.h index 7243d182bc..c25027ef91 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphVisualNode.h @@ -34,9 +34,9 @@ namespace EMStudio void Sync() override; - MCORE_INLINE void SetEMFXNode(EMotionFX::AnimGraphNode* emfxNode) { mEMFXNode = emfxNode; } - MCORE_INLINE EMotionFX::AnimGraphNode* GetEMFXNode() { return mEMFXNode; } - MCORE_INLINE AnimGraphPlugin* GetAnimGraphPlugin() const { return mPlugin; } + MCORE_INLINE void SetEMFXNode(EMotionFX::AnimGraphNode* emfxNode) { m_emfxNode = emfxNode; } + MCORE_INLINE EMotionFX::AnimGraphNode* GetEMFXNode() { return m_emfxNode; } + MCORE_INLINE AnimGraphPlugin* GetAnimGraphPlugin() const { return m_plugin; } EMotionFX::AnimGraphInstance* ExtractAnimGraphInstance() const; void RenderTracks(QPainter& painter, const QColor bgColor, const QColor bgColor2, int32 heightOffset = 0); @@ -48,8 +48,8 @@ namespace EMStudio protected: QColor AzColorToQColor(const AZ::Color& col) const; - EMotionFX::AnimGraphNode* mEMFXNode; - EMotionFX::AnimGraphPose mPose; - AnimGraphPlugin* mPlugin; + EMotionFX::AnimGraphNode* m_emfxNode; + EMotionFX::AnimGraphPose m_pose; + AnimGraphPlugin* m_plugin; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.cpp index 3eb9447eb9..f3d629f300 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.cpp @@ -41,17 +41,17 @@ namespace EMStudio AttributesWindow::AttributesWindow(AnimGraphPlugin* plugin, QWidget* parent) : QWidget(parent) { - mPlugin = plugin; - mPasteConditionsWindow = nullptr; - mScrollArea = new QScrollArea(); + m_plugin = plugin; + m_pasteConditionsWindow = nullptr; + m_scrollArea = new QScrollArea(); QVBoxLayout* mainLayout = new QVBoxLayout(); mainLayout->setMargin(0); mainLayout->setSpacing(1); setLayout(mainLayout); - mainLayout->addWidget(mScrollArea); - mScrollArea->setWidgetResizable(true); + mainLayout->addWidget(m_scrollArea); + m_scrollArea->setWidgetResizable(true); // The main reflected widget will contain the non-custom attribute version of the // attribute widget. The intention is to reuse the Reflected Property Editor and @@ -111,7 +111,7 @@ namespace EMStudio m_conditionsLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); conditionsVerticalLayout->addLayout(m_conditionsLayout); - m_addConditionButton = new AddConditionButton(mPlugin, m_conditionsWidget); + m_addConditionButton = new AddConditionButton(m_plugin, m_conditionsWidget); m_addConditionButton->setObjectName("EMFX.AttributesWindowWidget.NodeTransition.AddConditionsWidget"); connect(m_addConditionButton, &AddConditionButton::ObjectTypeChosen, this, [=](AZ::TypeId conditionType) { @@ -137,7 +137,7 @@ namespace EMStudio m_actionsLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); actionVerticalLayout->addLayout(m_actionsLayout); - AddActionButton* addActionButton = new AddActionButton(mPlugin, m_actionsWidget); + AddActionButton* addActionButton = new AddActionButton(m_plugin, m_actionsWidget); connect(addActionButton, &AddActionButton::ObjectTypeChosen, this, [=](AZ::TypeId actionType) { const AnimGraphModel::ModelItemType itemType = m_displayingModelIndex.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value(); @@ -171,9 +171,9 @@ namespace EMStudio if (m_mainReflectedWidget) { - if (mScrollArea->widget() == m_mainReflectedWidget) + if (m_scrollArea->widget() == m_mainReflectedWidget) { - mScrollArea->takeWidget(); + m_scrollArea->takeWidget(); } delete m_mainReflectedWidget; } @@ -216,15 +216,15 @@ namespace EMStudio EMotionFX::AnimGraphObject* object = modelIndex.data(AnimGraphModel::ROLE_ANIM_GRAPH_OBJECT_PTR).value(); - QWidget* attributeWidget = mPlugin->GetGraphNodeFactory()->CreateAttributeWidget(azrtti_typeid(object)); + QWidget* attributeWidget = m_plugin->GetGraphNodeFactory()->CreateAttributeWidget(azrtti_typeid(object)); if (attributeWidget) { // In the case we have a custom attribute widget, we cannot reuse the widget, so we just replace it - if (mScrollArea->widget() == m_mainReflectedWidget) + if (m_scrollArea->widget() == m_mainReflectedWidget) { - mScrollArea->takeWidget(); + m_scrollArea->takeWidget(); } - mScrollArea->setWidget(attributeWidget); + m_scrollArea->setWidget(attributeWidget); } else { @@ -235,7 +235,7 @@ namespace EMStudio } else { - animGraph = mPlugin->GetActiveAnimGraph(); + animGraph = m_plugin->GetActiveAnimGraph(); } m_animGraphEditor->SetAnimGraph(animGraph); @@ -270,9 +270,9 @@ namespace EMStudio m_objectCard->setVisible(object); - if (mScrollArea->widget() != m_mainReflectedWidget) + if (m_scrollArea->widget() != m_mainReflectedWidget) { - mScrollArea->setWidget(m_mainReflectedWidget); + m_scrollArea->setWidget(m_mainReflectedWidget); } } @@ -472,7 +472,7 @@ namespace EMStudio void AttributesWindow::AddTransitionCopyPasteMenuEntries(QMenu* menu) { - const NodeGraph* activeGraph = mPlugin->GetGraphWidget()->GetActiveGraph(); + const NodeGraph* activeGraph = m_plugin->GetGraphWidget()->GetActiveGraph(); if (!activeGraph) { return; @@ -533,7 +533,7 @@ namespace EMStudio AZ_UNUSED(selected); AZ_UNUSED(deselected); - const QModelIndexList modelIndexes = mPlugin->GetAnimGraphModel().GetSelectionModel().selectedRows(); + const QModelIndexList modelIndexes = m_plugin->GetAnimGraphModel().GetSelectionModel().selectedRows(); if (!modelIndexes.empty()) { Init(modelIndexes.front()); @@ -729,9 +729,9 @@ namespace EMStudio if (contents.IsSuccess()) { CopyPasteConditionObject copyPasteObject; - copyPasteObject.mContents = contents.GetValue(); - copyPasteObject.mConditionType = azrtti_typeid(condition); - condition->GetSummary(©PasteObject.mSummary); + copyPasteObject.m_contents = contents.GetValue(); + copyPasteObject.m_conditionType = azrtti_typeid(condition); + condition->GetSummary(©PasteObject.m_summary); m_copyPasteClipboard.m_conditions.push_back(copyPasteObject); } } @@ -776,9 +776,9 @@ namespace EMStudio CommandSystem::CommandAddTransitionCondition* addConditionCommand = aznew CommandSystem::CommandAddTransitionCondition( transition->GetAnimGraph()->GetID(), transition->GetId(), - copyPasteObject.mConditionType, + copyPasteObject.m_conditionType, /*insertAt=*/AZStd::nullopt, - copyPasteObject.mContents); + copyPasteObject.m_contents); commandGroup.AddCommand(addConditionCommand); } } @@ -804,14 +804,14 @@ namespace EMStudio return; } - delete mPasteConditionsWindow; - mPasteConditionsWindow = nullptr; + delete m_pasteConditionsWindow; + m_pasteConditionsWindow = nullptr; EMotionFX::AnimGraphStateTransition* transition = m_displayingModelIndex.data(AnimGraphModel::ROLE_TRANSITION_POINTER).value(); // Open the select conditions window and return if the user canceled it. - mPasteConditionsWindow = new PasteConditionsWindow(this); - if (mPasteConditionsWindow->exec() == QDialog::Rejected) + m_pasteConditionsWindow = new PasteConditionsWindow(this); + if (m_pasteConditionsWindow->exec() == QDialog::Rejected) { return; } @@ -824,7 +824,7 @@ namespace EMStudio for (size_t i = 0; i < numConditions; ++i) { // check if the condition was selected in the window, if not skip it - if (!mPasteConditionsWindow->GetIsConditionSelected(i)) + if (!m_pasteConditionsWindow->GetIsConditionSelected(i)) { continue; } @@ -832,9 +832,9 @@ namespace EMStudio CommandSystem::CommandAddTransitionCondition* addConditionCommand = aznew CommandSystem::CommandAddTransitionCondition( transition->GetAnimGraph()->GetID(), transition->GetId(), - m_copyPasteClipboard.m_conditions[i].mConditionType, + m_copyPasteClipboard.m_conditions[i].m_conditionType, /*insertAt=*/AZStd::nullopt, - m_copyPasteClipboard.m_conditions[i].mContents); + m_copyPasteClipboard.m_conditions[i].m_contents); commandGroup.AddCommand(addConditionCommand); numPastedConditions++; @@ -911,28 +911,28 @@ namespace EMStudio layout->addWidget(new QLabel("Please select the conditions you want to paste:")); - mCheckboxes.clear(); + m_checkboxes.clear(); const AttributesWindow::CopyPasteClipboard& copyPasteClipboard = attributeWindow->GetCopyPasteConditionClipboard(); for (const AttributesWindow::CopyPasteConditionObject& copyPasteObject : copyPasteClipboard.m_conditions) { - QCheckBox* checkbox = new QCheckBox(copyPasteObject.mSummary.c_str()); - mCheckboxes.push_back(checkbox); + QCheckBox* checkbox = new QCheckBox(copyPasteObject.m_summary.c_str()); + m_checkboxes.push_back(checkbox); checkbox->setCheckState(Qt::Checked); layout->addWidget(checkbox); } // create the ok and cancel buttons QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mCancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); + m_okButton = new QPushButton("OK"); + m_cancelButton = new QPushButton("Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); layout->addLayout(buttonLayout); setLayout(layout); - connect(mOKButton, &QPushButton::clicked, this, &PasteConditionsWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &PasteConditionsWindow::reject); + connect(m_okButton, &QPushButton::clicked, this, &PasteConditionsWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &PasteConditionsWindow::reject); } @@ -945,7 +945,7 @@ namespace EMStudio // check if the condition is selected bool PasteConditionsWindow::GetIsConditionSelected(size_t index) const { - return mCheckboxes[index]->checkState() == Qt::Checked; + return m_checkboxes[index]->checkState() == Qt::Checked; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.h index 5e278760a6..38bceb4426 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AttributesWindow.h @@ -82,9 +82,9 @@ namespace EMStudio virtual ~PasteConditionsWindow(); bool GetIsConditionSelected(size_t index) const; private: - QPushButton* mOKButton; - QPushButton* mCancelButton; - AZStd::vector mCheckboxes; + QPushButton* m_okButton; + QPushButton* m_cancelButton; + AZStd::vector m_checkboxes; }; @@ -102,9 +102,9 @@ namespace EMStudio // copy & paste struct CopyPasteConditionObject { - AZStd::string mContents; - AZStd::string mSummary; - AZ::TypeId mConditionType; + AZStd::string m_contents; + AZStd::string m_summary; + AZ::TypeId m_conditionType; }; struct CopyPasteClipboard @@ -156,8 +156,8 @@ namespace EMStudio void PasteTransition(bool pasteTransitionProperties, bool pasteConditions); - AnimGraphPlugin* mPlugin; - QScrollArea* mScrollArea; + AnimGraphPlugin* m_plugin; + QScrollArea* m_scrollArea; QPersistentModelIndex m_displayingModelIndex; QWidget* m_mainReflectedWidget; @@ -187,7 +187,7 @@ namespace EMStudio QLayout* m_actionsLayout; AZStd::vector m_actionsCachedWidgets; - PasteConditionsWindow* mPasteConditionsWindow; + PasteConditionsWindow* m_pasteConditionsWindow; CopyPasteClipboard m_copyPasteClipboard; 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 328f266cb1..59a7e33f04 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 @@ -369,9 +369,9 @@ namespace EMStudio toolBar->addAction(m_actions[NAVIGATION_FORWARD]); - mNavigationLink = new NavigationLinkWidget(m_parentPlugin, this); - mNavigationLink->setMinimumHeight(28); - toolBar->addWidget(mNavigationLink); + m_navigationLink = new NavigationLinkWidget(m_parentPlugin, this); + m_navigationLink->setMinimumHeight(28); + toolBar->addWidget(m_navigationLink); toolBar->addAction(m_actions[NAVIGATION_NAVPANETOGGLE]); @@ -580,11 +580,11 @@ namespace EMStudio m_openMenu->addAction(m_actions[FILE_OPEN]); - const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); + const size_t numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); if (numAnimGraphs > 0) { m_openMenu->addSeparator(); - for (uint32 i = 0; i < numAnimGraphs; ++i) + for (size_t i = 0; i < numAnimGraphs; ++i) { EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().GetAnimGraph(i); if (animGraph->GetIsOwnedByRuntime() == false) @@ -627,7 +627,7 @@ namespace EMStudio { // get the current selection list and the number of actor instances selected const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); // Activate the new anim graph automatically (The shown anim graph should always be the activated one). if (numActorInstances > 0) @@ -656,7 +656,7 @@ namespace EMStudio if (motionSet) { // Activate anim graph on all actor instances in case there is a motion set. - for (uint32 i = 0; i < numActorInstances; ++i) + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); commandGroup.AddCommandString(AZStd::string::format("ActivateAnimGraph -actorInstanceID %d -animGraphID %%LASTRESULT%% -motionSetID %d", actorInstance->GetID(), motionSet->GetID())); 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 d1ebfb67d4..f795bef347 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 @@ -133,7 +133,7 @@ namespace EMStudio QHBoxLayout* m_toolbarLayout = nullptr; AZStd::array m_actions{}; AnimGraphPlugin* m_parentPlugin = nullptr; - NavigationLinkWidget* mNavigationLink = nullptr; + NavigationLinkWidget* m_navigationLink = nullptr; QStackedWidget m_viewportStack; QSplitter* m_viewportSplitter = nullptr; 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 8a4a338b6e..293dc51864 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 @@ -51,10 +51,10 @@ namespace EMStudio // constructor BlendGraphWidget::BlendGraphWidget(AnimGraphPlugin* plugin, QWidget* parent) : NodeGraphWidget(plugin, nullptr, parent) - , mContextMenuEventMousePos(0, 0) - , mDoubleClickHappened(false) + , m_contextMenuEventMousePos(0, 0) + , m_doubleClickHappened(false) { - mMoveGroup.SetGroupName("Move anim graph nodes"); + m_moveGroup.SetGroupName("Move anim graph nodes"); setAutoFillBackground(false); setAttribute(Qt::WA_OpaquePaintEvent); @@ -78,9 +78,9 @@ namespace EMStudio return; } - if (!mActiveGraph || - !mPlugin->GetActionFilter().m_createNodes || - mActiveGraph->IsInReferencedGraph()) + if (!m_activeGraph || + !m_plugin->GetActionFilter().m_createNodes || + m_activeGraph->IsInReferencedGraph()) { event->ignore(); return; @@ -440,7 +440,7 @@ namespace EMStudio QAction* action = qobject_cast(sender()); // calculate the position - const QPoint offset = SnapLocalToGrid(LocalToGlobal(mContextMenuEventMousePos)); + const QPoint offset = SnapLocalToGrid(LocalToGlobal(m_contextMenuEventMousePos)); // build the name prefix and create the node const AZStd::string typeString = FromQtString(action->whatsThis()); @@ -523,7 +523,7 @@ namespace EMStudio void BlendGraphWidget::OnContextMenuEvent(QPoint mousePos, QPoint globalMousePos, const AnimGraphActionFilter& actionFilter) { - if (!mAllowContextMenu) + if (!m_allowContextMenu) { return; } @@ -542,7 +542,7 @@ namespace EMStudio return; } - mContextMenuEventMousePos = mousePos; + m_contextMenuEventMousePos = mousePos; const AZStd::vector selectedAnimGraphNodes = nodeGraph->GetSelectedAnimGraphNodes(); const AZStd::vector selectedConnections = nodeGraph->GetSelectedNodeConnections(); @@ -597,7 +597,7 @@ namespace EMStudio EMotionFX::AnimGraphStateTransition* transition = FindTransitionForConnection(selectedConnections[0]); if (transition) { - mPlugin->GetAttributesWindow()->AddTransitionCopyPasteMenuEntries(&menu); + m_plugin->GetAttributesWindow()->AddTransitionCopyPasteMenuEntries(&menu); } } } @@ -608,7 +608,7 @@ namespace EMStudio } if (actionFilter.m_delete && - !mActiveGraph->IsInReferencedGraph()) + !m_activeGraph->IsInReferencedGraph()) { QAction* removeConnectionAction = menu.addAction(removeConnectionActionName); connect(removeConnectionAction, &QAction::triggered, this, static_cast(&BlendGraphWidget::DeleteSelectedItems)); @@ -618,22 +618,22 @@ namespace EMStudio } else { - OnContextMenuEvent(this, mousePos, globalMousePos, mPlugin, selectedAnimGraphNodes, true, false, actionFilter); + OnContextMenuEvent(this, mousePos, globalMousePos, m_plugin, selectedAnimGraphNodes, true, false, actionFilter); } } void BlendGraphWidget::mouseDoubleClickEvent(QMouseEvent* event) { - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return; } - mDoubleClickHappened = true; + m_doubleClickHappened = true; NodeGraphWidget::mouseDoubleClickEvent(event); - GraphNode* node = mActiveGraph->FindNode(event->pos()); + GraphNode* node = m_activeGraph->FindNode(event->pos()); if (node) { const QModelIndex nodeModelIndex = node->GetModelIndex(); @@ -642,9 +642,9 @@ namespace EMStudio { if (animGraphNode->GetHasVisualGraph()) { - if (!node->GetIsInsideArrowRect(mMousePos)) + if (!node->GetIsInsideArrowRect(m_mousePos)) { - mPlugin->GetAnimGraphModel().Focus(nodeModelIndex); + m_plugin->GetAnimGraphModel().Focus(nodeModelIndex); } } } @@ -656,7 +656,7 @@ namespace EMStudio void BlendGraphWidget::mousePressEvent(QMouseEvent* event) { - mDoubleClickHappened = false; + m_doubleClickHappened = false; NodeGraphWidget::mousePressEvent(event); } @@ -666,25 +666,25 @@ namespace EMStudio { //MCore::LogError("mouse release"); - if (mDoubleClickHappened == false) + if (m_doubleClickHappened == false) { if (event->button() == Qt::RightButton) { - OnContextMenuEvent(event->pos(), event->globalPos(), mPlugin->GetActionFilter()); + OnContextMenuEvent(event->pos(), event->globalPos(), m_plugin->GetActionFilter()); //setCursor( Qt::ArrowCursor ); } } NodeGraphWidget::mouseReleaseEvent(event); //setCursor( Qt::ArrowCursor ); - mDoubleClickHappened = false; + m_doubleClickHappened = false; } // start moving void BlendGraphWidget::OnMoveStart() { - mMoveGroup.RemoveAllCommands(); + m_moveGroup.RemoveAllCommands(); } @@ -701,7 +701,7 @@ namespace EMStudio y); // add it to the group - mMoveGroup.AddCommandString(moveString); + m_moveGroup.AddCommandString(moveString); } @@ -711,7 +711,7 @@ namespace EMStudio AZStd::string resultString; // execute the command - if (GetCommandManager()->ExecuteCommandGroup(mMoveGroup, resultString) == false) + if (GetCommandManager()->ExecuteCommandGroup(m_moveGroup, resultString) == false) { if (resultString.size() > 0) { @@ -810,12 +810,12 @@ namespace EMStudio // check if a connection is valid or not - bool BlendGraphWidget::CheckIfIsCreateConnectionValid(uint32 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) + bool BlendGraphWidget::CheckIfIsCreateConnectionValid(AZ::u16 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) { MCORE_UNUSED(port); - MCORE_ASSERT(mActiveGraph); + MCORE_ASSERT(m_activeGraph); - GraphNode* sourceNode = mActiveGraph->GetCreateConnectionNode(); + GraphNode* sourceNode = m_activeGraph->GetCreateConnectionNode(); GraphNode* targetNode = portNode; // don't allow connection to itself @@ -828,7 +828,7 @@ namespace EMStudio if (sourceNode->GetType() != StateGraphNode::TYPE_ID || targetNode->GetType() != StateGraphNode::TYPE_ID) { // dont allow to connect an input port to another input port or output port to another output port - if (isInputPort == mActiveGraph->GetCreateConnectionIsInputPort()) + if (isInputPort == m_activeGraph->GetCreateConnectionIsInputPort()) { return false; } @@ -845,15 +845,15 @@ namespace EMStudio MCORE_ASSERT(sourceNode->GetType() == BlendTreeVisualNode::TYPE_ID); BlendTreeVisualNode* targetBlendNode; BlendTreeVisualNode* sourceBlendNode; - uint32 sourcePortNr; - uint32 targetPortNr; + AZ::u16 sourcePortNr; + AZ::u16 targetPortNr; // make sure the input always comes from the source node if (isInputPort) { sourceBlendNode = static_cast(sourceNode); targetBlendNode = static_cast(targetNode); - sourcePortNr = mActiveGraph->GetCreateConnectionPortNr(); + sourcePortNr = m_activeGraph->GetCreateConnectionPortNr(); targetPortNr = portNr; } else @@ -861,7 +861,7 @@ namespace EMStudio sourceBlendNode = static_cast(targetNode); targetBlendNode = static_cast(sourceNode); sourcePortNr = portNr; - targetPortNr = mActiveGraph->GetCreateConnectionPortNr(); + targetPortNr = m_activeGraph->GetCreateConnectionPortNr(); } EMotionFX::AnimGraphNode::Port& sourcePort = sourceBlendNode->GetEMFXNode()->GetOutputPort(sourcePortNr); @@ -933,15 +933,15 @@ namespace EMStudio // create the connection - void BlendGraphWidget::OnCreateConnection(uint32 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, uint32 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) + void BlendGraphWidget::OnCreateConnection(AZ::u16 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, AZ::u16 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) { MCORE_UNUSED(targetIsInputPort); - MCORE_ASSERT(mActiveGraph); + MCORE_ASSERT(m_activeGraph); GraphNode* realSourceNode; GraphNode* realTargetNode; - uint32 realInputPortNr; - uint32 realOutputPortNr; + AZ::u16 realInputPortNr; + AZ::u16 realOutputPortNr; if (sourceIsInputPort) { @@ -964,7 +964,7 @@ namespace EMStudio AZStd::string command; // Check if there already is a connection plugged into the port where we want to put our new connection in. - NodeConnection* existingConnection = mActiveGraph->FindInputConnection(realTargetNode, realInputPortNr); + NodeConnection* existingConnection = m_activeGraph->FindInputConnection(realTargetNode, realInputPortNr); // Special case for state nodes. AZ::TypeId transitionType = AZ::TypeId::CreateNull(); @@ -1039,12 +1039,12 @@ namespace EMStudio // curved connection when creating a new one? bool BlendGraphWidget::CreateConnectionMustBeCurved() { - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return true; } - if (mActiveGraph->GetCreateConnectionNode()->GetType() == StateGraphNode::TYPE_ID) + if (m_activeGraph->GetCreateConnectionNode()->GetType() == StateGraphNode::TYPE_ID) { return false; } @@ -1056,12 +1056,12 @@ namespace EMStudio // show helper connection suggestion lines when creating a new connection? bool BlendGraphWidget::CreateConnectionShowsHelpers() { - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return true; } - if (mActiveGraph->GetCreateConnectionNode()->GetType() == StateGraphNode::TYPE_ID) + if (m_activeGraph->GetCreateConnectionNode()->GetType() == StateGraphNode::TYPE_ID) { return false; } @@ -1181,7 +1181,7 @@ namespace EMStudio QAction* action = qobject_cast(sender()); // find the selected node - const QItemSelection selection = mPlugin->GetAnimGraphModel().GetSelectionModel().selection(); + const QItemSelection selection = m_plugin->GetAnimGraphModel().GetSelectionModel().selection(); const QModelIndexList selectionList = selection.indexes(); if (selectionList.empty()) { @@ -1266,19 +1266,19 @@ namespace EMStudio bool BlendGraphWidget::PreparePainting() { // skip rendering in case rendering is disabled - if (mPlugin->GetDisableRendering()) + if (m_plugin->GetDisableRendering()) { return false; } - if (mActiveGraph) + if (m_activeGraph) { // enable or disable graph animation - mActiveGraph->SetUseAnimation(mPlugin->GetAnimGraphOptions().GetGraphAnimation()); + m_activeGraph->SetUseAnimation(m_plugin->GetAnimGraphOptions().GetGraphAnimation()); } // pass down the show fps options flag - NodeGraphWidget::SetShowFPS(mPlugin->GetAnimGraphOptions().GetShowFPS()); + NodeGraphWidget::SetShowFPS(m_plugin->GetAnimGraphOptions().GetShowFPS()); return true; } @@ -1310,7 +1310,7 @@ namespace EMStudio void BlendGraphWidget::OnSetupVisualizeOptions(GraphNode* node) { BlendTreeVisualNode* blendNode = static_cast(node); - mPlugin->GetActionManager().ShowNodeColorPicker(blendNode->GetEMFXNode()); + m_plugin->GetActionManager().ShowNodeColorPicker(blendNode->GetEMFXNode()); } @@ -1326,7 +1326,7 @@ namespace EMStudio boldFont.setBold(true); QFontMetrics boldFontMetrics(boldFont); - if (mActiveGraph) + if (m_activeGraph) { AZStd::string toolTipString; @@ -1335,7 +1335,7 @@ namespace EMStudio QPoint tooltipPos = helpEvent->globalPos(); // find the connection at the mouse position - NodeConnection* connection = mActiveGraph->FindConnection(globalPos); + NodeConnection* connection = m_activeGraph->FindConnection(globalPos); if (connection) { bool conditionFound = false; @@ -1357,8 +1357,8 @@ namespace EMStudio } // get the output and the input port numbers - const uint32 outputPortNr = connection->GetOutputPortNr(); - const uint32 inputPortNr = connection->GetInputPortNr(); + const AZ::u16 outputPortNr = connection->GetOutputPortNr(); + const AZ::u16 inputPortNr = connection->GetInputPortNr(); // show connection or state transition tooltip if (conditionFound == false) @@ -1455,7 +1455,7 @@ namespace EMStudio } } - GraphNode* node = mActiveGraph->FindNode(localPos); + GraphNode* node = m_activeGraph->FindNode(localPos); EMotionFX::AnimGraphNode* animGraphNode = nullptr; if (node) @@ -1475,10 +1475,10 @@ namespace EMStudio if (animGraphNode->GetCanHaveChildren()) { // child nodes - toolTipString += AZStd::string::format("Child Nodes:%i", animGraphNode->GetNumChildNodes()); + toolTipString += AZStd::string::format("Child Nodes:%zu", animGraphNode->GetNumChildNodes()); // recursive child nodes - toolTipString += AZStd::string::format("Recursive Child Nodes:%i", animGraphNode->RecursiveCalcNumNodes()); + toolTipString += AZStd::string::format("Recursive Child Nodes:%zu", animGraphNode->RecursiveCalcNumNodes()); } // states @@ -1542,15 +1542,15 @@ namespace EMStudio const AZ::s32 newEndOffsetX = transition->GetVisualEndOffsetX(); const AZ::s32 newEndOffsetY = transition->GetVisualEndOffsetY(); - mActiveGraph->StopReplaceTransitionHead(); - mActiveGraph->StopReplaceTransitionTail(); + m_activeGraph->StopReplaceTransitionHead(); + m_activeGraph->StopReplaceTransitionTail(); // Reset the visual transition before calling the actual command so that undo captures the right previous values. stateConnection->SetSourceNode(oldSourceNode); stateConnection->SetTargetNode(oldTargetNode); transition->SetVisualOffsets(oldStartOffset.x(), oldStartOffset.y(), oldEndOffset.x(), oldEndOffset.y()); - if (mActiveGraph->GetReplaceTransitionValid()) + if (m_activeGraph->GetReplaceTransitionValid()) { CommandSystem::AdjustTransition(transition, /*isDisabled=*/AZStd::nullopt, @@ -1706,8 +1706,8 @@ namespace EMStudio if (newFocusIndex != newFocusParent) { // We are focusing on a node inside a blendtree/statemachine/referencenode - GraphNode* graphNode = mActiveGraph->FindGraphNode(newFocusIndex); - mActiveGraph->ZoomOnRect(graphNode->GetRect(), geometry().width(), geometry().height(), true); + GraphNode* graphNode = m_activeGraph->FindGraphNode(newFocusIndex); + m_activeGraph->ZoomOnRect(graphNode->GetRect(), geometry().width(), geometry().height(), true); } } else 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 575e45731a..f213b0f2e6 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 @@ -43,7 +43,7 @@ namespace EMStudio BlendGraphWidget(AnimGraphPlugin* plugin, QWidget* parent); // overloaded - bool CheckIfIsCreateConnectionValid(uint32 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) override; + bool CheckIfIsCreateConnectionValid(AZ::u16 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) override; bool CheckIfIsValidTransition(GraphNode* sourceState, GraphNode* targetState) override; bool CheckIfIsValidTransitionSource(GraphNode* sourceState) override; bool CreateConnectionMustBeCurved() override; @@ -60,7 +60,7 @@ namespace EMStudio void OnSetupVisualizeOptions(GraphNode* node) override; void ReplaceTransition(NodeConnection* connection, QPoint oldStartOffset, QPoint oldEndOffset, GraphNode* oldSourceNode, GraphNode* oldTargetNode, GraphNode* newSourceNode, GraphNode* newTargetNode) override; - void OnCreateConnection(uint32 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, uint32 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) override; + void OnCreateConnection(AZ::u16 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, AZ::u16 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) override; void DeleteSelectedItems(NodeGraph* nodeGraph); @@ -126,8 +126,8 @@ namespace EMStudio using NodeGraphByModelIndex = AZStd::unordered_map, QPersistentModelIndexHash>; NodeGraphByModelIndex m_nodeGraphByModelIndex; - QPoint mContextMenuEventMousePos; - bool mDoubleClickHappened; - MCore::CommandGroup mMoveGroup; + QPoint m_contextMenuEventMousePos; + bool m_doubleClickHappened; + MCore::CommandGroup m_moveGroup; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.cpp deleted file mode 100644 index 42550753ca..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// include the required headers -#include "BlendGraphWidgetCallback.h" -//#include "GraphNode.h" -#include "AnimGraphPlugin.h" -#include "NodeGraph.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace EMStudio -{ - // constructor - BlendGraphWidgetCallback::BlendGraphWidgetCallback(BlendGraphWidget* widget) - : GraphWidgetCallback(widget) - { - mBlendGraphWidget = widget; - - mFont.setPixelSize(12); - mTextOptions.setAlignment(Qt::AlignCenter); - mFontMetrics = new QFontMetrics(mFont); - } - - - // destructor - BlendGraphWidgetCallback::~BlendGraphWidgetCallback() - { - delete mFontMetrics; - } - - - void BlendGraphWidgetCallback::DrawOverlay(QPainter& painter) - { - // get the plugin and return directly in case we're not showing the processed nodes - AnimGraphPlugin* plugin = mBlendGraphWidget->GetPlugin(); - //if (plugin->GetShowProcessed() == false) - // return; - - // if we're going to display some visualization information - // if (plugin->GetDisplayPlaySpeeds() || plugin->GetDisplayGlobalWeights() || plugin->GetDisplaySyncStatus()) - if (plugin->GetDisplayFlags() != 0) - { - // get the active graph and the corresponding emfx node and return if they are invalid or in case the opened node is no blend tree - NodeGraph* activeGraph = mBlendGraphWidget->GetActiveGraph(); - EMotionFX::AnimGraphNode* currentNode = mBlendGraphWidget->GetCurrentNode(); - if (activeGraph == nullptr || currentNode == nullptr) - { - return; - } - - // get the currently selected actor instance and its anim graph instance and return if they are not valid - EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); - if (actorInstance == nullptr || actorInstance->GetAnimGraphInstance() == nullptr) - { - return; - } - - EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); - - // get the number of nodes and iterate through them - const uint32 numNodes = activeGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) - { - GraphNode* graphNode = activeGraph->GetNode(i); - EMotionFX::AnimGraphNode* emfxNode = currentNode->RecursiveFindNodeById(graphNode->GetId()); - - // skip invisible graph nodes - if (graphNode->GetIsVisible() == false) - { - continue; - } - - // make sure the corresponding anim graph node is valid - if (emfxNode == nullptr) - { - continue; - } - - // skip non-processed nodes and nodes that have no output pose - if (emfxNode->GetHasOutputPose() == false || graphNode->GetIsProcessed() == false) - { - continue; - } - - if (graphNode->GetIsHighlighted()) - { - continue; - } - - // get the unique data - EMotionFX::AnimGraphNodeData* uniqueData = emfxNode->FindUniqueNodeData(animGraphInstance); - - // draw the background darkened rect - uint32 requiredHeight = 5; - const uint32 rectWidth = 155; - const uint32 heightSpacing = 11; - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYSPEED)) - { - requiredHeight += heightSpacing; - } - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_GLOBALWEIGHT)) - { - requiredHeight += heightSpacing; - } - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_SYNCSTATUS)) - { - requiredHeight += heightSpacing; - } - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYPOSITION)) - { - requiredHeight += heightSpacing; - } - const QRect& nodeRect = graphNode->GetFinalRect(); - QRect textRect(nodeRect.center().x() - rectWidth / 2, nodeRect.center().y() - requiredHeight / 2, rectWidth, requiredHeight); - const uint32 alpha = (graphNode->GetIsHighlighted()) ? 225 : 175; - const QColor backgroundColor(0, 0, 0, alpha); - painter.setBrush(backgroundColor); - painter.setPen(Qt::black); - painter.drawRect(textRect); - - QColor textColor(255, 255, 0); - //textColor = graphNode->GetBaseColor(); - if (graphNode->GetIsHighlighted()) - { - textColor = QColor(0, 255, 0); - } - - painter.setPen(textColor); - painter.setFont(mFont); - - QPoint textPosition = textRect.topLeft(); - textPosition.setX(textPosition.x() + 3); - textPosition.setY(textPosition.y() + 11); - - // add the playspeed - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYSPEED)) - { - mQtTempString.sprintf("Play Speed = %.2f", emfxNode->GetPlaySpeed(animGraphInstance)); - painter.drawText(textPosition, mQtTempString); - textPosition.setY(textPosition.y() + heightSpacing); - } - - // add the global weight - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_GLOBALWEIGHT)) - { - mQtTempString.sprintf("Global Weight = %.2f", uniqueData->GetGlobalWeight()); - painter.drawText(textPosition, mQtTempString); - textPosition.setY(textPosition.y() + heightSpacing); - } - - // add the sync - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_SYNCSTATUS)) - { - mQtTempString.sprintf("Synced = %s", animGraphInstance->GetIsSynced(emfxNode->GetObjectIndex()) ? "Yes" : "No"); - painter.drawText(textPosition, mQtTempString); - textPosition.setY(textPosition.y() + heightSpacing); - } - - // add the play position - if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYPOSITION)) - { - mQtTempString.sprintf("Play Time = %.3f / %.3f", uniqueData->GetCurrentPlayTime(), uniqueData->GetDuration()); - painter.drawText(textPosition, mQtTempString); - textPosition.setY(textPosition.y() + heightSpacing); - } - } - } - - - const EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); - if (!actorInstance) - { - return; - } - - EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); - if (!animGraphInstance) - { - return; - } - - // get the active graph and the corresponding emfx node and return if they are invalid or in case the opened node is no blend tree - NodeGraph* activeGraph = mBlendGraphWidget->GetActiveGraph(); - EMotionFX::AnimGraphNode* currentNode = mBlendGraphWidget->GetCurrentNode(); - - if (!activeGraph || !currentNode || azrtti_typeid(currentNode) != azrtti_typeid()) - { - return; - } - - const EMotionFX::AnimGraph* simulatedAnimGraph = animGraphInstance->GetAnimGraph(); - const EMotionFX::AnimGraph* renderedAnimGraph = currentNode->GetAnimGraph(); - if (simulatedAnimGraph != renderedAnimGraph) - { - AzFramework::StringFunc::Path::GetFileName(simulatedAnimGraph->GetFileName(), m_tempStringA); - AzFramework::StringFunc::Path::GetFileName(renderedAnimGraph->GetFileName(), m_tempStringB); - - m_tempStringC = AZStd::string::format("Simulated anim graph on character (%s) differs from the currently shown one (%s).", m_tempStringA.c_str(), m_tempStringB.c_str()); - GraphNode::RenderText(painter, m_tempStringC.c_str(), QColor(255, 0, 0), mFont, *mFontMetrics, Qt::AlignLeft, QRect(8, 0, 50, 20)); - } - - if (activeGraph->GetScale() < 0.5f) - { - return; - } - - // get the number of nodes and iterate through them - const uint32 numNodes = activeGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) - { - GraphNode* graphNode = activeGraph->GetNode(i); - EMotionFX::AnimGraphNode* emfxNode = currentNode->RecursiveFindNodeById(graphNode->GetId()); - - // make sure the corresponding anim graph node is valid - if (emfxNode == nullptr) - { - continue; - } - - // iterate through all connections connected to this node - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) - { - NodeConnection* visualConnection = graphNode->GetConnection(c); - - // get the source and target nodes - GraphNode* sourceNode = visualConnection->GetSourceNode(); - EMotionFX::AnimGraphNode* emfxSourceNode = currentNode->RecursiveFindNodeById(sourceNode->GetId()); - GraphNode* targetNode = visualConnection->GetTargetNode(); - EMotionFX::AnimGraphNode* emfxTargetNode = currentNode->RecursiveFindNodeById(targetNode->GetId()); - - //QColor color(255,0,255); - QColor color = visualConnection->GetTargetNode()->GetInputPort(visualConnection->GetInputPortNr())->GetColor(); - - // only show values for connections that are processed - if (visualConnection->GetIsProcessed() == false) - { - continue; - } - - const uint32 inputPortNr = visualConnection->GetInputPortNr(); - const uint32 outputPortNr = visualConnection->GetOutputPortNr(); - MCore::Attribute* attribute = emfxSourceNode->GetOutputValue(animGraphInstance, outputPortNr); - - // fill the string with data - m_tempStringA.clear(); - switch (attribute->GetType()) - { - // float attributes - case MCore::AttributeFloat::TYPE_ID: - { - MCore::AttributeFloat* floatAttribute = static_cast(attribute); - m_tempStringA = AZStd::string::format("%.2f", floatAttribute->GetValue()); - break; - } - - // vector 2 attributes - case MCore::AttributeVector2::TYPE_ID: - { - MCore::AttributeVector2* vecAttribute = static_cast(attribute); - AZ::Vector2 vec = vecAttribute->GetValue(); - m_tempStringA = AZStd::string::format("(%.2f, %.2f)", static_cast(vec.GetX()), static_cast(vec.GetY())); - break; - } - - // vector 3 attributes - case MCore::AttributeVector3::TYPE_ID: - { - MCore::AttributeVector3* vecAttribute = static_cast(attribute); - AZ::PackedVector3f vec = vecAttribute->GetValue(); - m_tempStringA = AZStd::string::format("(%.2f, %.2f, %.2f)", static_cast(vec.GetX()), static_cast(vec.GetY()), static_cast(vec.GetZ())); - break; - } - - // vector 4 attributes - case MCore::AttributeVector4::TYPE_ID: - { - MCore::AttributeVector4* vecAttribute = static_cast(attribute); - AZ::Vector4 vec = vecAttribute->GetValue(); - m_tempStringA = AZStd::string::format("(%.2f, %.2f, %.2f, %.2f)", static_cast(vec.GetX()), static_cast(vec.GetY()), static_cast(vec.GetZ()), static_cast(vec.GetW())); - break; - } - - // boolean attributes - case MCore::AttributeBool::TYPE_ID: - { - MCore::AttributeBool* boolAttribute = static_cast(attribute); - m_tempStringA = AZStd::string::format("%s", AZStd::to_string(boolAttribute->GetValue()).c_str()); - break; - } - - // rotation attributes - case MCore::AttributeQuaternion::TYPE_ID: - { - MCore::AttributeQuaternion* quatAttribute = static_cast(attribute); - const AZ::Vector3 eulerAngles = quatAttribute->GetValue().ToEuler(); - m_tempStringA = AZStd::string::format("(%.2f, %.2f, %.2f)", static_cast(eulerAngles.GetX()), static_cast(eulerAngles.GetY()), static_cast(eulerAngles.GetZ())); - break; - } - - - // pose attribute - case EMotionFX::AttributePose::TYPE_ID: - { - // handle blend 2 nodes - if (azrtti_typeid(emfxTargetNode) == azrtti_typeid()) - { - // type-cast the target node to our blend node - EMotionFX::BlendTreeBlend2Node* blendNode = static_cast(emfxTargetNode); - - // get the weight from the input port - float weight = blendNode->GetInputNumberAsFloat(animGraphInstance, EMotionFX::BlendTreeBlend2Node::INPUTPORT_WEIGHT); - weight = MCore::Clamp(weight, 0.0f, 1.0f); - - // map the weight to the connection - if (inputPortNr == 0) - { - m_tempStringA = AZStd::string::format("%.2f", 1.0f - weight); - } - else - { - m_tempStringA = AZStd::string::format("%.2f", weight); - } - } - - // handle blend N nodes - if (azrtti_typeid(emfxTargetNode) == azrtti_typeid()) - { - // type-cast the target node to our blend node - EMotionFX::BlendTreeBlendNNode* blendNode = static_cast(emfxTargetNode); - - // get two nodes that we receive input poses from, and get the blend weight - float weight; - EMotionFX::AnimGraphNode* nodeA; - EMotionFX::AnimGraphNode* nodeB; - uint32 poseIndexA; - uint32 poseIndexB; - blendNode->FindBlendNodes(animGraphInstance, &nodeA, &nodeB, &poseIndexA, &poseIndexB, &weight); - - // map the weight to the connection - if (inputPortNr == poseIndexA) - { - m_tempStringA = AZStd::string::format("%.2f", 1.0f - weight); - } - else - { - m_tempStringA = AZStd::string::format("%.2f", weight); - } - } - break; - } - - default: - { - attribute->ConvertToString(m_mcoreTempString); - m_tempStringA = m_mcoreTempString.c_str(); - } - } - - // only display the value in case it is not empty - if (!m_tempStringA.empty()) - { - QPoint connectionAttachPoint = visualConnection->CalcFinalRect().center(); - - int halfTextHeight = 6; - int textWidth = mFontMetrics->width(m_tempStringA.c_str()); - int halfTextWidth = textWidth / 2; - - QRect textRect(connectionAttachPoint.x() - halfTextWidth - 1, connectionAttachPoint.y() - halfTextHeight, textWidth + 4, halfTextHeight * 2); - QPoint textPosition = textRect.bottomLeft(); - textPosition.setY(textPosition.y() - 1); - textPosition.setX(textPosition.x() + 2); - - const QColor backgroundColor(30, 30, 30); - - // draw the background rect for the text - painter.setBrush(backgroundColor); - painter.setPen(Qt::black); - painter.drawRect(textRect); - - // draw the text - painter.setPen(color); - painter.setFont(mFont); - // OLD: - //painter.drawText( textPosition, mTempString.c_str() ); - // NEW: - GraphNode::RenderText(painter, m_tempStringA.c_str(), color, mFont, *mFontMetrics, Qt::AlignCenter, textRect); - } - } - } - } -} // namespace EMStudio - -#include diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.h deleted file mode 100644 index 399c679a29..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidgetCallback.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#ifndef __EMSTUDIO_BLENDGRAPHWIDGETCALLBACK_H -#define __EMSTUDIO_BLENDGRAPHWIDGETCALLBACK_H - -// include required headers -#if !defined(Q_MOC_RUN) -#include -#include "../StandardPluginsConfig.h" -#include "GraphWidgetCallback.h" -#include "BlendGraphWidget.h" -#include -#include -#include -#endif - - -namespace EMStudio -{ - // blend graph widget callback - class BlendGraphWidgetCallback - : public GraphWidgetCallback - { - MCORE_MEMORYOBJECTCATEGORY(BlendGraphWidgetCallback, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - - public: - BlendGraphWidgetCallback(BlendGraphWidget* widget); - virtual ~BlendGraphWidgetCallback(); - - void DrawOverlay(QPainter& painter); - - private: - BlendGraphWidget* mBlendGraphWidget; - - QFont mFont; - QString mQtTempString; - QTextOption mTextOptions; - QFontMetrics* mFontMetrics; - AZStd::string m_tempStringA; - AZStd::string m_tempStringB; - AZStd::string m_tempStringC; - AZStd::string m_mcoreTempString; - }; -} // namespace EMStudio - - -#endif diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.cpp index 81812145e7..3b130f5bd7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.cpp @@ -22,27 +22,27 @@ namespace EMStudio QVBoxLayout* layout = new QVBoxLayout(); - mHierarchyWidget = new AnimGraphHierarchyWidget(this); + m_hierarchyWidget = new AnimGraphHierarchyWidget(this); // create the ok and cancel buttons QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mCancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); + m_okButton = new QPushButton("OK"); + m_cancelButton = new QPushButton("Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); - layout->addWidget(mHierarchyWidget); + layout->addWidget(m_hierarchyWidget); layout->addLayout(buttonLayout); setLayout(layout); setMinimumSize(QSize(400, 400)); - mOKButton->setEnabled(false); + m_okButton->setEnabled(false); - connect(mOKButton, &QPushButton::clicked, this, &BlendNodeSelectionWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &BlendNodeSelectionWindow::reject); - connect(mHierarchyWidget, &AnimGraphHierarchyWidget::OnSelectionDone, this, &BlendNodeSelectionWindow::OnNodeSelected); - connect(mHierarchyWidget, &AnimGraphHierarchyWidget::OnSelectionChanged, this, &BlendNodeSelectionWindow::OnSelectionChanged); + connect(m_okButton, &QPushButton::clicked, this, &BlendNodeSelectionWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &BlendNodeSelectionWindow::reject); + connect(m_hierarchyWidget, &AnimGraphHierarchyWidget::OnSelectionDone, this, &BlendNodeSelectionWindow::OnNodeSelected); + connect(m_hierarchyWidget, &AnimGraphHierarchyWidget::OnSelectionChanged, this, &BlendNodeSelectionWindow::OnSelectionChanged); } @@ -54,7 +54,7 @@ namespace EMStudio void BlendNodeSelectionWindow::OnNodeSelected() { - if (mUseSingleSelection) + if (m_useSingleSelection) { accept(); } @@ -66,7 +66,7 @@ namespace EMStudio AZ_UNUSED(selected); AZ_UNUSED(deselected); - mOKButton->setEnabled(mHierarchyWidget->HasSelectedItems()); + m_okButton->setEnabled(m_hierarchyWidget->HasSelectedItems()); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.h index 048d79a696..9d49008d40 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendNodeSelectionWindow.h @@ -27,9 +27,9 @@ namespace EMStudio * 2. Use the itemSelectionChanged() signal of the GetNodeHierarchyWidget()->GetTreeWidget() to detect when the user adjusts the selection in the node hierarchy widget. * 3. Use the OnSelectionDone() in the GetNodeHierarchyWidget() to detect when the user finished selecting and pressed the OK button. * Example: - * connect( mNodeSelectionWindow, SIGNAL(rejected()), this, SLOT(UserWantsToCancel_1()) ); - * connect( mNodeSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged_2()) ); - * connect( mNodeSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(MCore::Array)), this, SLOT(FinishedSelectionAndPressedOK_3(MCore::Array)) ); + * connect( m_nodeSelectionWindow, SIGNAL(rejected()), this, SLOT(UserWantsToCancel_1()) ); + * connect( m_nodeSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged_2()) ); + * connect( m_nodeSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); */ class BlendNodeSelectionWindow : public QDialog @@ -41,16 +41,16 @@ namespace EMStudio BlendNodeSelectionWindow(QWidget* parent = nullptr); virtual ~BlendNodeSelectionWindow(); - AnimGraphHierarchyWidget& GetAnimGraphHierarchyWidget() { return *mHierarchyWidget; } + AnimGraphHierarchyWidget& GetAnimGraphHierarchyWidget() { return *m_hierarchyWidget; } public slots: void OnNodeSelected(); void OnSelectionChanged(const QItemSelection& selected, const QItemSelection& deselected); private: - AnimGraphHierarchyWidget* mHierarchyWidget; - QPushButton* mOKButton; - QPushButton* mCancelButton; - bool mUseSingleSelection; + AnimGraphHierarchyWidget* m_hierarchyWidget; + QPushButton* m_okButton; + QPushButton* m_cancelButton; + bool m_useSingleSelection; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendTreeVisualNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendTreeVisualNode.cpp index 2f86196068..823d9a4a88 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendTreeVisualNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendTreeVisualNode.cpp @@ -38,26 +38,26 @@ namespace EMStudio RemoveAllConnections(); // add all input ports - const AZStd::vector& inPorts = mEMFXNode->GetInputPorts(); - const uint32 numInputs = static_cast(inPorts.size()); - mInputPorts.Reserve(numInputs); - for (uint32 i = 0; i < numInputs; ++i) + const AZStd::vector& inPorts = m_emfxNode->GetInputPorts(); + const AZ::u16 numInputs = aznumeric_caster(inPorts.size()); + m_inputPorts.reserve(numInputs); + for (AZ::u16 i = 0; i < numInputs; ++i) { NodePort* port = AddInputPort(false); - port->SetNameID(inPorts[i].mNameID); + port->SetNameID(inPorts[i].m_nameId); port->SetColor(GetPortColor(inPorts[i])); } if (GetHasVisualOutputPorts()) { // add all output ports - const AZStd::vector& outPorts = mEMFXNode->GetOutputPorts(); - const uint32 numOutputs = static_cast(outPorts.size()); - mOutputPorts.Reserve(numOutputs); - for (uint32 i = 0; i < numOutputs; ++i) + const AZStd::vector& outPorts = m_emfxNode->GetOutputPorts(); + const AZ::u16 numOutputs = aznumeric_caster(outPorts.size()); + m_outputPorts.reserve(numOutputs); + for (AZ::u16 i = 0; i < numOutputs; ++i) { NodePort* port = AddOutputPort(false); - port->SetNameID(outPorts[i].mNameID); + port->SetNameID(outPorts[i].m_nameId); port->SetColor(GetPortColor(outPorts[i])); } } @@ -71,12 +71,12 @@ namespace EMStudio { EMotionFX::BlendTreeConnection* connection = childIndex.data(AnimGraphModel::ROLE_CONNECTION_POINTER).value(); - GraphNode* source = mParentGraph->FindGraphNode(connection->GetSourceNode()); + GraphNode* source = m_parentGraph->FindGraphNode(connection->GetSourceNode()); GraphNode* target = this; - const uint32 sourcePort = connection->GetSourcePort(); - const uint32 targetPort = connection->GetTargetPort(); + const AZ::u16 sourcePort = connection->GetSourcePort(); + const AZ::u16 targetPort = connection->GetTargetPort(); - NodeConnection* visualConnection = new NodeConnection(mParentGraph, childIndex, target, targetPort, source, sourcePort); + NodeConnection* visualConnection = new NodeConnection(m_parentGraph, childIndex, target, targetPort, source, sourcePort); target->AddConnection(visualConnection); } } @@ -90,7 +90,7 @@ namespace EMStudio // get the port color for a given EMotion FX port QColor BlendTreeVisualNode::GetPortColor(const EMotionFX::AnimGraphNode::Port& port) const { - switch (port.mCompatibleTypes[0]) + switch (port.m_compatibleTypes[0]) { case EMotionFX::AttributePose::TYPE_ID: return QColor(150, 150, 255); @@ -112,7 +112,6 @@ namespace EMStudio default: return QColor(50, 250, 250); } - ; } @@ -120,7 +119,7 @@ namespace EMStudio void BlendTreeVisualNode::Render(QPainter& painter, QPen* pen, bool renderShadow) { // only render if the given node is visible - if (mIsVisible == false) + if (m_isVisible == false) { return; } @@ -131,8 +130,8 @@ namespace EMStudio RenderShadow(painter); } - float opacityFactor = mOpacity; - if (mIsEnabled == false) + float opacityFactor = m_opacity; + if (m_isEnabled == false) { opacityFactor *= 0.35f; } @@ -156,7 +155,7 @@ namespace EMStudio { borderColor.setRgb(255, 128, 0); - if (mParentGraph->GetScale() > 0.75f) + if (m_parentGraph->GetScale() > 0.75f) { pen->setWidth(2); } @@ -167,12 +166,9 @@ namespace EMStudio { borderColor.setRgb(255, 0, 0); } - //else - //if (mIsProcessed) - //borderColor.setRgb(255,225,0); else { - borderColor = mBorderColor; + borderColor = m_borderColor; } } @@ -184,11 +180,11 @@ namespace EMStudio } else // not selected { - if (mIsEnabled) + if (m_isEnabled) { - if (mIsProcessed || colorAllNodes) + if (m_isProcessed || colorAllNodes) { - bgColor = mBaseColor; + bgColor = m_baseColor; } else { @@ -205,9 +201,9 @@ namespace EMStudio // blinking error if (hasError && !isSelected) { - if (mParentGraph->GetUseAnimation()) + if (m_parentGraph->GetUseAnimation()) { - borderColor = mParentGraph->GetErrorBlinkColor(); + borderColor = m_parentGraph->GetErrorBlinkColor(); } else { @@ -221,16 +217,13 @@ namespace EMStudio QColor headerBgColor; bgColor2 = bgColor.lighter(30);// make darker actually, 30% of the old color, same as bgColor * 0.3f; - //if (mIsProcessed == false/* && mIsUpdated*/ && hasError == false && mIsSelected == false) - //headerBgColor = mBaseColor.lighter(30); - //else headerBgColor = bgColor.lighter(20); // text color QColor textColor; if (!isSelected) { - if (mIsEnabled) + if (m_isEnabled) { textColor = Qt::white; } @@ -244,10 +237,10 @@ namespace EMStudio textColor = QColor(bgColor); } - if (mIsCollapsed == false) + if (m_isCollapsed == false) { // is highlighted/hovered (on-mouse-over effect) - if (mIsHighlighted) + if (m_isHighlighted) { bgColor = bgColor.lighter(120); bgColor2 = bgColor2.lighter(120); @@ -256,9 +249,9 @@ namespace EMStudio // draw the main rect painter.setPen(borderColor); - if (!mIsProcessed && mIsEnabled && !isSelected && !colorAllNodes) + if (!m_isProcessed && m_isEnabled && !isSelected && !colorAllNodes) { - if (mIsHighlighted == false) + if (m_isHighlighted == false) { painter.setBrush(QColor(40, 40, 40)); } @@ -269,21 +262,21 @@ namespace EMStudio } else { - QLinearGradient bgGradient(0, mRect.top(), 0, mRect.bottom()); + QLinearGradient bgGradient(0, m_rect.top(), 0, m_rect.bottom()); bgGradient.setColorAt(0.0f, bgColor); bgGradient.setColorAt(1.0f, bgColor2); painter.setBrush(bgGradient); } - painter.drawRoundedRect(mRect, BORDER_RADIUS, BORDER_RADIUS); + painter.drawRoundedRect(m_rect, BORDER_RADIUS, BORDER_RADIUS); // if the scale is so small that we can't see those small things anymore - QRect fullHeaderRect(mRect.left(), mRect.top(), mRect.width(), 30); - QRect headerRect(mRect.left(), mRect.top(), mRect.width(), 15); - QRect subHeaderRect(mRect.left(), mRect.top() + 13, mRect.width(), 15); + QRect fullHeaderRect(m_rect.left(), m_rect.top(), m_rect.width(), 30); + QRect headerRect(m_rect.left(), m_rect.top(), m_rect.width(), 15); + QRect subHeaderRect(m_rect.left(), m_rect.top() + 13, m_rect.width(), 15); // if the scale is so small that we can't see those small things anymore - if (mParentGraph->GetScale() < 0.3f) + if (m_parentGraph->GetScale() < 0.3f) { painter.setOpacity(1.0f); painter.setClipping(false); @@ -295,19 +288,19 @@ namespace EMStudio painter.setPen(borderColor); painter.setClipRect(fullHeaderRect, Qt::ReplaceClip); painter.setBrush(headerBgColor); - painter.drawRoundedRect(mRect, BORDER_RADIUS, BORDER_RADIUS); + painter.drawRoundedRect(m_rect, BORDER_RADIUS, BORDER_RADIUS); painter.setClipping(false); // if the scale is so small that we can't see those small things anymore - if (mParentGraph->GetScale() > 0.5f) + if (m_parentGraph->GetScale() > 0.5f) { // draw the input ports QColor portBrushColor, portPenColor; - const uint32 numInputs = mInputPorts.GetLength(); - for (uint32 i = 0; i < numInputs; ++i) + const AZ::u16 numInputs = aznumeric_caster(m_inputPorts.size()); + for (AZ::u16 i = 0; i < numInputs; ++i) { // get the input port and the corresponding rect - NodePort* inputPort = &mInputPorts[i]; + NodePort* inputPort = &m_inputPorts[i]; const QRect& portRect = inputPort->GetRect(); // get and set the pen and brush colors @@ -322,11 +315,11 @@ namespace EMStudio if (GetHasVisualOutputPorts()) { // draw the output ports - const uint32 numOutputs = mOutputPorts.GetLength(); - for (uint32 i = 0; i < numOutputs; ++i) + const AZ::u16 numOutputs = aznumeric_caster(m_outputPorts.size()); + for (AZ::u16 i = 0; i < numOutputs; ++i) { // get the output port and the corresponding rect - NodePort* outputPort = &mOutputPorts[i]; + NodePort* outputPort = &m_outputPorts[i]; const QRect& portRect = outputPort->GetRect(); // get and set the pen and brush colors @@ -343,16 +336,16 @@ namespace EMStudio else // it is collapsed { // is highlighted/hovered (on-mouse-over effect) - if (mIsHighlighted) + if (m_isHighlighted) { bgColor = bgColor.lighter(160); headerBgColor = headerBgColor.lighter(160); } // if the scale is so small that we can't see those small things anymore - QRect fullHeaderRect(mRect.left(), mRect.top(), mRect.width(), 30); - QRect headerRect(mRect.left(), mRect.top(), mRect.width(), 15); - QRect subHeaderRect(mRect.left(), mRect.top() + 13, mRect.width(), 15); + QRect fullHeaderRect(m_rect.left(), m_rect.top(), m_rect.width(), 30); + QRect headerRect(m_rect.left(), m_rect.top(), m_rect.width(), 15); + QRect subHeaderRect(m_rect.left(), m_rect.top() + 13, m_rect.width(), 15); // draw the header painter.setPen(borderColor); @@ -360,7 +353,7 @@ namespace EMStudio painter.drawRoundedRect(fullHeaderRect, 7.0, 7.0); // if the scale is so small that we can't see those small things anymore - if (mParentGraph->GetScale() < 0.3f) + if (m_parentGraph->GetScale() < 0.3f) { painter.setOpacity(1.0f); return; @@ -371,7 +364,7 @@ namespace EMStudio painter.setClipping(false); } - if (mParentGraph->GetScale() > 0.3f) + if (m_parentGraph->GetScale() > 0.3f) { // draw the collapse triangle if (isSelected) @@ -385,37 +378,37 @@ namespace EMStudio painter.setBrush(QColor(175, 175, 175)); } - if (mIsCollapsed == false) + if (m_isCollapsed == false) { QPoint triangle[3]; - triangle[0].setX(mArrowRect.left()); - triangle[0].setY(mArrowRect.top()); - triangle[1].setX(mArrowRect.right()); - triangle[1].setY(mArrowRect.top()); - triangle[2].setX(mArrowRect.center().x()); - triangle[2].setY(mArrowRect.bottom()); + triangle[0].setX(m_arrowRect.left()); + triangle[0].setY(m_arrowRect.top()); + triangle[1].setX(m_arrowRect.right()); + triangle[1].setY(m_arrowRect.top()); + triangle[2].setX(m_arrowRect.center().x()); + triangle[2].setY(m_arrowRect.bottom()); painter.drawPolygon(triangle, 3, Qt::WindingFill); } else { QPoint triangle[3]; - triangle[0].setX(mArrowRect.left()); - triangle[0].setY(mArrowRect.top()); - triangle[1].setX(mArrowRect.right()); - triangle[1].setY(mArrowRect.center().y()); - triangle[2].setX(mArrowRect.left()); - triangle[2].setY(mArrowRect.bottom()); + triangle[0].setX(m_arrowRect.left()); + triangle[0].setY(m_arrowRect.top()); + triangle[1].setX(m_arrowRect.right()); + triangle[1].setY(m_arrowRect.center().y()); + triangle[2].setX(m_arrowRect.left()); + triangle[2].setY(m_arrowRect.bottom()); painter.drawPolygon(triangle, 3, Qt::WindingFill); } // draw the visualize area - if (mCanVisualize) + if (m_canVisualize) { RenderVisualizeRect(painter, bgColor, bgColor2); } // render the tracks etc - if (mIsCollapsed == false && mEMFXNode->GetHasOutputPose() && mIsProcessed) + if (m_isCollapsed == false && m_emfxNode->GetHasOutputPose() && m_isProcessed) { RenderTracks(painter, bgColor, bgColor2); } @@ -425,60 +418,57 @@ namespace EMStudio } // render the text overlay with the pre-baked node name and port names etc. - float textOpacity = MCore::Clamp(mParentGraph->GetScale() * mParentGraph->GetScale() * 1.5f, 0.0f, 1.0f); - //if (mIsProcessed == false && mIsEnabled) - //textOpacity *= 0.65f; + float textOpacity = MCore::Clamp(m_parentGraph->GetScale() * m_parentGraph->GetScale() * 1.5f, 0.0f, 1.0f); painter.setOpacity(textOpacity); // draw the title - //painter.drawPixmap( mRect, mTextPixmap ); painter.setBrush(Qt::NoBrush); painter.setPen(textColor); - painter.setFont(mHeaderFont); - painter.drawStaticText(mRect.left(), mRect.top(), mTitleText); + painter.setFont(m_headerFont); + painter.drawStaticText(m_rect.left(), m_rect.top(), m_titleText); // draw the subtitle - painter.setFont(mSubTitleFont); - painter.drawStaticText(mRect.left(), aznumeric_cast(mRect.top() + mTitleText.size().height() - 3), mSubTitleText); + painter.setFont(m_subTitleFont); + painter.drawStaticText(m_rect.left(), aznumeric_cast(m_rect.top() + m_titleText.size().height() - 3), m_subTitleText); // draw the info text - if (mIsCollapsed == false) + if (m_isCollapsed == false) { // draw info text QRect textRect; CalcInfoTextRect(textRect, false); - painter.setFont(mInfoTextFont); + painter.setFont(m_infoTextFont); painter.setPen(QColor(255, 128, 0)); - painter.drawStaticText(mRect.left(), textRect.top() + 4, mInfoText); + painter.drawStaticText(m_rect.left(), textRect.top() + 4, m_infoText); painter.setPen(textColor); - painter.setFont(mPortNameFont); + painter.setFont(m_portNameFont); // draw input port text - const uint32 numInputs = mInputPorts.GetLength(); - for (uint32 i = 0; i < numInputs; ++i) + const AZ::u16 numInputs = aznumeric_caster(m_inputPorts.size()); + for (AZ::u16 i = 0; i < numInputs; ++i) { - NodePort* inputPort = &mInputPorts[i]; + NodePort* inputPort = &m_inputPorts[i]; const QRect& portRect = inputPort->GetRect(); if (inputPort->GetNameID() == MCORE_INVALIDINDEX32) { continue; } - painter.drawStaticText(mRect.left() + 8, portRect.top() - 3, mInputPortText[i]); + painter.drawStaticText(m_rect.left() + 8, portRect.top() - 3, m_inputPortText[i]); } // draw output port text - const uint32 numOutputs = mOutputPorts.GetLength(); - for (uint32 i = 0; i < numOutputs; ++i) + const AZ::u16 numOutputs = aznumeric_caster(m_outputPorts.size()); + for (AZ::u16 i = 0; i < numOutputs; ++i) { - NodePort* outputPort = &mOutputPorts[i]; + NodePort* outputPort = &m_outputPorts[i]; const QRect& portRect = outputPort->GetRect(); if (outputPort->GetNameID() == MCORE_INVALIDINDEX32) { continue; } - painter.drawStaticText(aznumeric_cast(mRect.right() - 10 - mOutputPortText[i].size().width()), portRect.top() - 3, mOutputPortText[i]); + painter.drawStaticText(aznumeric_cast(m_rect.right() - 10 - m_outputPortText[i].size().width()), portRect.top() - 3, m_outputPortText[i]); } } 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 aed7ec08bb..01a7cb1bd1 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 @@ -36,7 +36,7 @@ namespace EMStudio const AZStd::vector& objectPrototypes = plugin->GetAnimGraphObjectFactory()->GetUiObjectPrototypes(); for (EMotionFX::AnimGraphObject* objectPrototype : objectPrototypes) { - if (mPlugin->CheckIfCanCreateObject(focusedGraphObject, objectPrototype, category)) + if (m_plugin->CheckIfCanCreateObject(focusedGraphObject, objectPrototype, category)) { isEmpty = false; break; @@ -54,7 +54,7 @@ namespace EMStudio for (const EMotionFX::AnimGraphObject* objectPrototype : objectPrototypes) { - if (mPlugin->CheckIfCanCreateObject(focusedGraphObject, objectPrototype, category)) + if (m_plugin->CheckIfCanCreateObject(focusedGraphObject, objectPrototype, category)) { const EMotionFX::AnimGraphNode* nodePrototype = static_cast(objectPrototype); QAction* action = menu->addAction(nodePrototype->GetPaletteName()); @@ -72,17 +72,17 @@ namespace EMStudio QMenu* nodeGroupMenu = new QMenu("Node Group", menu); bool isNodeInNoneGroup = true; QAction* noneNodeGroupAction = nodeGroupMenu->addAction("None"); - noneNodeGroupAction->setData(0); // this index is there to know it's the real none action in case one node group is also called like that + noneNodeGroupAction->setData(qulonglong(0)); // this index is there to know it's the real none action in case one node group is also called like that connect(noneNodeGroupAction, &QAction::triggered, this, &BlendGraphWidget::OnNodeGroupSelected); noneNodeGroupAction->setCheckable(true); - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); - for (uint32 i = 0; i < numNodeGroups; ++i) + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); + for (size_t i = 0; i < numNodeGroups; ++i) { EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(i); QAction* nodeGroupAction = nodeGroupMenu->addAction(nodeGroup->GetName()); - nodeGroupAction->setData(i + 1); // index of the menu added, not used + nodeGroupAction->setData(qulonglong(i + 1)); // index of the menu added, not used connect(nodeGroupAction, &QAction::triggered, this, &BlendGraphWidget::OnNodeGroupSelected); nodeGroupAction->setCheckable(true); @@ -144,7 +144,7 @@ namespace EMStudio else { QMenu* previewMotionMenu = new QMenu("Preview Motions", menu); - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { const char* motionId = motionNode->GetMotionId(i); QAction* previewMotionAction = previewMotionMenu->addAction(motionId); @@ -287,7 +287,7 @@ namespace EMStudio { menu->addSeparator(); QAction* action = menu->addAction("Adjust Visualization Color"); - connect(action, &QAction::triggered, [this, animGraphNode](bool) { mPlugin->GetActionManager().ShowNodeColorPicker(animGraphNode); }); + connect(action, &QAction::triggered, [this, animGraphNode](bool) { m_plugin->GetActionManager().ShowNodeColorPicker(animGraphNode); }); } } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp index 7038441e4c..4c32cdb0cc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.cpp @@ -20,17 +20,17 @@ BOOL CALLBACK GameController::EnumJoysticksCallback(const DIDEVICEINSTANCE* pdid GameController* manager = static_cast(pContext); // store the name - manager->mDeviceInfo.mName = pdidInstance->tszProductName; + manager->m_deviceInfo.m_name = pdidInstance->tszProductName; // Skip anything other than the perferred Joystick device as defined by the control panel. // Instead you could store all the enumerated Joysticks and let the user pick. - if (manager->mEnumContext.mPrefJoystickConfigValid && IsEqualGUID(pdidInstance->guidInstance, manager->mEnumContext.mPrefJoystickConfig->guidInstance) == false) + if (manager->m_enumContext.m_prefJoystickConfigValid && IsEqualGUID(pdidInstance->guidInstance, manager->m_enumContext.m_prefJoystickConfig->guidInstance) == false) { return DIENUM_CONTINUE; } // Obtain an interface to the enumerated Joystick. - HRESULT result = manager->mDirectInput->CreateDevice(pdidInstance->guidInstance, &manager->mJoystick, nullptr); + HRESULT result = manager->m_directInput->CreateDevice(pdidInstance->guidInstance, &manager->m_joystick, nullptr); // If it failed, then we can't use this Joystick. (Maybe the user unplugged // it while we were in the middle of enumerating it.) @@ -63,7 +63,7 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* diprg.lMax = +1000; // Set the range for the axis - if (FAILED(manager->mJoystick->SetProperty(DIPROP_RANGE, &diprg.diph))) + if (FAILED(manager->m_joystick->SetProperty(DIPROP_RANGE, &diprg.diph))) { return DIENUM_STOP; } @@ -71,103 +71,94 @@ BOOL CALLBACK GameController::EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* if (pdidoi->guidType == GUID_XAxis) { - manager->mDeviceElements[ ELEM_POS_X ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_POS_X ].mPresent = true; - manager->mDeviceElements[ ELEM_POS_X ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_POS_X ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_POS_X ].mType = ELEMTYPE_AXIS; - manager->mDeviceInfo.mNumAxes++; + manager->m_deviceElements[ ELEM_POS_X ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_POS_X ].m_present = true; + manager->m_deviceElements[ ELEM_POS_X ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_POS_X ].m_type = ELEMTYPE_AXIS; + manager->m_deviceInfo.m_numAxes++; } if (pdidoi->guidType == GUID_YAxis) { - manager->mDeviceElements[ ELEM_POS_Y ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_POS_Y ].mPresent = true; - manager->mDeviceElements[ ELEM_POS_Y ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_POS_Y ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_POS_Y ].mType = ELEMTYPE_AXIS; - manager->mDeviceInfo.mNumAxes++; + manager->m_deviceElements[ ELEM_POS_Y ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_POS_Y ].m_present = true; + manager->m_deviceElements[ ELEM_POS_Y ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_POS_Y ].m_type = ELEMTYPE_AXIS; + manager->m_deviceInfo.m_numAxes++; } if (pdidoi->guidType == GUID_ZAxis) { - manager->mDeviceElements[ ELEM_POS_Z ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_POS_Z ].mPresent = true; - manager->mDeviceElements[ ELEM_POS_Z ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_POS_Z ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_POS_Z ].mType = ELEMTYPE_AXIS; - manager->mDeviceInfo.mNumAxes++; + manager->m_deviceElements[ ELEM_POS_Z ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_POS_Z ].m_present = true; + manager->m_deviceElements[ ELEM_POS_Z ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_POS_Z ].m_type = ELEMTYPE_AXIS; + manager->m_deviceInfo.m_numAxes++; } if (pdidoi->guidType == GUID_RxAxis) { - manager->mDeviceElements[ ELEM_ROT_X ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_ROT_X ].mPresent = true; - manager->mDeviceElements[ ELEM_ROT_X ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_ROT_X ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_ROT_X ].mType = ELEMTYPE_AXIS; - manager->mDeviceInfo.mNumAxes++; + manager->m_deviceElements[ ELEM_ROT_X ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_ROT_X ].m_present = true; + manager->m_deviceElements[ ELEM_ROT_X ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_ROT_X ].m_type = ELEMTYPE_AXIS; + manager->m_deviceInfo.m_numAxes++; } if (pdidoi->guidType == GUID_RyAxis) { - manager->mDeviceElements[ ELEM_ROT_Y ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_ROT_Y ].mPresent = true; - manager->mDeviceElements[ ELEM_ROT_Y ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_ROT_Y ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_ROT_Y ].mType = ELEMTYPE_AXIS; - manager->mDeviceInfo.mNumAxes++; + manager->m_deviceElements[ ELEM_ROT_Y ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_ROT_Y ].m_present = true; + manager->m_deviceElements[ ELEM_ROT_Y ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_ROT_Y ].m_type = ELEMTYPE_AXIS; + manager->m_deviceInfo.m_numAxes++; } if (pdidoi->guidType == GUID_RzAxis) { - manager->mDeviceElements[ ELEM_ROT_Z ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_ROT_Z ].mPresent = true; - manager->mDeviceElements[ ELEM_ROT_Z ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_ROT_Z ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_ROT_Z ].mType = ELEMTYPE_AXIS; - manager->mDeviceInfo.mNumAxes++; + manager->m_deviceElements[ ELEM_ROT_Z ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_ROT_Z ].m_present = true; + manager->m_deviceElements[ ELEM_ROT_Z ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_ROT_Z ].m_type = ELEMTYPE_AXIS; + manager->m_deviceInfo.m_numAxes++; } // a slider if (pdidoi->guidType == GUID_Slider) { - if (manager->mDeviceInfo.mNumSliders == 0) + if (manager->m_deviceInfo.m_numSliders == 0) { - manager->mDeviceElements[ ELEM_SLIDER_1 ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_SLIDER_1 ].mPresent = true; - manager->mDeviceElements[ ELEM_SLIDER_1 ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_SLIDER_1 ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_SLIDER_1 ].mType = ELEMTYPE_SLIDER; + manager->m_deviceElements[ ELEM_SLIDER_1 ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_SLIDER_1 ].m_present = true; + manager->m_deviceElements[ ELEM_SLIDER_1 ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_SLIDER_1 ].m_type = ELEMTYPE_SLIDER; } else { - manager->mDeviceElements[ ELEM_SLIDER_2 ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_SLIDER_2 ].mPresent = true; - manager->mDeviceElements[ ELEM_SLIDER_2 ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_SLIDER_2 ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_SLIDER_2 ].mType = ELEMTYPE_SLIDER; + manager->m_deviceElements[ ELEM_SLIDER_2 ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_SLIDER_2 ].m_present = true; + manager->m_deviceElements[ ELEM_SLIDER_2 ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_SLIDER_2 ].m_type = ELEMTYPE_SLIDER; } - manager->mDeviceInfo.mNumSliders++; + manager->m_deviceInfo.m_numSliders++; } // a POV if (pdidoi->guidType == GUID_POV) { - const uint32 povIndex = manager->mDeviceInfo.mNumPOVs; - manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mName = pdidoi->tszName; - manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mPresent = true; - manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mValue = 0.0f; - //manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mCalibrationValue = 0.0f; - manager->mDeviceElements[ ELEM_POV_1 + povIndex ].mType = ELEMTYPE_POV; - manager->mDeviceInfo.mNumPOVs++; + const uint32 povIndex = manager->m_deviceInfo.m_numPoVs; + manager->m_deviceElements[ ELEM_POV_1 + povIndex ].m_name = pdidoi->tszName; + manager->m_deviceElements[ ELEM_POV_1 + povIndex ].m_present = true; + manager->m_deviceElements[ ELEM_POV_1 + povIndex ].m_value = 0.0f; + manager->m_deviceElements[ ELEM_POV_1 + povIndex ].m_type = ELEMTYPE_POV; + manager->m_deviceInfo.m_numPoVs++; } // a button if (pdidoi->guidType == GUID_Button) { - manager->mDeviceInfo.mNumButtons++; + manager->m_deviceInfo.m_numButtons++; } return DIENUM_CONTINUE; @@ -183,7 +174,7 @@ bool GameController::Init(HWND hWnd) // reinit if (FAILED(InitDirectInput(hWnd))) { - mValid = false; + m_valid = false; return false; } @@ -199,24 +190,24 @@ HRESULT GameController::InitDirectInput(HWND hWnd) HRESULT result; // reset the device info - mDeviceInfo.mName = ""; - mDeviceInfo.mNumAxes = 0; - mDeviceInfo.mNumButtons = 0; - mDeviceInfo.mNumPOVs = 0; - mDeviceInfo.mNumSliders = 0; + m_deviceInfo.m_name = ""; + m_deviceInfo.m_numAxes = 0; + m_deviceInfo.m_numButtons = 0; + m_deviceInfo.m_numPoVs = 0; + m_deviceInfo.m_numSliders = 0; uint32 i; for (i = 0; i < NUM_ELEMENTS; ++i) { - mDeviceElements[i].mPresent = false; - mDeviceElements[i].mValue = 0.0f; + m_deviceElements[i].m_present = false; + m_deviceElements[i].m_value = 0.0f; } // register with the DirectInput subsystem and get a pointer to a IDirectInput interface we can use - result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, ( VOID** )&mDirectInput, nullptr); + result = DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, ( VOID** )&m_directInput, nullptr); if (FAILED(result)) { - mValid = false; + m_valid = false; return result; } @@ -224,21 +215,21 @@ HRESULT GameController::InitDirectInput(HWND hWnd) memset(&prefJoystickConfig, 0, sizeof(DIJOYCONFIG)); prefJoystickConfig.dwSize = sizeof(DIJOYCONFIG); - mEnumContext.mPrefJoystickConfig = &prefJoystickConfig; - mEnumContext.mPrefJoystickConfigValid = false; + m_enumContext.m_prefJoystickConfig = &prefJoystickConfig; + m_enumContext.m_prefJoystickConfigValid = false; IDirectInputJoyConfig8* joystickConfig = nullptr; - result = mDirectInput->QueryInterface(IID_IDirectInputJoyConfig8, (void**)&joystickConfig); + result = m_directInput->QueryInterface(IID_IDirectInputJoyConfig8, (void**)&joystickConfig); if (FAILED(result)) { - mValid = false; + m_valid = false; return result; } result = joystickConfig->GetConfig(0, &prefJoystickConfig, DIJC_GUIDINSTANCE); if (SUCCEEDED(result)) // this function is expected to fail if no joystick is attached { - mEnumContext.mPrefJoystickConfigValid = true; + m_enumContext.m_prefJoystickConfigValid = true; } if (joystickConfig) @@ -248,18 +239,18 @@ HRESULT GameController::InitDirectInput(HWND hWnd) } // look for a simple Joystick we can use for this sample program. - result = mDirectInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, this, DIEDFL_ATTACHEDONLY); + result = m_directInput->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback, this, DIEDFL_ATTACHEDONLY); if (FAILED(result)) { - mValid = false; + m_valid = false; return result; } // make sure we got a Joystick - if (mJoystick == nullptr) + if (m_joystick == nullptr) { // No joystick found. - mValid = false; + m_valid = false; return S_OK; } @@ -268,10 +259,10 @@ HRESULT GameController::InitDirectInput(HWND hWnd) // A data format specifies which controls on a device we are interested in, // and how they should be reported. This tells DInput that we will be // passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState(). - result = mJoystick->SetDataFormat(&c_dfDIJoystick2); + result = m_joystick->SetDataFormat(&c_dfDIJoystick2); if (FAILED(result)) { - mValid = false; + m_valid = false; return result; } @@ -279,10 +270,10 @@ HRESULT GameController::InitDirectInput(HWND hWnd) // interact with the system and with other DInput applications. if (hWnd) { - result = mJoystick->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_BACKGROUND); + result = m_joystick->SetCooperativeLevel(hWnd, DISCL_EXCLUSIVE | DISCL_BACKGROUND); if (FAILED(result)) { - mValid = false; + m_valid = false; return result; } } @@ -290,37 +281,37 @@ HRESULT GameController::InitDirectInput(HWND hWnd) // Enumerate the Joystick objects. The callback function enabled user // interface elements for objects that are found, and sets the min/max // values property for discovered axes. - result = mJoystick->EnumObjects(EnumObjectsCallback, (VOID*)this, DIDFT_ALL); + result = m_joystick->EnumObjects(EnumObjectsCallback, (VOID*)this, DIDFT_ALL); if (FAILED(result)) { - mValid = false; + m_valid = false; return result; } // acquire the joystick - mJoystick->Acquire(); + m_joystick->Acquire(); // display the device info - MCore::LogDetailedInfo("- Controller = %s", mDeviceInfo.mName.c_str()); - MCore::LogDetailedInfo(" + Num buttons = %d", mDeviceInfo.mNumButtons); - MCore::LogDetailedInfo(" + Num axes = %d", mDeviceInfo.mNumAxes); - MCore::LogDetailedInfo(" + Num sliders = %d", mDeviceInfo.mNumSliders); - MCore::LogDetailedInfo(" + Num POVs = %d", mDeviceInfo.mNumPOVs); + MCore::LogDetailedInfo("- Controller = %s", m_deviceInfo.m_name.c_str()); + MCore::LogDetailedInfo(" + Num buttons = %d", m_deviceInfo.m_numButtons); + MCore::LogDetailedInfo(" + Num axes = %d", m_deviceInfo.m_numAxes); + MCore::LogDetailedInfo(" + Num sliders = %d", m_deviceInfo.m_numSliders); + MCore::LogDetailedInfo(" + Num POVs = %d", m_deviceInfo.m_numPoVs); // display all elements uint32 numPresentElements = 0; for (i = 0; i < NUM_ELEMENTS; ++i) { - if (mDeviceElements[i].mPresent == false) + if (m_deviceElements[i].m_present == false) { continue; } numPresentElements++; - MCore::LogDetailedInfo(" + Element #%d = %s", numPresentElements, mDeviceElements[i].mName.c_str()); + MCore::LogDetailedInfo(" + Element #%d = %s", numPresentElements, m_deviceElements[i].m_name.c_str()); } - mValid = true; + m_valid = true; return S_OK; } @@ -329,18 +320,18 @@ HRESULT GameController::InitDirectInput(HWND hWnd) void GameController::Shutdown() { // unacquire the device one last time just in case - if (mJoystick) + if (m_joystick) { - mJoystick->Unacquire(); - mJoystick->Release(); - mJoystick = nullptr; + m_joystick->Unacquire(); + m_joystick->Release(); + m_joystick = nullptr; } // release any DirectInput objects - if (mDirectInput) + if (m_directInput) { - mDirectInput->Release(); - mDirectInput = nullptr; + m_directInput->Release(); + m_directInput = nullptr; } } @@ -348,42 +339,38 @@ void GameController::Shutdown() // calibrate void GameController::Calibrate() { - mDeviceElements[ELEM_POS_X].mCalibrationValue = -(mJoystickState.lX / 1000.0f); - mDeviceElements[ELEM_POS_Y].mCalibrationValue = -(mJoystickState.lY / 1000.0f); - mDeviceElements[ELEM_POS_Z].mCalibrationValue = -(mJoystickState.lZ / 1000.0f); - mDeviceElements[ELEM_ROT_X].mCalibrationValue = -(mJoystickState.lRx / 1000.0f); - mDeviceElements[ELEM_ROT_Y].mCalibrationValue = -(mJoystickState.lRy / 1000.0f); - mDeviceElements[ELEM_ROT_Z].mCalibrationValue = -(mJoystickState.lRz / 1000.0f); - //mDeviceElements[ELEM_POV_1].mCalibrationValue = -(mJoystickState.rgdwPOV[0] / 1000.0f); - //mDeviceElements[ELEM_POV_2].mCalibrationValue = -(mJoystickState.rgdwPOV[1] / 1000.0f); - //mDeviceElements[ELEM_POV_3].mCalibrationValue = -(mJoystickState.rgdwPOV[2] / 1000.0f); - //mDeviceElements[ELEM_POV_4].mCalibrationValue = -(mJoystickState.rgdwPOV[3] / 1000.0f); - mDeviceElements[ELEM_SLIDER_1].mCalibrationValue = -(mJoystickState.rglSlider[0] / 1000.0f); - mDeviceElements[ELEM_SLIDER_2].mCalibrationValue = -(mJoystickState.rglSlider[1] / 1000.0f); + m_deviceElements[ELEM_POS_X].m_calibrationValue = -(m_joystickState.lX / 1000.0f); + m_deviceElements[ELEM_POS_Y].m_calibrationValue = -(m_joystickState.lY / 1000.0f); + m_deviceElements[ELEM_POS_Z].m_calibrationValue = -(m_joystickState.lZ / 1000.0f); + m_deviceElements[ELEM_ROT_X].m_calibrationValue = -(m_joystickState.lRx / 1000.0f); + m_deviceElements[ELEM_ROT_Y].m_calibrationValue = -(m_joystickState.lRy / 1000.0f); + m_deviceElements[ELEM_ROT_Z].m_calibrationValue = -(m_joystickState.lRz / 1000.0f); + m_deviceElements[ELEM_SLIDER_1].m_calibrationValue = -(m_joystickState.rglSlider[0] / 1000.0f); + m_deviceElements[ELEM_SLIDER_2].m_calibrationValue = -(m_joystickState.rglSlider[1] / 1000.0f); } // update the controller bool GameController::Update() { - if (mJoystick == nullptr) + if (m_joystick == nullptr) { - mValid = false; + m_valid = false; return false; } // poll the device to read the current state - HRESULT result = mJoystick->Poll(); + HRESULT result = m_joystick->Poll(); if (FAILED(result)) { // DInput is telling us that the input stream has been // interrupted. We aren't tracking any state between polls, so // we don't have any special reset that needs to be done. We // just re-acquire and try again. - result = mJoystick->Acquire(); + result = m_joystick->Acquire(); while (result == DIERR_INPUTLOST) { - result = mJoystick->Acquire(); + result = m_joystick->Acquire(); } // reset all buttons @@ -398,70 +385,70 @@ bool GameController::Update() // switching, so just try again later if (result == DIERR_OTHERAPPHASPRIO) { - mValid = true; + m_valid = true; return true; } if (FAILED(result)) { - mValid = false; + m_valid = false; return false; } } // Get the input's device state - result = mJoystick->GetDeviceState(sizeof(DIJOYSTATE2), &mJoystickState); + result = m_joystick->GetDeviceState(sizeof(DIJOYSTATE2), &m_joystickState); if (FAILED(result)) { - mValid = false; + m_valid = false; return false; // The device should have been acquired during the Poll() } // update the values of the elements - mDeviceElements[ELEM_POS_X].mValue = mJoystickState.lX / 1000.0f; - mDeviceElements[ELEM_POS_Y].mValue = mJoystickState.lY / 1000.0f; - mDeviceElements[ELEM_POS_Z].mValue = mJoystickState.lZ / 1000.0f; - mDeviceElements[ELEM_ROT_X].mValue = mJoystickState.lRx / 1000.0f; - mDeviceElements[ELEM_ROT_Y].mValue = mJoystickState.lRy / 1000.0f; - mDeviceElements[ELEM_ROT_Z].mValue = mJoystickState.lRz / 1000.0f; - mDeviceElements[ELEM_SLIDER_1].mValue = mJoystickState.rglSlider[0] / 1000.0f; - mDeviceElements[ELEM_SLIDER_2].mValue = mJoystickState.rglSlider[1] / 1000.0f; + m_deviceElements[ELEM_POS_X].m_value = m_joystickState.lX / 1000.0f; + m_deviceElements[ELEM_POS_Y].m_value = m_joystickState.lY / 1000.0f; + m_deviceElements[ELEM_POS_Z].m_value = m_joystickState.lZ / 1000.0f; + m_deviceElements[ELEM_ROT_X].m_value = m_joystickState.lRx / 1000.0f; + m_deviceElements[ELEM_ROT_Y].m_value = m_joystickState.lRy / 1000.0f; + m_deviceElements[ELEM_ROT_Z].m_value = m_joystickState.lRz / 1000.0f; + m_deviceElements[ELEM_SLIDER_1].m_value = m_joystickState.rglSlider[0] / 1000.0f; + m_deviceElements[ELEM_SLIDER_2].m_value = m_joystickState.rglSlider[1] / 1000.0f; - if (mJoystickState.rgdwPOV[0] == MCORE_INVALIDINDEX32) + if (m_joystickState.rgdwPOV[0] == MCORE_INVALIDINDEX32) { - mDeviceElements[ELEM_POV_1].mValue = 0.0f; + m_deviceElements[ELEM_POV_1].m_value = 0.0f; } else { - mDeviceElements[ELEM_POV_1].mValue = (mJoystickState.rgdwPOV[0] / 100.0f) / 360.0f; + m_deviceElements[ELEM_POV_1].m_value = (m_joystickState.rgdwPOV[0] / 100.0f) / 360.0f; } - if (mJoystickState.rgdwPOV[1] == MCORE_INVALIDINDEX32) + if (m_joystickState.rgdwPOV[1] == MCORE_INVALIDINDEX32) { - mDeviceElements[ELEM_POV_2].mValue = 0.0f; + m_deviceElements[ELEM_POV_2].m_value = 0.0f; } else { - mDeviceElements[ELEM_POV_2].mValue = (mJoystickState.rgdwPOV[1] / 100.0f) / 360.0f; + m_deviceElements[ELEM_POV_2].m_value = (m_joystickState.rgdwPOV[1] / 100.0f) / 360.0f; } - if (mJoystickState.rgdwPOV[2] == MCORE_INVALIDINDEX32) + if (m_joystickState.rgdwPOV[2] == MCORE_INVALIDINDEX32) { - mDeviceElements[ELEM_POV_3].mValue = 0.0f; + m_deviceElements[ELEM_POV_3].m_value = 0.0f; } else { - mDeviceElements[ELEM_POV_3].mValue = (mJoystickState.rgdwPOV[2] / 100.0f) / 360.0f; + m_deviceElements[ELEM_POV_3].m_value = (m_joystickState.rgdwPOV[2] / 100.0f) / 360.0f; } - if (mJoystickState.rgdwPOV[3] == MCORE_INVALIDINDEX32) + if (m_joystickState.rgdwPOV[3] == MCORE_INVALIDINDEX32) { - mDeviceElements[ELEM_POV_4].mValue = 0.0f; + m_deviceElements[ELEM_POV_4].m_value = 0.0f; } else { - mDeviceElements[ELEM_POV_4].mValue = (mJoystickState.rgdwPOV[3] / 100.0f) / 360.0f; + m_deviceElements[ELEM_POV_4].m_value = (m_joystickState.rgdwPOV[3] / 100.0f) / 360.0f; } // apply the dead zone - const float minValue = mDeadZone; + const float minValue = m_deadZone; const float maxValue = 1.0f; const float range = maxValue - minValue; @@ -469,12 +456,12 @@ bool GameController::Update() for (uint32 i = 0; i < 8; ++i) { // get the current normalized value - float value = mDeviceElements[i].mValue; + float value = m_deviceElements[i].m_value; // ignore all values that are smaller than the dead zone - if (value > -mDeadZone && value < mDeadZone) + if (value > -m_deadZone && value < m_deadZone) { - mDeviceElements[i].mValue = 0.0f; + m_deviceElements[i].m_value = 0.0f; } else { @@ -487,14 +474,14 @@ bool GameController::Update() } // calculate the value in the new range excluding the dead zone range - const float newValue = (value - mDeadZone) / range; + const float newValue = (value - m_deadZone) / range; // set it back in normal or negated version - mDeviceElements[i].mValue = negativeValue == false ? newValue : -newValue; + m_deviceElements[i].m_value = negativeValue == false ? newValue : -newValue; } } - mValid = true; + m_valid = true; return true; } @@ -559,7 +546,7 @@ const char* GameController::GetElementEnumName(uint32 index) } -uint32 GameController::FindElemendIDByName(const AZStd::string& elementEnumName) +uint32 GameController::FindElementIDByName(const AZStd::string& elementEnumName) { if (elementEnumName == "Pos X") { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.h index d48ca7efd1..47cfb9ddfc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameController.h @@ -59,7 +59,7 @@ public: ELEMTYPE_POV = 2 }; - GameController() { mDirectInput = nullptr; mJoystick = nullptr; mHWnd = nullptr; mDeadZone = 0.15f; mValid = false; } + GameController() { m_directInput = nullptr; m_joystick = nullptr; m_hWnd = nullptr; m_deadZone = 0.15f; m_valid = false; } ~GameController() { Shutdown(); } bool Init(HWND hWnd); @@ -67,61 +67,61 @@ public: void Calibrate(); void Shutdown(); - MCORE_INLINE IDirectInputDevice8* GetJoystick() const { return mJoystick; } // returns nullptr when no joystick found during init + MCORE_INLINE IDirectInputDevice8* GetJoystick() const { return m_joystick; } // returns nullptr when no joystick found during init - MCORE_INLINE const char* GetDeviceName() const { return mDeviceInfo.mName.c_str(); } - MCORE_INLINE const AZStd::string& GetDeviceNameString() const { return mDeviceInfo.mName; } - MCORE_INLINE uint32 GetNumButtons() const { return mDeviceInfo.mNumButtons; } - MCORE_INLINE uint32 GetNumSliders() const { return mDeviceInfo.mNumSliders; } - MCORE_INLINE uint32 GetNumPOVs() const { return mDeviceInfo.mNumPOVs; } - MCORE_INLINE uint32 GetNumAxes() const { return mDeviceInfo.mNumAxes; } - void SetDeadZone(float deadZone) { mDeadZone = deadZone; } - MCORE_INLINE float GetDeadZone() const { return mDeadZone; } + MCORE_INLINE const char* GetDeviceName() const { return m_deviceInfo.m_name.c_str(); } + MCORE_INLINE const AZStd::string& GetDeviceNameString() const { return m_deviceInfo.m_name; } + MCORE_INLINE uint32 GetNumButtons() const { return m_deviceInfo.m_numButtons; } + MCORE_INLINE uint32 GetNumSliders() const { return m_deviceInfo.m_numSliders; } + MCORE_INLINE uint32 GetNumPOVs() const { return m_deviceInfo.m_numPoVs; } + MCORE_INLINE uint32 GetNumAxes() const { return m_deviceInfo.m_numAxes; } + void SetDeadZone(float deadZone) { m_deadZone = deadZone; } + MCORE_INLINE float GetDeadZone() const { return m_deadZone; } const char* GetElementEnumName(uint32 index); - uint32 FindElemendIDByName(const AZStd::string& elementEnumName); + uint32 FindElementIDByName(const AZStd::string& elementEnumName); - MCORE_INLINE bool GetIsPresent(uint32 elementID) const { return mDeviceElements[elementID].mPresent; } + MCORE_INLINE bool GetIsPresent(uint32 elementID) const { return m_deviceElements[elementID].m_present; } MCORE_INLINE bool GetIsButtonPressed(uint8 buttonIndex) const { if (buttonIndex < 128) { - return (mJoystickState.rgbButtons[buttonIndex] & 0x80) != 0; + return (m_joystickState.rgbButtons[buttonIndex] & 0x80) != 0; } return false; } - MCORE_INLINE float GetValue(uint32 elementID) const { return mDeviceElements[elementID].mValue; } - MCORE_INLINE const char* GetElementName(uint32 elementID) const { return mDeviceElements[elementID].mName.c_str(); } - MCORE_INLINE bool GetIsValid() const { return mValid; } + MCORE_INLINE float GetValue(uint32 elementID) const { return m_deviceElements[elementID].m_value; } + MCORE_INLINE const char* GetElementName(uint32 elementID) const { return m_deviceElements[elementID].m_name.c_str(); } + MCORE_INLINE bool GetIsValid() const { return m_valid; } private: struct DeviceInfo { MCORE_MEMORYOBJECTCATEGORY(GameController::DeviceInfo, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - AZStd::string mName; - uint32 mNumButtons; - uint32 mNumAxes; - uint32 mNumPOVs; - uint32 mNumSliders; + AZStd::string m_name; + uint32 m_numButtons; + uint32 m_numAxes; + uint32 m_numPoVs; + uint32 m_numSliders; }; struct DeviceElement { MCORE_MEMORYOBJECTCATEGORY(GameController::DeviceElement, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - AZStd::string mName; - float mValue; - float mCalibrationValue; - ElementType mType; - bool mPresent; + AZStd::string m_name; + float m_value; + float m_calibrationValue; + ElementType m_type; + bool m_present; }; struct EnumContext { MCORE_MEMORYOBJECTCATEGORY(GameController::EnumContext, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - DIJOYCONFIG* mPrefJoystickConfig; - bool mPrefJoystickConfigValid; + DIJOYCONFIG* m_prefJoystickConfig; + bool m_prefJoystickConfigValid; }; MCORE_INLINE void SetButtonPressed(uint8 buttonIndex, bool isPressed) @@ -132,23 +132,23 @@ private: } if (isPressed) { - mJoystickState.rgbButtons[buttonIndex] |= 0x80; + m_joystickState.rgbButtons[buttonIndex] |= 0x80; } else { - mJoystickState.rgbButtons[buttonIndex] &= ~0x80; + m_joystickState.rgbButtons[buttonIndex] &= ~0x80; } } - IDirectInput8* mDirectInput; - IDirectInputDevice8* mJoystick; - DIJOYSTATE2 mJoystickState; // DInput Joystick state - EnumContext mEnumContext; - HWND mHWnd; - DeviceInfo mDeviceInfo; - DeviceElement mDeviceElements[NUM_ELEMENTS]; - float mDeadZone; - bool mValid; + IDirectInput8* m_directInput; + IDirectInputDevice8* m_joystick; + DIJOYSTATE2 m_joystickState; // DInput Joystick state + EnumContext m_enumContext; + HWND m_hWnd; + DeviceInfo m_deviceInfo; + DeviceElement m_deviceElements[NUM_ELEMENTS]; + float m_deadZone; + bool m_valid; static BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, void* pContext); static BOOL CALLBACK EnumObjectsCallback(const DIDEVICEOBJECTINSTANCE* pdidoi, void* pContext); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp index 47bb9660a8..c17ff12947 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.cpp @@ -54,20 +54,20 @@ namespace EMStudio GameControllerWindow::GameControllerWindow(AnimGraphPlugin* plugin, QWidget* parent) : QWidget(parent) { - mPlugin = plugin; - mAnimGraph = nullptr; - mDynamicWidget = nullptr; - mPresetNameLineEdit = nullptr; - mParameterGridLayout = nullptr; - mDeadZoneValueLabel = nullptr; - mButtonGridLayout = nullptr; - mDeadZoneSlider = nullptr; - mPresetComboBox = nullptr; - mInterfaceTimerID = MCORE_INVALIDINDEX32; - mGameControllerTimerID = MCORE_INVALIDINDEX32; - mString.reserve(4096); + m_plugin = plugin; + m_animGraph = nullptr; + m_dynamicWidget = nullptr; + m_presetNameLineEdit = nullptr; + m_parameterGridLayout = nullptr; + m_deadZoneValueLabel = nullptr; + m_buttonGridLayout = nullptr; + m_deadZoneSlider = nullptr; + m_presetComboBox = nullptr; + m_interfaceTimerId = MCORE_INVALIDINDEX32; + m_gameControllerTimerId = MCORE_INVALIDINDEX32; + m_string.reserve(4096); #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - mGameController = nullptr; + m_gameController = nullptr; #endif Init(); @@ -78,29 +78,29 @@ namespace EMStudio GameControllerWindow::~GameControllerWindow() { // stop the timers - mInterfaceTimer.stop(); - mGameControllerTimer.stop(); + m_interfaceTimer.stop(); + m_gameControllerTimer.stop(); // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mCreateCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustCallback, false); - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - delete mCreateCallback; - delete mRemoveCallback; - delete mAdjustCallback; - delete mClearSelectionCallback; - delete mSelectCallback; - delete mUnselectCallback; + GetCommandManager()->RemoveCommandCallback(m_createCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustCallback, false); + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + delete m_createCallback; + delete m_removeCallback; + delete m_adjustCallback; + delete m_clearSelectionCallback; + delete m_selectCallback; + delete m_unselectCallback; // get rid of the game controller #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (mGameController) + if (m_gameController) { - mGameController->Shutdown(); - delete mGameController; + m_gameController->Shutdown(); + delete m_gameController; } #endif } @@ -110,20 +110,20 @@ namespace EMStudio void GameControllerWindow::Init() { // create the callbacks - mCreateCallback = new CommandCreateBlendParameterCallback(false); - mRemoveCallback = new CommandRemoveBlendParameterCallback(false); - mAdjustCallback = new CommandAdjustBlendParameterCallback(false); - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); - mClearSelectionCallback = new CommandClearSelectionCallback(false); + m_createCallback = new CommandCreateBlendParameterCallback(false); + m_removeCallback = new CommandRemoveBlendParameterCallback(false); + m_adjustCallback = new CommandAdjustBlendParameterCallback(false); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); + m_clearSelectionCallback = new CommandClearSelectionCallback(false); // hook the callbacks to the commands - GetCommandManager()->RegisterCommandCallback("AnimGraphCreateParameter", mCreateCallback); - GetCommandManager()->RegisterCommandCallback("AnimGraphRemoveParameter", mRemoveCallback); - GetCommandManager()->RegisterCommandCallback("AnimGraphAdjustParameter", mAdjustCallback); - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); + GetCommandManager()->RegisterCommandCallback("AnimGraphCreateParameter", m_createCallback); + GetCommandManager()->RegisterCommandCallback("AnimGraphRemoveParameter", m_removeCallback); + GetCommandManager()->RegisterCommandCallback("AnimGraphAdjustParameter", m_adjustCallback); + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); InitGameController(); @@ -132,11 +132,11 @@ namespace EMStudio setLayout(layout); // create the dialog stack - mDialogStack = new MysticQt::DialogStack(); - layout->addWidget(mDialogStack); + m_dialogStack = new MysticQt::DialogStack(); + layout->addWidget(m_dialogStack); // add the game controller - mGameControllerComboBox = new QComboBox(); + m_gameControllerComboBox = new QComboBox(); UpdateGameControllerComboBox(); QHBoxLayout* gameControllerLayout = new QHBoxLayout(); @@ -144,44 +144,44 @@ namespace EMStudio QLabel* activeControllerLabel = new QLabel("Active Controller:"); activeControllerLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); gameControllerLayout->addWidget(activeControllerLabel); - gameControllerLayout->addWidget(mGameControllerComboBox); + gameControllerLayout->addWidget(m_gameControllerComboBox); gameControllerLayout->addWidget(EMStudioManager::MakeSeperatorLabel(1, 20)); // create the presets interface QHBoxLayout* horizontalLayout = new QHBoxLayout(); horizontalLayout->setMargin(0); - mPresetComboBox = new QComboBox(); - mAddPresetButton = new QPushButton(); - mRemovePresetButton = new QPushButton(); - mPresetNameLineEdit = new QLineEdit(); + m_presetComboBox = new QComboBox(); + m_addPresetButton = new QPushButton(); + m_removePresetButton = new QPushButton(); + m_presetNameLineEdit = new QLineEdit(); - connect(mPresetComboBox, static_cast(&QComboBox::currentIndexChanged), this, &GameControllerWindow::OnPresetComboBox); - connect(mAddPresetButton, &QPushButton::clicked, this, &GameControllerWindow::OnAddPresetButton); - connect(mRemovePresetButton, &QPushButton::clicked, this, &GameControllerWindow::OnRemovePresetButton); - connect(mPresetNameLineEdit, &QLineEdit::textEdited, this, &GameControllerWindow::OnPresetNameEdited); - connect(mPresetNameLineEdit, &QLineEdit::returnPressed, this, &GameControllerWindow::OnPresetNameChanged); + connect(m_presetComboBox, static_cast(&QComboBox::currentIndexChanged), this, &GameControllerWindow::OnPresetComboBox); + connect(m_addPresetButton, &QPushButton::clicked, this, &GameControllerWindow::OnAddPresetButton); + connect(m_removePresetButton, &QPushButton::clicked, this, &GameControllerWindow::OnRemovePresetButton); + connect(m_presetNameLineEdit, &QLineEdit::textEdited, this, &GameControllerWindow::OnPresetNameEdited); + connect(m_presetNameLineEdit, &QLineEdit::returnPressed, this, &GameControllerWindow::OnPresetNameChanged); - EMStudioManager::MakeTransparentButton(mAddPresetButton, "Images/Icons/Plus.svg", "Add a game controller preset"); - EMStudioManager::MakeTransparentButton(mRemovePresetButton, "Images/Icons/Remove.svg", "Remove a game controller preset"); + EMStudioManager::MakeTransparentButton(m_addPresetButton, "Images/Icons/Plus.svg", "Add a game controller preset"); + EMStudioManager::MakeTransparentButton(m_removePresetButton, "Images/Icons/Remove.svg", "Remove a game controller preset"); QHBoxLayout* buttonsLayout = new QHBoxLayout(); - buttonsLayout->addWidget(mAddPresetButton); - buttonsLayout->addWidget(mRemovePresetButton); + buttonsLayout->addWidget(m_addPresetButton); + buttonsLayout->addWidget(m_removePresetButton); buttonsLayout->setSpacing(0); buttonsLayout->setMargin(0); horizontalLayout->addWidget(new QLabel("Preset:")); - horizontalLayout->addWidget(mPresetComboBox); + horizontalLayout->addWidget(m_presetComboBox); horizontalLayout->addLayout(buttonsLayout); - horizontalLayout->addWidget(mPresetNameLineEdit); + horizontalLayout->addWidget(m_presetNameLineEdit); gameControllerLayout->addLayout(horizontalLayout); QWidget* dummyWidget = new QWidget(); dummyWidget->setObjectName("StyledWidgetDark"); dummyWidget->setLayout(gameControllerLayout); - mDialogStack->Add(dummyWidget, "Game Controller And Preset Selection"); - connect(mGameControllerComboBox, static_cast(&QComboBox::currentIndexChanged), this, &GameControllerWindow::OnGameControllerComboBox); + m_dialogStack->Add(dummyWidget, "Game Controller And Preset Selection"); + connect(m_gameControllerComboBox, static_cast(&QComboBox::currentIndexChanged), this, &GameControllerWindow::OnGameControllerComboBox); DisablePresetInterface(); AutoSelectGameController(); @@ -195,13 +195,13 @@ namespace EMStudio { #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER // this will call ReInit(); - if (mGameController->GetDeviceNameString().empty() == false && mGameControllerComboBox->count() > 1) + if (m_gameController->GetDeviceNameString().empty() == false && m_gameControllerComboBox->count() > 1) { - mGameControllerComboBox->setCurrentIndex(1); + m_gameControllerComboBox->setCurrentIndex(1); } else { - mGameControllerComboBox->setCurrentIndex(0); + m_gameControllerComboBox->setCurrentIndex(0); } #endif } @@ -211,15 +211,15 @@ namespace EMStudio void GameControllerWindow::InitGameController() { #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (mGameController) + if (m_gameController) { - mGameController->Shutdown(); - delete mGameController; - mGameController = nullptr; + m_gameController->Shutdown(); + delete m_gameController; + m_gameController = nullptr; } // create the game controller object - mGameController = new GameController(); + m_gameController = new GameController(); // Call mainWindow->window() to make sure you get the top level window which the mainWindow might not in fact be. //IEditor* editor = nullptr; @@ -227,7 +227,7 @@ namespace EMStudio //QMainWindow* mainWindow = editor->GetEditorMainWindow(); //HWND hWnd = reinterpret_cast( mainWindow->window()->winId() ); HWND hWnd = nullptr; - if (mGameController->Init(hWnd) == false) + if (m_gameController->Init(hWnd) == false) { MCore::LogError("Cannot initialize game controller."); } @@ -238,19 +238,19 @@ namespace EMStudio void GameControllerWindow::UpdateGameControllerComboBox() { // clear it and add the none option - mGameControllerComboBox->clear(); - mGameControllerComboBox->addItem(NO_GAMECONTROLLER_NAME); + m_gameControllerComboBox->clear(); + m_gameControllerComboBox->addItem(NO_GAMECONTROLLER_NAME); // add the gamepad in case it is valid and the device name is not empty #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (mGameController->GetIsValid() && mGameController->GetDeviceNameString().empty() == false) + if (m_gameController->GetIsValid() && m_gameController->GetDeviceNameString().empty() == false) { - mGameControllerComboBox->addItem(mGameController->GetDeviceName()); + m_gameControllerComboBox->addItem(m_gameController->GetDeviceName()); } #endif // always adjust the size of the combobox to the currently selected text - mGameControllerComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); + m_gameControllerComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); } @@ -264,24 +264,24 @@ namespace EMStudio ReInit(); // update the parameter window - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } void GameControllerWindow::DisablePresetInterface() { - mPresetComboBox->blockSignals(true); - mPresetComboBox->clear(); - mPresetComboBox->blockSignals(false); - - mPresetNameLineEdit->blockSignals(true); - mPresetNameLineEdit->setText(""); - mPresetNameLineEdit->blockSignals(false); - - mPresetComboBox->setEnabled(false); - mPresetNameLineEdit->setEnabled(false); - mAddPresetButton->setEnabled(false); - mRemovePresetButton->setEnabled(false); + m_presetComboBox->blockSignals(true); + m_presetComboBox->clear(); + m_presetComboBox->blockSignals(false); + + m_presetNameLineEdit->blockSignals(true); + m_presetNameLineEdit->setText(""); + m_presetNameLineEdit->blockSignals(false); + + m_presetComboBox->setEnabled(false); + m_presetNameLineEdit->setEnabled(false); + m_addPresetButton->setEnabled(false); + m_removePresetButton->setEnabled(false); } @@ -289,21 +289,21 @@ namespace EMStudio void GameControllerWindow::ReInit() { // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); - mAnimGraph = animGraph; + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); + m_animGraph = animGraph; // remove all existing items - if (mDynamicWidget) + if (m_dynamicWidget) { - mDialogStack->Remove(mDynamicWidget); + m_dialogStack->Remove(m_dynamicWidget); } - mDynamicWidget = nullptr; - mInterfaceTimer.stop(); - mGameControllerTimer.stop(); + m_dynamicWidget = nullptr; + m_interfaceTimer.stop(); + m_gameControllerTimer.stop(); // check if we need to recreate the dynamic widget #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (mGameController->GetIsValid() == false || mGameControllerComboBox->currentText() != mGameController->GetDeviceName()) + if (m_gameController->GetIsValid() == false || m_gameControllerComboBox->currentText() != m_gameController->GetDeviceName()) { DisablePresetInterface(); return; @@ -320,14 +320,14 @@ namespace EMStudio } // create the dynamic widget - mDynamicWidget = new QWidget(); - mDynamicWidget->setObjectName("StyledWidgetDark"); + m_dynamicWidget = new QWidget(); + m_dynamicWidget->setObjectName("StyledWidgetDark"); // get the game controller settings from the anim graph EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = animGraph->GetGameControllerSettings(); // in case there is no preset yet create a default one - uint32 numPresets = static_cast(gameControllerSettings.GetNumPresets()); + size_t numPresets = gameControllerSettings.GetNumPresets(); if (numPresets == 0) { EMotionFX::AnimGraphGameControllerSettings::Preset* preset = aznew EMotionFX::AnimGraphGameControllerSettings::Preset("Default"); @@ -340,19 +340,18 @@ namespace EMStudio EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); // create the parameter grid layout - mParameterGridLayout = new QGridLayout(); - mParameterGridLayout->setAlignment(Qt::AlignTop); - mParameterGridLayout->setMargin(0); + m_parameterGridLayout = new QGridLayout(); + m_parameterGridLayout->setAlignment(Qt::AlignTop); + m_parameterGridLayout->setMargin(0); // add all parameters - // uint32 startRow = 0; - mParameterInfos.Clear(); + m_parameterInfos.clear(); const EMotionFX::ValueParameterVector& parameters = animGraph->RecursivelyGetValueParameters(); - const size_t numParameters = parameters.size(); - mParameterInfos.Reserve(static_cast(numParameters)); + const int numParameters = aznumeric_caster(parameters.size()); + m_parameterInfos.reserve(numParameters); - for (size_t parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex) + for (int parameterIndex = 0; parameterIndex < numParameters; ++parameterIndex) { const EMotionFX::ValueParameter* parameter = parameters[parameterIndex]; @@ -374,7 +373,7 @@ namespace EMStudio QLabel* label = new QLabel(labelString.c_str()); label->setToolTip(parameter->GetDescription().c_str()); label->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - mParameterGridLayout->addWidget(label, static_cast(parameterIndex), 0); + m_parameterGridLayout->addWidget(label, static_cast(parameterIndex), 0); // add the axis combo box to the layout QComboBox* axesComboBox = new QComboBox(); @@ -390,10 +389,10 @@ namespace EMStudio for (uint32 j = 0; j < GameController::NUM_ELEMENTS; ++j) { // check if the element is present and add it to the combo box if yes - if (mGameController->GetIsPresent(j)) + if (m_gameController->GetIsPresent(j)) { // add the name of the element to the combo box - axesComboBox->addItem(mGameController->GetElementEnumName(j)); + axesComboBox->addItem(m_gameController->GetElementEnumName(j)); // in case the current element is the one the parameter is assigned to, remember the correct index if (j == settingsInfo->m_axis) @@ -409,7 +408,7 @@ namespace EMStudio else if (parameter->GetType() == MCore::AttributeVector2::TYPE_ID) { uint32 numPresentElements = 0; - if (mGameController->GetIsPresent(GameController::ELEM_POS_X) && mGameController->GetIsPresent(GameController::ELEM_POS_Y)) + if (m_gameController->GetIsPresent(GameController::ELEM_POS_X) && m_gameController->GetIsPresent(GameController::ELEM_POS_Y)) { axesComboBox->addItem("Pos XY"); if (settingsInfo->m_axis == 0) @@ -419,7 +418,7 @@ namespace EMStudio numPresentElements++; } - if (mGameController->GetIsPresent(GameController::ELEM_ROT_X) && mGameController->GetIsPresent(GameController::ELEM_ROT_Y)) + if (m_gameController->GetIsPresent(GameController::ELEM_ROT_X) && m_gameController->GetIsPresent(GameController::ELEM_ROT_Y)) { axesComboBox->addItem("Rot XY"); if (settingsInfo->m_axis == 1) @@ -434,7 +433,7 @@ namespace EMStudio // select the given axis in the combo box or select none if there is no assignment yet or the assigned axis wasn't found on the current game controller axesComboBox->setCurrentIndex(selectedComboItem); - mParameterGridLayout->addWidget(axesComboBox, static_cast(parameterIndex), 1); + m_parameterGridLayout->addWidget(axesComboBox, static_cast(parameterIndex), 1); // add the mode combo box to the layout QComboBox* modeComboBox = new QComboBox(); @@ -447,7 +446,7 @@ namespace EMStudio modeComboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); connect(modeComboBox, static_cast(&QComboBox::currentIndexChanged), this, &GameControllerWindow::OnParameterModeComboBox); modeComboBox->setCurrentIndex(settingsInfo->m_mode); - mParameterGridLayout->addWidget(modeComboBox, static_cast(parameterIndex), 2); + m_parameterGridLayout->addWidget(modeComboBox, static_cast(parameterIndex), 2); // add the invert checkbox to the layout QHBoxLayout* invertCheckBoxLayout = new QHBoxLayout(); @@ -460,7 +459,7 @@ namespace EMStudio connect(invertCheckbox, &QCheckBox::stateChanged, this, &GameControllerWindow::OnInvertCheckBoxChanged); invertCheckbox->setCheckState(settingsInfo->m_invert ? Qt::Checked : Qt::Unchecked); invertCheckBoxLayout->addWidget(invertCheckbox); - mParameterGridLayout->addLayout(invertCheckBoxLayout, static_cast(parameterIndex), 3); + m_parameterGridLayout->addLayout(invertCheckBoxLayout, static_cast(parameterIndex), 3); // add the current value edit field to the layout QLineEdit* valueEdit = new QLineEdit(); @@ -469,42 +468,42 @@ namespace EMStudio valueEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); valueEdit->setMinimumWidth(70); valueEdit->setMaximumWidth(70); - mParameterGridLayout->addWidget(valueEdit, static_cast(parameterIndex), 4); + m_parameterGridLayout->addWidget(valueEdit, static_cast(parameterIndex), 4); // create the parameter info and add it to the array ParameterInfo paramInfo; - paramInfo.mParameter = parameter; - paramInfo.mAxis = axesComboBox; - paramInfo.mMode = modeComboBox; - paramInfo.mInvert = invertCheckbox; - paramInfo.mValue = valueEdit; - mParameterInfos.Add(paramInfo); + paramInfo.m_parameter = parameter; + paramInfo.m_axis = axesComboBox; + paramInfo.m_mode = modeComboBox; + paramInfo.m_invert = invertCheckbox; + paramInfo.m_value = valueEdit; + m_parameterInfos.emplace_back(paramInfo); // update the interface UpdateParameterInterface(¶mInfo); } // create the button layout - mButtonGridLayout = new QGridLayout(); - mButtonGridLayout->setAlignment(Qt::AlignTop); - mButtonGridLayout->setMargin(0); + m_buttonGridLayout = new QGridLayout(); + m_buttonGridLayout->setAlignment(Qt::AlignTop); + m_buttonGridLayout->setMargin(0); // clear the button infos - mButtonInfos.Clear(); + m_buttonInfos.clear(); // get the number of buttons and iterate through them #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - const uint32 numButtons = mGameController->GetNumButtons(); + const uint32 numButtons = m_gameController->GetNumButtons(); for (uint32 i = 0; i < numButtons; ++i) { EMotionFX::AnimGraphGameControllerSettings::ButtonInfo* settingsInfo = activePreset->FindButtonInfo(i); MCORE_ASSERT(settingsInfo); // add the button name to the layout - mString = AZStd::string::format("Button %s%d", (i < 10) ? "0" : "", i); - QLabel* nameLabel = new QLabel(mString.c_str()); + m_string = AZStd::string::format("Button %s%d", (i < 10) ? "0" : "", i); + QLabel* nameLabel = new QLabel(m_string.c_str()); nameLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - mButtonGridLayout->addWidget(nameLabel, i, 0); + m_buttonGridLayout->addWidget(nameLabel, i, 0); // add the mode combo box to the layout QComboBox* modeComboBox = new QComboBox(); @@ -518,17 +517,17 @@ namespace EMStudio modeComboBox->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); connect(modeComboBox, static_cast(&QComboBox::currentIndexChanged), this, &GameControllerWindow::OnButtonModeComboBox); modeComboBox->setCurrentIndex(settingsInfo->m_mode); - mButtonGridLayout->addWidget(modeComboBox, i, 1); + m_buttonGridLayout->addWidget(modeComboBox, i, 1); - mButtonInfos.Add(ButtonInfo(i, modeComboBox)); + m_buttonInfos.emplace_back(ButtonInfo(i, modeComboBox)); // reinit the dynamic part of the button layout ReInitButtonInterface(i); } // real time preview of the controller - mPreviewLabels.Clear(); - mPreviewLabels.Resize(GameController::NUM_ELEMENTS + 1); + m_previewLabels.clear(); + m_previewLabels.resize(GameController::NUM_ELEMENTS + 1); QVBoxLayout* realtimePreviewLayout = new QVBoxLayout(); QGridLayout* previewGridLayout = new QGridLayout(); previewGridLayout->setAlignment(Qt::AlignTop); @@ -536,30 +535,30 @@ namespace EMStudio uint32 realTimePreviewLabelCounter = 0; for (uint32 i = 0; i < GameController::NUM_ELEMENTS; ++i) { - if (mGameController->GetIsPresent(i)) + if (m_gameController->GetIsPresent(i)) { - QLabel* elementNameLabel = new QLabel(mGameController->GetElementEnumName(i)); + QLabel* elementNameLabel = new QLabel(m_gameController->GetElementEnumName(i)); elementNameLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); previewGridLayout->addWidget(elementNameLabel, realTimePreviewLabelCounter, 0); - mPreviewLabels[i] = new QLabel(); - previewGridLayout->addWidget(mPreviewLabels[i], realTimePreviewLabelCounter, 1, Qt::AlignLeft); + m_previewLabels[i] = new QLabel(); + previewGridLayout->addWidget(m_previewLabels[i], realTimePreviewLabelCounter, 1, Qt::AlignLeft); realTimePreviewLabelCounter++; } else { - mPreviewLabels[i] = nullptr; + m_previewLabels[i] = nullptr; } } realtimePreviewLayout->addLayout(previewGridLayout); // add the special case label for the pressed buttons - mPreviewLabels[GameController::NUM_ELEMENTS] = new QLabel(); + m_previewLabels[GameController::NUM_ELEMENTS] = new QLabel(); QLabel* realtimeButtonNameLabel = new QLabel("Buttons"); realtimeButtonNameLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); previewGridLayout->addWidget(realtimeButtonNameLabel, realTimePreviewLabelCounter, 0); - previewGridLayout->addWidget(mPreviewLabels[GameController::NUM_ELEMENTS], realTimePreviewLabelCounter, 1, Qt::AlignLeft); + previewGridLayout->addWidget(m_previewLabels[GameController::NUM_ELEMENTS], realTimePreviewLabelCounter, 1, Qt::AlignLeft); // add the dead zone elements QHBoxLayout* deadZoneLayout = new QHBoxLayout(); @@ -569,26 +568,26 @@ namespace EMStudio deadZoneLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); previewGridLayout->addWidget(deadZoneLabel, realTimePreviewLabelCounter + 1, 0); - mDeadZoneSlider = new AzQtComponents::SliderInt(Qt::Horizontal); - mDeadZoneSlider->setRange(1, 90); - mDeadZoneSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - deadZoneLayout->addWidget(mDeadZoneSlider); + m_deadZoneSlider = new AzQtComponents::SliderInt(Qt::Horizontal); + m_deadZoneSlider->setRange(1, 90); + m_deadZoneSlider->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + deadZoneLayout->addWidget(m_deadZoneSlider); - mDeadZoneValueLabel = new QLabel(); - deadZoneLayout->addWidget(mDeadZoneValueLabel); + m_deadZoneValueLabel = new QLabel(); + deadZoneLayout->addWidget(m_deadZoneValueLabel); previewGridLayout->addLayout(deadZoneLayout, realTimePreviewLabelCounter + 1, 1); - mDeadZoneSlider->setValue(aznumeric_cast(mGameController->GetDeadZone() * 100)); - mString = AZStd::string::format("%.2f", mGameController->GetDeadZone()); - mDeadZoneValueLabel->setText(mString.c_str()); - connect(mDeadZoneSlider, &AzQtComponents::SliderInt::valueChanged, this, &GameControllerWindow::OnDeadZoneSliderChanged); + m_deadZoneSlider->setValue(aznumeric_cast(m_gameController->GetDeadZone() * 100)); + m_string = AZStd::string::format("%.2f", m_gameController->GetDeadZone()); + m_deadZoneValueLabel->setText(m_string.c_str()); + connect(m_deadZoneSlider, &AzQtComponents::SliderInt::valueChanged, this, &GameControllerWindow::OnDeadZoneSliderChanged); #endif // start the timers - mInterfaceTimer.start(1000 / 20, this); - mInterfaceTimerID = mInterfaceTimer.timerId(); - mGameControllerTimer.start(1000 / 100, this); - mGameControllerTimerID = mGameControllerTimer.timerId(); + m_interfaceTimer.start(1000 / 20, this); + m_interfaceTimerId = m_interfaceTimer.timerId(); + m_gameControllerTimer.start(1000 / 100, this); + m_gameControllerTimerId = m_gameControllerTimer.timerId(); // create the vertical layout for the parameter and the button setup QVBoxLayout* verticalLayout = new QVBoxLayout(); @@ -596,34 +595,34 @@ namespace EMStudio //////////////////////////// - mPresetComboBox->blockSignals(true); - mPresetComboBox->clear(); + m_presetComboBox->blockSignals(true); + m_presetComboBox->clear(); // add the presets to the combo box - for (uint32 i = 0; i < numPresets; ++i) + for (size_t i = 0; i < numPresets; ++i) { - mPresetComboBox->addItem(gameControllerSettings.GetPreset(i)->GetName()); + m_presetComboBox->addItem(gameControllerSettings.GetPreset(i)->GetName()); } // select the active preset - const uint32 activePresetIndex = gameControllerSettings.GetActivePresetIndex(); - if (activePresetIndex != MCORE_INVALIDINDEX32) + const size_t activePresetIndex = gameControllerSettings.GetActivePresetIndex(); + if (activePresetIndex != InvalidIndex) { - mPresetComboBox->setCurrentIndex(activePresetIndex); + m_presetComboBox->setCurrentIndex(aznumeric_caster(activePresetIndex)); } - mPresetComboBox->blockSignals(false); + m_presetComboBox->blockSignals(false); // set the name of the active preset if (gameControllerSettings.GetActivePreset()) { - mPresetNameLineEdit->blockSignals(true); - mPresetNameLineEdit->setText(gameControllerSettings.GetActivePreset()->GetName()); - mPresetNameLineEdit->blockSignals(false); + m_presetNameLineEdit->blockSignals(true); + m_presetNameLineEdit->setText(gameControllerSettings.GetActivePreset()->GetName()); + m_presetNameLineEdit->blockSignals(false); } - mPresetComboBox->setEnabled(true); - mPresetNameLineEdit->setEnabled(true); - mAddPresetButton->setEnabled(true); - mRemovePresetButton->setEnabled(true); + m_presetComboBox->setEnabled(true); + m_presetNameLineEdit->setEnabled(true); + m_addPresetButton->setEnabled(true); + m_removePresetButton->setEnabled(true); //////////////////////////// @@ -659,9 +658,9 @@ namespace EMStudio buttonNameLayout->addWidget(spacerItem); verticalLayout->addLayout(parameterNameLayout); - verticalLayout->addLayout(mParameterGridLayout); + verticalLayout->addLayout(m_parameterGridLayout); verticalLayout->addLayout(buttonNameLayout); - verticalLayout->addLayout(mButtonGridLayout); + verticalLayout->addLayout(m_buttonGridLayout); // main dynamic widget layout QHBoxLayout* dynamicWidgetLayout = new QHBoxLayout(); @@ -680,18 +679,18 @@ namespace EMStudio dynamicWidgetLayout->addWidget(realTimePreviewWidget); dynamicWidgetLayout->setAlignment(realTimePreviewWidget, Qt::AlignTop); #endif - mDynamicWidget->setLayout(dynamicWidgetLayout); + m_dynamicWidget->setLayout(dynamicWidgetLayout); - mDialogStack->Add(mDynamicWidget, "Game Controller Mapping", false, true); + m_dialogStack->Add(m_dynamicWidget, "Game Controller Mapping", false, true); } void GameControllerWindow::OnDeadZoneSliderChanged(int value) { #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - mGameController->SetDeadZone(value * 0.01f); - mString = AZStd::string::format("%.2f", value * 0.01f); - mDeadZoneValueLabel->setText(mString.c_str()); + m_gameController->SetDeadZone(value * 0.01f); + m_string = AZStd::string::format("%.2f", value * 0.01f); + m_deadZoneValueLabel->setText(m_string.c_str()); #else MCORE_UNUSED(value); #endif @@ -701,34 +700,22 @@ namespace EMStudio GameControllerWindow::ButtonInfo* GameControllerWindow::FindButtonInfo(QWidget* widget) { // get the number of button infos and iterate through them - const uint32 numButtonInfos = mButtonInfos.GetLength(); - for (uint32 i = 0; i < numButtonInfos; ++i) + const auto foundButtonInfo = AZStd::find_if(begin(m_buttonInfos), end(m_buttonInfos), [widget](const ButtonInfo& buttonInfo) { - if (mButtonInfos[i].mWidget == widget) - { - return &mButtonInfos[i]; - } - } - - // return failure - return nullptr; + return buttonInfo.m_widget == widget; + }); + return foundButtonInfo != end(m_buttonInfos) ? &(*foundButtonInfo) : nullptr; } GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByModeComboBox(QComboBox* comboBox) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [comboBox](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mMode == comboBox) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.m_mode == comboBox; + }); + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -736,36 +723,30 @@ namespace EMStudio GameControllerWindow::ParameterInfo* GameControllerWindow::FindButtonInfoByAttributeInfo(const EMotionFX::Parameter* parameter) { // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [parameter](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mParameter == parameter) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.m_parameter == parameter; + }); + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } // enable/disable controls for a given parameter void GameControllerWindow::UpdateParameterInterface(ParameterInfo* parameterInfo) { - int comboAxisIndex = parameterInfo->mAxis->currentIndex(); + int comboAxisIndex = parameterInfo->m_axis->currentIndex(); if (comboAxisIndex == 0) // None { - parameterInfo->mMode->setEnabled(false); - parameterInfo->mInvert->setEnabled(false); - parameterInfo->mValue->setEnabled(false); - parameterInfo->mValue->setText(""); + parameterInfo->m_mode->setEnabled(false); + parameterInfo->m_invert->setEnabled(false); + parameterInfo->m_value->setEnabled(false); + parameterInfo->m_value->setText(""); } else // some mode set { - parameterInfo->mMode->setEnabled(true); - parameterInfo->mInvert->setEnabled(true); - parameterInfo->mValue->setEnabled(true); + parameterInfo->m_mode->setEnabled(true); + parameterInfo->m_invert->setEnabled(true); + parameterInfo->m_value->setEnabled(true); } } @@ -775,7 +756,7 @@ namespace EMStudio MCORE_UNUSED(value); // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -791,7 +772,7 @@ namespace EMStudio return; } - EMotionFX::AnimGraphGameControllerSettings::ParameterInfo* settingsInfo = activePreset->FindParameterInfo(paramInfo->mParameter->GetName().c_str()); + EMotionFX::AnimGraphGameControllerSettings::ParameterInfo* settingsInfo = activePreset->FindParameterInfo(paramInfo->m_parameter->GetName().c_str()); MCORE_ASSERT(settingsInfo); settingsInfo->m_mode = (EMotionFX::AnimGraphGameControllerSettings::ParameterMode)combo->currentIndex(); } @@ -800,7 +781,7 @@ namespace EMStudio void GameControllerWindow::ReInitButtonInterface(uint32 buttonIndex) { // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -813,7 +794,7 @@ namespace EMStudio MCORE_ASSERT(settingsInfo); // remove the old widget - QLayoutItem* oldLayoutItem = mButtonGridLayout->itemAtPosition(buttonIndex, 2); + QLayoutItem* oldLayoutItem = m_buttonGridLayout->itemAtPosition(buttonIndex, 2); if (oldLayoutItem) { QWidget* oldWidget = oldLayoutItem->widget(); @@ -869,7 +850,7 @@ namespace EMStudio layout->setMargin(0); QComboBox* comboBox = new QComboBox(); - const EMotionFX::ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); + const EMotionFX::ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); for (const EMotionFX::ValueParameter* valueParameter : valueParameters) { if (azrtti_typeid(valueParameter) == azrtti_typeid() || @@ -907,7 +888,7 @@ namespace EMStudio if (widget) { - mButtonGridLayout->addWidget(widget, buttonIndex, 2); + m_buttonGridLayout->addWidget(widget, buttonIndex, 2); } } @@ -924,7 +905,7 @@ namespace EMStudio } // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -955,8 +936,8 @@ namespace EMStudio return; } - settingsInfo->m_string = selectedStates[0].mNodeName.c_str(); - browseEdit->setPlaceholderText(selectedStates[0].mNodeName.c_str()); + settingsInfo->m_string = selectedStates[0].m_nodeName.c_str(); + browseEdit->setPlaceholderText(selectedStates[0].m_nodeName.c_str()); } @@ -966,7 +947,7 @@ namespace EMStudio MCORE_UNUSED(value); // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -982,7 +963,7 @@ namespace EMStudio MCORE_ASSERT(settingsInfo); const AZStd::string parameterName = combo->currentText().toUtf8().data(); - const EMotionFX::Parameter* parameter = mAnimGraph->FindParameterByName(parameterName); + const EMotionFX::Parameter* parameter = m_animGraph->FindParameterByName(parameterName); if (parameter) { settingsInfo->m_string = parameter->GetName(); @@ -993,7 +974,7 @@ namespace EMStudio } // update the parameter window - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } @@ -1003,7 +984,7 @@ namespace EMStudio MCORE_UNUSED(value); // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -1019,7 +1000,7 @@ namespace EMStudio return; } - EMotionFX::AnimGraphGameControllerSettings::ButtonInfo* settingsInfo = activePreset->FindButtonInfo(buttonInfo->mButtonIndex); + EMotionFX::AnimGraphGameControllerSettings::ButtonInfo* settingsInfo = activePreset->FindButtonInfo(buttonInfo->m_buttonIndex); MCORE_ASSERT(settingsInfo); settingsInfo->m_mode = (EMotionFX::AnimGraphGameControllerSettings::ButtonMode)combo->currentIndex(); @@ -1029,7 +1010,7 @@ namespace EMStudio { // The parameter name is empty in case the button info has not been assigned with one yet. // Default it to the first compatible parameter. - const EMotionFX::ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); + const EMotionFX::ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); for (const EMotionFX::ValueParameter* valueParameter : valueParameters) { if (azrtti_typeid(valueParameter) == azrtti_typeid() || @@ -1041,27 +1022,27 @@ namespace EMStudio } } - ReInitButtonInterface(buttonInfo->mButtonIndex); + ReInitButtonInterface(buttonInfo->m_buttonIndex); // update the parameter window - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } void GameControllerWindow::OnAddPresetButton() { // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); - uint32 presetNumber = static_cast(gameControllerSettings.GetNumPresets()); - mString = AZStd::string::format("Preset %d", presetNumber); - while (gameControllerSettings.FindPresetIndexByName(mString.c_str()) != MCORE_INVALIDINDEX32) + size_t presetNumber = gameControllerSettings.GetNumPresets(); + m_string = AZStd::string::format("Preset %zu", presetNumber); + while (gameControllerSettings.FindPresetIndexByName(m_string.c_str()) != InvalidIndex) { presetNumber++; - mString = AZStd::string::format("Preset %d", presetNumber); + m_string = AZStd::string::format("Preset %zu", presetNumber); } - EMotionFX::AnimGraphGameControllerSettings::Preset* preset = aznew EMotionFX::AnimGraphGameControllerSettings::Preset(mString.c_str()); + EMotionFX::AnimGraphGameControllerSettings::Preset* preset = aznew EMotionFX::AnimGraphGameControllerSettings::Preset(m_string.c_str()); gameControllerSettings.AddPreset(preset); ReInit(); @@ -1073,7 +1054,7 @@ namespace EMStudio MCORE_UNUSED(value); // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); QComboBox* combo = qobject_cast(sender()); EMotionFX::AnimGraphGameControllerSettings::Preset* preset = gameControllerSettings.GetPreset(combo->currentIndex()); @@ -1086,9 +1067,9 @@ namespace EMStudio void GameControllerWindow::OnRemovePresetButton() { // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); - uint32 presetIndex = mPresetComboBox->currentIndex(); + uint32 presetIndex = m_presetComboBox->currentIndex(); gameControllerSettings.RemovePreset(presetIndex); EMotionFX::AnimGraphGameControllerSettings::Preset* preset = nullptr; @@ -1113,7 +1094,7 @@ namespace EMStudio void GameControllerWindow::OnPresetNameChanged() { // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); assert(sender()->inherits("QLineEdit")); QLineEdit* widget = qobject_cast(sender()); @@ -1121,10 +1102,10 @@ namespace EMStudio FromQtString(widget->text(), &newValue); // get the currently selected preset - uint32 presetIndex = mPresetComboBox->currentIndex(); + uint32 presetIndex = m_presetComboBox->currentIndex(); - uint32 newValueIndex = static_cast(gameControllerSettings.FindPresetIndexByName(newValue.c_str())); - if (newValueIndex == MCORE_INVALIDINDEX32) + size_t newValueIndex = gameControllerSettings.FindPresetIndexByName(newValue.c_str()); + if (newValueIndex == InvalidIndex) { EMotionFX::AnimGraphGameControllerSettings::Preset* preset = gameControllerSettings.GetPreset(presetIndex); preset->SetName(newValue.c_str()); @@ -1136,35 +1117,28 @@ namespace EMStudio void GameControllerWindow::OnPresetNameEdited(const QString& text) { // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // check if there already is a preset with the currently entered name - uint32 presetIndex = static_cast(gameControllerSettings.FindPresetIndexByName(FromQtString(text).c_str())); - if (presetIndex != MCORE_INVALIDINDEX32 && presetIndex != gameControllerSettings.GetActivePresetIndex()) + size_t presetIndex = gameControllerSettings.FindPresetIndexByName(FromQtString(text).c_str()); + if (presetIndex != InvalidIndex && presetIndex != gameControllerSettings.GetActivePresetIndex()) { - GetManager()->SetWidgetAsInvalidInput(mPresetNameLineEdit); + GetManager()->SetWidgetAsInvalidInput(m_presetNameLineEdit); } else { - mPresetNameLineEdit->setStyleSheet(""); + m_presetNameLineEdit->setStyleSheet(""); } } GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByAxisComboBox(QComboBox* comboBox) { - // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [comboBox](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mAxis == comboBox) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.m_axis == comboBox; + }); + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1173,7 +1147,7 @@ namespace EMStudio MCORE_UNUSED(value); // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -1189,13 +1163,13 @@ namespace EMStudio return; } - EMotionFX::AnimGraphGameControllerSettings::ParameterInfo* settingsInfo = activePreset->FindParameterInfo(paramInfo->mParameter->GetName().c_str()); + EMotionFX::AnimGraphGameControllerSettings::ParameterInfo* settingsInfo = activePreset->FindParameterInfo(paramInfo->m_parameter->GetName().c_str()); MCORE_ASSERT(settingsInfo); #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (azrtti_istypeof(paramInfo->mParameter)) + if (azrtti_istypeof(paramInfo->m_parameter)) { - const uint32 elementID = mGameController->FindElemendIDByName(FromQtString(combo->currentText()).c_str()); + const uint32 elementID = m_gameController->FindElementIDByName(FromQtString(combo->currentText()).c_str()); if (elementID >= MCORE_INVALIDINDEX8) { settingsInfo->m_axis = MCORE_INVALIDINDEX8; @@ -1206,7 +1180,7 @@ namespace EMStudio } } else - if (azrtti_typeid(paramInfo->mParameter) == azrtti_typeid()) + if (azrtti_typeid(paramInfo->m_parameter) == azrtti_typeid()) { if (value == 0) { @@ -1225,24 +1199,17 @@ namespace EMStudio UpdateParameterInterface(paramInfo); // update the parameter window - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } GameControllerWindow::ParameterInfo* GameControllerWindow::FindParamInfoByCheckBox(QCheckBox* checkBox) { - // get the number of parameter infos and iterate through them - const uint32 numParamInfos = mParameterInfos.GetLength(); - for (uint32 i = 0; i < numParamInfos; ++i) + const auto foundParameterInfo = AZStd::find_if(begin(m_parameterInfos), end(m_parameterInfos), [checkBox](const ParameterInfo& parameterInfo) { - if (mParameterInfos[i].mInvert == checkBox) - { - return &mParameterInfos[i]; - } - } - - // return failure - return nullptr; + return parameterInfo.m_invert == checkBox; + }); + return foundParameterInfo != end(m_parameterInfos) ? &(*foundParameterInfo) : nullptr; } @@ -1251,7 +1218,7 @@ namespace EMStudio MCORE_UNUSED(state); // get the game controller settings from the current anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -1267,7 +1234,7 @@ namespace EMStudio return; } - EMotionFX::AnimGraphGameControllerSettings::ParameterInfo* settingsInfo = activePreset->FindParameterInfo(paramInfo->mParameter->GetName().c_str()); + EMotionFX::AnimGraphGameControllerSettings::ParameterInfo* settingsInfo = activePreset->FindParameterInfo(paramInfo->m_parameter->GetName().c_str()); MCORE_ASSERT(settingsInfo); settingsInfo->m_invert = checkBox->checkState() == Qt::Checked ? true : false; } @@ -1281,7 +1248,7 @@ namespace EMStudio UpdateGameControllerComboBox(); AutoSelectGameController(); ReInit(); - mPlugin->GetParameterWindow()->Reinit(/*forceReinit*/true); + m_plugin->GetParameterWindow()->Reinit(/*forceReinit*/true); } @@ -1299,10 +1266,10 @@ namespace EMStudio // update the game controller #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - mGameController->Update(); + m_gameController->Update(); // check if the game controller is usable and if we have actually checked it in the combobox, if not return directly - if (mGameController->GetIsValid() == false || mGameControllerComboBox->currentIndex() == 0) + if (m_gameController->GetIsValid() == false || m_gameControllerComboBox->currentIndex() == 0) { return; } @@ -1323,7 +1290,7 @@ namespace EMStudio animGraphInstance = actorInstance->GetAnimGraphInstance(); if (animGraphInstance) { - if (animGraphInstance->GetAnimGraph() != mAnimGraph) // if the selected anim graph instance isn't equal to the one of the actor instance + if (animGraphInstance->GetAnimGraph() != m_animGraph) // if the selected anim graph instance isn't equal to the one of the actor instance { return; } @@ -1334,7 +1301,7 @@ namespace EMStudio } // get the game controller settings from the anim graph - EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = mAnimGraph->GetGameControllerSettings(); + EMotionFX::AnimGraphGameControllerSettings& gameControllerSettings = m_animGraph->GetGameControllerSettings(); // get the active preset EMotionFX::AnimGraphGameControllerSettings::Preset* activePreset = gameControllerSettings.GetActivePreset(); @@ -1343,10 +1310,10 @@ namespace EMStudio return; } - const float timeDelta = mDeltaTimer.StampAndGetDeltaTimeInSeconds(); + const float timeDelta = m_deltaTimer.StampAndGetDeltaTimeInSeconds(); // get the number of parameters and iterate through them - const EMotionFX::ValueParameterVector& valueParameters = mAnimGraph->RecursivelyGetValueParameters(); + const EMotionFX::ValueParameterVector& valueParameters = m_animGraph->RecursivelyGetValueParameters(); const size_t valueParametersCount = valueParameters.size(); for (size_t parameterIndex = 0; parameterIndex < valueParametersCount; ++parameterIndex) { @@ -1367,7 +1334,7 @@ namespace EMStudio if (attribute->GetType() == MCore::AttributeFloat::TYPE_ID) { // get the current value from the game controller - float value = mGameController->GetValue(settingsInfo->m_axis); + float value = m_gameController->GetValue(settingsInfo->m_axis); const EMotionFX::FloatParameter* floatParameter = static_cast(valueParameter); const float minValue = floatParameter->GetMinValue(); const float maxValue = floatParameter->GetMaxValue(); @@ -1454,7 +1421,7 @@ namespace EMStudio // only process in case the parameter info is enabled if (settingsInfo->m_enabled) { - AZ::Quaternion localRot = actorInstance->GetLocalSpaceTransform().mRotation; + AZ::Quaternion localRot = actorInstance->GetLocalSpaceTransform().m_rotation; localRot = localRot * MCore::CreateFromAxisAndAngle(AZ::Vector3(0.0f, 0.0f, 1.0f), value * timeDelta * 3.0f); actorInstance->SetLocalSpaceRotation(localRot); } @@ -1471,20 +1438,20 @@ namespace EMStudio } // check if we also need to update the attribute widget in the parameter window - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { // find the corresponding attribute widget and set the value in case the parameter info is enabled if (settingsInfo->m_enabled) { - mPlugin->GetParameterWindow()->UpdateParameterValue(valueParameter); + m_plugin->GetParameterWindow()->UpdateParameterValue(valueParameter); } // also update the preview value in the game controller window ParameterInfo* interfaceParamInfo = FindButtonInfoByAttributeInfo(valueParameter); if (interfaceParamInfo) { - mString = AZStd::string::format("%.2f", value); - interfaceParamInfo->mValue->setText(mString.c_str()); + m_string = AZStd::string::format("%.2f", value); + interfaceParamInfo->m_value->setText(m_string.c_str()); } } } // if it's a float attribute @@ -1494,13 +1461,13 @@ namespace EMStudio AZ::Vector2 value(0.0f, 0.0f); if (settingsInfo->m_axis == 0) { - value.SetX(mGameController->GetValue(GameController::ELEM_POS_X)); - value.SetY(mGameController->GetValue(GameController::ELEM_POS_Y)); + value.SetX(m_gameController->GetValue(GameController::ELEM_POS_X)); + value.SetY(m_gameController->GetValue(GameController::ELEM_POS_Y)); } else { - value.SetX(mGameController->GetValue(GameController::ELEM_ROT_X)); - value.SetY(mGameController->GetValue(GameController::ELEM_ROT_Y)); + value.SetX(m_gameController->GetValue(GameController::ELEM_ROT_X)); + value.SetY(m_gameController->GetValue(GameController::ELEM_ROT_Y)); } const EMotionFX::Vector2Parameter* vector2Parameter = static_cast(valueParameter); @@ -1610,7 +1577,7 @@ namespace EMStudio // only process in case the parameter info is enabled if (settingsInfo->m_enabled) { - AZ::Quaternion localRot = actorInstance->GetLocalSpaceTransform().mRotation; + AZ::Quaternion localRot = actorInstance->GetLocalSpaceTransform().m_rotation; localRot = localRot * MCore::CreateFromAxisAndAngle(AZ::Vector3(0.0f, 0.0f, 1.0f), value.GetX() * timeDelta * 3.0f); actorInstance->SetLocalSpaceRotation(localRot); } @@ -1629,30 +1596,30 @@ namespace EMStudio } // check if we also need to update the attribute widget in the parameter window - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { // find the corresponding attribute widget and set the value in case the parameter info is enabled if (settingsInfo->m_enabled) { - mPlugin->GetParameterWindow()->UpdateParameterValue(valueParameter); + m_plugin->GetParameterWindow()->UpdateParameterValue(valueParameter); } // also update the preview value in the game controller window ParameterInfo* interfaceParamInfo = FindButtonInfoByAttributeInfo(valueParameter); if (interfaceParamInfo) { - mString = AZStd::string::format("%.2f, %.2f", value.GetX(), value.GetY()); - interfaceParamInfo->mValue->setText(mString.c_str()); + m_string = AZStd::string::format("%.2f, %.2f", value.GetX(), value.GetY()); + interfaceParamInfo->m_value->setText(m_string.c_str()); } } } // if it's a vector2 attribute } // for all parameters // update the buttons - const uint32 numButtons = mGameController->GetNumButtons(); + const uint32 numButtons = m_gameController->GetNumButtons(); for (uint32 i = 0; i < numButtons; ++i) { - const bool isPressed = mGameController->GetIsButtonPressed(i); + const bool isPressed = m_gameController->GetIsButtonPressed(i); // get the game controller settings info for the given button EMotionFX::AnimGraphGameControllerSettings::ButtonInfo* settingsInfo = activePreset->FindButtonInfo(i); @@ -1670,12 +1637,12 @@ namespace EMStudio } // Find the corresponding value parameter. - const AZ::Outcome parameterIndex = mAnimGraph->FindValueParameterIndexByName(settingsInfo->m_string); + const AZ::Outcome parameterIndex = m_animGraph->FindValueParameterIndexByName(settingsInfo->m_string); MCore::AttributeBool* boolAttribute = nullptr; if (parameterIndex.IsSuccess()) { - MCore::Attribute* attribute = animGraphInstance->GetParameterValue(static_cast(parameterIndex.GetValue())); + MCore::Attribute* attribute = animGraphInstance->GetParameterValue(parameterIndex.GetValue()); if (attribute->GetType() == MCore::AttributeBool::TYPE_ID) { @@ -1713,10 +1680,10 @@ namespace EMStudio } // check if we also need to update the attribute widget in the parameter window - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { - const EMotionFX::ValueParameter* valueParameter = mAnimGraph->FindValueParameter(parameterIndex.GetValue()); - mPlugin->GetParameterWindow()->UpdateParameterValue(valueParameter); + const EMotionFX::ValueParameter* valueParameter = m_animGraph->FindValueParameter(parameterIndex.GetValue()); + m_plugin->GetParameterWindow()->UpdateParameterValue(valueParameter); } } @@ -1730,10 +1697,10 @@ namespace EMStudio boolAttribute->SetValue(isPressed ? true : false); // check if we also need to update the attribute widget in the parameter window - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { - const EMotionFX::ValueParameter* valueParameter = mAnimGraph->FindValueParameter(parameterIndex.GetValue()); - mPlugin->GetParameterWindow()->UpdateParameterValue(valueParameter); + const EMotionFX::ValueParameter* valueParameter = m_animGraph->FindValueParameter(parameterIndex.GetValue()); + m_plugin->GetParameterWindow()->UpdateParameterValue(valueParameter); } } @@ -1747,10 +1714,10 @@ namespace EMStudio boolAttribute->SetValue((!isPressed) ? true : false); // check if we also need to update the attribute widget in the parameter window - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { - const EMotionFX::ValueParameter* valueParameter = mAnimGraph->FindValueParameter(parameterIndex.GetValue()); - mPlugin->GetParameterWindow()->UpdateParameterValue(valueParameter); + const EMotionFX::ValueParameter* valueParameter = m_animGraph->FindValueParameter(parameterIndex.GetValue()); + m_plugin->GetParameterWindow()->UpdateParameterValue(valueParameter); } } @@ -1784,10 +1751,10 @@ namespace EMStudio } // check if we also need to update the attribute widget in the parameter window - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { - const EMotionFX::ValueParameter* valueParameter = mAnimGraph->FindValueParameter(parameterIndex.GetValue()); - mPlugin->GetParameterWindow()->UpdateParameterValue(valueParameter); + const EMotionFX::ValueParameter* valueParameter = m_animGraph->FindValueParameter(parameterIndex.GetValue()); + m_plugin->GetParameterWindow()->UpdateParameterValue(valueParameter); } } @@ -1800,43 +1767,43 @@ namespace EMStudio } // check if the interface timer is ticking - if (event->timerId() == mInterfaceTimerID) + if (event->timerId() == m_interfaceTimerId) { // update the interface elements for (uint32 i = 0; i < GameController::NUM_ELEMENTS; ++i) { - if (mGameController->GetIsPresent(i)) + if (m_gameController->GetIsPresent(i)) { - const float value = mGameController->GetValue(i); + const float value = m_gameController->GetValue(i); if (value > 1000.0f) { - mString.clear(); + m_string.clear(); } else { - mString = AZStd::string::format("%.2f", value); + m_string = AZStd::string::format("%.2f", value); } - mPreviewLabels[i]->setText(mString.c_str()); + m_previewLabels[i]->setText(m_string.c_str()); } } // update the active button string - mString.clear(); + m_string.clear(); for (uint32 i = 0; i < numButtons; ++i) { - if (mGameController->GetIsButtonPressed(i)) + if (m_gameController->GetIsButtonPressed(i)) { - mString += AZStd::string::format("%s%d ", (i < 10) ? "0" : "", i); + m_string += AZStd::string::format("%s%d ", (i < 10) ? "0" : "", i); } } - if (mString.size() == 0) + if (m_string.size() == 0) { - mPreviewLabels[GameController::NUM_ELEMENTS]->setText(" "); + m_previewLabels[GameController::NUM_ELEMENTS]->setText(" "); } else { - mPreviewLabels[GameController::NUM_ELEMENTS]->setText(mString.c_str()); + m_previewLabels[GameController::NUM_ELEMENTS]->setText(m_string.c_str()); } } #endif diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.h index 7236842ef0..059108625a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GameControllerWindow.h @@ -14,7 +14,7 @@ #include -#include +#include #include #include #include @@ -71,15 +71,15 @@ namespace EMStudio MCORE_INLINE bool GetIsGameControllerValid() const { #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - if (mGameController == nullptr) + if (m_gameController == nullptr) { return false; } - if (mGameControllerComboBox->currentIndex() == 0) + if (m_gameControllerComboBox->currentIndex() == 0) { return false; } - return mGameController->GetIsValid(); + return m_gameController->GetIsValid(); #else return false; #endif @@ -112,22 +112,22 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandUnselectCallback); MCORE_DEFINECOMMANDCALLBACK(CommandClearSelectionCallback); - CommandCreateBlendParameterCallback* mCreateCallback; - CommandRemoveBlendParameterCallback* mRemoveCallback; - CommandAdjustBlendParameterCallback* mAdjustCallback; - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; - CommandClearSelectionCallback* mClearSelectionCallback; + CommandCreateBlendParameterCallback* m_createCallback; + CommandRemoveBlendParameterCallback* m_removeCallback; + CommandAdjustBlendParameterCallback* m_adjustCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; + CommandClearSelectionCallback* m_clearSelectionCallback; struct ParameterInfo { MCORE_MEMORYOBJECTCATEGORY(GameControllerWindow::ParameterInfo, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - const EMotionFX::Parameter* mParameter; - QComboBox* mAxis; - QComboBox* mMode; - QCheckBox* mInvert; - QLineEdit* mValue; + const EMotionFX::Parameter* m_parameter; + QComboBox* m_axis; + QComboBox* m_mode; + QCheckBox* m_invert; + QLineEdit* m_value; }; struct ButtonInfo @@ -135,12 +135,12 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(GameControllerWindow::ButtonInfo, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); ButtonInfo(uint32 index, QWidget* widget) { - mButtonIndex = index; - mWidget = widget; + m_buttonIndex = index; + m_widget = widget; } - uint32 mButtonIndex; - QWidget* mWidget; + uint32 m_buttonIndex; + QWidget* m_widget; }; ParameterInfo* FindParamInfoByModeComboBox(QComboBox* comboBox); @@ -153,37 +153,37 @@ namespace EMStudio void UpdateParameterInterface(ParameterInfo* parameterInfo); void UpdateGameControllerComboBox(); - AnimGraphPlugin* mPlugin; - MCore::Array mPreviewLabels; - MCore::Array mParameterInfos; - MCore::Array mButtonInfos; - QBasicTimer mInterfaceTimer; - QBasicTimer mGameControllerTimer; - AZ::Debug::Timer mDeltaTimer; - int mInterfaceTimerID; - int mGameControllerTimerID; + AnimGraphPlugin* m_plugin; + AZStd::vector m_previewLabels; + AZStd::vector m_parameterInfos; + AZStd::vector m_buttonInfos; + QBasicTimer m_interfaceTimer; + QBasicTimer m_gameControllerTimer; + AZ::Debug::Timer m_deltaTimer; + int m_interfaceTimerId; + int m_gameControllerTimerId; #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - GameController* mGameController; + GameController* m_gameController; #endif - EMotionFX::AnimGraph* mAnimGraph; + EMotionFX::AnimGraph* m_animGraph; - MysticQt::DialogStack* mDialogStack; + MysticQt::DialogStack* m_dialogStack; - QWidget* mDynamicWidget; - AzQtComponents::SliderInt* mDeadZoneSlider; - QLabel* mDeadZoneValueLabel; - QGridLayout* mParameterGridLayout; - QGridLayout* mButtonGridLayout; - QComboBox* mGameControllerComboBox; + QWidget* m_dynamicWidget; + AzQtComponents::SliderInt* m_deadZoneSlider; + QLabel* m_deadZoneValueLabel; + QGridLayout* m_parameterGridLayout; + QGridLayout* m_buttonGridLayout; + QComboBox* m_gameControllerComboBox; // preset interface elements - QComboBox* mPresetComboBox; - QLineEdit* mPresetNameLineEdit; - QPushButton* mAddPresetButton; - QPushButton* mRemovePresetButton; + QComboBox* m_presetComboBox; + QLineEdit* m_presetNameLineEdit; + QPushButton* m_addPresetButton; + QPushButton* m_removePresetButton; - AZStd::string mString; + AZStd::string m_string; void timerEvent(QTimerEvent* event); void InitGameController(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.cpp index fe2e5894c4..75cca66e3d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.cpp @@ -17,63 +17,59 @@ namespace EMStudio { // statics - QColor GraphNode::mPortHighlightColor = QColor(255, 128, 0); - QColor GraphNode::mPortHighlightBGColor = QColor(128, 64, 0); + QColor GraphNode::s_portHighlightColo = QColor(255, 128, 0); + QColor GraphNode::s_portHighlightBGColor = QColor(128, 64, 0); // constructor - GraphNode::GraphNode(const QModelIndex& modelIndex, const char* name, uint32 numInputs, uint32 numOutputs) + GraphNode::GraphNode(const QModelIndex& modelIndex, const char* name, AZ::u16 numInputs, AZ::u16 numOutputs) : m_modelIndex(modelIndex) { - mConnections.SetMemoryCategory(MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - mInputPorts.SetMemoryCategory(MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - mOutputPorts.SetMemoryCategory(MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - - mRect = QRect(0, 0, 200, 128); - mBaseColor = QColor(74, 63, 238); - mVisualizeColor = QColor(0, 255, 0); - mOpacity = 1.0f; - mFinalRect = mRect; - mIsDeletable = true; - mIsHighlighted = false; - mConFromOutputOnly = false; - mIsCollapsed = false; - mIsProcessed = false; - mIsUpdated = false; - mIsEnabled = true; - mVisualize = false; - mCanVisualize = false; - mVisualizeHighlighted = false; - mNameAndPortsUpdated = false; - mCanHaveChildren = false; - mHasVisualGraph = false; - mHasVisualOutputPorts = true; - mMaxInputWidth = 0; - mMaxOutputWidth = 0; - - mHeaderFont.setPixelSize(12); - mHeaderFont.setBold(true); - mPortNameFont.setPixelSize(9); - mInfoTextFont.setPixelSize(10); - mInfoTextFont.setBold(true); - mSubTitleFont.setPixelSize(10); + m_rect = QRect(0, 0, 200, 128); + m_baseColor = QColor(74, 63, 238); + m_visualizeColor = QColor(0, 255, 0); + m_opacity = 1.0f; + m_finalRect = m_rect; + m_isDeletable = true; + m_isHighlighted = false; + m_conFromOutputOnly = false; + m_isCollapsed = false; + m_isProcessed = false; + m_isUpdated = false; + m_isEnabled = true; + m_visualize = false; + m_canVisualize = false; + m_visualizeHighlighted = false; + m_nameAndPortsUpdated = false; + m_canHaveChildren = false; + m_hasVisualGraph = false; + m_hasVisualOutputPorts = true; + m_maxInputWidth = 0; + m_maxOutputWidth = 0; + + m_headerFont.setPixelSize(12); + m_headerFont.setBold(true); + m_portNameFont.setPixelSize(9); + m_infoTextFont.setPixelSize(10); + m_infoTextFont.setBold(true); + m_subTitleFont.setPixelSize(10); // has child node indicator - mSubstPoly.resize(4); + m_substPoly.resize(4); - mTextOptionsCenter.setAlignment(Qt::AlignCenter); - mTextOptionsCenterHV.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); - mTextOptionsAlignRight.setAlignment(Qt::AlignRight | Qt::AlignVCenter); - mTextOptionsAlignLeft.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); + m_textOptionsCenter.setAlignment(Qt::AlignCenter); + m_textOptionsCenterHv.setAlignment(Qt::AlignHCenter | Qt::AlignVCenter); + m_textOptionsAlignRight.setAlignment(Qt::AlignRight | Qt::AlignVCenter); + m_textOptionsAlignLeft.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); - mInputPorts.Resize(numInputs); - mOutputPorts.Resize(numOutputs); + m_inputPorts.resize(numInputs); + m_outputPorts.resize(numOutputs); // initialize the port metrics - mPortFontMetrics = new QFontMetrics(mPortNameFont); - mHeaderFontMetrics = new QFontMetrics(mHeaderFont); - mInfoFontMetrics = new QFontMetrics(mInfoTextFont); - mSubTitleFontMetrics = new QFontMetrics(mSubTitleFont); + m_portFontMetrics = new QFontMetrics(m_portNameFont); + m_headerFontMetrics = new QFontMetrics(m_headerFont); + m_infoFontMetrics = new QFontMetrics(m_infoTextFont); + m_subTitleFontMetrics = new QFontMetrics(m_subTitleFont); SetName(name, false); ResetBorderColor(); @@ -84,10 +80,10 @@ namespace EMStudio GraphNode::~GraphNode() { // delete the font metrics - delete mPortFontMetrics; - delete mHeaderFontMetrics; - delete mInfoFontMetrics; - delete mSubTitleFontMetrics; + delete m_portFontMetrics; + delete m_headerFontMetrics; + delete m_infoFontMetrics; + delete m_subTitleFontMetrics; RemoveAllConnections(); } @@ -97,165 +93,74 @@ namespace EMStudio void GraphNode::UpdateTextPixmap() { // init the title text - mTitleText.setTextOption(mTextOptionsCenter); - mTitleText.setTextFormat(Qt::PlainText); - mTitleText.setPerformanceHint(QStaticText::AggressiveCaching); - mTitleText.setTextWidth(mRect.width()); - mTitleText.setText(mElidedName); - mTitleText.prepare(QTransform(), mHeaderFont); + m_titleText.setTextOption(m_textOptionsCenter); + m_titleText.setTextFormat(Qt::PlainText); + m_titleText.setPerformanceHint(QStaticText::AggressiveCaching); + m_titleText.setTextWidth(m_rect.width()); + m_titleText.setText(m_elidedName); + m_titleText.prepare(QTransform(), m_headerFont); // init the title text - mSubTitleText.setTextOption(mTextOptionsCenter); - mSubTitleText.setTextFormat(Qt::PlainText); - mSubTitleText.setPerformanceHint(QStaticText::AggressiveCaching); - mSubTitleText.setTextWidth(mRect.width()); - mSubTitleText.setText(mElidedSubTitle); - mSubTitleText.prepare(QTransform(), mSubTitleFont); + m_subTitleText.setTextOption(m_textOptionsCenter); + m_subTitleText.setTextFormat(Qt::PlainText); + m_subTitleText.setPerformanceHint(QStaticText::AggressiveCaching); + m_subTitleText.setTextWidth(m_rect.width()); + m_subTitleText.setText(m_elidedSubTitle); + m_subTitleText.prepare(QTransform(), m_subTitleFont); // draw the info text QRect textRect; CalcInfoTextRect(textRect, true); - mInfoText.setTextOption(mTextOptionsCenterHV); - mInfoText.setTextFormat(Qt::PlainText); - mInfoText.setPerformanceHint(QStaticText::AggressiveCaching); - mInfoText.setTextWidth(mRect.width()); - mInfoText.setText(mElidedNodeInfo); - mInfoText.prepare(QTransform(), mSubTitleFont); + m_infoText.setTextOption(m_textOptionsCenterHv); + m_infoText.setTextFormat(Qt::PlainText); + m_infoText.setPerformanceHint(QStaticText::AggressiveCaching); + m_infoText.setTextWidth(m_rect.width()); + m_infoText.setText(m_elidedNodeInfo); + m_infoText.prepare(QTransform(), m_subTitleFont); // input ports - const uint32 numInputs = mInputPorts.GetLength(); - mInputPortText.Resize(numInputs); - for (uint32 i = 0; i < numInputs; ++i) + const size_t numInputs = m_inputPorts.size(); + m_inputPortText.resize(numInputs); + for (size_t i = 0; i < numInputs; ++i) { - QStaticText& staticText = mInputPortText[i]; + QStaticText& staticText = m_inputPortText[i]; staticText.setTextFormat(Qt::PlainText); staticText.setPerformanceHint(QStaticText::AggressiveCaching); - // staticText.setTextWidth( mRect.width() ); - staticText.setText(mInputPorts[i].GetName()); - staticText.prepare(QTransform(), mPortNameFont); + staticText.setText(m_inputPorts[i].GetName()); + staticText.prepare(QTransform(), m_portNameFont); } // output ports - const uint32 numOutputs = mOutputPorts.GetLength(); - mOutputPortText.Resize(numOutputs); - for (uint32 i = 0; i < numOutputs; ++i) + const size_t numOutputs = m_outputPorts.size(); + m_outputPortText.resize(numOutputs); + for (size_t i = 0; i < numOutputs; ++i) { - QStaticText& staticText = mOutputPortText[i]; + QStaticText& staticText = m_outputPortText[i]; staticText.setTextFormat(Qt::PlainText); staticText.setPerformanceHint(QStaticText::AggressiveCaching); - // staticText.setTextWidth( mRect.width() ); - staticText.setText(mOutputPorts[i].GetName()); - staticText.prepare(QTransform(), mPortNameFont); + staticText.setText(m_outputPorts[i].GetName()); + staticText.prepare(QTransform(), m_portNameFont); } - - //------------------------------------------- - /* - // create a new pixmap with the new and correct resolution - const uint32 nodeWidth = mRect.width(); - const uint32 nodeHeight = mRect.height(); - mTextPixmap = QPixmap(nodeWidth, nodeHeight); - - // make the pixmap fully transparent - mTextPixmap.fill(Qt::transparent); - - mTextPainter.begin( &mTextPixmap ); - - // setup colors - QColor textColor; - if (!GetIsSelected()) - { - if (mIsEnabled) - textColor = Qt::white; - else - textColor = QColor( 100, 100, 100 ); - } - else - textColor = QColor(255,128,0); - - // some rects we need for the text - QRect fullHeaderRect( 0, 0, mRect.width(), 25 ); - QRect headerRect( 0, 0, mRect.width(), 15 ); - QRect subHeaderRect( 0, 13, mRect.width(), 10 ); - - // draw header text - mTextPainter.setBrush( Qt::NoBrush ); - mTextPainter.setPen( textColor ); - mTextPainter.setFont( mHeaderFont ); - mTextPainter.drawText( headerRect, mElidedName, mTextOptionsCenter ); - - mTextPainter.setFont( mSubTitleFont ); - mTextPainter.drawText( subHeaderRect, mElidedSubTitle, mTextOptionsCenter ); - - if (mIsCollapsed == false) - { - // draw the info text - QRect textRect; - CalcInfoTextRect( textRect, true ); - mTextPainter.setPen( QColor(255,128,0) ); - mTextPainter.setFont( mInfoTextFont ); - mTextPainter.drawText( textRect, mElidedNodeInfo, mTextOptionsCenterHV ); - - mTextPainter.setPen( textColor ); - - // draw the input ports - mTextPainter.setPen( textColor ); - mTextPainter.setFont( mPortNameFont ); - const uint32 numInputs = mInputPorts.GetLength(); - for (uint32 i=0; iGetRect(); - - if (inputPort->GetNameID() == MCORE_INVALIDINDEX32) - continue; - - // draw the text - CalcInputPortTextRect(i, textRect, true); - mTextPainter.drawText( textRect, inputPort->GetName(), mTextOptionsAlignLeft ); - } - - // draw the output ports - const uint32 numOutputs = mOutputPorts.GetLength(); - for (uint32 i=0; iGetNameID() == MCORE_INVALIDINDEX32) - continue; - - const QRect& portRect = outputPort->GetRect(); - - // draw the text - CalcOutputPortTextRect(i, textRect, true); - mTextPainter.drawText( textRect, outputPort->GetName(), mTextOptionsAlignRight ); - } - } - - mTextPainter.end(); - */ } // remove all node connections void GraphNode::RemoveAllConnections() { - const uint32 numConnections = mConnections.GetLength(); - for (uint32 i = 0; i < numConnections; ++i) + for (NodeConnection* connection : m_connections) { - delete mConnections[i]; + delete connection; } - mConnections.Clear(); + m_connections.clear(); } // set the name of the node void GraphNode::SetName(const char* name, bool updatePixmap) { - mName = name; - mElidedName = mHeaderFontMetrics->elidedText(name, Qt::ElideMiddle, MAX_NODEWIDTH); + m_name = name; + m_elidedName = m_headerFontMetrics->elidedText(name, Qt::ElideMiddle, MAX_NODEWIDTH); if (updatePixmap) { @@ -268,8 +173,8 @@ namespace EMStudio void GraphNode::SetSubTitle(const char* subTitle, bool updatePixmap) { - mSubTitle = subTitle; - mElidedSubTitle = mSubTitleFontMetrics->elidedText(subTitle, Qt::ElideMiddle, MAX_NODEWIDTH); + m_subTitle = subTitle; + m_elidedSubTitle = m_subTitleFontMetrics->elidedText(subTitle, Qt::ElideMiddle, MAX_NODEWIDTH); if (updatePixmap) { @@ -282,8 +187,8 @@ namespace EMStudio void GraphNode::SetNodeInfo(const AZStd::string& info) { - mNodeInfo = info; - mElidedNodeInfo = mInfoFontMetrics->elidedText(mNodeInfo.c_str(), Qt::ElideMiddle, MAX_NODEWIDTH - mMaxInputWidth - mMaxOutputWidth); + m_nodeInfo = info; + m_elidedNodeInfo = m_infoFontMetrics->elidedText(m_nodeInfo.c_str(), Qt::ElideMiddle, MAX_NODEWIDTH - m_maxInputWidth - m_maxOutputWidth); UpdateNameAndPorts(); UpdateRects(); @@ -294,18 +199,18 @@ namespace EMStudio void GraphNode::UpdateRects() { // calc window rect - mRect.setWidth(CalcRequiredWidth()); - mRect.setHeight(CalcRequiredHeight()); + m_rect.setWidth(CalcRequiredWidth()); + m_rect.setHeight(CalcRequiredHeight()); // calc the rect in screen space (after scrolling and zooming) - mFinalRect = mParentGraph->GetTransform().mapRect(mRect); + m_finalRect = m_parentGraph->GetTransform().mapRect(m_rect); } // adjust the collapsed state void GraphNode::SetIsCollapsed(bool collapsed) { - mIsCollapsed = collapsed; + m_isCollapsed = collapsed; UpdateRects(); UpdateTextPixmap(); } @@ -317,49 +222,46 @@ namespace EMStudio UpdateRects(); // check if this rect is visible - mIsVisible = mFinalRect.intersects(visibleRect); + m_isVisible = m_finalRect.intersects(visibleRect); // check if the node is visible and skip some calculations in case its not - mIsHighlighted = false; - mVisualizeHighlighted = false; - //if (mIsVisible) - //{ + m_isHighlighted = false; + m_visualizeHighlighted = false; // check if the mouse is over the node, if yes highlight the node - if (mIsVisible && mRect.contains(mousePos)) + if (m_isVisible && m_rect.contains(mousePos)) { - mIsHighlighted = true; + m_isHighlighted = true; } // set the arrow rect - mArrowRect.setCoords(mRect.left() + 5, mRect.top() + 9, mRect.left() + 17, mRect.top() + 20); + m_arrowRect.setCoords(m_rect.left() + 5, m_rect.top() + 9, m_rect.left() + 17, m_rect.top() + 20); // set the visualize rect - mVisualizeRect.setCoords(mRect.right() - 13, mRect.top() + 6, mRect.right() - 5, mRect.top() + 14); + m_visualizeRect.setCoords(m_rect.right() - 13, m_rect.top() + 6, m_rect.right() - 5, m_rect.top() + 14); // update the input ports and reset the port highlight flags - uint32 i; - const uint32 numInputPorts = mInputPorts.GetLength(); - for (i = 0; i < numInputPorts; ++i) + const AZ::u16 numInputPorts = aznumeric_caster(m_inputPorts.size()); + for (AZ::u16 i = 0; i < numInputPorts; ++i) { - mInputPorts[i].SetRect(CalcInputPortRect(i)); - mInputPorts[i].SetIsHighlighted(false); + m_inputPorts[i].SetRect(CalcInputPortRect(i)); + m_inputPorts[i].SetIsHighlighted(false); } // update the output ports and reset the port highlight flags - const uint32 numOutputPorts = mOutputPorts.GetLength(); - for (i = 0; i < numOutputPorts; ++i) + const AZ::u16 numOutputPorts = aznumeric_caster(m_outputPorts.size()); + for (AZ::u16 i = 0; i < numOutputPorts; ++i) { - mOutputPorts[i].SetRect(CalcOutputPortRect(i)); - mOutputPorts[i].SetIsHighlighted(false); + m_outputPorts[i].SetRect(CalcOutputPortRect(i)); + m_outputPorts[i].SetIsHighlighted(false); } // update the visualize highlight flag, only do this in case: // the mouse position is inside the node and we haven't zoomed too much out - if (mIsHighlighted && mParentGraph->GetScale() > 0.3f) + if (m_isHighlighted && m_parentGraph->GetScale() > 0.3f) { - if (mCanVisualize && GetIsInsideVisualizeRect(mousePos)) + if (m_canVisualize && GetIsInsideVisualizeRect(mousePos)) { - mVisualizeHighlighted = true; + m_visualizeHighlighted = true; } } @@ -367,20 +269,19 @@ namespace EMStudio // 1. the node is NOT collapsed // 2. we haven't zoomed too much out so that the ports aren't visible anymore // 3. the mouse position is inside the adjusted node rect, adjusted because the ports stand bit out of the node - if (mIsCollapsed == false && mParentGraph->GetScale() > 0.5f && mRect.adjusted(-6, 0, 6, 0).contains(mousePos)) + if (m_isCollapsed == false && m_parentGraph->GetScale() > 0.5f && m_rect.adjusted(-6, 0, 6, 0).contains(mousePos)) { // set the set highlight flags for the input ports bool highlightedPortFound = false; - for (i = 0; i < numInputPorts; ++i) + for (NodePort& inputPort : m_inputPorts) { // get the input port and the corresponding rect - NodePort* inputPort = &mInputPorts[i]; - const QRect& portRect = inputPort->GetRect(); + const QRect& portRect = inputPort.GetRect(); // check if the mouse position is inside the port rect and break the loop in this case, as the mouse can be only over one port at the time if (portRect.contains(mousePos)) { - inputPort->SetIsHighlighted(true); + inputPort.SetIsHighlighted(true); highlightedPortFound = true; break; } @@ -390,16 +291,15 @@ namespace EMStudio if (highlightedPortFound == false) { // set the set highlight flags for the output ports - for (i = 0; i < numOutputPorts; ++i) + for (NodePort& outputPort : m_outputPorts) { // get the output port and the corresponding rect - NodePort* outputPort = &mOutputPorts[i]; - const QRect& portRect = outputPort->GetRect(); + const QRect& portRect = outputPort.GetRect(); // check if the mouse position is inside the port rect and break the loop in this case, as the mouse can be only over one port at the time if (portRect.contains(mousePos)) { - outputPort->SetIsHighlighted(true); + outputPort.SetIsHighlighted(true); break; } } @@ -407,8 +307,8 @@ namespace EMStudio } // Update the connections - const uint32 numConnections = GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { GetConnection(c)->Update(visibleRect, mousePos); } @@ -418,7 +318,7 @@ namespace EMStudio void GraphNode::Render(QPainter& painter, QPen* pen, bool renderShadow) { // only render if the given node is visible - if (mIsVisible == false) + if (m_isVisible == false) { return; } @@ -432,8 +332,8 @@ namespace EMStudio RenderShadow(painter); } - float opacityFactor = mOpacity; - if (mIsEnabled == false) + float opacityFactor = m_opacity; + if (m_isEnabled == false) { opacityFactor *= 0.35f; } @@ -454,20 +354,11 @@ namespace EMStudio { borderColor.setRgb(255, 128, 0); - if (mParentGraph->GetScale() > 0.75f) + if (m_parentGraph->GetScale() > 0.75f) { pen->setWidth(2); } } - else - { - /* if (mHasError) - borderColor.setRgb(255,0,0); - else if (mIsProcessed) - borderColor.setRgb(255,0,255); - else - borderColor = mBorderColor;*/ - } // background and header colors QColor bgColor; @@ -477,9 +368,9 @@ namespace EMStudio } else // not selected { - if (mIsEnabled) + if (m_isEnabled) { - bgColor = mBaseColor; + bgColor = m_baseColor; } else { @@ -496,7 +387,7 @@ namespace EMStudio QColor textColor; if (!isSelected) { - if (mIsEnabled) + if (m_isEnabled) { textColor = Qt::white; } @@ -511,30 +402,30 @@ namespace EMStudio } - if (mIsCollapsed == false) + if (m_isCollapsed == false) { // is highlighted/hovered (on-mouse-over effect) - if (mIsHighlighted) + if (m_isHighlighted) { bgColor = bgColor.lighter(120); bgColor2 = bgColor2.lighter(120); } // draw the main rect - QLinearGradient bgGradient(0, mRect.top(), 0, mRect.bottom()); + QLinearGradient bgGradient(0, m_rect.top(), 0, m_rect.bottom()); bgGradient.setColorAt(0.0f, bgColor); bgGradient.setColorAt(1.0f, bgColor2); painter.setBrush(bgGradient); painter.setPen(borderColor); - painter.drawRoundedRect(mRect, BORDER_RADIUS, BORDER_RADIUS); + painter.drawRoundedRect(m_rect, BORDER_RADIUS, BORDER_RADIUS); // if the scale is so small that we can't see those small things anymore - QRect fullHeaderRect(mRect.left(), mRect.top(), mRect.width(), 25); - QRect headerRect(mRect.left(), mRect.top(), mRect.width(), 15); - QRect subHeaderRect(mRect.left(), mRect.top() + 13, mRect.width(), 10); + QRect fullHeaderRect(m_rect.left(), m_rect.top(), m_rect.width(), 25); + QRect headerRect(m_rect.left(), m_rect.top(), m_rect.width(), 15); + QRect subHeaderRect(m_rect.left(), m_rect.top() + 13, m_rect.width(), 10); // if the scale is so small that we can't see those small things anymore - if (mParentGraph->GetScale() < 0.3f) + if (m_parentGraph->GetScale() < 0.3f) { painter.setOpacity(1.0f); painter.setClipping(false); @@ -546,39 +437,28 @@ namespace EMStudio painter.setPen(borderColor); painter.setClipRect(fullHeaderRect, Qt::ReplaceClip); painter.setBrush(headerBgColor); - painter.drawRoundedRect(mRect, BORDER_RADIUS, BORDER_RADIUS); + painter.drawRoundedRect(m_rect, BORDER_RADIUS, BORDER_RADIUS); - // draw header text - // REPLACED BY PIXMAP - /*painter.setBrush( Qt::NoBrush ); - painter.setPen( textColor ); - painter.setFont( mHeaderFont ); - painter.drawText( headerRect, mElidedName, mTextOptionsCenter ); - - painter.setFont( mSubTitleFont ); - painter.setBrush( Qt::NoBrush ); - painter.setPen( textColor ); - painter.drawText( subHeaderRect, mElidedSubTitle, mTextOptionsCenter );*/ painter.setClipping(false); // if the scale is so small that we can't see those small things anymore - if (mParentGraph->GetScale() > 0.5f) + if (m_parentGraph->GetScale() > 0.5f) { QRect textRect; // draw the info text CalcInfoTextRect(textRect); painter.setPen(QColor(255, 128, 0)); - painter.setFont(mInfoTextFont); - painter.drawText(textRect, mElidedNodeInfo, mTextOptionsCenterHV); + painter.setFont(m_infoTextFont); + painter.drawText(textRect, m_elidedNodeInfo, m_textOptionsCenterHv); // draw the input ports QColor portBrushColor, portPenColor; - const uint32 numInputs = mInputPorts.GetLength(); - for (uint32 i = 0; i < numInputs; ++i) + const AZ::u16 numInputs = aznumeric_caster(m_inputPorts.size()); + for (AZ::u16 i = 0; i < numInputs; ++i) { // get the input port and the corresponding rect - NodePort* inputPort = &mInputPorts[i]; + NodePort* inputPort = &m_inputPorts[i]; const QRect& portRect = inputPort->GetRect(); // get and set the pen and brush colors @@ -592,18 +472,18 @@ namespace EMStudio // draw the text CalcInputPortTextRect(i, textRect); painter.setPen(textColor); - painter.setFont(mPortNameFont); - painter.drawText(textRect, inputPort->GetName(), mTextOptionsAlignLeft); + painter.setFont(m_portNameFont); + painter.drawText(textRect, inputPort->GetName(), m_textOptionsAlignLeft); } if (GetHasVisualOutputPorts()) { // draw the output ports - const uint32 numOutputs = mOutputPorts.GetLength(); - for (uint32 i = 0; i < numOutputs; ++i) + const AZ::u16 numOutputs = aznumeric_caster(m_outputPorts.size()); + for (AZ::u16 i = 0; i < numOutputs; ++i) { // get the output port and the corresponding rect - NodePort* outputPort = &mOutputPorts[i]; + NodePort* outputPort = &m_outputPorts[i]; const QRect& portRect = outputPort->GetRect(); // get and set the pen and brush colors @@ -617,8 +497,8 @@ namespace EMStudio // draw the text CalcOutputPortTextRect(i, textRect); painter.setPen(textColor); - painter.setFont(mPortNameFont); - painter.drawText(textRect, outputPort->GetName(), mTextOptionsAlignRight); + painter.setFont(m_portNameFont); + painter.drawText(textRect, outputPort->GetName(), m_textOptionsAlignRight); } } } @@ -626,16 +506,16 @@ namespace EMStudio else { // is highlighted/hovered (on-mouse-over effect) - if (mIsHighlighted) + if (m_isHighlighted) { bgColor = bgColor.lighter(160); headerBgColor = headerBgColor.lighter(160); } // if the scale is so small that we can't see those small things anymore - QRect fullHeaderRect(mRect.left(), mRect.top(), mRect.width(), 25); - QRect headerRect(mRect.left(), mRect.top(), mRect.width(), 15); - QRect subHeaderRect(mRect.left(), mRect.top() + 13, mRect.width(), 10); + QRect fullHeaderRect(m_rect.left(), m_rect.top(), m_rect.width(), 25); + QRect headerRect(m_rect.left(), m_rect.top(), m_rect.width(), 15); + QRect subHeaderRect(m_rect.left(), m_rect.top() + 13, m_rect.width(), 10); // draw the header painter.setPen(borderColor); @@ -643,7 +523,7 @@ namespace EMStudio painter.drawRoundedRect(fullHeaderRect, 7.0, 7.0); // if the scale is so small that we can't see those small things anymore - if (mParentGraph->GetScale() < 0.3f) + if (m_parentGraph->GetScale() < 0.3f) { painter.setOpacity(1.0f); return; @@ -656,15 +536,15 @@ namespace EMStudio QTextOption textOptions; textOptions.setAlignment(Qt::AlignCenter); painter.setPen(textColor); - painter.setFont(mHeaderFont); - painter.drawText(headerRect, mElidedName, textOptions); + painter.setFont(m_headerFont); + painter.drawText(headerRect, m_elidedName, textOptions); - painter.setFont(mSubTitleFont); - painter.drawText(subHeaderRect, mElidedSubTitle, textOptions); + painter.setFont(m_subTitleFont); + painter.drawText(subHeaderRect, m_elidedSubTitle, textOptions); painter.setClipping(false); } - if (mParentGraph->GetScale() > 0.3f) + if (m_parentGraph->GetScale() > 0.3f) { // draw the collapse triangle if (isSelected) @@ -678,31 +558,31 @@ namespace EMStudio painter.setBrush(QColor(175, 175, 175)); } - if (mIsCollapsed == false) + if (m_isCollapsed == false) { QPoint triangle[3]; - triangle[0].setX(mArrowRect.left()); - triangle[0].setY(mArrowRect.top()); - triangle[1].setX(mArrowRect.right()); - triangle[1].setY(mArrowRect.top()); - triangle[2].setX(mArrowRect.center().x()); - triangle[2].setY(mArrowRect.bottom()); + triangle[0].setX(m_arrowRect.left()); + triangle[0].setY(m_arrowRect.top()); + triangle[1].setX(m_arrowRect.right()); + triangle[1].setY(m_arrowRect.top()); + triangle[2].setX(m_arrowRect.center().x()); + triangle[2].setY(m_arrowRect.bottom()); painter.drawPolygon(triangle, 3, Qt::WindingFill); } else { QPoint triangle[3]; - triangle[0].setX(mArrowRect.left()); - triangle[0].setY(mArrowRect.top()); - triangle[1].setX(mArrowRect.right()); - triangle[1].setY(mArrowRect.center().y()); - triangle[2].setX(mArrowRect.left()); - triangle[2].setY(mArrowRect.bottom()); + triangle[0].setX(m_arrowRect.left()); + triangle[0].setY(m_arrowRect.top()); + triangle[1].setX(m_arrowRect.right()); + triangle[1].setY(m_arrowRect.center().y()); + triangle[2].setX(m_arrowRect.left()); + triangle[2].setY(m_arrowRect.bottom()); painter.drawPolygon(triangle, 3, Qt::WindingFill); } // draw the visualize area - if (mCanVisualize) + if (m_canVisualize) { RenderVisualizeRect(painter, bgColor, bgColor2); } @@ -710,12 +590,6 @@ namespace EMStudio // render the marker which indicates that you can go inside this node RenderHasChildsIndicator(painter, pen, borderColor, bgColor2); } - - /* // render the text overlay with the pre-baked node name and port names etc. - const float textOpacity = mParentGraph->GetScale(); - painter.setOpacity( textOpacity ); - painter.drawPixmap( mRect, mTextPixmap ); - painter.setOpacity( 1.0f );*/ } @@ -725,10 +599,10 @@ namespace EMStudio MCORE_UNUSED(pen); // render the marker which indicates that you can go inside this node - if (mCanHaveChildren || mHasVisualGraph) + if (m_canHaveChildren || m_hasVisualGraph) { const int indicatorSize = 13; - QRect childIndicatorRect(aznumeric_cast(mRect.right() - indicatorSize - 2 * BORDER_RADIUS), mRect.top(), aznumeric_cast(indicatorSize + 2 * BORDER_RADIUS + 1), aznumeric_cast(indicatorSize + 2 * BORDER_RADIUS)); + QRect childIndicatorRect(aznumeric_cast(m_rect.right() - indicatorSize - 2 * BORDER_RADIUS), m_rect.top(), aznumeric_cast(indicatorSize + 2 * BORDER_RADIUS + 1), aznumeric_cast(indicatorSize + 2 * BORDER_RADIUS)); // set the border color to the same one as the node border painter.setPen(borderColor); @@ -744,10 +618,10 @@ namespace EMStudio } // construct the clipping polygon - mSubstPoly[0] = QPointF(childIndicatorRect.right() - indicatorSize, childIndicatorRect.top()); // top right - mSubstPoly[1] = QPointF(childIndicatorRect.right() - 5 * indicatorSize, childIndicatorRect.top()); // top left - mSubstPoly[2] = QPointF(childIndicatorRect.right() + 1, childIndicatorRect.top() + 5 * indicatorSize);// bottom down - mSubstPoly[3] = QPointF(childIndicatorRect.right() + 1, childIndicatorRect.top() + indicatorSize);// bottom up + m_substPoly[0] = QPointF(childIndicatorRect.right() - indicatorSize, childIndicatorRect.top()); // top right + m_substPoly[1] = QPointF(childIndicatorRect.right() - 5 * indicatorSize, childIndicatorRect.top()); // top left + m_substPoly[2] = QPointF(childIndicatorRect.right() + 1, childIndicatorRect.top() + 5 * indicatorSize);// bottom down + m_substPoly[3] = QPointF(childIndicatorRect.right() + 1, childIndicatorRect.top() + indicatorSize);// bottom up // matched mini rounded rect on top of the node rect QPainterPath path; @@ -755,7 +629,7 @@ namespace EMStudio // substract the clipping polygon from the mini rounded rect QPainterPath substPath; - substPath.addPolygon(mSubstPoly); + substPath.addPolygon(m_substPoly); QPainterPath finalPath = path.subtracted(substPath); // draw the indicator @@ -781,8 +655,8 @@ namespace EMStudio } else { - *outPenColor = mPortHighlightColor; - *outBrushColor = mPortHighlightBGColor; + *outPenColor = s_portHighlightColo; + *outBrushColor = s_portHighlightBGColor; } } } @@ -791,8 +665,8 @@ namespace EMStudio // render the shadow for this node void GraphNode::RenderShadow(QPainter& painter) { - float opacityFactor = mOpacity; - if (mIsEnabled == false) + float opacityFactor = m_opacity; + if (m_isEnabled == false) { opacityFactor = 0.10f; } @@ -802,9 +676,9 @@ namespace EMStudio painter.setBrush(QColor(0, 0, 0, 70)); // normal - if (mIsCollapsed == false) + if (m_isCollapsed == false) { - QRect shadowRect = mRect; + QRect shadowRect = m_rect; shadowRect.translate(3, 4); // draw the shadow rect @@ -812,7 +686,7 @@ namespace EMStudio } else // collapsed { - QRect shadowRect(mRect.left(), mRect.top(), mRect.width(), 25); + QRect shadowRect(m_rect.left(), m_rect.top(), m_rect.width(), 25); shadowRect.translate(3, 4); // draw the shadow rect @@ -827,14 +701,12 @@ namespace EMStudio const bool alwaysColor = GetAlwaysColor(); // for all connections - const uint32 numConnections = mConnections.GetLength(); - for (uint32 c = 0; c < numConnections; ++c) + for (NodeConnection* nodeConnection : m_connections) { - NodeConnection* nodeConnection = mConnections[c]; if (nodeConnection->GetIsVisible()) { float opacity = 1.0f; - if (!mIsEnabled) + if (!m_isEnabled) { opacity = 0.25f; } @@ -863,7 +735,7 @@ namespace EMStudio { QColor vizBorder; QColor vizBackGround = bgColor2.lighter(110); - if (mVisualize) + if (m_visualize) { vizBorder = Qt::black; } @@ -872,58 +744,57 @@ namespace EMStudio vizBorder = bgColor.darker(180); } - painter.setPen(mVisualizeHighlighted ? QColor(255, 128, 0) : vizBorder); + painter.setPen(m_visualizeHighlighted ? QColor(255, 128, 0) : vizBorder); if (!GetIsSelected()) { - painter.setBrush(mVisualize ? mVisualizeColor : vizBackGround); + painter.setBrush(m_visualize ? m_visualizeColor : vizBackGround); } else { - painter.setBrush(mVisualize ? QColor(255, 128, 0) : bgColor); + painter.setBrush(m_visualize ? QColor(255, 128, 0) : bgColor); } - painter.drawRect(mVisualizeRect); + painter.drawRect(m_visualizeRect); } // test if a point is inside the node bool GraphNode::GetIsInside(const QPoint& globalPoint) const { - return mFinalRect.contains(globalPoint); + return m_finalRect.contains(globalPoint); } // check if we are selected bool GraphNode::GetIsSelected() const { - return mParentGraph->GetAnimGraphModel().GetSelectionModel().isSelected(m_modelIndex); + return m_parentGraph->GetAnimGraphModel().GetSelectionModel().isSelected(m_modelIndex); } // move the node relatively void GraphNode::MoveRelative(const QPoint& deltaMove) { - mRect.translate(deltaMove); + m_rect.translate(deltaMove); } // move absolute void GraphNode::MoveAbsolute(const QPoint& newUpperLeft) { - const int32 width = mRect.width(); - const int32 height = mRect.height(); - mRect = QRect(newUpperLeft.x(), newUpperLeft.y(), width, height); - //MCore::LOG("MoveAbsolute: (%i, %i, %i, %i)", mRect.top(), mRect.left(), mRect.bottom(), mRect.right()); + const int32 width = m_rect.width(); + const int32 height = m_rect.height(); + m_rect = QRect(newUpperLeft.x(), newUpperLeft.y(), width, height); } // calculate the height (including title and bottom) int32 GraphNode::CalcRequiredHeight() const { - if (mIsCollapsed == false) + if (m_isCollapsed == false) { - uint32 numPorts = MCore::Max(mInputPorts.GetLength(), mOutputPorts.GetLength()); - uint32 result = (numPorts * 15) + 34; + int32 numPorts = aznumeric_caster(AZStd::max(m_inputPorts.size(), m_outputPorts.size())); + int32 result = (numPorts * 15) + 34; return MCore::Math::Align(result, 10); } else @@ -934,33 +805,26 @@ namespace EMStudio // calc the max input port width - uint32 GraphNode::CalcMaxInputPortWidth() const + int GraphNode::CalcMaxInputPortWidth() const { // calc the maximum input port width - uint32 maxInputWidth = 0; - uint32 width; - const uint32 numInputPorts = mInputPorts.GetLength(); - for (uint32 i = 0; i < numInputPorts; ++i) + int maxInputWidth = 0; + for (const NodePort& nodePort : m_inputPorts) { - const NodePort* nodePort = &mInputPorts[i]; - width = mPortFontMetrics->horizontalAdvance(nodePort->GetName()); - maxInputWidth = MCore::Max(maxInputWidth, width); + maxInputWidth = AZStd::max(maxInputWidth, m_portFontMetrics->horizontalAdvance(nodePort.GetName())); } return maxInputWidth; } // calculate the max output port width - uint32 GraphNode::CalcMaxOutputPortWidth() const + int GraphNode::CalcMaxOutputPortWidth() const { // calc the maximum output port width - uint32 width; - uint32 maxOutputWidth = 0; - const uint32 numOutputPorts = mOutputPorts.GetLength(); - for (uint32 i = 0; i < numOutputPorts; ++i) + int maxOutputWidth = 0; + for (const NodePort& nodePort : m_outputPorts) { - width = mPortFontMetrics->horizontalAdvance(mOutputPorts[i].GetName()); - maxOutputWidth = MCore::Max(maxOutputWidth, width); + maxOutputWidth = AZStd::max(maxOutputWidth, m_portFontMetrics->horizontalAdvance(nodePort.GetName())); } return maxOutputWidth; @@ -969,41 +833,40 @@ namespace EMStudio // calculate the width int32 GraphNode::CalcRequiredWidth() { - if (mNameAndPortsUpdated) + if (m_nameAndPortsUpdated) { - return mRequiredWidth; + return m_requiredWidth; } // calc the maximum input port width - mMaxInputWidth = CalcMaxInputPortWidth(); - mMaxOutputWidth = CalcMaxOutputPortWidth(); + m_maxInputWidth = CalcMaxInputPortWidth(); + m_maxOutputWidth = CalcMaxOutputPortWidth(); - const uint32 infoWidth = mInfoFontMetrics->horizontalAdvance(mElidedNodeInfo); - const uint32 totalPortWidth = mMaxInputWidth + mMaxOutputWidth + 40 + infoWidth; + const int infoWidth = m_infoFontMetrics->horizontalAdvance(m_elidedNodeInfo); + const int totalPortWidth = m_maxInputWidth + m_maxOutputWidth + 40 + infoWidth; // make sure the node is at least 100 units in width - uint32 headerWidth = mHeaderFontMetrics->horizontalAdvance(mElidedName) + 40; - headerWidth = MCore::Max(headerWidth, 100); + const int headerWidth = AZStd::max(m_headerFontMetrics->horizontalAdvance(m_elidedName) + 40, 100); - mRequiredWidth = MCore::Max(headerWidth, totalPortWidth); - mNameAndPortsUpdated = true; + m_requiredWidth = AZStd::max(headerWidth, totalPortWidth); + m_requiredWidth = MCore::Math::Align(m_requiredWidth, 10); - mRequiredWidth = MCore::Math::Align(mRequiredWidth, 10); + m_nameAndPortsUpdated = true; - return mRequiredWidth; + return m_requiredWidth; } // get the rect for a given input port - QRect GraphNode::CalcInputPortRect(uint32 portNr) + QRect GraphNode::CalcInputPortRect(AZ::u16 portNr) { - return QRect(mRect.left() - 5, mRect.top() + 35 + portNr * 15, 8, 8); + return QRect(m_rect.left() - 5, m_rect.top() + 35 + portNr * 15, 8, 8); } // get the rect for a given output port - QRect GraphNode::CalcOutputPortRect(uint32 portNr) + QRect GraphNode::CalcOutputPortRect(AZ::u16 portNr) { - return QRect(mRect.right() - 5, mRect.top() + 35 + portNr * 15, 8, 8); + return QRect(m_rect.right() - 5, m_rect.top() + 35 + portNr * 15, 8, 8); } @@ -1012,39 +875,39 @@ namespace EMStudio { if (local == false) { - outRect = QRect(mRect.left() + 15 + mMaxInputWidth, mRect.top() + 24, mRect.width() - 20 - mMaxInputWidth - mMaxOutputWidth, 20); + outRect = QRect(m_rect.left() + 15 + m_maxInputWidth, m_rect.top() + 24, m_rect.width() - 20 - m_maxInputWidth - m_maxOutputWidth, 20); } else { - outRect = QRect(15 + mMaxInputWidth, 24, mRect.width() - 20 - mMaxInputWidth - mMaxOutputWidth, 20); + outRect = QRect(15 + m_maxInputWidth, 24, m_rect.width() - 20 - m_maxInputWidth - m_maxOutputWidth, 20); } } // calculate the text rect for the input port - void GraphNode::CalcInputPortTextRect(uint32 portNr, QRect& outRect, bool local) + void GraphNode::CalcInputPortTextRect(AZ::u16 portNr, QRect& outRect, bool local) { if (local == false) { - outRect = QRect(mRect.left() + 10, mRect.top() + 24 + portNr * 15, mRect.width() - 20, 20); + outRect = QRect(m_rect.left() + 10, m_rect.top() + 24 + portNr * 15, m_rect.width() - 20, 20); } else { - outRect = QRect(10, 24 + portNr * 15, mRect.width() - 20, 20); + outRect = QRect(10, 24 + portNr * 15, m_rect.width() - 20, 20); } } // calculate the text rect for the input port - void GraphNode::CalcOutputPortTextRect(uint32 portNr, QRect& outRect, bool local) + void GraphNode::CalcOutputPortTextRect(AZ::u16 portNr, QRect& outRect, bool local) { if (local == false) { - outRect = QRect(mRect.left() + 10, mRect.top() + 24 + portNr * 15, mRect.width() - 20, 20); + outRect = QRect(m_rect.left() + 10, m_rect.top() + 24 + portNr * 15, m_rect.width() - 20, 20); } else { - outRect = QRect(10, 24 + portNr * 15, mRect.width() - 20, 20); + outRect = QRect(10, 24 + portNr * 15, m_rect.width() - 20, 20); } } @@ -1052,76 +915,54 @@ namespace EMStudio // remove all input ports void GraphNode::RemoveAllInputPorts() { - mInputPorts.Clear(false); + m_inputPorts.clear(); } // remove all output ports void GraphNode::RemoveAllOutputPorts() { - mOutputPorts.Clear(false); + m_outputPorts.clear(); } // add a new input port NodePort* GraphNode::AddInputPort(bool updateTextPixMap) { - mInputPorts.AddEmpty(); - mInputPorts.GetLast().SetNode(this); + m_inputPorts.emplace_back(); + m_inputPorts.back().SetNode(this); if (updateTextPixMap) { UpdateTextPixmap(); } - return &mInputPorts.GetLast(); + return &m_inputPorts.back(); } // add a new output port NodePort* GraphNode::AddOutputPort(bool updateTextPixMap) { - mOutputPorts.AddEmpty(); - mOutputPorts.GetLast().SetNode(this); + m_outputPorts.emplace_back(); + m_outputPorts.back().SetNode(this); if (updateTextPixMap) { UpdateTextPixmap(); } - return &mOutputPorts.GetLast(); + return &m_outputPorts.back(); } - /* - // update port text path - void GraphNode::UpdatePortTextPath() - { - mPortTextPath = QPainterPath(); - - QRect textRect; - const uint32 numInputs = mInputPorts.GetLength(); - for (uint32 i=0; iGetName()), mTextOptionsAlignLeft ); - mPortTextPath.addText( textRect.left(), textRect.center().y(), mPortNameFont, QString::fromWCharArray(inputPort->GetName())); - } - } - */ // remove all input ports - NodePort* GraphNode::FindPort(int32 x, int32 y, uint32* outPortNr, bool* outIsInputPort, bool includeInputPorts) + NodePort* GraphNode::FindPort(int32 x, int32 y, AZ::u16* outPortNr, bool* outIsInputPort, bool includeInputPorts) { - uint32 i; - // if the node is not visible at all skip directly - if (mIsVisible == false) + if (m_isVisible == false) { return nullptr; } // if the node is collapsed we can skip directly, too - if (mIsCollapsed) + if (m_isCollapsed) { return nullptr; } @@ -1129,29 +970,29 @@ namespace EMStudio // check the input ports if (includeInputPorts) { - const uint32 numInputPorts = mInputPorts.GetLength(); - for (i = 0; i < numInputPorts; ++i) + const AZ::u16 numInputPorts = aznumeric_caster(m_inputPorts.size()); + for (AZ::u16 i = 0; i < numInputPorts; ++i) { QRect rect = CalcInputPortRect(i); if (rect.contains(QPoint(x, y))) { *outPortNr = i; *outIsInputPort = true; - return &mInputPorts[i]; + return &m_inputPorts[i]; } } } // check the output ports - const uint32 numOutputPorts = mOutputPorts.GetLength(); - for (i = 0; i < numOutputPorts; ++i) + const AZ::u16 numOutputPorts = aznumeric_caster(m_outputPorts.size()); + for (AZ::u16 i = 0; i < numOutputPorts; ++i) { QRect rect = CalcOutputPortRect(i); if (rect.contains(QPoint(x, y))) { *outPortNr = i; *outIsInputPort = false; - return &mOutputPorts[i]; + return &m_outputPorts[i]; } } @@ -1161,56 +1002,58 @@ namespace EMStudio // remove a given connection bool GraphNode::RemoveConnection(const void* connection, bool removeFromMemory) { - const uint32 numConnections = mConnections.GetLength(); - for (uint32 i = 0; i < numConnections; ++i) + const auto foundConnection = AZStd::find_if(begin(m_connections), end(m_connections), [match = connection](const NodeConnection* connection) { - // if this is the connection we're searching for - if (mConnections[i]->GetModelIndex().data(AnimGraphModel::ROLE_POINTER).value() == connection) - { - if (removeFromMemory) - { - delete mConnections[i]; - } - mConnections.Remove(i); - return true; - } + return connection->GetModelIndex().data(AnimGraphModel::ROLE_POINTER).value() == match; + }); + + if (foundConnection == end(m_connections)) + { + return false; } - return false; + + if (removeFromMemory) + { + delete *foundConnection; + } + m_connections.erase(foundConnection); + return true; } // Remove a given connection by model index bool GraphNode::RemoveConnection(const QModelIndex& modelIndex, bool removeFromMemory) { - const uint32 numConnections = mConnections.GetLength(); - for (uint32 i = 0; i < numConnections; ++i) + const auto foundConnection = AZStd::find_if(begin(m_connections), end(m_connections), [match = modelIndex](const NodeConnection* connection) { - // if this is the connection we're searching for - if (mConnections[i]->GetModelIndex() == modelIndex) - { - if (removeFromMemory) - { - delete mConnections[i]; - } - mConnections.Remove(i); - return true; - } + return connection->GetModelIndex() == match; + }); + + if (foundConnection == end(m_connections)) + { + return false; + } + + if (removeFromMemory) + { + delete *foundConnection; } - return false; + m_connections.erase(foundConnection); + return true; } // called when the name of a port got changed void NodePort::OnNameChanged() { - if (mNode == nullptr) + if (m_node == nullptr) { return; } - mNode->UpdateNameAndPorts(); - mNode->UpdateRects(); - mNode->UpdateTextPixmap(); + m_node->UpdateNameAndPorts(); + m_node->UpdateRects(); + m_node->UpdateTextPixmap(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.h index 42c5c7e123..297e6c2cd1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphNode.h @@ -9,7 +9,7 @@ #pragma once #include -#include +#include #include #include #include "../StandardPluginsConfig.h" @@ -43,29 +43,28 @@ namespace EMStudio public: NodePort() - : mIsHighlighted(false) { mNode = nullptr; mNameID = MCORE_INVALIDINDEX32; mColor.setRgb(50, 150, 250); } - ~NodePort() {} - - MCORE_INLINE void SetName(const char* name) { mNameID = MCore::GetStringIdPool().GenerateIdForString(name); OnNameChanged(); } - MCORE_INLINE const char* GetName() const { return MCore::GetStringIdPool().GetName(mNameID).c_str(); } - MCORE_INLINE void SetNameID(uint32 id) { mNameID = id; } - MCORE_INLINE uint32 GetNameID() const { return mNameID; } - MCORE_INLINE void SetRect(const QRect& rect) { mRect = rect; } - MCORE_INLINE const QRect& GetRect() const { return mRect; } - MCORE_INLINE void SetColor(const QColor& color) { mColor = color; } - MCORE_INLINE const QColor& GetColor() const { return mColor; } - MCORE_INLINE void SetNode(GraphNode* node) { mNode = node; } - MCORE_INLINE bool GetIsHighlighted() const { return mIsHighlighted; } - MCORE_INLINE void SetIsHighlighted(bool enabled) { mIsHighlighted = enabled; } + : m_isHighlighted(false) { m_node = nullptr; m_nameId = MCORE_INVALIDINDEX32; m_color.setRgb(50, 150, 250); } + + MCORE_INLINE void SetName(const char* name) { m_nameId = MCore::GetStringIdPool().GenerateIdForString(name); OnNameChanged(); } + MCORE_INLINE const char* GetName() const { return MCore::GetStringIdPool().GetName(m_nameId).c_str(); } + MCORE_INLINE void SetNameID(uint32 id) { m_nameId = id; } + MCORE_INLINE uint32 GetNameID() const { return m_nameId; } + MCORE_INLINE void SetRect(const QRect& rect) { m_rect = rect; } + MCORE_INLINE const QRect& GetRect() const { return m_rect; } + MCORE_INLINE void SetColor(const QColor& color) { m_color = color; } + MCORE_INLINE const QColor& GetColor() const { return m_color; } + MCORE_INLINE void SetNode(GraphNode* node) { m_node = node; } + MCORE_INLINE bool GetIsHighlighted() const { return m_isHighlighted; } + MCORE_INLINE void SetIsHighlighted(bool enabled) { m_isHighlighted = enabled; } void OnNameChanged(); private: - QRect mRect; - QColor mColor; - GraphNode* mNode; - uint32 mNameID; - bool mIsHighlighted; + QRect m_rect; + QColor m_color; + GraphNode* m_node; + uint32 m_nameId; + bool m_isHighlighted; }; @@ -79,64 +78,63 @@ namespace EMStudio TYPE_ID = 0x00000001 }; - GraphNode(const QModelIndex& modelIndex, const char* name, uint32 numInputs = 0, uint32 numOutputs = 0); + GraphNode(const QModelIndex& modelIndex, const char* name, AZ::u16 numInputs = 0, AZ::u16 numOutputs = 0); virtual ~GraphNode(); const QModelIndex& GetModelIndex() const { return m_modelIndex; } - MCORE_INLINE void UpdateNameAndPorts() { mNameAndPortsUpdated = false; } - MCORE_INLINE MCore::Array& GetConnections() { return mConnections; } - MCORE_INLINE uint32 GetNumConnections() { return mConnections.GetLength(); } - MCORE_INLINE NodeConnection* GetConnection(uint32 index) { return mConnections[index]; } - MCORE_INLINE NodeConnection* AddConnection(NodeConnection* con) { mConnections.Add(con); return con; } - MCORE_INLINE void SetParentGraph(NodeGraph* graph) { mParentGraph = graph; } - MCORE_INLINE NodeGraph* GetParentGraph() { return mParentGraph; } - MCORE_INLINE NodePort* GetInputPort(uint32 index) { return &mInputPorts[index]; } - MCORE_INLINE NodePort* GetOutputPort(uint32 index) { return &mOutputPorts[index]; } - MCORE_INLINE const QRect& GetRect() const { return mRect; } - MCORE_INLINE const QRect& GetFinalRect() const { return mFinalRect; } - MCORE_INLINE const QRect& GetVizRect() const { return mVisualizeRect; } - MCORE_INLINE void SetBaseColor(const QColor& color) { mBaseColor = color; } - MCORE_INLINE QColor GetBaseColor() const { return mBaseColor; } - MCORE_INLINE bool GetIsVisible() const { return mIsVisible; } - MCORE_INLINE const char* GetName() const { return mName.c_str(); } - MCORE_INLINE const AZStd::string& GetNameString() const { return mName; } - - MCORE_INLINE bool GetCreateConFromOutputOnly() const { return mConFromOutputOnly; } - MCORE_INLINE void SetCreateConFromOutputOnly(bool enable) { mConFromOutputOnly = enable; } - MCORE_INLINE bool GetIsDeletable() const { return mIsDeletable; } - MCORE_INLINE bool GetIsCollapsed() const { return mIsCollapsed; } + MCORE_INLINE void UpdateNameAndPorts() { m_nameAndPortsUpdated = false; } + MCORE_INLINE AZStd::vector& GetConnections() { return m_connections; } + MCORE_INLINE size_t GetNumConnections() { return m_connections.size(); } + MCORE_INLINE NodeConnection* GetConnection(size_t index) { return m_connections[index]; } + MCORE_INLINE NodeConnection* AddConnection(NodeConnection* con) { m_connections.emplace_back(con); return con; } + MCORE_INLINE void SetParentGraph(NodeGraph* graph) { m_parentGraph = graph; } + MCORE_INLINE NodeGraph* GetParentGraph() { return m_parentGraph; } + MCORE_INLINE NodePort* GetInputPort(AZ::u16 index) { return &m_inputPorts[index]; } + MCORE_INLINE NodePort* GetOutputPort(AZ::u16 index) { return &m_outputPorts[index]; } + MCORE_INLINE const QRect& GetRect() const { return m_rect; } + MCORE_INLINE const QRect& GetFinalRect() const { return m_finalRect; } + MCORE_INLINE const QRect& GetVizRect() const { return m_visualizeRect; } + MCORE_INLINE void SetBaseColor(const QColor& color) { m_baseColor = color; } + MCORE_INLINE QColor GetBaseColor() const { return m_baseColor; } + MCORE_INLINE bool GetIsVisible() const { return m_isVisible; } + MCORE_INLINE const char* GetName() const { return m_name.c_str(); } + MCORE_INLINE const AZStd::string& GetNameString() const { return m_name; } + + MCORE_INLINE bool GetCreateConFromOutputOnly() const { return m_conFromOutputOnly; } + MCORE_INLINE void SetCreateConFromOutputOnly(bool enable) { m_conFromOutputOnly = enable; } + MCORE_INLINE bool GetIsDeletable() const { return m_isDeletable; } + MCORE_INLINE bool GetIsCollapsed() const { return m_isCollapsed; } void SetIsCollapsed(bool collapsed); - MCORE_INLINE void SetDeletable(bool deletable) { mIsDeletable = deletable; } + MCORE_INLINE void SetDeletable(bool deletable) { m_isDeletable = deletable; } void SetSubTitle(const char* subTitle, bool updatePixmap = true); - MCORE_INLINE const char* GetSubTitle() const { return mSubTitle.c_str(); } - //MCORE_INLINE const AZStd::string& GetSubTitleString() const { return mSubTitle; } - MCORE_INLINE bool GetIsInsideArrowRect(const QPoint& point) const { return mArrowRect.contains(point, true); } + MCORE_INLINE const char* GetSubTitle() const { return m_subTitle.c_str(); } + MCORE_INLINE bool GetIsInsideArrowRect(const QPoint& point) const { return m_arrowRect.contains(point, true); } - MCORE_INLINE void SetVisualizeColor(const QColor& color) { mVisualizeColor = color; } - MCORE_INLINE const QColor& GetVisualizeColor() const { return mVisualizeColor; } + MCORE_INLINE void SetVisualizeColor(const QColor& color) { m_visualizeColor = color; } + MCORE_INLINE const QColor& GetVisualizeColor() const { return m_visualizeColor; } - MCORE_INLINE void SetHasChildIndicatorColor(const QColor& color) { mHasChildIndicatorColor = color; } - MCORE_INLINE const QColor& GetHasChildIndicatorColor() const { return mHasChildIndicatorColor; } + MCORE_INLINE void SetHasChildIndicatorColor(const QColor& color) { m_hasChildIndicatorColor = color; } + MCORE_INLINE const QColor& GetHasChildIndicatorColor() const { return m_hasChildIndicatorColor; } - MCORE_INLINE bool GetIsHighlighted() const { return mIsHighlighted; } - MCORE_INLINE bool GetIsVisualizedHighlighted() const { return mVisualizeHighlighted; } - MCORE_INLINE bool GetIsInsideVisualizeRect(const QPoint& point) const { return mVisualizeRect.contains(point, true); } + MCORE_INLINE bool GetIsHighlighted() const { return m_isHighlighted; } + MCORE_INLINE bool GetIsVisualizedHighlighted() const { return m_visualizeHighlighted; } + MCORE_INLINE bool GetIsInsideVisualizeRect(const QPoint& point) const { return m_visualizeRect.contains(point, true); } - MCORE_INLINE void SetIsVisualized(bool enabled) { mVisualize = enabled; } - MCORE_INLINE bool GetIsVisualized() const { return mVisualize; } + MCORE_INLINE void SetIsVisualized(bool enabled) { m_visualize = enabled; } + MCORE_INLINE bool GetIsVisualized() const { return m_visualize; } - MCORE_INLINE void SetIsEnabled(bool enabled) { mIsEnabled = enabled; } - MCORE_INLINE bool GetIsEnabled() const { return mIsEnabled; } + MCORE_INLINE void SetIsEnabled(bool enabled) { m_isEnabled = enabled; } + MCORE_INLINE bool GetIsEnabled() const { return m_isEnabled; } - MCORE_INLINE void SetCanVisualize(bool canViz) { mCanVisualize = canViz; } - MCORE_INLINE bool GetCanVisualize() const { return mCanVisualize; } + MCORE_INLINE void SetCanVisualize(bool canViz) { m_canVisualize = canViz; } + MCORE_INLINE bool GetCanVisualize() const { return m_canVisualize; } - MCORE_INLINE float GetOpacity() const { return mOpacity; } - MCORE_INLINE void SetOpacity(float opacity) { mOpacity = opacity; } + MCORE_INLINE float GetOpacity() const { return m_opacity; } + MCORE_INLINE void SetOpacity(float opacity) { m_opacity = opacity; } - uint32 GetNumInputPorts() const { return mInputPorts.GetLength(); } - uint32 GetNumOutputPorts() const { return mOutputPorts.GetLength(); } + AZ::u16 GetNumInputPorts() const { return aznumeric_caster(m_inputPorts.size()); } + AZ::u16 GetNumOutputPorts() const { return aznumeric_caster(m_outputPorts.size()); } NodePort* AddInputPort(bool updateTextPixMap); NodePort* AddOutputPort(bool updateTextPixMap); @@ -151,8 +149,8 @@ namespace EMStudio virtual int32 CalcRequiredHeight() const; virtual int32 CalcRequiredWidth(); - virtual uint32 CalcMaxInputPortWidth() const; - virtual uint32 CalcMaxOutputPortWidth() const; + virtual int CalcMaxInputPortWidth() const; + virtual int CalcMaxOutputPortWidth() const; bool GetIsInside(const QPoint& globalPoint) const; bool GetIsSelected() const; @@ -174,31 +172,31 @@ namespace EMStudio virtual void RenderHasChildsIndicator(QPainter& painter, QPen* pen, QColor borderColor, QColor bgColor); virtual void RenderVisualizeRect(QPainter& painter, const QColor& bgColor, const QColor& bgColor2); - virtual QRect CalcInputPortRect(uint32 portNr); - virtual QRect CalcOutputPortRect(uint32 portNr); - virtual NodePort* FindPort(int32 x, int32 y, uint32* outPortNr, bool* outIsInputPort, bool includeInputPorts); + virtual QRect CalcInputPortRect(AZ::u16 portNr); + virtual QRect CalcOutputPortRect(AZ::u16 portNr); + virtual NodePort* FindPort(int32 x, int32 y, AZ::u16* outPortNr, bool* outIsInputPort, bool includeInputPorts); virtual bool GetAlwaysColor() const { return true; } virtual bool GetHasError() const { return true; } - MCORE_INLINE bool GetIsProcessed() const { return mIsProcessed; } - MCORE_INLINE void SetIsProcessed(bool processed) { mIsProcessed = processed; } + MCORE_INLINE bool GetIsProcessed() const { return m_isProcessed; } + MCORE_INLINE void SetIsProcessed(bool processed) { m_isProcessed = processed; } - MCORE_INLINE bool GetIsUpdated() const { return mIsUpdated; } - MCORE_INLINE void SetIsUpdated(bool updated) { mIsUpdated = updated; } + MCORE_INLINE bool GetIsUpdated() const { return m_isUpdated; } + MCORE_INLINE void SetIsUpdated(bool updated) { m_isUpdated = updated; } virtual void Sync() {} - void CalcOutputPortTextRect(uint32 portNr, QRect& outRect, bool local = false); - void CalcInputPortTextRect(uint32 portNr, QRect& outRect, bool local = false); + void CalcOutputPortTextRect(AZ::u16 portNr, QRect& outRect, bool local = false); + void CalcInputPortTextRect(AZ::u16 portNr, QRect& outRect, bool local = false); void CalcInfoTextRect(QRect& outRect, bool local = false); - MCORE_INLINE void SetHasVisualOutputPorts(bool hasVisualOutputPorts) { mHasVisualOutputPorts = hasVisualOutputPorts; } - MCORE_INLINE bool GetHasVisualOutputPorts() const { return mHasVisualOutputPorts; } + MCORE_INLINE void SetHasVisualOutputPorts(bool hasVisualOutputPorts) { m_hasVisualOutputPorts = hasVisualOutputPorts; } + MCORE_INLINE bool GetHasVisualOutputPorts() const { return m_hasVisualOutputPorts; } - const QColor& GetBorderColor() const { return mBorderColor; } - void SetBorderColor(const QColor& color) { mBorderColor = color; } - void ResetBorderColor() { mBorderColor = QColor(0, 0, 0); } + const QColor& GetBorderColor() const { return m_borderColor; } + void SetBorderColor(const QColor& color) { m_borderColor = color; } + void ResetBorderColor() { m_borderColor = QColor(0, 0, 0); } virtual void UpdateTextPixmap(); static void RenderText(QPainter& painter, const QString& text, const QColor& textColor, const QFont& font, const QFontMetrics& fontMetrics, Qt::Alignment textAlignment, const QRect& rect); @@ -209,75 +207,74 @@ namespace EMStudio void GetNodePortColors(NodePort* nodePort, const QColor& borderColor, const QColor& headerBgColor, QColor* outBrushColor, QColor* outPenColor); QPersistentModelIndex m_modelIndex; - AZStd::string mName; - QString mElidedName; - - QPainter mTextPainter; - //QPixmap mTextPixmap; - AZStd::string mSubTitle; - QString mElidedSubTitle; - AZStd::string mNodeInfo; - QString mElidedNodeInfo; - QBrush mBrush; - QColor mBaseColor; - QRect mRect; - QRect mFinalRect; - QRect mArrowRect; - QRect mVisualizeRect; - QColor mBorderColor; - QColor mVisualizeColor; - QColor mHasChildIndicatorColor; - MCore::Array mConnections; - float mOpacity; - bool mIsVisible; - static QColor mPortHighlightColor; - static QColor mPortHighlightBGColor; + AZStd::string m_name; + QString m_elidedName; + + QPainter m_textPainter; + AZStd::string m_subTitle; + QString m_elidedSubTitle; + AZStd::string m_nodeInfo; + QString m_elidedNodeInfo; + QBrush m_brush; + QColor m_baseColor; + QRect m_rect; + QRect m_finalRect; + QRect m_arrowRect; + QRect m_visualizeRect; + QColor m_borderColor; + QColor m_visualizeColor; + QColor m_hasChildIndicatorColor; + AZStd::vector m_connections; + float m_opacity; + bool m_isVisible; + static QColor s_portHighlightColo; + static QColor s_portHighlightBGColor; // font stuff - QFont mHeaderFont; - QFont mPortNameFont; - QFont mSubTitleFont; - QFont mInfoTextFont; - QFontMetrics* mPortFontMetrics; - QFontMetrics* mHeaderFontMetrics; - QFontMetrics* mInfoFontMetrics; - QFontMetrics* mSubTitleFontMetrics; - QTextOption mTextOptionsCenter; - QTextOption mTextOptionsAlignLeft; - QTextOption mTextOptionsAlignRight; - QTextOption mTextOptionsCenterHV; - - QStaticText mTitleText; - QStaticText mSubTitleText; - QStaticText mInfoText; - - MCore::Array mInputPortText; - MCore::Array mOutputPortText; - - int32 mRequiredWidth; - bool mNameAndPortsUpdated; - - NodeGraph* mParentGraph; - MCore::Array mInputPorts; - MCore::Array mOutputPorts; - bool mConFromOutputOnly; - bool mIsDeletable; - bool mIsCollapsed; - bool mIsProcessed; - bool mIsUpdated; - bool mVisualize; - bool mCanVisualize; - bool mVisualizeHighlighted; - bool mIsEnabled; - bool mIsHighlighted; - bool mCanHaveChildren; - bool mHasVisualGraph; - bool mHasVisualOutputPorts; - - uint32 mMaxInputWidth; // will be calculated automatically in CalcRequiredWidth() - uint32 mMaxOutputWidth; // will be calculated automatically in CalcRequiredWidth() + QFont m_headerFont; + QFont m_portNameFont; + QFont m_subTitleFont; + QFont m_infoTextFont; + QFontMetrics* m_portFontMetrics; + QFontMetrics* m_headerFontMetrics; + QFontMetrics* m_infoFontMetrics; + QFontMetrics* m_subTitleFontMetrics; + QTextOption m_textOptionsCenter; + QTextOption m_textOptionsAlignLeft; + QTextOption m_textOptionsAlignRight; + QTextOption m_textOptionsCenterHv; + + QStaticText m_titleText; + QStaticText m_subTitleText; + QStaticText m_infoText; + + AZStd::vector m_inputPortText; + AZStd::vector m_outputPortText; + + int32 m_requiredWidth; + bool m_nameAndPortsUpdated; + + NodeGraph* m_parentGraph; + AZStd::vector m_inputPorts; + AZStd::vector m_outputPorts; + bool m_conFromOutputOnly; + bool m_isDeletable; + bool m_isCollapsed; + bool m_isProcessed; + bool m_isUpdated; + bool m_visualize; + bool m_canVisualize; + bool m_visualizeHighlighted; + bool m_isEnabled; + bool m_isHighlighted; + bool m_canHaveChildren; + bool m_hasVisualGraph; + bool m_hasVisualOutputPorts; + + int m_maxInputWidth; // will be calculated automatically in CalcRequiredWidth() + int m_maxOutputWidth; // will be calculated automatically in CalcRequiredWidth() // has child node indicator - QPolygonF mSubstPoly; + QPolygonF m_substPoly; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphWidgetCallback.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphWidgetCallback.h index f57828c646..ff14484dc5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphWidgetCallback.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/GraphWidgetCallback.h @@ -27,13 +27,13 @@ namespace EMStudio public: // constructor and destructor - GraphWidgetCallback(NodeGraphWidget* graphWidget) { mGraphWidget = graphWidget; } + GraphWidgetCallback(NodeGraphWidget* graphWidget) { m_graphWidget = graphWidget; } virtual ~GraphWidgetCallback() {} virtual void DrawOverlay(QPainter& painter) = 0; protected: - NodeGraphWidget* mGraphWidget; + NodeGraphWidget* m_graphWidget; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.cpp index 85c8850ede..c8a36b9f8e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.cpp @@ -17,22 +17,22 @@ namespace EMStudio { // constructor - NodeConnection::NodeConnection(NodeGraph* parentGraph, const QModelIndex& modelIndex, GraphNode* targetNode, uint32 portNr, GraphNode* sourceNode, uint32 sourceOutputPortNr) + NodeConnection::NodeConnection(NodeGraph* parentGraph, const QModelIndex& modelIndex, GraphNode* targetNode, AZ::u16 portNr, GraphNode* sourceNode, AZ::u16 sourceOutputPortNr) : m_modelIndex(modelIndex) , m_parentGraph(parentGraph) { - mSourceNode = sourceNode; - mSourcePortNr = sourceOutputPortNr; - mTargetNode = targetNode; - mPortNr = portNr; - mIsVisible = false; - mIsProcessed = false; - mIsDashed = false; - mIsDisabled = false; - mIsHeadHighlighted = false; - mIsTailHighlighted = false; - mIsSynced = false; - mColor = QColor(128, 255, 128); + m_sourceNode = sourceNode; + m_sourcePortNr = sourceOutputPortNr; + m_targetNode = targetNode; + m_portNr = portNr; + m_isVisible = false; + m_isProcessed = false; + m_isDashed = false; + m_isDisabled = false; + m_isHeadHighlighted = false; + m_isTailHighlighted = false; + m_isSynced = false; + m_color = QColor(128, 255, 128); } @@ -48,15 +48,15 @@ namespace EMStudio MCORE_UNUSED(mousePos); // calculate the rects - mRect = CalcRect(); - mFinalRect = CalcFinalRect(); + m_rect = CalcRect(); + m_finalRect = CalcFinalRect(); // check for visibility - mIsVisible = mFinalRect.intersects(visibleRect); + m_isVisible = m_finalRect.intersects(visibleRect); // reset the is highlighted flags - mIsHighlighted = false; - mIsConnectedHighlighted = false; + m_isHighlighted = false; + m_isConnectedHighlighted = false; } @@ -73,12 +73,12 @@ namespace EMStudio int32 endY = targetRect.center().y() + 1; // draw the connection - mPainterPath = QPainterPath(); + m_painterPath = QPainterPath(); const float width = aznumeric_cast(abs((endX - 3) - (startX + 3))); - mPainterPath.moveTo(startX, startY); - mPainterPath.lineTo(startX + 3, startY); - mPainterPath.cubicTo(startX + (width / 2), startY, endX - (width / 2), endY, endX - 3, endY); - mPainterPath.lineTo(endX, endY); + m_painterPath.moveTo(startX, startY); + m_painterPath.lineTo(startX + 3, startY); + m_painterPath.cubicTo(startX + (width / 2), startY, endX - (width / 2), endY, endX - 3, endY); + m_painterPath.lineTo(endX, endY); } @@ -90,14 +90,14 @@ namespace EMStudio AZ_UNUSED(visibleRect); // used when relinking - if (mIsDashed) + if (m_isDashed) { return; } painter.setOpacity(opacity); - const float scale = mSourceNode->GetParentGraph()->GetScale(); + const float scale = m_sourceNode->GetParentGraph()->GetScale(); QColor penColor; // draw some small horizontal lines that go outside of the connection port @@ -117,11 +117,10 @@ namespace EMStudio else // unselected { // don't make it bold when not selected - if (mIsProcessed == false && alwaysColor == false) + if (m_isProcessed == false && alwaysColor == false) { - if (mSourceNode) + if (m_sourceNode) { - //penColor = mSourceNode->GetOutputPort(mSourcePortNr)->GetColor(); penColor.setRgb(75, 75, 75); } else @@ -133,14 +132,14 @@ namespace EMStudio } else { - if (mSourceNode) + if (m_sourceNode) { if (alwaysColor == false) { pen->setWidthF(1.5f); } - penColor = mSourceNode->GetOutputPort(mSourcePortNr)->GetColor(); + penColor = m_sourceNode->GetOutputPort(m_sourcePortNr)->GetColor(); } else { @@ -152,13 +151,13 @@ namespace EMStudio } // lighten the color in case the transition is highlighted - if (mIsHighlighted) + if (m_isHighlighted) { penColor = penColor.lighter(160); } // lighten the color in case the transition is connected to the currently selected node - if (mIsConnectedHighlighted) + if (m_isConnectedHighlighted) { const float minInput = 0.1f; const float maxInput = 1.0f; @@ -184,9 +183,9 @@ namespace EMStudio } // blinking red error color - if (mSourceNode && mSourceNode->GetHasError() && !GetIsSelected()) + if (m_sourceNode && m_sourceNode->GetHasError() && !GetIsSelected()) { - NodeGraph* parentGraph = mTargetNode->GetParentGraph(); + NodeGraph* parentGraph = m_targetNode->GetParentGraph(); if (parentGraph->GetUseAnimation()) { penColor = parentGraph->GetErrorBlinkColor(); @@ -199,9 +198,9 @@ namespace EMStudio // set the pen pen->setColor(penColor); - if (mIsProcessed) + if (m_isProcessed) { - NodeGraph* parentGraph = mTargetNode->GetParentGraph(); + NodeGraph* parentGraph = m_targetNode->GetParentGraph(); if (parentGraph->GetScale() > 0.5f && parentGraph->GetUseAnimation()) { pen->setStyle(Qt::PenStyle::DashLine); @@ -229,7 +228,7 @@ namespace EMStudio // draw the curve UpdatePainterPath(); - painter.drawPath(mPainterPath); + painter.drawPath(m_painterPath); // restore opacity and width painter.setOpacity(1.0f); @@ -240,11 +239,11 @@ namespace EMStudio // get the source rect QRect NodeConnection::GetSourceRect() const { - if (mSourceNode) + if (m_sourceNode) { - if (mSourceNode->GetIsCollapsed() == false) + if (m_sourceNode->GetIsCollapsed() == false) { - return mSourceNode->GetOutputPort(mSourcePortNr)->GetRect(); + return m_sourceNode->GetOutputPort(m_sourcePortNr)->GetRect(); } else { @@ -262,9 +261,9 @@ namespace EMStudio // get the target rect QRect NodeConnection::GetTargetRect() const { - if (mTargetNode->GetIsCollapsed() == false) + if (m_targetNode->GetIsCollapsed() == false) { - return mTargetNode->GetInputPort(mPortNr)->GetRect(); + return m_targetNode->GetInputPort(m_portNr)->GetRect(); } else { @@ -276,7 +275,7 @@ namespace EMStudio // intersects this connection? bool NodeConnection::Intersects(const QRect& rect) { - if (mRect.intersects(rect) == false) + if (m_rect.intersects(rect) == false) { return false; } @@ -291,7 +290,7 @@ namespace EMStudio //testPath.addRect( rect ); UpdatePainterPath(); - return mPainterPath.intersects(rect); + return m_painterPath.intersects(rect); } @@ -299,12 +298,12 @@ namespace EMStudio bool NodeConnection::CheckIfIsCloseTo(const QPoint& point) { // if we're not visible don't check - if (mIsVisible == false) + if (m_isVisible == false) { return false; } - if (mRect.contains(point) == false) + if (m_rect.contains(point) == false) { return false; } @@ -325,7 +324,7 @@ namespace EMStudio // get the collapsed source rect QRect NodeConnection::CalcCollapsedSourceRect() const { - QRect tempRect = mSourceNode->GetRect(); + QRect tempRect = m_sourceNode->GetRect(); // QPoint a = QPoint(tempRect.right(), tempRect.top() + tempRect.height() / 2); QPoint a = QPoint(tempRect.right(), tempRect.top() + 13); return QRect(a - QPoint(1, 1), a); @@ -335,7 +334,7 @@ namespace EMStudio // get the collapsed target rect QRect NodeConnection::CalcCollapsedTargetRect() const { - QRect tempRect = mTargetNode->GetRect(); + QRect tempRect = m_targetNode->GetRect(); // QPoint a = QPoint(tempRect.left(), tempRect.top() + tempRect.height() / 2); QPoint a = QPoint(tempRect.left(), tempRect.top() + 13); return QRect(a, a + QPoint(1, 1)); @@ -354,14 +353,14 @@ namespace EMStudio // calc the final rect QRect NodeConnection::CalcFinalRect() const { - if (mSourceNode) + if (m_sourceNode) { - return mSourceNode->GetParentGraph()->GetTransform().mapRect(CalcRect()); + return m_sourceNode->GetParentGraph()->GetTransform().mapRect(CalcRect()); } - if (mTargetNode) + if (m_targetNode) { - return mTargetNode->GetParentGraph()->GetTransform().mapRect(CalcRect()); + return m_targetNode->GetParentGraph()->GetTransform().mapRect(CalcRect()); } MCORE_ASSERT(false); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.h index bc7812388d..4fd7d41c97 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeConnection.h @@ -37,7 +37,7 @@ namespace EMStudio TYPE_ID = 0x00000001 }; - NodeConnection(NodeGraph* parentGraph, const QModelIndex& modelIndex, GraphNode* targetNode, uint32 portNr, GraphNode* sourceNode, uint32 sourceOutputPortNr); + NodeConnection(NodeGraph* parentGraph, const QModelIndex& modelIndex, GraphNode* targetNode, AZ::u16 portNr, GraphNode* sourceNode, AZ::u16 sourceOutputPortNr); virtual ~NodeConnection(); const QModelIndex& GetModelIndex() const { return m_modelIndex; } @@ -49,7 +49,7 @@ namespace EMStudio void UpdatePainterPath(); virtual void Update(const QRect& visibleRect, const QPoint& mousePos); - virtual uint32 GetType() { return TYPE_ID; } + virtual uint32 GetType() const { return TYPE_ID; } QRect CalcRect() const; QRect CalcFinalRect() const; @@ -60,71 +60,71 @@ namespace EMStudio bool GetIsSelected() const; - MCORE_INLINE bool GetIsVisible() { return mIsVisible; } + MCORE_INLINE bool GetIsVisible() { return m_isVisible; } - MCORE_INLINE uint32 GetInputPortNr() const { return mPortNr; } - MCORE_INLINE uint32 GetOutputPortNr() const { return mSourcePortNr; } - MCORE_INLINE GraphNode* GetSourceNode() { return mSourceNode; } - MCORE_INLINE GraphNode* GetTargetNode() { return mTargetNode; } + MCORE_INLINE AZ::u16 GetInputPortNr() const { return m_portNr; } + MCORE_INLINE AZ::u16 GetOutputPortNr() const { return m_sourcePortNr; } + MCORE_INLINE GraphNode* GetSourceNode() { return m_sourceNode; } + MCORE_INLINE GraphNode* GetTargetNode() { return m_targetNode; } - MCORE_INLINE bool GetIsSynced() const { return mIsSynced; } - MCORE_INLINE void SetIsSynced(bool synced) { mIsSynced = synced; } + MCORE_INLINE bool GetIsSynced() const { return m_isSynced; } + MCORE_INLINE void SetIsSynced(bool synced) { m_isSynced = synced; } - MCORE_INLINE bool GetIsProcessed() const { return mIsProcessed; } - MCORE_INLINE void SetIsProcessed(bool processed) { mIsProcessed = processed; } + MCORE_INLINE bool GetIsProcessed() const { return m_isProcessed; } + MCORE_INLINE void SetIsProcessed(bool processed) { m_isProcessed = processed; } - MCORE_INLINE bool GetIsDashed() const { return mIsDashed; } - MCORE_INLINE void SetIsDashed(bool flag) { mIsDashed = flag; } + MCORE_INLINE bool GetIsDashed() const { return m_isDashed; } + MCORE_INLINE void SetIsDashed(bool flag) { m_isDashed = flag; } - MCORE_INLINE bool GetIsDisabled() const { return mIsDisabled; } - MCORE_INLINE void SetIsDisabled(bool flag) { mIsDisabled = flag; } + MCORE_INLINE bool GetIsDisabled() const { return m_isDisabled; } + MCORE_INLINE void SetIsDisabled(bool flag) { m_isDisabled = flag; } - MCORE_INLINE bool GetIsHighlighted() const { return mIsHighlighted; } - MCORE_INLINE void SetIsHighlighted(bool flag) { mIsHighlighted = flag; } + MCORE_INLINE bool GetIsHighlighted() const { return m_isHighlighted; } + MCORE_INLINE void SetIsHighlighted(bool flag) { m_isHighlighted = flag; } // when a node is selected, we highlight all incoming/outgoing connections from/to that, this is the flag to indicate that - MCORE_INLINE bool GetIsConnectedHighlighted() const { return mIsConnectedHighlighted; } - MCORE_INLINE void SetIsConnectedHighlighted(bool flag) { mIsConnectedHighlighted = flag; } + MCORE_INLINE bool GetIsConnectedHighlighted() const { return m_isConnectedHighlighted; } + MCORE_INLINE void SetIsConnectedHighlighted(bool flag) { m_isConnectedHighlighted = flag; } - MCORE_INLINE void SetIsTailHighlighted(bool flag) { mIsTailHighlighted = flag; } - MCORE_INLINE void SetIsHeadHighlighted(bool flag) { mIsHeadHighlighted = flag; } - MCORE_INLINE bool GetIsTailHighlighted() const { return mIsTailHighlighted; } - MCORE_INLINE bool GetIsHeadHighlighted() const { return mIsHeadHighlighted; } + MCORE_INLINE void SetIsTailHighlighted(bool flag) { m_isTailHighlighted = flag; } + MCORE_INLINE void SetIsHeadHighlighted(bool flag) { m_isHeadHighlighted = flag; } + MCORE_INLINE bool GetIsTailHighlighted() const { return m_isTailHighlighted; } + MCORE_INLINE bool GetIsHeadHighlighted() const { return m_isHeadHighlighted; } virtual bool CheckIfIsCloseToHead(const QPoint& point) const { MCORE_UNUSED(point); return false; } virtual bool CheckIfIsCloseToTail(const QPoint& point) const { MCORE_UNUSED(point); return false; } virtual void CalcStartAndEndPoints(QPoint& start, QPoint& end) const { MCORE_UNUSED(start); MCORE_UNUSED(end); } virtual bool GetIsWildcardTransition() const { return false; } - MCORE_INLINE void SetColor(const QColor& color) { mColor = color; } - MCORE_INLINE const QColor& GetColor() const { return mColor; } + MCORE_INLINE void SetColor(const QColor& color) { m_color = color; } + MCORE_INLINE const QColor& GetColor() const { return m_color; } - void SetSourceNode(GraphNode* node) { mSourceNode = node; } - void SetTargetNode(GraphNode* node) { mTargetNode = node; } + void SetSourceNode(GraphNode* node) { m_sourceNode = node; } + void SetTargetNode(GraphNode* node) { m_targetNode = node; } - void SetTargetPort(uint32 portIndex) { mPortNr = portIndex; } + void SetTargetPort(AZ::u16 portIndex) { m_portNr = portIndex; } protected: NodeGraph* m_parentGraph = nullptr; QPersistentModelIndex m_modelIndex; - QRect mRect; - QRect mFinalRect; - QColor mColor; - GraphNode* mSourceNode; // source node from which the connection comes - GraphNode* mTargetNode; // the target node - QPainterPath mPainterPath; - uint32 mPortNr; // input port where this is connected to - uint32 mSourcePortNr; // source output port number - bool mIsVisible; // is this connection visible? - bool mIsProcessed; // is this connection processed? - bool mIsDisabled; - bool mIsDashed; - bool mIsHighlighted; - bool mIsHeadHighlighted; - bool mIsTailHighlighted; - bool mIsConnectedHighlighted; - bool mIsSynced; + QRect m_rect; + QRect m_finalRect; + QColor m_color; + GraphNode* m_sourceNode; // source node from which the connection comes + GraphNode* m_targetNode; // the target node + QPainterPath m_painterPath; + AZ::u16 m_portNr; // input port where this is connected to + AZ::u16 m_sourcePortNr; // source output port number + bool m_isVisible; // is this connection visible? + bool m_isProcessed; // is this connection processed? + bool m_isDisabled; + bool m_isDashed; + bool m_isHighlighted; + bool m_isHeadHighlighted; + bool m_isTailHighlighted; + bool m_isConnectedHighlighted; + bool m_isSynced; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.cpp index 761baaffcf..596f3d7e30 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.cpp @@ -6,6 +6,7 @@ * */ +#include "AzCore/std/numeric.h" #include #include #include @@ -41,55 +42,55 @@ namespace EMStudio parent = parent.parent(); } - mErrorBlinkOffset = 0.0f; - mUseAnimation = true; - mDashOffset = 0.0f; - mScale = 1.0f; - mScrollOffset = QPoint(0, 0); - mScalePivot = QPoint(0, 0); - mMinStepSize = 1; - mMaxStepSize = 75; - mEntryNode = nullptr; + m_errorBlinkOffset = 0.0f; + m_useAnimation = true; + m_dashOffset = 0.0f; + m_scale = 1.0f; + m_scrollOffset = QPoint(0, 0); + m_scalePivot = QPoint(0, 0); + m_minStepSize = 1; + m_maxStepSize = 75; + m_entryNode = nullptr; // init connection creation - mConStartOffset = QPoint(0, 0); - mConEndOffset = QPoint(0, 0); - mConPortNr = MCORE_INVALIDINDEX32; - mConIsInputPort = true; - mConNode = nullptr; // nullptr when no connection is being created - mConPort = nullptr; - mConIsValid = false; - mTargetPort = nullptr; - mRelinkConnection = nullptr; - mReplaceTransitionHead = nullptr; - mReplaceTransitionTail = nullptr; - mReplaceTransitionSourceNode = nullptr; - mReplaceTransitionTargetNode = nullptr; - mReplaceTransitionStartOffset = QPoint(0, 0); - mReplaceTransitionEndOffset = QPoint(0, 0); + m_conStartOffset = QPoint(0, 0); + m_conEndOffset = QPoint(0, 0); + m_conPortNr = InvalidIndex16; + m_conIsInputPort = true; + m_conNode = nullptr; // nullptr when no connection is being created + m_conPort = nullptr; + m_conIsValid = false; + m_targetPort = nullptr; + m_relinkConnection = nullptr; + m_replaceTransitionHead = nullptr; + m_replaceTransitionTail = nullptr; + m_replaceTransitionSourceNode = nullptr; + m_replaceTransitionTargetNode = nullptr; + m_replaceTransitionStartOffset = QPoint(0, 0); + m_replaceTransitionEndOffset = QPoint(0, 0); // setup scroll interpolator - mStartScrollOffset = QPointF(0.0f, 0.0f); - mTargetScrollOffset = QPointF(0.0f, 0.0f); - mScrollTimer.setSingleShot(false); - connect(&mScrollTimer, &QTimer::timeout, this, &NodeGraph::UpdateAnimatedScrollOffset); + m_startScrollOffset = QPointF(0.0f, 0.0f); + m_targetScrollOffset = QPointF(0.0f, 0.0f); + m_scrollTimer.setSingleShot(false); + connect(&m_scrollTimer, &QTimer::timeout, this, &NodeGraph::UpdateAnimatedScrollOffset); // setup scale interpolator - mStartScale = 1.0f; - mTargetScale = 1.0f; - mScaleTimer.setSingleShot(false); - connect(&mScaleTimer, &QTimer::timeout, this, &NodeGraph::UpdateAnimatedScale); + m_startScale = 1.0f; + m_targetScale = 1.0f; + m_scaleTimer.setSingleShot(false); + connect(&m_scaleTimer, &QTimer::timeout, this, &NodeGraph::UpdateAnimatedScale); - mReplaceTransitionValid = false; + m_replaceTransitionValid = false; // Overlay - mFont.setPixelSize(12); - mTextOptions.setAlignment(Qt::AlignCenter); - mFontMetrics = new QFontMetrics(mFont); + m_font.setPixelSize(12); + m_textOptions.setAlignment(Qt::AlignCenter); + m_fontMetrics = new QFontMetrics(m_font); // Group nodes m_groupFont.setPixelSize(18); - m_groupFontMetrics = new QFontMetrics(mFont); + m_groupFontMetrics = new QFontMetrics(m_font); } @@ -98,7 +99,7 @@ namespace EMStudio { m_graphNodeByModelIndex.clear(); - delete mFontMetrics; + delete m_fontMetrics; } AZStd::vector NodeGraph::GetSelectedGraphNodes() const @@ -137,8 +138,8 @@ namespace EMStudio GraphNode* graphNode = indexAndGraphNode.second.get(); // get the number of connections and iterate through them - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = graphNode->GetConnection(c); if (connection->GetIsSelected()) @@ -212,7 +213,7 @@ namespace EMStudio const QColor textColor = graphNode->GetIsHighlighted() ? QColor(0, 255, 0) : QColor(255, 255, 0); painter.setPen(textColor); - painter.setFont(mFont); + painter.setFont(m_font); QPoint textPosition = textRect.topLeft(); textPosition.setX(textPosition.x() + 3); @@ -221,32 +222,32 @@ namespace EMStudio // add the playspeed if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYSPEED)) { - mQtTempString.asprintf("Play Speed = %.2f", emfxNode->GetPlaySpeed(animGraphInstance)); - painter.drawText(textPosition, mQtTempString); + m_qtTempString.asprintf("Play Speed = %.2f", emfxNode->GetPlaySpeed(animGraphInstance)); + painter.drawText(textPosition, m_qtTempString); textPosition.setY(textPosition.y() + heightSpacing); } // add the global weight if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_GLOBALWEIGHT)) { - mQtTempString.asprintf("Global Weight = %.2f", uniqueData->GetGlobalWeight()); - painter.drawText(textPosition, mQtTempString); + m_qtTempString.asprintf("Global Weight = %.2f", uniqueData->GetGlobalWeight()); + painter.drawText(textPosition, m_qtTempString); textPosition.setY(textPosition.y() + heightSpacing); } // add the sync if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_SYNCSTATUS)) { - mQtTempString.asprintf("Synced = %s", animGraphInstance->GetIsSynced(emfxNode->GetObjectIndex()) ? "Yes" : "No"); - painter.drawText(textPosition, mQtTempString); + m_qtTempString.asprintf("Synced = %s", animGraphInstance->GetIsSynced(emfxNode->GetObjectIndex()) ? "Yes" : "No"); + painter.drawText(textPosition, m_qtTempString); textPosition.setY(textPosition.y() + heightSpacing); } // add the play position if (plugin->GetIsDisplayFlagEnabled(AnimGraphPlugin::DISPLAYFLAG_PLAYPOSITION)) { - mQtTempString.asprintf("Play Time = %.3f / %.3f", uniqueData->GetCurrentPlayTime(), uniqueData->GetDuration()); - painter.drawText(textPosition, mQtTempString); + m_qtTempString.asprintf("Play Time = %.3f / %.3f", uniqueData->GetCurrentPlayTime(), uniqueData->GetDuration()); + painter.drawText(textPosition, m_qtTempString); textPosition.setY(textPosition.y() + heightSpacing); } } @@ -271,8 +272,8 @@ namespace EMStudio EMotionFX::AnimGraphNode* emfxTargetNode = indexAndGraphNode.first.data(AnimGraphModel::ROLE_NODE_POINTER).value(); // iterate through all connections connected to this node - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* visualConnection = graphNode->GetConnection(c); @@ -286,8 +287,8 @@ namespace EMStudio continue; } - const uint32 inputPortNr = visualConnection->GetInputPortNr(); - const uint32 outputPortNr = visualConnection->GetOutputPortNr(); + const AZ::u16 inputPortNr = visualConnection->GetInputPortNr(); + const AZ::u16 outputPortNr = visualConnection->GetOutputPortNr(); MCore::Attribute* attribute = emfxSourceNode->GetOutputValue(animGraphInstance, outputPortNr); // fill the string with data @@ -410,7 +411,7 @@ namespace EMStudio QPoint connectionAttachPoint = visualConnection->CalcFinalRect().center(); const int halfTextHeight = 6; - const int textWidth = mFontMetrics->horizontalAdvance(m_tempStringA.c_str()); + const int textWidth = m_fontMetrics->horizontalAdvance(m_tempStringA.c_str()); const int halfTextWidth = textWidth / 2; const QRect textRect(connectionAttachPoint.x() - halfTextWidth - 1, connectionAttachPoint.y() - halfTextHeight, textWidth + 4, halfTextHeight * 2); @@ -428,11 +429,8 @@ namespace EMStudio // draw the text const QColor& color = visualConnection->GetTargetNode()->GetInputPort(visualConnection->GetInputPortNr())->GetColor(); painter.setPen(color); - painter.setFont(mFont); - // OLD: - //painter.drawText( textPosition, mTempString.c_str() ); - // NEW: - GraphNode::RenderText(painter, m_tempStringA.c_str(), color, mFont, *mFontMetrics, Qt::AlignCenter, textRect); + painter.setFont(m_font); + GraphNode::RenderText(painter, m_tempStringA.c_str(), color, m_font, *m_fontMetrics, Qt::AlignCenter, textRect); } } } @@ -606,8 +604,8 @@ namespace EMStudio GraphNode* graphNode = indexAndGraphNode.second.get(); // iterate over all connections - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = graphNode->GetConnection(c); if (connection->CheckIfIsCloseTo(mousePos)) @@ -632,8 +630,8 @@ namespace EMStudio GraphNode* graphNode = indexAndGraphNode.second.get(); // iterate over all connections - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = graphNode->GetConnection(c); GraphNode* sourceNode = connection->GetSourceNode(); @@ -655,12 +653,12 @@ namespace EMStudio connection->SetIsTailHighlighted(false); } - if (mReplaceTransitionHead == connection) + if (m_replaceTransitionHead == connection) { connection->SetIsHeadHighlighted(true); } - if (mReplaceTransitionTail == connection) + if (m_replaceTransitionTail == connection) { connection->SetIsTailHighlighted(true); } @@ -692,8 +690,8 @@ namespace EMStudio void NodeGraph::Render(const QItemSelectionModel& selectionModel, QPainter& painter, int32 width, int32 height, const QPoint& mousePos, float timePassedInSeconds) { // control the scroll speed of the dashed blend tree connections etc - mDashOffset -= 7.5f * timePassedInSeconds; - mErrorBlinkOffset += 5.0f * timePassedInSeconds; + m_dashOffset -= 7.5f * timePassedInSeconds; + m_errorBlinkOffset += 5.0f * timePassedInSeconds; #ifdef GRAPH_PERFORMANCE_FRAMEDURATION MCore::Timer timer; @@ -705,11 +703,11 @@ namespace EMStudio //visibleRect.adjust(50, 50, -50, -50); // setup the transform - mTransform.reset(); - mTransform.translate(mScalePivot.x(), mScalePivot.y()); - mTransform.scale(mScale, mScale); - mTransform.translate(-mScalePivot.x() + mScrollOffset.x(), -mScalePivot.y() + mScrollOffset.y()); - painter.setTransform(mTransform); + m_transform.reset(); + m_transform.translate(m_scalePivot.x(), m_scalePivot.y()); + m_transform.scale(m_scale, m_scale); + m_transform.translate(-m_scalePivot.x() + m_scrollOffset.x(), -m_scalePivot.y() + m_scrollOffset.y()); + painter.setTransform(m_transform); // render the background #ifdef GRAPH_PERFORMANCE_INFO @@ -743,10 +741,10 @@ namespace EMStudio // calculate the connection stepsize // the higher the value, the less lines it renders (so faster) - int32 stepSize = aznumeric_cast(((1.0f / (mScale * (mScale * 1.75f))) * 10) - 7); - stepSize = MCore::Clamp(stepSize, mMinStepSize, mMaxStepSize); + int32 stepSize = aznumeric_cast(((1.0f / (m_scale * (m_scale * 1.75f))) * 10) - 7); + stepSize = MCore::Clamp(stepSize, m_minStepSize, m_maxStepSize); - QRect scaledVisibleRect = mTransform.inverted().mapRect(visibleRect); + QRect scaledVisibleRect = m_transform.inverted().mapRect(visibleRect); bool renderShadow = false; if (GetScale() >= 0.3f) @@ -790,35 +788,13 @@ namespace EMStudio StateConnection::RenderInterruptedTransitions(painter, GetAnimGraphModel(), *this); // render the entry state arrow - RenderEntryPoint(painter, mEntryNode); + RenderEntryPoint(painter, m_entryNode); #ifdef GRAPH_PERFORMANCE_FRAMEDURATION MCore::LogInfo("GraphRenderingTime: %.2f ms.", timer.GetTime() * 1000); #endif RenderTitlebar(painter, width); - - // render FPS counter - //#ifdef GRAPH_PERFORMANCE_FRAMEDURATION - /* static MCore::AnsiString tempFPSString; - static MCore::Timer fpsTimer; - static double fpsTimeElapsed = 0.0; - static uint32 fpsNumFrames = 0; - static uint32 lastFPS = 0; - fpsTimeElapsed += fpsTimer.GetTimeDelta(); - fpsNumFrames++; - if (fpsTimeElapsed > 1.0f) - { - lastFPS = fpsNumFrames; - fpsTimeElapsed = 0.0; - fpsNumFrames = 0; - } - tempFPSString.Format( "%i FPS", lastFPS ); - painter.setPen( QColor(255, 255, 255) ); - painter.resetTransform(); - painter.drawText( 5, 20, tempFPSString.c_str() ); - */ - //#endif } void NodeGraph::RenderTitlebar(QPainter& painter, const QString& text, int32 width) @@ -836,7 +812,7 @@ namespace EMStudio painter.setOpacity(1.0f); painter.setPen(QColor(233, 233, 233)); - painter.setFont(mFont); + painter.setFont(m_font); painter.drawText(titleRect, text, QTextOption(Qt::AlignCenter)); painter.restore(); @@ -898,8 +874,8 @@ namespace EMStudio AnimGraphModel::AddToItemSelection(newSelection, modelIndex, nodePreviouslySelected, nodeNewlySelected, toggleMode, overwriteCurSelection); - const uint32 numConnections = node->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = node->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = node->GetConnection(c); const bool connectionPreviouslySelected = std::find(oldSelectionModelIndices.begin(), oldSelectionModelIndices.end(), connection->GetModelIndex()) != oldSelectionModelIndices.end(); @@ -970,8 +946,8 @@ namespace EMStudio { GraphNode* node = indexAndGraphNode.second.get(); - const uint32 numConnections = node->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = node->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = node->GetConnection(c); const bool isNewlySelected = connection->CheckIfIsCloseTo(point); @@ -990,8 +966,8 @@ namespace EMStudio painter.setPen(QColor(40, 40, 40)); // calculate the coordinates in 'zoomed out and scrolled' coordinates, of the window rect - QPoint upperLeft = mTransform.inverted().map(QPoint(0, 0)); - QPoint lowerRight = mTransform.inverted().map(QPoint(width, height)); + QPoint upperLeft = m_transform.inverted().map(QPoint(0, 0)); + QPoint lowerRight = m_transform.inverted().map(QPoint(width, height)); // calculate the start and end ranges in 'scrolled and zoomed out' coordinates // we need to render sub-grids covering that area @@ -1007,7 +983,7 @@ namespace EMStudio */ // calculate the alpha - float scale = mScale * mScale * 1.5f; + float scale = m_scale * m_scale * 1.5f; scale = MCore::Clamp(scale, 0.0f, 1.0f); const int32 alpha = aznumeric_cast(MCore::CalcCosineInterpolationWeight(scale) * 255); @@ -1016,16 +992,14 @@ namespace EMStudio return; } - // mGridPen.setColor( QColor(58, 58, 58, alpha) ); - // mGridPen.setColor( QColor(46, 46, 46, alpha) ); - mGridPen.setColor(QColor(61, 61, 61, alpha)); - mSubgridPen.setColor(QColor(55, 55, 55, alpha)); + m_gridPen.setColor(QColor(61, 61, 61, alpha)); + m_subgridPen.setColor(QColor(55, 55, 55, alpha)); // setup spacing and size of the grid const int32 spacing = 10; // grid cell size of 20 // draw subgridlines first - painter.setPen(mSubgridPen); + painter.setPen(m_subgridPen); // draw vertical lines for (int32 x = startX; x < endX; x += spacing) @@ -1046,7 +1020,7 @@ namespace EMStudio } // draw render grid lines - painter.setPen(mGridPen); + painter.setPen(m_gridPen); // draw vertical lines for (int32 x = startX; x < endX; x += spacing) @@ -1217,20 +1191,12 @@ namespace EMStudio // calc the number of selected nodes - uint32 NodeGraph::CalcNumSelectedNodes() const + size_t NodeGraph::CalcNumSelectedNodes() const { - uint32 result = 0; - - for (const GraphNodeByModelIndex::value_type& indexAndGraphNode : m_graphNodeByModelIndex) + return AZStd::accumulate(begin(m_graphNodeByModelIndex), end(m_graphNodeByModelIndex), size_t{0}, [](size_t total, const auto& indexAndGraphNode) { - GraphNode* node = indexAndGraphNode.second.get(); - if (node->GetIsSelected()) - { - result++; - } - } - - return result; + return total + indexAndGraphNode.second->GetIsSelected(); + }); } @@ -1254,8 +1220,8 @@ namespace EMStudio if (includeConnections) { // for all connections - const uint32 numConnections = node->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = node->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { if (node->GetConnection(c)->GetIsSelected()) { @@ -1283,8 +1249,8 @@ namespace EMStudio result |= graphNode->GetRect(); // for all connections - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { result |= graphNode->GetConnection(c)->CalcRect(); } @@ -1321,8 +1287,8 @@ namespace EMStudio } else { - mScrollOffset = offset; - mScale = 1.0f; + m_scrollOffset = offset; + m_scale = 1.0f; } } else @@ -1338,7 +1304,7 @@ namespace EMStudio } else { - mScrollOffset = offset; + m_scrollOffset = offset; } // set the zoom factor so it exactly fits @@ -1362,7 +1328,7 @@ namespace EMStudio if (animate == false) { - mScale = MCore::Min(widthZoom, heightZoom); + m_scale = MCore::Min(widthZoom, heightZoom); } else { @@ -1375,10 +1341,10 @@ namespace EMStudio // start an animated scroll to the given scroll offset void NodeGraph::ScrollTo(const QPointF& point) { - mStartScrollOffset = mScrollOffset; - mTargetScrollOffset = point; - mScrollTimer.start(1000 / 60); - mScrollPreciseTimer.Stamp(); + m_startScrollOffset = m_scrollOffset; + m_targetScrollOffset = point; + m_scrollTimer.start(1000 / 60); + m_scrollPreciseTimer.Stamp(); } @@ -1387,16 +1353,15 @@ namespace EMStudio { const float duration = 0.75f; // duration in seconds - float timePassed = mScrollPreciseTimer.GetDeltaTimeInSeconds(); + float timePassed = m_scrollPreciseTimer.GetDeltaTimeInSeconds(); if (timePassed > duration) { timePassed = duration; - mScrollTimer.stop(); + m_scrollTimer.stop(); } const float t = timePassed / duration; - mScrollOffset = MCore::CosineInterpolate(mStartScrollOffset, mTargetScrollOffset, t).toPoint(); - //mGraphWidget->update(); + m_scrollOffset = MCore::CosineInterpolate(m_startScrollOffset, m_targetScrollOffset, t).toPoint(); } @@ -1405,16 +1370,15 @@ namespace EMStudio { const float duration = 0.75f; // duration in seconds - float timePassed = mScalePreciseTimer.GetDeltaTimeInSeconds(); + float timePassed = m_scalePreciseTimer.GetDeltaTimeInSeconds(); if (timePassed > duration) { timePassed = duration; - mScaleTimer.stop(); + m_scaleTimer.stop(); } const float t = timePassed / duration; - mScale = MCore::CosineInterpolate(mStartScale, mTargetScale, t); - //mGraphWidget->update(); + m_scale = MCore::CosineInterpolate(m_startScale, m_targetScale, t); } //static float scaleExp = 1.0f; @@ -1429,7 +1393,7 @@ namespace EMStudio //float t = -6 + (6 * scaleExp); //float newScale = 1/(1+exp(-t)) * 2; - float newScale = mScale + 0.35f; + float newScale = m_scale + 0.35f; newScale = MCore::Clamp(newScale, sLowestScale, 1.0f); ZoomTo(newScale); } @@ -1439,7 +1403,7 @@ namespace EMStudio // zoom out void NodeGraph::ZoomOut() { - float newScale = mScale - 0.35f; + float newScale = m_scale - 0.35f; //scaleExp -= 0.2f; //if (scaleExp < 0.01f) //scaleExp = 0.01f; @@ -1455,10 +1419,10 @@ namespace EMStudio // zoom to a given amount void NodeGraph::ZoomTo(float scale) { - mStartScale = mScale; - mTargetScale = scale; - mScaleTimer.start(1000 / 60); - mScalePreciseTimer.Stamp(); + m_startScale = m_scale; + m_targetScale = scale; + m_scaleTimer.start(1000 / 60); + m_scalePreciseTimer.Stamp(); if (scale < sLowestScale) { sLowestScale = scale; @@ -1469,14 +1433,14 @@ namespace EMStudio // stop an animated zoom void NodeGraph::StopAnimatedZoom() { - mScaleTimer.stop(); + m_scaleTimer.stop(); } // stop an animated scroll void NodeGraph::StopAnimatedScroll() { - mScrollTimer.stop(); + m_scrollTimer.stop(); } @@ -1491,7 +1455,7 @@ namespace EMStudio if (sceneRect.isEmpty() == false) { - const int border = aznumeric_cast(10.0f * (1.0f / mScale)); + const int border = aznumeric_cast(10.0f * (1.0f / m_scale)); sceneRect.adjust(-border, -border, border, border); ZoomOnRect(sceneRect, width, height, animate); } @@ -1499,7 +1463,7 @@ namespace EMStudio // find the port at a given location - NodePort* NodeGraph::FindPort(int32 x, int32 y, GraphNode** outNode, uint32* outPortNr, bool* outIsInputPort, bool includeInputPorts) + NodePort* NodeGraph::FindPort(int32 x, int32 y, GraphNode** outNode, AZ::u16* outPortNr, bool* outIsInputPort, bool includeInputPorts) { // get the number of nodes in the graph and iterate through them for (const GraphNodeByModelIndex::value_type& indexAndGraphNode : m_graphNodeByModelIndex) @@ -1527,22 +1491,22 @@ namespace EMStudio // start creating a connection - void NodeGraph::StartCreateConnection(uint32 portNr, bool isInputPort, GraphNode* portNode, NodePort* port, const QPoint& startOffset) + void NodeGraph::StartCreateConnection(AZ::u16 portNr, bool isInputPort, GraphNode* portNode, NodePort* port, const QPoint& startOffset) { - mConPortNr = portNr; - mConIsInputPort = isInputPort; - mConNode = portNode; - mConPort = port; - mConStartOffset = startOffset; + m_conPortNr = portNr; + m_conIsInputPort = isInputPort; + m_conNode = portNode; + m_conPort = port; + m_conStartOffset = startOffset; } // start relinking a connection - void NodeGraph::StartRelinkConnection(NodeConnection* connection, uint32 portNr, GraphNode* node) + void NodeGraph::StartRelinkConnection(NodeConnection* connection, AZ::u16 portNr, GraphNode* node) { - mConPortNr = portNr; - mConNode = node; - mRelinkConnection = connection; + m_conPortNr = portNr; + m_conNode = node; + m_relinkConnection = connection; //MCore::LogInfo( "StartRelinkConnection: Connection=(%s->%s) portNr=%i, graphNode=%s", connection->GetSourceNode()->GetName(), connection->GetTargetNode()->GetName(), portNr, node->GetName() ); } @@ -1550,53 +1514,53 @@ namespace EMStudio void NodeGraph::StartReplaceTransitionHead(NodeConnection* connection, QPoint startOffset, QPoint endOffset, GraphNode* sourceNode, GraphNode* targetNode) { - mReplaceTransitionHead = connection; + m_replaceTransitionHead = connection; - mReplaceTransitionStartOffset = startOffset; - mReplaceTransitionEndOffset = endOffset; - mReplaceTransitionSourceNode = sourceNode; - mReplaceTransitionTargetNode = targetNode; + m_replaceTransitionStartOffset = startOffset; + m_replaceTransitionEndOffset = endOffset; + m_replaceTransitionSourceNode = sourceNode; + m_replaceTransitionTargetNode = targetNode; } void NodeGraph::StartReplaceTransitionTail(NodeConnection* connection, QPoint startOffset, QPoint endOffset, GraphNode* sourceNode, GraphNode* targetNode) { - mReplaceTransitionTail = connection; + m_replaceTransitionTail = connection; - mReplaceTransitionStartOffset = startOffset; - mReplaceTransitionEndOffset = endOffset; - mReplaceTransitionSourceNode = sourceNode; - mReplaceTransitionTargetNode = targetNode; + m_replaceTransitionStartOffset = startOffset; + m_replaceTransitionEndOffset = endOffset; + m_replaceTransitionSourceNode = sourceNode; + m_replaceTransitionTargetNode = targetNode; } void NodeGraph::GetReplaceTransitionInfo(NodeConnection** outOldConnection, QPoint* outOldStartOffset, QPoint* outOldEndOffset, GraphNode** outOldSourceNode, GraphNode** outOldTargetNode) { - if (mReplaceTransitionHead) + if (m_replaceTransitionHead) { - *outOldConnection = mReplaceTransitionHead; + *outOldConnection = m_replaceTransitionHead; } - if (mReplaceTransitionTail) + if (m_replaceTransitionTail) { - *outOldConnection = mReplaceTransitionTail; + *outOldConnection = m_replaceTransitionTail; } - *outOldStartOffset = mReplaceTransitionStartOffset; - *outOldEndOffset = mReplaceTransitionEndOffset; - *outOldSourceNode = mReplaceTransitionSourceNode; - *outOldTargetNode = mReplaceTransitionTargetNode; + *outOldStartOffset = m_replaceTransitionStartOffset; + *outOldEndOffset = m_replaceTransitionEndOffset; + *outOldSourceNode = m_replaceTransitionSourceNode; + *outOldTargetNode = m_replaceTransitionTargetNode; } void NodeGraph::StopReplaceTransitionHead() { - mReplaceTransitionHead = nullptr; + m_replaceTransitionHead = nullptr; } void NodeGraph::StopReplaceTransitionTail() { - mReplaceTransitionTail = nullptr; + m_replaceTransitionTail = nullptr; } @@ -1604,11 +1568,11 @@ namespace EMStudio // reset members void NodeGraph::StopRelinkConnection() { - mConPortNr = MCORE_INVALIDINDEX32; - mConNode = nullptr; - mRelinkConnection = nullptr; - mConIsValid = false; - mTargetPort = nullptr; + m_conPortNr = InvalidIndex16; + m_conNode = nullptr; + m_relinkConnection = nullptr; + m_conIsValid = false; + m_targetPort = nullptr; } @@ -1616,12 +1580,12 @@ namespace EMStudio // reset members void NodeGraph::StopCreateConnection() { - mConPortNr = MCORE_INVALIDINDEX32; - mConIsInputPort = true; - mConNode = nullptr; // nullptr when no connection is being created - mConPort = nullptr; - mTargetPort = nullptr; - mConIsValid = false; + m_conPortNr = InvalidIndex16; + m_conIsInputPort = true; + m_conNode = nullptr; // nullptr when no connection is being created + m_conPort = nullptr; + m_targetPort = nullptr; + m_conIsValid = false; } @@ -1640,8 +1604,8 @@ namespace EMStudio GraphNode* graphNode = indexAndGraphNode.second.get(); // get the number of connections and iterate through them - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 j = 0; j < numConnections; ++j) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t j = 0; j < numConnections; ++j) { NodeConnection* connection = graphNode->GetConnection(j); @@ -1672,9 +1636,6 @@ namespace EMStudio { // gather some information from the connection NodeConnection* connection = GetRelinkConnection(); - //GraphNode* sourceNode = connection->GetSourceNode(); - //uint32 sourcePortNr = connection->GetOutputPortNr(); - //NodePort* port = sourceNode->GetOutputPort( connection->GetOutputPortNr() ); QPoint start = connection->GetSourceRect().center(); QPoint end = m_graphWidget->GetMousePos(); @@ -1701,10 +1662,10 @@ namespace EMStudio } // now check all ports to see if they would be valid - const uint32 numInputPorts = node->GetNumInputPorts(); - for (uint32 i = 0; i < numInputPorts; ++i) + const AZ::u16 numInputPorts = node->GetNumInputPorts(); + for (AZ::u16 i = 0; i < numInputPorts; ++i) { - if (CheckIfIsRelinkConnectionValid(mRelinkConnection, node, i, true)) + if (CheckIfIsRelinkConnectionValid(m_relinkConnection, node, i, true)) { QPoint tempStart = end; QPoint tempEnd = node->GetInputPort(i)->GetRect().center(); @@ -1718,9 +1679,9 @@ namespace EMStudio } // figure out the color of the connection line - if (mTargetPort) + if (m_targetPort) { - if (mConIsValid) + if (m_conIsValid) { painter.setPen(QColor(0, 255, 0)); } @@ -1778,8 +1739,8 @@ namespace EMStudio } // now check all ports to see if they would be valid - const uint32 numInputPorts = node->GetNumInputPorts(); - for (uint32 i = 0; i < numInputPorts; ++i) + const AZ::u16 numInputPorts = node->GetNumInputPorts(); + for (AZ::u16 i = 0; i < numInputPorts; ++i) { if (m_graphWidget->CheckIfIsCreateConnectionValid(i, node, node->GetInputPort(i), true)) { @@ -1793,8 +1754,8 @@ namespace EMStudio } // now check all ports to see if they would be valid - const uint32 numOutputPorts = node->GetNumOutputPorts(); - for (uint32 a = 0; a < numOutputPorts; ++a) + const AZ::u16 numOutputPorts = node->GetNumOutputPorts(); + for (AZ::u16 a = 0; a < numOutputPorts; ++a) { if (m_graphWidget->CheckIfIsCreateConnectionValid(a, node, node->GetOutputPort(a), false)) { @@ -1812,14 +1773,13 @@ namespace EMStudio //------------------------------ // update the end point - //start = mConPort->GetRect().center(); start = GetCreateConnectionNode()->GetRect().topLeft() + GetCreateConnectionStartOffset(); end = m_graphWidget->GetMousePos(); // figure out the color of the connection line - if (mTargetPort) + if (m_targetPort) { - if (mConIsValid) + if (m_conIsValid) { painter.setPen(QColor(0, 255, 0)); } @@ -1864,10 +1824,10 @@ namespace EMStudio // check if this connection already exists - bool NodeGraph::CheckIfHasConnection(GraphNode* sourceNode, uint32 outputPortNr, GraphNode* targetNode, uint32 inputPortNr) const + bool NodeGraph::CheckIfHasConnection(GraphNode* sourceNode, AZ::u16 outputPortNr, GraphNode* targetNode, AZ::u16 inputPortNr) const { - const uint32 numConnections = targetNode->GetNumConnections(); - for (uint32 i = 0; i < numConnections; ++i) + const size_t numConnections = targetNode->GetNumConnections(); + for (size_t i = 0; i < numConnections; ++i) { NodeConnection* connection = targetNode->GetConnection(i); @@ -1888,15 +1848,15 @@ namespace EMStudio } - NodeConnection* NodeGraph::FindInputConnection(GraphNode* targetNode, uint32 targetPortNr) const + NodeConnection* NodeGraph::FindInputConnection(GraphNode* targetNode, AZ::u16 targetPortNr) const { - if (targetNode == nullptr || targetPortNr == MCORE_INVALIDINDEX32) + if (targetNode == nullptr || targetPortNr == InvalidIndex16) { return nullptr; } - const uint32 numConnections = targetNode->GetNumConnections(); - for (uint32 i = 0; i < numConnections; ++i) + const size_t numConnections = targetNode->GetNumConnections(); + for (size_t i = 0; i < numConnections; ++i) { NodeConnection* connection = targetNode->GetConnection(i); @@ -1967,8 +1927,8 @@ namespace EMStudio const QModelIndex parentModelIndex = modelIndex.model()->parent(modelIndex); EMotionFX::AnimGraphNode* parentNode = parentModelIndex.data(AnimGraphModel::ROLE_NODE_POINTER).value(); GraphNode* target = FindGraphNode(parentNode); - const uint32 sourcePort = connection->GetSourcePort(); - const uint32 targetPort = connection->GetTargetPort(); + const AZ::u16 sourcePort = connection->GetSourcePort(); + const AZ::u16 targetPort = connection->GetTargetPort(); NodeConnection* visualConnection = new NodeConnection(this, modelIndex, target, targetPort, source, sourcePort); target->AddConnection(visualConnection); break; @@ -1999,9 +1959,9 @@ namespace EMStudio GraphNodeByModelIndex::const_iterator it = m_graphNodeByModelIndex.find(modelIndex); if (it != m_graphNodeByModelIndex.end()) { - if (it->second.get() == mEntryNode) + if (it->second.get() == m_entryNode) { - mEntryNode = nullptr; + m_entryNode = nullptr; } m_graphNodeByModelIndex.erase(it); } @@ -2013,9 +1973,9 @@ namespace EMStudio // So we have to rely on the UI data. for (const GraphNodeByModelIndex::value_type& target : m_graphNodeByModelIndex) { - MCore::Array& connections = target.second->GetConnections(); - const uint32 connectionsCount = connections.GetLength(); - for (uint32 i = 0; i < connectionsCount; ++i) + AZStd::vector& connections = target.second->GetConnections(); + const size_t connectionsCount = connections.size(); + for (size_t i = 0; i < connectionsCount; ++i) { if (connections[i]->GetType() == StateConnection::TYPE_ID) { @@ -2023,7 +1983,7 @@ namespace EMStudio if (visualStateConnection->GetModelIndex() == modelIndex) { delete connections[i]; - connections.Remove(i); + connections.erase(AZStd::next(begin(connections), i)); break; } } @@ -2086,13 +2046,12 @@ namespace EMStudio GraphNode* targetGraphNode = FindGraphNode(targetNode); bool foundConnection = false; - MCore::Array& connections = targetGraphNode->GetConnections(); - const uint32 connectionsCount = connections.GetLength(); - for (uint32 i = 0; i < connectionsCount; ++i) + AZStd::vector& connections = targetGraphNode->GetConnections(); + for (NodeConnection* connection : connections) { - if (connections[i]->GetType() == StateConnection::TYPE_ID) + if (connection->GetType() == StateConnection::TYPE_ID) { - StateConnection* visualStateConnection = static_cast(connections[i]); + StateConnection* visualStateConnection = static_cast(connection); if (visualStateConnection->GetModelIndex() == modelIndex) { SyncTransition(visualStateConnection, transition, targetGraphNode); @@ -2110,13 +2069,11 @@ namespace EMStudio { GraphNode* visualNode = indexAndGraphNode.second.get(); - MCore::Array& connections2 = visualNode->GetConnections(); - const uint32 connectionsCount2 = connections2.GetLength(); - for (uint32 i = 0; i < connectionsCount2; ++i) + for (NodeConnection* connection : visualNode->GetConnections()) { - if (connections2[i]->GetType() == StateConnection::TYPE_ID) + if (connection->GetType() == StateConnection::TYPE_ID) { - StateConnection* visualStateConnection = static_cast(connections2[i]); + StateConnection* visualStateConnection = static_cast(connection); if (visualStateConnection->GetModelIndex() == modelIndex) { // Transfer ownership from the previous visual node to where we relinked the transition to. @@ -2176,13 +2133,12 @@ namespace EMStudio // We have to rely on the UI data. for (const GraphNodeByModelIndex::value_type& target : m_graphNodeByModelIndex) { - MCore::Array& connections = target.second->GetConnections(); - const uint32 connectionsCount = connections.GetLength(); - for (uint32 i = 0; i < connectionsCount; ++i) + AZStd::vector& connections = target.second->GetConnections(); + for (NodeConnection* connection : connections) { - if (connections[i]->GetType() == StateConnection::TYPE_ID) + if (connection->GetType() == StateConnection::TYPE_ID) { - StateConnection* visualStateConnection = static_cast(connections[i]); + StateConnection* visualStateConnection = static_cast(connection); if (visualStateConnection->GetModelIndex() == modelIndex) { return visualStateConnection; @@ -2205,13 +2161,12 @@ namespace EMStudio GraphNode* target = FindGraphNode(parentModelIndex); if (target) { - MCore::Array& connections = target->GetConnections(); - const uint32 connectionsCount = connections.GetLength(); - for (uint32 i = 0; i < connectionsCount; ++i) + AZStd::vector& connections = target->GetConnections(); + for (NodeConnection* connection : connections) { - if (connections[i]->GetType() == NodeConnection::TYPE_ID) + if (connection->GetType() == NodeConnection::TYPE_ID) { - NodeConnection* visualNodeConnection = static_cast(connections[i]); + NodeConnection* visualNodeConnection = static_cast(connection); if (visualNodeConnection->GetModelIndex() == modelIndex) { return visualNodeConnection; @@ -2239,8 +2194,8 @@ namespace EMStudio graphNode->SetIsProcessed(graphNodeAnimGraphInstance->GetIsOutputReady(emfxNode->GetObjectIndex())); graphNode->SetIsUpdated(graphNodeAnimGraphInstance->GetIsUpdateReady(emfxNode->GetObjectIndex())); - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = graphNode->GetConnection(c); if (connection->GetType() == NodeConnection::TYPE_ID) @@ -2255,8 +2210,8 @@ namespace EMStudio graphNode->SetIsProcessed(false); graphNode->SetIsUpdated(false); - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = graphNode->GetConnection(c); if (connection->GetType() == NodeConnection::TYPE_ID) @@ -2266,8 +2221,8 @@ namespace EMStudio } } - const uint32 numConnections = graphNode->GetNumConnections(); - for (uint32 c = 0; c < numConnections; ++c) + const size_t numConnections = graphNode->GetNumConnections(); + for (size_t c = 0; c < numConnections; ++c) { NodeConnection* connection = graphNode->GetConnection(c); if (connection->GetType() == NodeConnection::TYPE_ID) @@ -2287,12 +2242,12 @@ namespace EMStudio } // check if a connection is valid or not - bool NodeGraph::CheckIfIsRelinkConnectionValid(NodeConnection* connection, GraphNode* newTargetNode, uint32 newTargetPortNr, bool isTargetInput) + bool NodeGraph::CheckIfIsRelinkConnectionValid(NodeConnection* connection, GraphNode* newTargetNode, AZ::u16 newTargetPortNr, bool isTargetInput) { GraphNode* targetNode = connection->GetSourceNode(); GraphNode* sourceNode = newTargetNode; - uint32 sourcePortNr = connection->GetOutputPortNr(); - uint32 targetPortNr = newTargetPortNr; + AZ::u16 sourcePortNr = connection->GetOutputPortNr(); + AZ::u16 targetPortNr = newTargetPortNr; // don't allow connection to itself if (sourceNode == targetNode) @@ -2343,8 +2298,8 @@ namespace EMStudio graphNode->ResetBorderColor(); // recurse through the inputs - const uint32 numConnections = startNode->GetNumConnections(); - for (uint32 i = 0; i < numConnections; ++i) + const size_t numConnections = startNode->GetNumConnections(); + for (size_t i = 0; i < numConnections; ++i) { EMotionFX::BlendTreeConnection* connection = startNode->GetConnection(i); RecursiveSetOpacity(connection->GetSourceNode(), opacity); @@ -2460,8 +2415,8 @@ namespace EMStudio // get the number of node groups and iterate through them QRect nodeRect; QRect groupRect; - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); - for (uint32 i = 0; i < numNodeGroups; ++i) + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); + for (size_t i = 0; i < numNodeGroups; ++i) { // get the current node group EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(i); @@ -2473,7 +2428,7 @@ namespace EMStudio } // get the number of nodes inside the node group and skip the group in case there are no nodes in - const uint32 numNodes = nodeGroup->GetNumNodes(); + const size_t numNodes = nodeGroup->GetNumNodes(); if (numNodes == 0) { continue; @@ -2485,7 +2440,7 @@ namespace EMStudio int32 right = std::numeric_limits::lowest(); bool nodesInGroupDisplayed = false; - for (uint32 j = 0; j < numNodes; ++j) + for (size_t j = 0; j < numNodes; ++j) { // get the graph node by the id and skip it if the node is not inside the currently visible node graph const EMotionFX::AnimGraphNodeId nodeId = nodeGroup->GetNode(j); @@ -2526,11 +2481,7 @@ namespace EMStudio // draw the name on top color.setAlpha(255); - //painter.setPen( color ); - //mTempString = nodeGroup->GetName(); - //painter.setFont( m_groupFont ); GraphNode::RenderText(painter, nodeGroup->GetName(), color, m_groupFont, *m_groupFontMetrics, Qt::AlignLeft, textRect); - //painter.drawText( left - 7, top - 7, mTempString ); } } // for all node groups } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.h index 8af772d95e..47b316ff81 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraph.h @@ -49,56 +49,56 @@ namespace EMStudio bool IsInReferencedGraph() const { return m_parentReferenceNode.isValid(); } - const QTransform& GetTransform() const { return mTransform; } - float GetScale() const { return mScale; } - void SetScale(float scale) { mScale = scale; } - const QPoint& GetScrollOffset() const { return mScrollOffset; } - void SetScrollOffset(const QPoint& offset) { mScrollOffset = offset; } - void SetScalePivot(const QPoint& pivot) { mScalePivot = pivot; } + const QTransform& GetTransform() const { return m_transform; } + float GetScale() const { return m_scale; } + void SetScale(float scale) { m_scale = scale; } + const QPoint& GetScrollOffset() const { return m_scrollOffset; } + void SetScrollOffset(const QPoint& offset) { m_scrollOffset = offset; } + void SetScalePivot(const QPoint& pivot) { m_scalePivot = pivot; } float GetLowestScale() const { return sLowestScale; } - bool GetIsCreatingConnection() const { return (mConNode && mRelinkConnection == nullptr); } - bool GetIsRelinkingConnection() const { return (mConNode && mRelinkConnection); } - void SetCreateConnectionIsValid(bool isValid) { mConIsValid = isValid; } - bool GetIsCreateConnectionValid() const { return mConIsValid; } - void SetTargetPort(NodePort* port) { mTargetPort = port; } - NodePort* GetTargetPort() { return mTargetPort; } - float GetDashOffset() const { return mDashOffset; } - QColor GetErrorBlinkColor() const { int32 red = aznumeric_cast(160 + ((0.5f + 0.5f * MCore::Math::Cos(mErrorBlinkOffset)) * 96)); red = MCore::Clamp(red, 0, 255); return QColor(red, 0, 0); } - - bool GetIsRepositioningTransitionHead() const { return (mReplaceTransitionHead); } - bool GetIsRepositioningTransitionTail() const { return (mReplaceTransitionTail); } - NodeConnection* GetRepositionedTransitionHead() const { return mReplaceTransitionHead; } - NodeConnection* GetRepositionedTransitionTail() const { return mReplaceTransitionTail; } + bool GetIsCreatingConnection() const { return (m_conNode && m_relinkConnection == nullptr); } + bool GetIsRelinkingConnection() const { return (m_conNode && m_relinkConnection); } + void SetCreateConnectionIsValid(bool isValid) { m_conIsValid = isValid; } + bool GetIsCreateConnectionValid() const { return m_conIsValid; } + void SetTargetPort(NodePort* port) { m_targetPort = port; } + NodePort* GetTargetPort() { return m_targetPort; } + float GetDashOffset() const { return m_dashOffset; } + QColor GetErrorBlinkColor() const { int32 red = aznumeric_cast(160 + ((0.5f + 0.5f * MCore::Math::Cos(m_errorBlinkOffset)) * 96)); red = MCore::Clamp(red, 0, 255); return QColor(red, 0, 0); } + + bool GetIsRepositioningTransitionHead() const { return (m_replaceTransitionHead); } + bool GetIsRepositioningTransitionTail() const { return (m_replaceTransitionTail); } + NodeConnection* GetRepositionedTransitionHead() const { return m_replaceTransitionHead; } + NodeConnection* GetRepositionedTransitionTail() const { return m_replaceTransitionTail; } void StartReplaceTransitionHead(NodeConnection* connection, QPoint startOffset, QPoint endOffset, GraphNode* sourceNode, GraphNode* targetNode); void StartReplaceTransitionTail(NodeConnection* connection, QPoint startOffset, QPoint endOffset, GraphNode* sourceNode, GraphNode* targetNode); void GetReplaceTransitionInfo(NodeConnection** outConnection, QPoint* outOldStartOffset, QPoint* outOldEndOffset, GraphNode** outOldSourceNode, GraphNode** outOldTargetNode); void StopReplaceTransitionHead(); void StopReplaceTransitionTail(); - void SetReplaceTransitionValid(bool isValid) { mReplaceTransitionValid = isValid; } - bool GetReplaceTransitionValid() const { return mReplaceTransitionValid; } + void SetReplaceTransitionValid(bool isValid) { m_replaceTransitionValid = isValid; } + bool GetReplaceTransitionValid() const { return m_replaceTransitionValid; } void RenderReplaceTransition(QPainter& painter); - GraphNode* GetCreateConnectionNode() { return mConNode; } - NodeConnection* GetRelinkConnection() { return mRelinkConnection; } - uint32 GetCreateConnectionPortNr() const { return mConPortNr; } - bool GetCreateConnectionIsInputPort() const { return mConIsInputPort; } - const QPoint& GetCreateConnectionStartOffset() const { return mConStartOffset; } - const QPoint& GetCreateConnectionEndOffset() const { return mConEndOffset; } - void SetCreateConnectionEndOffset(const QPoint& offset){ mConEndOffset = offset; } + GraphNode* GetCreateConnectionNode() { return m_conNode; } + NodeConnection* GetRelinkConnection() { return m_relinkConnection; } + AZ::u16 GetCreateConnectionPortNr() const { return m_conPortNr; } + bool GetCreateConnectionIsInputPort() const { return m_conIsInputPort; } + const QPoint& GetCreateConnectionStartOffset() const { return m_conStartOffset; } + const QPoint& GetCreateConnectionEndOffset() const { return m_conEndOffset; } + void SetCreateConnectionEndOffset(const QPoint& offset){ m_conEndOffset = offset; } - bool CheckIfHasConnection(GraphNode* sourceNode, uint32 outputPortNr, GraphNode* targetNode, uint32 inputPortNr) const; - NodeConnection* FindInputConnection(GraphNode* targetNode, uint32 targetPortNr) const; + bool CheckIfHasConnection(GraphNode* sourceNode, AZ::u16 outputPortNr, GraphNode* targetNode, AZ::u16 inputPortNr) const; + NodeConnection* FindInputConnection(GraphNode* targetNode, AZ::u16 targetPortNr) const; NodeConnection* FindConnection(const QPoint& mousePos); void SelectAllNodes(); void UnselectAllNodes(); - uint32 CalcNumSelectedNodes() const; + size_t CalcNumSelectedNodes() const; GraphNode* FindNode(const QPoint& globalPoint); - void StartCreateConnection(uint32 portNr, bool isInputPort, GraphNode* portNode, NodePort* port, const QPoint& startOffset); - void StartRelinkConnection(NodeConnection* connection, uint32 portNr, GraphNode* node); + void StartCreateConnection(AZ::u16 portNr, bool isInputPort, GraphNode* portNode, NodePort* port, const QPoint& startOffset); + void StartRelinkConnection(NodeConnection* connection, AZ::u16 portNr, GraphNode* node); void StopCreateConnection(); void StopRelinkConnection(); @@ -118,10 +118,10 @@ namespace EMStudio void SelectConnectionCloseTo(const QPoint& point, bool overwriteCurSelection = true, bool toggle = false); QRect CalcRectFromSelection(bool includeConnections = true) const; QRect CalcRectFromGraph() const; - NodePort* FindPort(int32 x, int32 y, GraphNode** outNode, uint32* outPortNr, bool* outIsInputPort, bool includeInputPorts = true); + NodePort* FindPort(int32 x, int32 y, GraphNode** outNode, AZ::u16* outPortNr, bool* outIsInputPort, bool includeInputPorts = true); // entry state helper functions - void SetEntryNode(GraphNode* entryNode) { mEntryNode = entryNode; } + void SetEntryNode(GraphNode* entryNode) { m_entryNode = entryNode; } static void RenderEntryPoint(QPainter& painter, GraphNode* node); void FitGraphOnScreen(int32 width, int32 height, const QPoint& mousePos, bool animate = true); @@ -140,8 +140,8 @@ namespace EMStudio static bool LineIntersectsRect(const QRect& b, float x1, float y1, float x2, float y2, double* outX = nullptr, double* outY = nullptr); void DrawOverlay(QPainter& painter); - bool GetUseAnimation() const { return mUseAnimation; } - void SetUseAnimation(bool useAnim) { mUseAnimation = useAnim; } + bool GetUseAnimation() const { return m_useAnimation; } + void SetUseAnimation(bool useAnim) { m_useAnimation = useAnim; } // These methods are not slots, they are being called from BlendGraphWidget void OnRowsAboutToBeRemoved(const QModelIndexList& modelIndexes); @@ -157,7 +157,7 @@ namespace EMStudio void UpdateVisualGraphFlags(); - static bool CheckIfIsRelinkConnectionValid(NodeConnection* connection, GraphNode* newTargetNode, uint32 newTargetPortNr, bool isTargetInput); + static bool CheckIfIsRelinkConnectionValid(NodeConnection* connection, GraphNode* newTargetNode, AZ::u16 newTargetPortNr, bool isTargetInput); void RecursiveSetOpacity(EMotionFX::AnimGraphNode* startNode, float opacity); @@ -175,55 +175,55 @@ namespace EMStudio using GraphNodeByModelIndex = AZStd::unordered_map, QPersistentModelIndexHash>; GraphNodeByModelIndex m_graphNodeByModelIndex; - GraphNode* mEntryNode; - QTransform mTransform; - float mScale; + GraphNode* m_entryNode; + QTransform m_transform; + float m_scale; static float sLowestScale; - int32 mMinStepSize; - int32 mMaxStepSize; - QPoint mScrollOffset; - QPoint mScalePivot; + int32 m_minStepSize; + int32 m_maxStepSize; + QPoint m_scrollOffset; + QPoint m_scalePivot; - QPointF mTargetScrollOffset; - QPointF mStartScrollOffset; - QTimer mScrollTimer; - AZ::Debug::Timer mScrollPreciseTimer; + QPointF m_targetScrollOffset; + QPointF m_startScrollOffset; + QTimer m_scrollTimer; + AZ::Debug::Timer m_scrollPreciseTimer; - float mTargetScale; - float mStartScale; - QTimer mScaleTimer; - AZ::Debug::Timer mScalePreciseTimer; + float m_targetScale; + float m_startScale; + QTimer m_scaleTimer; + AZ::Debug::Timer m_scalePreciseTimer; // connection info - QPoint mConStartOffset; - QPoint mConEndOffset; - uint32 mConPortNr; - bool mConIsInputPort; - GraphNode* mConNode; // nullptr when no connection is being created - NodeConnection* mRelinkConnection; // nullptr when not relinking a connection - NodePort* mConPort; - NodePort* mTargetPort; - bool mConIsValid; - float mDashOffset; - float mErrorBlinkOffset; - bool mUseAnimation; - - NodeConnection* mReplaceTransitionHead; // nullptr when not replacing a transition head - NodeConnection* mReplaceTransitionTail; // nullptr when not replacing a transition tail - QPoint mReplaceTransitionStartOffset; - QPoint mReplaceTransitionEndOffset; - GraphNode* mReplaceTransitionSourceNode; - GraphNode* mReplaceTransitionTargetNode; - bool mReplaceTransitionValid; - - QPen mSubgridPen; - QPen mGridPen; + QPoint m_conStartOffset; + QPoint m_conEndOffset; + AZ::u16 m_conPortNr; + bool m_conIsInputPort; + GraphNode* m_conNode; // nullptr when no connection is being created + NodeConnection* m_relinkConnection; // nullptr when not relinking a connection + NodePort* m_conPort; + NodePort* m_targetPort; + bool m_conIsValid; + float m_dashOffset; + float m_errorBlinkOffset; + bool m_useAnimation; + + NodeConnection* m_replaceTransitionHead; // nullptr when not replacing a transition head + NodeConnection* m_replaceTransitionTail; // nullptr when not replacing a transition tail + QPoint m_replaceTransitionStartOffset; + QPoint m_replaceTransitionEndOffset; + GraphNode* m_replaceTransitionSourceNode; + GraphNode* m_replaceTransitionTargetNode; + bool m_replaceTransitionValid; + + QPen m_subgridPen; + QPen m_gridPen; // Overlay drawing - QFont mFont; - QString mQtTempString; - QTextOption mTextOptions; - QFontMetrics* mFontMetrics; + QFont m_font; + QString m_qtTempString; + QTextOption m_textOptions; + QFontMetrics* m_fontMetrics; AZStd::string m_tempStringA; AZStd::string m_tempStringB; AZStd::string m_tempStringC; 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 8b8e651837..c8085a876a 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 @@ -37,8 +37,8 @@ namespace EMStudio { setObjectName("NodeGraphWidget"); - mPlugin = plugin; - mFontMetrics = new QFontMetrics(mFont); + m_plugin = plugin; + m_fontMetrics = new QFontMetrics(m_font); // update the active graph SetActiveGraph(activeGraph); @@ -47,19 +47,19 @@ namespace EMStudio setMouseTracking(true); // init members - mShowFPS = false; - mLeftMousePressed = false; - mPanning = false; - mMiddleMousePressed = false; - mRightMousePressed = false; - mRectSelecting = false; - mShiftPressed = false; - mControlPressed = false; - mAltPressed = false; - mMoveNode = nullptr; - mMouseLastPos = QPoint(0, 0); - mMouseLastPressPos = QPoint(0, 0); - mMousePos = QPoint(0, 0); + m_showFps = false; + m_leftMousePressed = false; + m_panning = false; + m_middleMousePressed = false; + m_rightMousePressed = false; + m_rectSelecting = false; + m_shiftPressed = false; + m_controlPressed = false; + m_altPressed = false; + m_moveNode = nullptr; + m_mouseLastPos = QPoint(0, 0); + m_mouseLastPressPos = QPoint(0, 0); + m_mousePos = QPoint(0, 0); // setup to get focus when we click or use the mouse wheel setFocusPolicy((Qt::FocusPolicy)(Qt::ClickFocus | Qt::WheelFocus)); @@ -70,10 +70,10 @@ namespace EMStudio setAutoFillBackground(false); setAttribute(Qt::WA_OpaquePaintEvent); - mCurWidth = geometry().width(); - mCurHeight = geometry().height(); - mPrevWidth = mCurWidth; - mPrevHeight = mCurHeight; + m_curWidth = geometry().width(); + m_curHeight = geometry().height(); + m_prevWidth = m_curWidth; + m_prevHeight = m_curHeight; } @@ -81,7 +81,7 @@ namespace EMStudio NodeGraphWidget::~NodeGraphWidget() { // delete the overlay font metrics - delete mFontMetrics; + delete m_fontMetrics; } @@ -98,20 +98,20 @@ namespace EMStudio { static QPoint sizeDiff(0, 0); - mCurWidth = w; - mCurHeight = h; + m_curWidth = w; + m_curHeight = h; // specify the center of the window, so that that is the origin - if (mActiveGraph) + if (m_activeGraph) { - mActiveGraph->SetScalePivot(QPoint(w / 2, h / 2)); + m_activeGraph->SetScalePivot(QPoint(w / 2, h / 2)); - QPoint scrollOffset = mActiveGraph->GetScrollOffset(); + QPoint scrollOffset = m_activeGraph->GetScrollOffset(); int32 scrollOffsetX = scrollOffset.x(); int32 scrollOffsetY = scrollOffset.y(); // calculate the size delta - QPoint oldSize = QPoint(mPrevWidth, mPrevHeight); + QPoint oldSize = QPoint(m_prevWidth, m_prevHeight); QPoint size = QPoint(w, h); QPoint diff = oldSize - size; sizeDiff += diff; @@ -136,35 +136,35 @@ namespace EMStudio sizeDiff.setY(modRes); } - mActiveGraph->SetScrollOffset(QPoint(scrollOffsetX, scrollOffsetY)); + m_activeGraph->SetScrollOffset(QPoint(scrollOffsetX, scrollOffsetY)); //MCore::LOG("%d, %d", scrollOffsetX, scrollOffsetY); } QOpenGLWidget::resizeGL(w, h); - mPrevWidth = w; - mPrevHeight = h; + m_prevWidth = w; + m_prevHeight = h; } // set the active graph void NodeGraphWidget::SetActiveGraph(NodeGraph* graph) { - if (mActiveGraph == graph) + if (m_activeGraph == graph) { return; } - if (mActiveGraph) + if (m_activeGraph) { - mActiveGraph->StopCreateConnection(); - mActiveGraph->StopRelinkConnection(); - mActiveGraph->StopReplaceTransitionHead(); - mActiveGraph->StopReplaceTransitionTail(); + m_activeGraph->StopCreateConnection(); + m_activeGraph->StopRelinkConnection(); + m_activeGraph->StopReplaceTransitionHead(); + m_activeGraph->StopReplaceTransitionTail(); } - mActiveGraph = graph; - mMoveNode = nullptr; + m_activeGraph = graph; + m_moveNode = nullptr; emit ActiveGraphChanged(); } @@ -173,7 +173,7 @@ namespace EMStudio // get the active graph NodeGraph* NodeGraphWidget::GetActiveGraph() const { - return mActiveGraph; + return m_activeGraph; } @@ -193,7 +193,7 @@ namespace EMStudio glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // calculate the time passed since the last render - const float timePassedInSeconds = mRenderTimer.StampAndGetDeltaTimeInSeconds(); + const float timePassedInSeconds = m_renderTimer.StampAndGetDeltaTimeInSeconds(); // start painting QPainter painter(this); @@ -202,8 +202,8 @@ namespace EMStudio painter.setRenderHint(QPainter::TextAntialiasing); // get the width and height - const uint32 width = mCurWidth; - const uint32 height = mCurHeight; + const uint32 width = m_curWidth; + const uint32 height = m_curHeight; // fill the background //painter.fillRect( event->rect(), QColor(30, 30, 30) ); @@ -212,19 +212,19 @@ namespace EMStudio painter.drawRect(QRect(0, 0, width, height)); // render the active graph - if (mActiveGraph) + if (m_activeGraph) { - mActiveGraph->Render(mPlugin->GetAnimGraphModel().GetSelectionModel(), painter, width, height, mMousePos, timePassedInSeconds); + m_activeGraph->Render(m_plugin->GetAnimGraphModel().GetSelectionModel(), painter, width, height, m_mousePos, timePassedInSeconds); } // render selection rect - if (mRectSelecting) + if (m_rectSelecting) { painter.resetTransform(); QRect selectRect; CalcSelectRect(selectRect); - if (mAltPressed) + if (m_altPressed) { painter.setBrush(QColor(0, 100, 200, 75)); painter.setPen(QColor(0, 100, 255)); @@ -242,10 +242,10 @@ namespace EMStudio OnDrawOverlay(painter); // render the callback overlay - if (mActiveGraph) + if (m_activeGraph) { painter.resetTransform(); - mActiveGraph->DrawOverlay(painter); + m_activeGraph->DrawOverlay(painter); } // draw the border @@ -277,7 +277,7 @@ namespace EMStudio //painter.setBackgroundMode(Qt::TransparentMode); // render FPS counter - if (mShowFPS) + if (m_showFps) { // get the time delta between the current time and the last frame static AZ::Debug::Timer perfTimer; @@ -288,7 +288,7 @@ namespace EMStudio static uint32 fpsNumFrames = 0; static uint32 lastFPS = 0; fpsTimeElapsed += perfTimeDelta; - const float renderTime = mRenderTimer.StampAndGetDeltaTimeInSeconds() * 1000.0f; + const float renderTime = m_renderTimer.StampAndGetDeltaTimeInSeconds() * 1000.0f; fpsNumFrames++; if (fpsTimeElapsed > 1.0f) { @@ -300,7 +300,7 @@ namespace EMStudio static AZStd::string perfTempString; perfTempString = AZStd::string::format("%i FPS (%.1f ms)", lastFPS, renderTime); - GraphNode::RenderText(painter, perfTempString.c_str(), QColor(150, 150, 150), mFont, *mFontMetrics, Qt::AlignRight, QRect(width - 55, height - 20, 50, 20)); + GraphNode::RenderText(painter, perfTempString.c_str(), QColor(150, 150, 150), m_font, *m_fontMetrics, Qt::AlignRight, QRect(width - 55, height - 20, 50, 20)); } // show the info to which actor the currently rendered graph belongs to @@ -312,13 +312,13 @@ namespace EMStudio EMotionFX::ActorInstance* firstActorInstance = selectionList.GetFirstActorInstance(); // update the stored short filename without path - if (mFullActorName != firstActorInstance->GetActor()->GetFileName()) + if (m_fullActorName != firstActorInstance->GetActor()->GetFileName()) { - AzFramework::StringFunc::Path::GetFileName(firstActorInstance->GetActor()->GetFileNameString().c_str(), mActorName); + AzFramework::StringFunc::Path::GetFileName(firstActorInstance->GetActor()->GetFileNameString().c_str(), m_actorName); } - mTempString = AZStd::string::format("Showing graph for ActorInstance with ID %d and Actor file \"%s\"", firstActorInstance->GetID(), mActorName.c_str()); - GraphNode::RenderText(painter, mTempString.c_str(), QColor(150, 150, 150), mFont, *mFontMetrics, Qt::AlignLeft, QRect(8, 0, 50, 20)); + m_tempString = AZStd::string::format("Showing graph for ActorInstance with ID %d and Actor file \"%s\"", firstActorInstance->GetID(), m_actorName.c_str()); + GraphNode::RenderText(painter, m_tempString.c_str(), QColor(150, 150, 150), m_font, *m_fontMetrics, Qt::AlignLeft, QRect(8, 0, 50, 20)); } } @@ -326,9 +326,9 @@ namespace EMStudio // convert to a global position QPoint NodeGraphWidget::LocalToGlobal(const QPoint& inPoint) const { - if (mActiveGraph) + if (m_activeGraph) { - return mActiveGraph->GetTransform().inverted().map(inPoint); + return m_activeGraph->GetTransform().inverted().map(inPoint); } return inPoint; @@ -338,9 +338,9 @@ namespace EMStudio // convert to a local position QPoint NodeGraphWidget::GlobalToLocal(const QPoint& inPoint) const { - if (mActiveGraph) + if (m_activeGraph) { - return mActiveGraph->GetTransform().map(inPoint); + return m_activeGraph->GetTransform().map(inPoint); } return inPoint; @@ -351,19 +351,16 @@ namespace EMStudio { MCORE_UNUSED(cellSize); - //QPoint scaledMouseDelta = (mousePos - mMouseLastPos) * (1.0f / mActiveGraph->GetScale()); - //QPoint unSnappedTopRight = oldTopRight + scaledMouseDelta; QPoint snapped; snapped.setX(inPoint.x() - aznumeric_cast(MCore::Math::FMod(aznumeric_cast(inPoint.x()), 10.0f))); snapped.setY(inPoint.y() - aznumeric_cast(MCore::Math::FMod(aznumeric_cast(inPoint.y()), 10.0f))); - //snapDelta = snappedTopRight - unSnappedTopRight; return snapped; } // mouse is moving over the widget void NodeGraphWidget::mouseMoveEvent(QMouseEvent* event) { - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return; } @@ -372,51 +369,51 @@ namespace EMStudio QPoint mousePos = event->pos(); QPoint snapDelta(0, 0); - if (mMoveNode && mLeftMousePressed && mPanning == false && mRectSelecting == false) + if (m_moveNode && m_leftMousePressed && m_panning == false && m_rectSelecting == false) { - QPoint oldTopRight = mMoveNode->GetRect().topRight(); - QPoint scaledMouseDelta = (mousePos - mMouseLastPos) * (1.0f / mActiveGraph->GetScale()); + QPoint oldTopRight = m_moveNode->GetRect().topRight(); + QPoint scaledMouseDelta = (mousePos - m_mouseLastPos) * (1.0f / m_activeGraph->GetScale()); QPoint unSnappedTopRight = oldTopRight + scaledMouseDelta; QPoint snappedTopRight = SnapLocalToGrid(unSnappedTopRight, 10); snapDelta = snappedTopRight - unSnappedTopRight; } - mousePos += snapDelta * mActiveGraph->GetScale(); - QPoint delta = (mousePos - mMouseLastPos) * (1.0f / mActiveGraph->GetScale()); - mMouseLastPos = mousePos; + mousePos += snapDelta * m_activeGraph->GetScale(); + QPoint delta = (mousePos - m_mouseLastPos) * (1.0f / m_activeGraph->GetScale()); + m_mouseLastPos = mousePos; QPoint globalPos = LocalToGlobal(mousePos); SetMousePos(globalPos); //if (delta.x() > 0 || delta.x() < -0 || delta.y() > 0 || delta.y() < -0) if (delta.x() != 0 || delta.y() != 0) { - mAllowContextMenu = false; + m_allowContextMenu = false; } // update modifiers - mAltPressed = event->modifiers() & Qt::AltModifier; - mShiftPressed = event->modifiers() & Qt::ShiftModifier; - mControlPressed = event->modifiers() & Qt::ControlModifier; + m_altPressed = event->modifiers() & Qt::AltModifier; + m_shiftPressed = event->modifiers() & Qt::ShiftModifier; + m_controlPressed = event->modifiers() & Qt::ControlModifier; /*GraphNode* node = */ UpdateMouseCursor(mousePos, globalPos); - if (mRectSelecting == false && mMoveNode == nullptr && - mPlugin->GetActionFilter().m_editConnections && - !mActiveGraph->IsInReferencedGraph()) + if (m_rectSelecting == false && m_moveNode == nullptr && + m_plugin->GetActionFilter().m_editConnections && + !m_activeGraph->IsInReferencedGraph()) { // check if we are clicking on a port GraphNode* portNode = nullptr; NodePort* port = nullptr; - uint32 portNr = MCORE_INVALIDINDEX32; + AZ::u16 portNr = InvalidIndex16; bool isInputPort = true; - port = mActiveGraph->FindPort(globalPos.x(), globalPos.y(), &portNode, &portNr, &isInputPort); + port = m_activeGraph->FindPort(globalPos.x(), globalPos.y(), &portNode, &portNr, &isInputPort); // check if we are adjusting a transition head or tail - if (mActiveGraph->GetIsRepositioningTransitionHead() || mActiveGraph->GetIsRepositioningTransitionTail()) + if (m_activeGraph->GetIsRepositioningTransitionHead() || m_activeGraph->GetIsRepositioningTransitionTail()) { - NodeConnection* connection = mActiveGraph->GetRepositionedTransitionHead(); + NodeConnection* connection = m_activeGraph->GetRepositionedTransitionHead(); if (connection == nullptr) { - connection = mActiveGraph->GetRepositionedTransitionTail(); + connection = m_activeGraph->GetRepositionedTransitionTail(); } MCORE_ASSERT(connection->GetType() == StateConnection::TYPE_ID); @@ -426,13 +423,13 @@ namespace EMStudio if (transition) { // check if our mouse is-over a node - GraphNode* hoveredNode = mActiveGraph->FindNode(mousePos); + GraphNode* hoveredNode = m_activeGraph->FindNode(mousePos); if (hoveredNode == nullptr && portNode) { hoveredNode = portNode; } - if (mActiveGraph->GetIsRepositioningTransitionHead()) + if (m_activeGraph->GetIsRepositioningTransitionHead()) { // when adjusting the arrow head and we are over the source node with the mouse if (hoveredNode @@ -440,11 +437,11 @@ namespace EMStudio && CheckIfIsValidTransition(stateConnection->GetSourceNode(), hoveredNode)) { stateConnection->SetTargetNode(hoveredNode); - mActiveGraph->SetReplaceTransitionValid(true); + m_activeGraph->SetReplaceTransitionValid(true); } else { - mActiveGraph->SetReplaceTransitionValid(false); + m_activeGraph->SetReplaceTransitionValid(false); } GraphNode* targetNode = stateConnection->GetTargetNode(); @@ -455,7 +452,7 @@ namespace EMStudio newEndOffset.x(), newEndOffset.y()); } } - else if (mActiveGraph->GetIsRepositioningTransitionTail()) + else if (m_activeGraph->GetIsRepositioningTransitionTail()) { // when adjusting the arrow tail and we are over the target node with the mouse if (hoveredNode @@ -463,11 +460,11 @@ namespace EMStudio && CheckIfIsValidTransition(hoveredNode, stateConnection->GetTargetNode())) { stateConnection->SetSourceNode(hoveredNode); - mActiveGraph->SetReplaceTransitionValid(true); + m_activeGraph->SetReplaceTransitionValid(true); } else { - mActiveGraph->SetReplaceTransitionValid(false); + m_activeGraph->SetReplaceTransitionValid(false); } GraphNode* sourceNode = stateConnection->GetSourceNode(); @@ -484,19 +481,19 @@ namespace EMStudio // connection relinking or creation if (port) { - if (mActiveGraph->GetIsCreatingConnection()) + if (m_activeGraph->GetIsCreatingConnection()) { const bool isValid = CheckIfIsCreateConnectionValid(portNr, portNode, port, isInputPort); - mActiveGraph->SetCreateConnectionIsValid(isValid); - mActiveGraph->SetTargetPort(port); + m_activeGraph->SetCreateConnectionIsValid(isValid); + m_activeGraph->SetTargetPort(port); //update(); return; } - else if (mActiveGraph->GetIsRelinkingConnection()) + else if (m_activeGraph->GetIsRelinkingConnection()) { - bool isValid = NodeGraph::CheckIfIsRelinkConnectionValid(mActiveGraph->GetRelinkConnection(), portNode, portNr, isInputPort); - mActiveGraph->SetCreateConnectionIsValid(isValid); - mActiveGraph->SetTargetPort(port); + bool isValid = NodeGraph::CheckIfIsRelinkConnectionValid(m_activeGraph->GetRelinkConnection(), portNode, portNr, isInputPort); + m_activeGraph->SetCreateConnectionIsValid(isValid); + m_activeGraph->SetTargetPort(port); //update(); return; } @@ -512,12 +509,12 @@ namespace EMStudio } else { - mActiveGraph->SetTargetPort(nullptr); + m_activeGraph->SetTargetPort(nullptr); } } // if we are panning - if (mPanning) + if (m_panning) { // handle mouse wrapping, to enable smoother panning bool mouseWrapped = false; @@ -525,26 +522,26 @@ namespace EMStudio { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX() - width(), event->globalY())); - mMouseLastPos = QPoint(event->x() - width(), event->y()); + m_mouseLastPos = QPoint(event->x() - width(), event->y()); } else if (event->x() < 0) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX() + width(), event->globalY())); - mMouseLastPos = QPoint(event->x() + width(), event->y()); + m_mouseLastPos = QPoint(event->x() + width(), event->y()); } if (event->y() > (int32)height()) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX(), event->globalY() - height())); - mMouseLastPos = QPoint(event->x(), event->y() - height()); + m_mouseLastPos = QPoint(event->x(), event->y() - height()); } else if (event->y() < 0) { mouseWrapped = true; QCursor::setPos(QPoint(event->globalX(), event->globalY() + height())); - mMouseLastPos = QPoint(event->x(), event->y() + height()); + m_mouseLastPos = QPoint(event->x(), event->y() + height()); } // don't apply the delta, if mouse has been wrapped @@ -553,15 +550,15 @@ namespace EMStudio delta = QPoint(0, 0); } - if (mActiveGraph) + if (m_activeGraph) { // scrolling - if (mAltPressed == false) + if (m_altPressed == false) { - QPoint newOffset = mActiveGraph->GetScrollOffset(); + QPoint newOffset = m_activeGraph->GetScrollOffset(); newOffset += delta; - mActiveGraph->SetScrollOffset(newOffset); - mActiveGraph->StopAnimatedScroll(); + m_activeGraph->SetScrollOffset(newOffset); + m_activeGraph->StopAnimatedScroll(); UpdateMouseCursor(mousePos, globalPos); //update(); return; @@ -570,12 +567,12 @@ namespace EMStudio else { // stop the automated zoom - mActiveGraph->StopAnimatedZoom(); + m_activeGraph->StopAnimatedZoom(); // calculate the new scale value const float scaleDelta = (delta.y() / 120.0f) * 0.2f; - float newScale = MCore::Clamp(mActiveGraph->GetScale() + scaleDelta, mActiveGraph->GetLowestScale(), 1.0f); - mActiveGraph->SetScale(newScale); + float newScale = MCore::Clamp(m_activeGraph->GetScale() + scaleDelta, m_activeGraph->GetLowestScale(), 1.0f); + m_activeGraph->SetScale(newScale); // redraw the viewport //update(); @@ -584,15 +581,15 @@ namespace EMStudio } // if the left mouse button is pressed - if (mLeftMousePressed) + if (m_leftMousePressed) { - if (mMoveNode) + if (m_moveNode) { - if (mActiveGraph && - mPlugin->GetActionFilter().m_editNodes && - !mActiveGraph->IsInReferencedGraph()) + if (m_activeGraph && + m_plugin->GetActionFilter().m_editNodes && + !m_activeGraph->IsInReferencedGraph()) { - const AZStd::vector selectedGraphNodes = mActiveGraph->GetSelectedGraphNodes(); + const AZStd::vector selectedGraphNodes = m_activeGraph->GetSelectedGraphNodes(); if (!selectedGraphNodes.empty()) { // move all selected nodes @@ -601,9 +598,9 @@ namespace EMStudio graphNode->MoveRelative(delta); } } - else if (mMoveNode) + else if (m_moveNode) { - mMoveNode->MoveRelative(delta); + m_moveNode->MoveRelative(delta); } return; } @@ -612,9 +609,9 @@ namespace EMStudio { //setCursor( Qt::ArrowCursor ); - if (mRectSelecting) + if (m_rectSelecting) { - mSelectEnd = mousePos; + m_selectEnd = mousePos; } } @@ -632,27 +629,27 @@ namespace EMStudio // mouse button has been pressed void NodeGraphWidget::mousePressEvent(QMouseEvent* event) { - if (!mActiveGraph) + if (!m_activeGraph) { return; } GetMainWindow()->DisableUndoRedo(); - mAllowContextMenu = true; + m_allowContextMenu = true; // get the mouse position, calculate the global mouse position and update the relevant data QPoint mousePos = event->pos(); - mMouseLastPos = mousePos; - mMouseLastPressPos = mousePos; + m_mouseLastPos = mousePos; + m_mouseLastPressPos = mousePos; QPoint globalPos = LocalToGlobal(mousePos); SetMousePos(globalPos); // update modifiers - mAltPressed = event->modifiers() & Qt::AltModifier; - mShiftPressed = event->modifiers() & Qt::ShiftModifier; - mControlPressed = event->modifiers() & Qt::ControlModifier; - const AnimGraphActionFilter& actionFilter = mPlugin->GetActionFilter(); + m_altPressed = event->modifiers() & Qt::AltModifier; + m_shiftPressed = event->modifiers() & Qt::ShiftModifier; + m_controlPressed = event->modifiers() & Qt::ControlModifier; + const AnimGraphActionFilter& actionFilter = m_plugin->GetActionFilter(); // check if we can start panning if ((event->buttons() & Qt::RightButton && event->buttons() & Qt::LeftButton) || event->button() == Qt::RightButton || event->button() == Qt::MidButton) @@ -660,21 +657,21 @@ namespace EMStudio // update button booleans if (event->buttons() & Qt::RightButton && event->buttons() & Qt::LeftButton) { - mLeftMousePressed = true; - mRightMousePressed = true; + m_leftMousePressed = true; + m_rightMousePressed = true; } if (event->button() == Qt::RightButton) { - mRightMousePressed = true; + m_rightMousePressed = true; GraphNode* node = UpdateMouseCursor(mousePos, globalPos); if (node && node->GetCanVisualize() && node->GetIsInsideVisualizeRect(globalPos)) { OnSetupVisualizeOptions(node); - mRectSelecting = false; - mPanning = false; - mMoveNode = nullptr; + m_rectSelecting = false; + m_panning = false; + m_moveNode = nullptr; //update(); return; } @@ -682,7 +679,7 @@ namespace EMStudio // Right click on the node will trigger a single selection, if the node is not already selected. if (node && !node->GetIsSelected() && !node->GetIsInsideArrowRect(globalPos)) { - mPlugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), + m_plugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); return; } @@ -690,37 +687,33 @@ namespace EMStudio if (event->button() == Qt::MidButton) { - mMiddleMousePressed = true; + m_middleMousePressed = true; } - mPanning = true; - mRectSelecting = false; + m_panning = true; + m_rectSelecting = false; setCursor(Qt::ClosedHandCursor); - //mMoveNode = nullptr; - - // update viewport and return - //update(); return; } // if we press the left mouse button if (event->button() == Qt::LeftButton) { - mLeftMousePressed = true; + m_leftMousePressed = true; // get the node we click on GraphNode* node = UpdateMouseCursor(mousePos, globalPos); // if we pressed the visualize icon - GraphNode* orgNode = mActiveGraph->FindNode(mousePos); + GraphNode* orgNode = m_activeGraph->FindNode(mousePos); if (orgNode && orgNode->GetCanVisualize() && orgNode->GetIsInsideVisualizeRect(globalPos)) { const bool viz = !orgNode->GetIsVisualized(); orgNode->SetIsVisualized(viz); OnVisualizeToggle(orgNode, viz); - mRectSelecting = false; - mPanning = false; - mMoveNode = nullptr; + m_rectSelecting = false; + m_panning = false; + m_moveNode = nullptr; //update(); return; } @@ -767,8 +760,8 @@ namespace EMStudio if (motionEntry && motionEntry->GetMotion()) { EMotionFX::Motion* motion = motionEntry->GetMotion(); - uint32 motionIndex = motionManager.FindMotionIndexByName(motion->GetName()); - commandString = AZStd::string::format("Select -motionIndex %d", motionIndex); + size_t motionIndex = motionManager.FindMotionIndexByName(motion->GetName()); + commandString = AZStd::string::format("Select -motionIndex %zu", motionIndex); commandGroup.AddCommandString(commandString); } } @@ -805,37 +798,29 @@ namespace EMStudio timeViewPlugin->SetMode(TimeViewMode::AnimGraph); } - if (!mActiveGraph->IsInReferencedGraph()) + if (!m_activeGraph->IsInReferencedGraph()) { // check if we are clicking on an input port GraphNode* portNode = nullptr; NodePort* port = nullptr; - uint32 portNr = MCORE_INVALIDINDEX32; + AZ::u16 portNr = InvalidIndex16; bool isInputPort = true; - port = mActiveGraph->FindPort(globalPos.x(), globalPos.y(), &portNode, &portNr, &isInputPort); + port = m_activeGraph->FindPort(globalPos.x(), globalPos.y(), &portNode, &portNr, &isInputPort); if (port) { - mMoveNode = nullptr; - mPanning = false; - mRectSelecting = false; + m_moveNode = nullptr; + m_panning = false; + m_rectSelecting = false; // relink existing connection - NodeConnection* connection = mActiveGraph->FindInputConnection(portNode, portNr); + NodeConnection* connection = m_activeGraph->FindInputConnection(portNode, portNr); if (actionFilter.m_editConnections && isInputPort && connection && portNode->GetType() != StateGraphNode::TYPE_ID) { - //connection->SetColor(); - //MCore::LOG("%s(%i)->%s(%i)", connection->GetSourceNode()->GetName(), connection->GetOutputPortNr(), connection->GetTargetNode()->GetName(), connection->GetInputPortNr()); - //GraphNode* createConNode = connection->GetSourceNode(); - //uint32 createConPortNr = connection->GetOutputPortNr(); - //NodePort* createConPort = createConNode->GetOutputPort( createConPortNr ); - //QPoint createConOffset = QPoint(0,0);//globalPos - createConNode->GetRect().topLeft(); connection->SetIsDashed(true); UpdateMouseCursor(mousePos, globalPos); - //mActiveGraph->StartCreateConnection( createConPortNr, !isInputPort, createConNode, createConPort, createConOffset ); - mActiveGraph->StartRelinkConnection(connection, portNr, portNode); - //update(); + m_activeGraph->StartRelinkConnection(connection, portNr, portNode); return; } @@ -847,7 +832,7 @@ namespace EMStudio { QPoint offset = globalPos - portNode->GetRect().topLeft(); UpdateMouseCursor(mousePos, globalPos); - mActiveGraph->StartCreateConnection(portNr, isInputPort, portNode, port, offset); + m_activeGraph->StartCreateConnection(portNr, isInputPort, portNode, port, offset); //update(); return; } @@ -855,7 +840,7 @@ namespace EMStudio } // check if we click on an transition arrow head or tail - NodeConnection* connection = mActiveGraph->FindConnection(globalPos); + NodeConnection* connection = m_activeGraph->FindConnection(globalPos); if (actionFilter.m_editConnections && connection && connection->GetType() == StateConnection::TYPE_ID) { @@ -868,21 +853,21 @@ namespace EMStudio if (!stateConnection->GetIsWildcardTransition() && stateConnection->CheckIfIsCloseToHead(globalPos)) { - mMoveNode = nullptr; - mPanning = false; - mRectSelecting = false; + m_moveNode = nullptr; + m_panning = false; + m_rectSelecting = false; - mActiveGraph->StartReplaceTransitionHead(stateConnection, startOffset, endOffset, stateConnection->GetSourceNode(), stateConnection->GetTargetNode()); + m_activeGraph->StartReplaceTransitionHead(stateConnection, startOffset, endOffset, stateConnection->GetSourceNode(), stateConnection->GetTargetNode()); return; } if (!stateConnection->GetIsWildcardTransition() && stateConnection->CheckIfIsCloseToTail(globalPos)) { - mMoveNode = nullptr; - mPanning = false; - mRectSelecting = false; + m_moveNode = nullptr; + m_panning = false; + m_rectSelecting = false; - mActiveGraph->StartReplaceTransitionTail(stateConnection, startOffset, endOffset, stateConnection->GetSourceNode(), stateConnection->GetTargetNode()); + m_activeGraph->StartReplaceTransitionTail(stateConnection, startOffset, endOffset, stateConnection->GetSourceNode(), stateConnection->GetTargetNode()); return; } } @@ -891,32 +876,32 @@ namespace EMStudio // get the node we click on node = UpdateMouseCursor(mousePos, globalPos); - if (node && mShiftPressed) + if (node && m_shiftPressed) { OnShiftClickedNode(node); } else { - if (node && mShiftPressed == false && mControlPressed == false && mAltPressed == false && + if (node && m_shiftPressed == false && m_controlPressed == false && m_altPressed == false && actionFilter.m_editNodes && - !mActiveGraph->IsInReferencedGraph()) + !m_activeGraph->IsInReferencedGraph()) { - mMoveNode = node; - mPanning = false; + m_moveNode = node; + m_panning = false; setCursor(Qt::ClosedHandCursor); } else { - mMoveNode = nullptr; - mPanning = false; - mRectSelecting = true; - mSelectStart = mousePos; - mSelectEnd = mSelectStart; + m_moveNode = nullptr; + m_panning = false; + m_rectSelecting = true; + m_selectStart = mousePos; + m_selectEnd = m_selectStart; setCursor(Qt::ArrowCursor); } } - if (mActiveGraph) + if (m_activeGraph) { // shift is used to activate a state, disable all selection behavior in case we press shift! // check if we clicked a node and additionally not clicked its arrow rect @@ -925,42 +910,42 @@ namespace EMStudio { nodeClicked = true; } - if (!mShiftPressed) + if (!m_shiftPressed) { // check the node we're clicking on - if (!mControlPressed) + if (!m_controlPressed) { // only reset the selection in case we clicked in empty space or in case the node we clicked on is not part of if (!node || (node && !node->GetIsSelected())) { - mPlugin->GetAnimGraphModel().GetSelectionModel().clear(); + m_plugin->GetAnimGraphModel().GetSelectionModel().clear(); } } // node clicked with shift only - if (nodeClicked && mControlPressed) + if (nodeClicked && m_controlPressed) { - mPlugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), + m_plugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), QItemSelectionModel::Toggle | QItemSelectionModel::Rows); } // node clicked with ctrl only - else if (nodeClicked && !mControlPressed) + else if (nodeClicked && !m_controlPressed) { - mPlugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), + m_plugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), QItemSelectionModel::Select | QItemSelectionModel::Rows); } // in case we didn't click on a node, check if we click on a connection else if (!nodeClicked) { - mActiveGraph->SelectConnectionCloseTo(LocalToGlobal(event->pos()), mControlPressed == false, true); + m_activeGraph->SelectConnectionCloseTo(LocalToGlobal(event->pos()), m_controlPressed == false, true); } } else { // in case shift and control are both pressed, special case! - if (mControlPressed && node) + if (m_controlPressed && node) { - mPlugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), + m_plugin->GetAnimGraphModel().GetSelectionModel().select(QItemSelection(node->GetModelIndex(), node->GetModelIndex()), QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); } } @@ -977,7 +962,7 @@ namespace EMStudio const QPoint globalPos = LocalToGlobal(mousePos); SetMousePos(globalPos); - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return; } @@ -985,24 +970,24 @@ namespace EMStudio GetMainWindow()->UpdateUndoRedo(); // update modifiers - mAltPressed = event->modifiers() & Qt::AltModifier; - mShiftPressed = event->modifiers() & Qt::ShiftModifier; - mControlPressed = event->modifiers() & Qt::ControlModifier; + m_altPressed = event->modifiers() & Qt::AltModifier; + m_shiftPressed = event->modifiers() & Qt::ShiftModifier; + m_controlPressed = event->modifiers() & Qt::ControlModifier; - const AnimGraphActionFilter& actionFilter = mPlugin->GetActionFilter(); + const AnimGraphActionFilter& actionFilter = m_plugin->GetActionFilter(); // both left and right released at the same time if (event->buttons() & Qt::RightButton && event->buttons() & Qt::LeftButton) { - mRightMousePressed = false; - mLeftMousePressed = false; + m_rightMousePressed = false; + m_leftMousePressed = false; } // right mouse button if (event->button() == Qt::RightButton) { - mRightMousePressed = false; - mPanning = false; + m_rightMousePressed = false; + m_panning = false; UpdateMouseCursor(mousePos, globalPos); //update(); return; @@ -1011,23 +996,23 @@ namespace EMStudio // middle mouse button if (event->button() == Qt::MidButton) { - mMiddleMousePressed = false; - mPanning = false; + m_middleMousePressed = false; + m_panning = false; } // if we release the left mouse button if (event->button() == Qt::LeftButton) { - const bool mouseMoved = (event->pos() != mMouseLastPressPos); + const bool mouseMoved = (event->pos() != m_mouseLastPressPos); // if we pressed the visualize icon GraphNode* node = UpdateMouseCursor(mousePos, globalPos); if (node && node->GetCanVisualize() && node->GetIsInsideVisualizeRect(globalPos)) { - mRectSelecting = false; - mPanning = false; - mMoveNode = nullptr; - mLeftMousePressed = false; + m_rectSelecting = false; + m_panning = false; + m_moveNode = nullptr; + m_leftMousePressed = false; UpdateMouseCursor(mousePos, globalPos); //update(); return; @@ -1035,80 +1020,80 @@ namespace EMStudio if (node && node->GetIsInsideArrowRect(globalPos)) { - mRectSelecting = false; - mPanning = false; - mMoveNode = nullptr; - mLeftMousePressed = false; + m_rectSelecting = false; + m_panning = false; + m_moveNode = nullptr; + m_leftMousePressed = false; UpdateMouseCursor(mousePos, globalPos); //update(); return; } // if we were creating a connection - if (mActiveGraph->GetIsCreatingConnection()) + if (m_activeGraph->GetIsCreatingConnection()) { - AZ_Assert(!mActiveGraph->IsInReferencedGraph(), "Expected to not be in a referenced graph"); + AZ_Assert(!m_activeGraph->IsInReferencedGraph(), "Expected to not be in a referenced graph"); // create the connection if needed - if (mActiveGraph->GetTargetPort()) + if (m_activeGraph->GetTargetPort()) { - if (mActiveGraph->GetIsCreateConnectionValid()) + if (m_activeGraph->GetIsCreateConnectionValid()) { - uint32 targetPortNr; + AZ::u16 targetPortNr; bool targetIsInputPort; GraphNode* targetNode; - NodePort* targetPort = mActiveGraph->FindPort(globalPos.x(), globalPos.y(), &targetNode, &targetPortNr, &targetIsInputPort); - if (targetPort && mActiveGraph->GetTargetPort() == targetPort - && targetNode != mActiveGraph->GetCreateConnectionNode()) + NodePort* targetPort = m_activeGraph->FindPort(globalPos.x(), globalPos.y(), &targetNode, &targetPortNr, &targetIsInputPort); + if (targetPort && m_activeGraph->GetTargetPort() == targetPort + && targetNode != m_activeGraph->GetCreateConnectionNode()) { #ifndef MCORE_DEBUG MCORE_UNUSED(targetPort); #endif QPoint endOffset = globalPos - targetNode->GetRect().topLeft(); - mActiveGraph->SetCreateConnectionEndOffset(endOffset); + m_activeGraph->SetCreateConnectionEndOffset(endOffset); // trigger the callback - OnCreateConnection(mActiveGraph->GetCreateConnectionPortNr(), - mActiveGraph->GetCreateConnectionNode(), - mActiveGraph->GetCreateConnectionIsInputPort(), + OnCreateConnection(m_activeGraph->GetCreateConnectionPortNr(), + m_activeGraph->GetCreateConnectionNode(), + m_activeGraph->GetCreateConnectionIsInputPort(), targetPortNr, targetNode, targetIsInputPort, - mActiveGraph->GetCreateConnectionStartOffset(), - mActiveGraph->GetCreateConnectionEndOffset()); + m_activeGraph->GetCreateConnectionStartOffset(), + m_activeGraph->GetCreateConnectionEndOffset()); } } } - mActiveGraph->StopCreateConnection(); - mLeftMousePressed = false; + m_activeGraph->StopCreateConnection(); + m_leftMousePressed = false; UpdateMouseCursor(mousePos, globalPos); //update(); return; } // if we were relinking a connection - if (mActiveGraph->GetIsRelinkingConnection()) + if (m_activeGraph->GetIsRelinkingConnection()) { AZ_Assert(actionFilter.m_editConnections, "Expected edit connections being enabled."); - AZ_Assert(!mActiveGraph->IsInReferencedGraph(), "Expected to not be in a referenced graph"); + AZ_Assert(!m_activeGraph->IsInReferencedGraph(), "Expected to not be in a referenced graph"); // get the information from the current mouse position - uint32 newTargetPortNr; + AZ::u16 newTargetPortNr; bool newTargetIsInputPort; GraphNode* newTargetNode; - NodePort* newTargetPort = mActiveGraph->FindPort(globalPos.x(), globalPos.y(), &newTargetNode, &newTargetPortNr, &newTargetIsInputPort); + NodePort* newTargetPort = m_activeGraph->FindPort(globalPos.x(), globalPos.y(), &newTargetNode, &newTargetPortNr, &newTargetIsInputPort); // relink existing connection NodeConnection* connection = nullptr; if (newTargetPort) { - connection = mActiveGraph->FindInputConnection(newTargetNode, newTargetPortNr); + connection = m_activeGraph->FindInputConnection(newTargetNode, newTargetPortNr); } - NodeConnection* relinkedConnection = mActiveGraph->GetRelinkConnection(); + NodeConnection* relinkedConnection = m_activeGraph->GetRelinkConnection(); if (relinkedConnection) { relinkedConnection->SetIsDashed(false); @@ -1119,10 +1104,10 @@ namespace EMStudio // get the information from the old connection which we want to relink GraphNode* sourceNode = relinkedConnection->GetSourceNode(); AZStd::string sourceNodeName = sourceNode->GetName(); - uint32 sourcePortNr = relinkedConnection->GetOutputPortNr(); + AZ::u16 sourcePortNr = relinkedConnection->GetOutputPortNr(); GraphNode* oldTargetNode = relinkedConnection->GetTargetNode(); AZStd::string oldTargetNodeName = oldTargetNode->GetName(); - uint32 oldTargetPortNr = relinkedConnection->GetInputPortNr(); + AZ::u16 oldTargetPortNr = relinkedConnection->GetInputPortNr(); if (NodeGraph::CheckIfIsRelinkConnectionValid(relinkedConnection, newTargetNode, newTargetPortNr, newTargetIsInputPort)) { @@ -1154,7 +1139,7 @@ namespace EMStudio CommandSystem::RelinkConnectionTarget(&commandGroup, animGraph->GetID(), sourceNodeName.c_str(), sourcePortNr, oldTargetNodeName.c_str(), oldTargetPortNr, newTargetNodeName.c_str(), newTargetPortNr); // call this before calling the commands as the commands will trigger a graph update - mActiveGraph->StopRelinkConnection(); + m_activeGraph->StopRelinkConnection(); // execute the command group AZStd::string commandResult; @@ -1168,113 +1153,111 @@ namespace EMStudio } } - //mActiveGraph->StopCreateConnection(); - mActiveGraph->StopRelinkConnection(); - mLeftMousePressed = false; + m_activeGraph->StopRelinkConnection(); + m_leftMousePressed = false; UpdateMouseCursor(mousePos, globalPos); - //update(); return; } // in case we adjusted a transition start or end point - if (mActiveGraph->GetIsRepositioningTransitionHead() || mActiveGraph->GetIsRepositioningTransitionTail()) + if (m_activeGraph->GetIsRepositioningTransitionHead() || m_activeGraph->GetIsRepositioningTransitionTail()) { AZ_Assert(actionFilter.m_editConnections, "Expected edit connections being enabled."); - AZ_Assert(!mActiveGraph->IsInReferencedGraph(), "Expected to not be in a referenced graph"); + AZ_Assert(!m_activeGraph->IsInReferencedGraph(), "Expected to not be in a referenced graph"); NodeConnection* connection; QPoint oldStartOffset, oldEndOffset; GraphNode* oldSourceNode; GraphNode* oldTargetNode; - mActiveGraph->GetReplaceTransitionInfo(&connection, &oldStartOffset, &oldEndOffset, &oldSourceNode, &oldTargetNode); - GraphNode* newDropNode = mActiveGraph->FindNode(event->pos()); + m_activeGraph->GetReplaceTransitionInfo(&connection, &oldStartOffset, &oldEndOffset, &oldSourceNode, &oldTargetNode); + GraphNode* newDropNode = m_activeGraph->FindNode(event->pos()); if (newDropNode && newDropNode != oldSourceNode) { - if (mActiveGraph->GetIsRepositioningTransitionHead()) + if (m_activeGraph->GetIsRepositioningTransitionHead()) { ReplaceTransition(connection, oldStartOffset, oldEndOffset, oldSourceNode, oldTargetNode, oldSourceNode, newDropNode); - mActiveGraph->StopReplaceTransitionHead(); + m_activeGraph->StopReplaceTransitionHead(); } - else if (mActiveGraph->GetIsRepositioningTransitionTail() && newDropNode != oldTargetNode) + else if (m_activeGraph->GetIsRepositioningTransitionTail() && newDropNode != oldTargetNode) { ReplaceTransition(connection, oldStartOffset, oldEndOffset, oldSourceNode, oldTargetNode, newDropNode, oldTargetNode); - mActiveGraph->StopReplaceTransitionTail(); + m_activeGraph->StopReplaceTransitionTail(); } } else { ReplaceTransition(connection, oldStartOffset, oldEndOffset, oldSourceNode, oldTargetNode, oldSourceNode, oldTargetNode); - if (mActiveGraph->GetIsRepositioningTransitionHead()) + if (m_activeGraph->GetIsRepositioningTransitionHead()) { - mActiveGraph->StopReplaceTransitionHead(); + m_activeGraph->StopReplaceTransitionHead(); } - else if (mActiveGraph->GetIsRepositioningTransitionTail()) + else if (m_activeGraph->GetIsRepositioningTransitionTail()) { - mActiveGraph->StopReplaceTransitionTail(); + m_activeGraph->StopReplaceTransitionTail(); } } return; } // if we are finished moving, trigger the OnMoveNode callbacks - if (mMoveNode && mouseMoved && + if (m_moveNode && mouseMoved && actionFilter.m_editNodes && - !mActiveGraph->IsInReferencedGraph()) + !m_activeGraph->IsInReferencedGraph()) { OnMoveStart(); bool moveNodeSelected = false; // prevent moving the same node twice - const AZStd::vector selectedNodes = mActiveGraph->GetSelectedGraphNodes(); + const AZStd::vector selectedNodes = m_activeGraph->GetSelectedGraphNodes(); for (GraphNode* currentNode : selectedNodes) { OnMoveNode(currentNode, currentNode->GetRect().topLeft().x(), currentNode->GetRect().topLeft().y()); - if (currentNode == mMoveNode) + if (currentNode == m_moveNode) { moveNodeSelected = true; } } - if (!moveNodeSelected && !mMoveNode) + if (!moveNodeSelected && !m_moveNode) { - OnMoveNode(mMoveNode, mMoveNode->GetRect().topLeft().x(), mMoveNode->GetRect().topLeft().y()); + OnMoveNode(m_moveNode, m_moveNode->GetRect().topLeft().x(), m_moveNode->GetRect().topLeft().y()); } OnMoveEnd(); } - mPanning = false; - mMoveNode = nullptr; + m_panning = false; + m_moveNode = nullptr; UpdateMouseCursor(mousePos, globalPos); // get the node we click on node = UpdateMouseCursor(mousePos, globalPos); - if (mRectSelecting && mouseMoved) + if (m_rectSelecting && mouseMoved) { // calc the selection rect QRect selectRect; CalcSelectRect(selectRect); // select things inside it - if (selectRect.isEmpty() == false && mActiveGraph) + if (selectRect.isEmpty() == false && m_activeGraph) { - selectRect = mActiveGraph->GetTransform().inverted().mapRect(selectRect); + selectRect = m_activeGraph->GetTransform().inverted().mapRect(selectRect); // select nodes when alt is not pressed - if (mAltPressed == false) + if (m_altPressed == false) { - const bool overwriteSelection = (mControlPressed == false); - mActiveGraph->SelectNodesInRect(selectRect, overwriteSelection, mControlPressed); + const bool overwriteSelection = (m_controlPressed == false); + m_activeGraph->SelectNodesInRect(selectRect, overwriteSelection, m_controlPressed); } else // zoom into the selected rect { - mActiveGraph->ZoomOnRect(selectRect, geometry().width(), geometry().height(), true); + m_activeGraph->ZoomOnRect(selectRect, geometry().width(), geometry().height(), true); } } } - mLeftMousePressed = false; - mRectSelecting = false; + m_leftMousePressed = false; + m_rectSelecting = false; } } @@ -1283,7 +1266,7 @@ namespace EMStudio void NodeGraphWidget::mouseDoubleClickEvent(QMouseEvent* event) { // only do things when a graph is active - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return; } @@ -1299,12 +1282,12 @@ namespace EMStudio if (event->button() == Qt::LeftButton) { // check if double clicked on a node - GraphNode* node = mActiveGraph->FindNode(mousePos); + GraphNode* node = m_activeGraph->FindNode(mousePos); if (node == nullptr) { // if we didn't double click on a node zoom in to the clicked area - mActiveGraph->ScrollTo(-LocalToGlobal(mousePos) + geometry().center()); - mActiveGraph->ZoomIn(); + m_activeGraph->ScrollTo(-LocalToGlobal(mousePos) + geometry().center()); + m_activeGraph->ZoomIn(); } } @@ -1312,18 +1295,18 @@ namespace EMStudio if (event->button() == Qt::RightButton) { // check if double clicked on a node - GraphNode* node = mActiveGraph->FindNode(mousePos); + GraphNode* node = m_activeGraph->FindNode(mousePos); if (node == nullptr) { - mActiveGraph->ScrollTo(-LocalToGlobal(mousePos) + geometry().center()); - mActiveGraph->ZoomOut(); + m_activeGraph->ScrollTo(-LocalToGlobal(mousePos) + geometry().center()); + m_activeGraph->ZoomOut(); } } setCursor(Qt::ArrowCursor); // reset flags - mRectSelecting = false; + m_rectSelecting = false; // redraw the viewport //update(); @@ -1334,7 +1317,7 @@ namespace EMStudio void NodeGraphWidget::wheelEvent(QWheelEvent* event) { // only do things when a graph is active - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return; } @@ -1352,12 +1335,12 @@ namespace EMStudio SetMousePos(globalPos); // stop the automated zoom - mActiveGraph->StopAnimatedZoom(); + m_activeGraph->StopAnimatedZoom(); // calculate the new scale value const float scaleDelta = (event->angleDelta().y() / 120.0f) * 0.05f; - float newScale = MCore::Clamp(mActiveGraph->GetScale() + scaleDelta, mActiveGraph->GetLowestScale(), 1.0f); - mActiveGraph->SetScale(newScale); + float newScale = MCore::Clamp(m_activeGraph->GetScale() + scaleDelta, m_activeGraph->GetLowestScale(), 1.0f); + m_activeGraph->SetScale(newScale); // redraw the viewport //update(); @@ -1368,20 +1351,20 @@ namespace EMStudio GraphNode* NodeGraphWidget::UpdateMouseCursor(const QPoint& localMousePos, const QPoint& globalMousePos) { // if there is no active graph - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { setCursor(Qt::ArrowCursor); return nullptr; } - if (mPanning || mMoveNode) + if (m_panning || m_moveNode) { setCursor(Qt::ClosedHandCursor); return nullptr; } // check if we hover above a node - GraphNode* node = mActiveGraph->FindNode(localMousePos); + GraphNode* node = m_activeGraph->FindNode(localMousePos); // check if the node is valid // we test firstly the node to have the visualize cursor correct @@ -1412,10 +1395,10 @@ namespace EMStudio } // check if we're hovering over a port - uint32 portNr; + AZ::u16 portNr; GraphNode* portNode; bool isInputPort; - NodePort* nodePort = mActiveGraph->FindPort(globalMousePos.x(), globalMousePos.y(), &portNode, &portNr, &isInputPort); + NodePort* nodePort = m_activeGraph->FindPort(globalMousePos.x(), globalMousePos.y(), &portNode, &portNr, &isInputPort); if (nodePort) { if ((isInputPort && portNode->GetCreateConFromOutputOnly() == false) || isInputPort == false) @@ -1432,10 +1415,10 @@ namespace EMStudio else // not hovering a node, simply check for ports { // check if we're hovering over a port - uint32 portNr; + AZ::u16 portNr; GraphNode* portNode; bool isInputPort; - NodePort* nodePort = mActiveGraph->FindPort(globalMousePos.x(), globalMousePos.y(), &portNode, &portNr, &isInputPort); + NodePort* nodePort = m_activeGraph->FindPort(globalMousePos.x(), globalMousePos.y(), &portNode, &portNr, &isInputPort); if (nodePort) { if ((isInputPort && portNode->GetCreateConFromOutputOnly() == false) || isInputPort == false) @@ -1462,10 +1445,10 @@ namespace EMStudio // calculate the selection rect void NodeGraphWidget::CalcSelectRect(QRect& outRect) { - const int32 startX = MCore::Min(mSelectStart.x(), mSelectEnd.x()); - const int32 startY = MCore::Min(mSelectStart.y(), mSelectEnd.y()); - const int32 width = abs(mSelectEnd.x() - mSelectStart.x()); - const int32 height = abs(mSelectEnd.y() - mSelectStart.y()); + const int32 startX = MCore::Min(m_selectStart.x(), m_selectEnd.x()); + const int32 startY = MCore::Min(m_selectStart.y(), m_selectEnd.y()); + const int32 width = abs(m_selectEnd.x() - m_selectStart.x()); + const int32 height = abs(m_selectEnd.y() - m_selectStart.y()); outRect = QRect(startX, startY, width, height); } @@ -1478,17 +1461,17 @@ namespace EMStudio { case Qt::Key_Shift: { - mShiftPressed = true; + m_shiftPressed = true; break; } case Qt::Key_Control: { - mControlPressed = true; + m_controlPressed = true; break; } case Qt::Key_Alt: { - mAltPressed = true; + m_altPressed = true; break; } } @@ -1503,17 +1486,17 @@ namespace EMStudio { case Qt::Key_Shift: { - mShiftPressed = false; + m_shiftPressed = false; break; } case Qt::Key_Control: { - mControlPressed = false; + m_controlPressed = false; break; } case Qt::Key_Alt: { - mAltPressed = false; + m_altPressed = false; break; } } @@ -1537,45 +1520,42 @@ namespace EMStudio void NodeGraphWidget::focusOutEvent(QFocusEvent* event) { MCORE_UNUSED(event); - mShiftPressed = false; - mControlPressed = false; - mAltPressed = false; + m_shiftPressed = false; + m_controlPressed = false; + m_altPressed = false; releaseKeyboard(); - if (mActiveGraph && mActiveGraph->GetIsCreatingConnection()) + if (m_activeGraph && m_activeGraph->GetIsCreatingConnection()) { - mActiveGraph->StopCreateConnection(); - mLeftMousePressed = false; + m_activeGraph->StopCreateConnection(); + m_leftMousePressed = false; } } // return the number of selected nodes - uint32 NodeGraphWidget::CalcNumSelectedNodes() const + size_t NodeGraphWidget::CalcNumSelectedNodes() const { - if (mActiveGraph) - { - return mActiveGraph->CalcNumSelectedNodes(); - } - else + if (m_activeGraph) { - return 0; + return m_activeGraph->CalcNumSelectedNodes(); } + return 0; } // is the given connection valid - bool NodeGraphWidget::CheckIfIsCreateConnectionValid(uint32 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) + bool NodeGraphWidget::CheckIfIsCreateConnectionValid(AZ::u16 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) { MCORE_UNUSED(portNr); MCORE_UNUSED(port); - if (mActiveGraph == nullptr) + if (m_activeGraph == nullptr) { return false; } - GraphNode* sourceNode = mActiveGraph->GetCreateConnectionNode(); + GraphNode* sourceNode = m_activeGraph->GetCreateConnectionNode(); GraphNode* targetNode = portNode; // don't allow connection to itself @@ -1585,7 +1565,7 @@ namespace EMStudio } // dont allow to connect an input port to another input port or output port to another output port - if (isInputPort == mActiveGraph->GetCreateConnectionIsInputPort()) + if (isInputPort == m_activeGraph->GetCreateConnectionIsInputPort()) { return false; } @@ -1608,7 +1588,7 @@ namespace EMStudio return true; } - void NodeGraphWidget::OnCreateConnection(uint32 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, uint32 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) + void NodeGraphWidget::OnCreateConnection(AZ::u16 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, AZ::u16 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset) { AZ_UNUSED(sourcePortNr); AZ_UNUSED(sourceNode); 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 111a0f3e3a..f3bea6d5f9 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 @@ -48,18 +48,18 @@ namespace EMStudio NodeGraphWidget(AnimGraphPlugin* plugin, NodeGraph* activeGraph = nullptr, QWidget* parent = nullptr); virtual ~NodeGraphWidget(); - AnimGraphPlugin* GetPlugin() { return mPlugin; } + AnimGraphPlugin* GetPlugin() { return m_plugin; } void SetActiveGraph(NodeGraph* graph); NodeGraph* GetActiveGraph() const; void SetCallback(GraphWidgetCallback* callback); - MCORE_INLINE GraphWidgetCallback* GetCallback() { return mCallback; } - MCORE_INLINE const QPoint& GetMousePos() const { return mMousePos; } - MCORE_INLINE void SetMousePos(const QPoint& pos) { mMousePos = pos; } - MCORE_INLINE void SetShowFPS(bool showFPS) { mShowFPS = showFPS; } + MCORE_INLINE GraphWidgetCallback* GetCallback() { return m_callback; } + MCORE_INLINE const QPoint& GetMousePos() const { return m_mousePos; } + MCORE_INLINE void SetMousePos(const QPoint& pos) { m_mousePos = pos; } + MCORE_INLINE void SetShowFPS(bool showFPS) { m_showFps = showFPS; } - uint32 CalcNumSelectedNodes() const; + size_t CalcNumSelectedNodes() const; QPoint LocalToGlobal(const QPoint& inPoint) const; QPoint GlobalToLocal(const QPoint& inPoint) const; @@ -69,7 +69,7 @@ namespace EMStudio virtual bool PreparePainting() { return true; } - virtual bool CheckIfIsCreateConnectionValid(uint32 portNr, GraphNode* portNode, NodePort* port, bool isInputPort); + virtual bool CheckIfIsCreateConnectionValid(AZ::u16 portNr, GraphNode* portNode, NodePort* port, bool isInputPort); virtual bool CheckIfIsValidTransition(GraphNode* sourceState, GraphNode* targetState); virtual bool CheckIfIsValidTransitionSource(GraphNode* sourceState); virtual bool CreateConnectionMustBeCurved() { return true; } @@ -80,7 +80,7 @@ namespace EMStudio virtual void OnMoveStart() {} virtual void OnMoveNode(GraphNode* node, int32 x, int32 y) { MCORE_UNUSED(node); MCORE_UNUSED(x); MCORE_UNUSED(y); } virtual void OnMoveEnd() {} - virtual void OnCreateConnection(uint32 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, uint32 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset); + virtual void OnCreateConnection(AZ::u16 sourcePortNr, GraphNode* sourceNode, bool sourceIsInputPort, AZ::u16 targetPortNr, GraphNode* targetNode, bool targetIsInputPort, const QPoint& startOffset, const QPoint& endOffset); virtual void OnNodeCollapsed(GraphNode* node, bool isCollapsed) { MCORE_UNUSED(node); MCORE_UNUSED(isCollapsed); } virtual void OnShiftClickedNode(GraphNode* node) { MCORE_UNUSED(node); } virtual void OnVisualizeToggle(GraphNode* node, bool visualizeEnabled) { MCORE_UNUSED(node); MCORE_UNUSED(visualizeEnabled); } @@ -125,35 +125,35 @@ namespace EMStudio GraphNode* UpdateMouseCursor(const QPoint& localMousePos, const QPoint& globalMousePos); protected: - AnimGraphPlugin* mPlugin; - bool mShowFPS; - QPoint mMousePos; - QPoint mMouseLastPos; - QPoint mMouseLastPressPos; - QPoint mSelectStart; - QPoint mSelectEnd; - int mPrevWidth; - int mPrevHeight; - int mCurWidth; - int mCurHeight; - GraphNode* mMoveNode; // the node we're moving - NodeGraph* mActiveGraph = nullptr; - GraphWidgetCallback* mCallback; - QFont mFont; - QFontMetrics* mFontMetrics; - AZ::Debug::Timer mRenderTimer; - AZStd::string mTempString; - AZStd::string mFullActorName; - AZStd::string mActorName; - bool mAllowContextMenu; - bool mLeftMousePressed; - bool mMiddleMousePressed; - bool mRightMousePressed; - bool mPanning; - bool mRectSelecting; - bool mShiftPressed; - bool mControlPressed; - bool mAltPressed; + AnimGraphPlugin* m_plugin; + bool m_showFps; + QPoint m_mousePos; + QPoint m_mouseLastPos; + QPoint m_mouseLastPressPos; + QPoint m_selectStart; + QPoint m_selectEnd; + int m_prevWidth; + int m_prevHeight; + int m_curWidth; + int m_curHeight; + GraphNode* m_moveNode; // the node we're moving + NodeGraph* m_activeGraph = nullptr; + GraphWidgetCallback* m_callback; + QFont m_font; + QFontMetrics* m_fontMetrics; + AZ::Debug::Timer m_renderTimer; + AZStd::string m_tempString; + AZStd::string m_fullActorName; + AZStd::string m_actorName; + bool m_allowContextMenu; + bool m_leftMousePressed; + bool m_middleMousePressed; + bool m_rightMousePressed; + bool m_panning; + bool m_rectSelecting; + bool m_shiftPressed; + bool m_controlPressed; + bool m_altPressed; bool m_borderOverwrite = false; QColor m_borderOverwriteColor; float m_borderOverwriteWidth; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp index 8ab7aa8d72..71eba1205e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp @@ -8,9 +8,11 @@ #include #include +#include #include #include #include +#include "MCore/Source/Config.h" #include "NodeGroupWindow.h" #include "AnimGraphPlugin.h" #include "GraphNode.h" @@ -50,8 +52,8 @@ namespace EMStudio : QDialog(parent) { // Store the values - mAnimGraph = animGraph; - mNodeGroup = nodeGroup; + m_animGraph = animGraph; + m_nodeGroup = nodeGroup; // set the window title setWindowTitle("Rename Node Group"); @@ -66,24 +68,23 @@ namespace EMStudio layout->addWidget(new QLabel("Please enter the new node group name:")); // add the line edit - mLineEdit = new QLineEdit(); - connect(mLineEdit, &QLineEdit::textEdited, this, &NodeGroupRenameWindow::TextEdited); - layout->addWidget(mLineEdit); + m_lineEdit = new QLineEdit(); + connect(m_lineEdit, &QLineEdit::textEdited, this, &NodeGroupRenameWindow::TextEdited); + layout->addWidget(m_lineEdit); // set the current name and select all - mLineEdit->setText(nodeGroup.c_str()); - mLineEdit->selectAll(); + m_lineEdit->setText(nodeGroup.c_str()); + m_lineEdit->selectAll(); // create the button layout QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); + m_okButton = new QPushButton("OK"); QPushButton* cancelButton = new QPushButton("Cancel"); - //buttonLayout->addWidget(mErrorMsg); - buttonLayout->addWidget(mOKButton); + buttonLayout->addWidget(m_okButton); buttonLayout->addWidget(cancelButton); // connect the buttons - connect(mOKButton, &QPushButton::clicked, this, &NodeGroupRenameWindow::Accepted); + connect(m_okButton, &QPushButton::clicked, this, &NodeGroupRenameWindow::Accepted); connect(cancelButton, &QPushButton::clicked, this, &NodeGroupRenameWindow::reject); // set the new layout @@ -97,36 +98,32 @@ namespace EMStudio const AZStd::string convertedNewName = FromQtString(text); if (text.isEmpty()) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); } - else if (mNodeGroup == convertedNewName) + else if (m_nodeGroup == convertedNewName) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } else { // find duplicate name in the anim graph other than this node group - const uint32 numNodeGroups = mAnimGraph->GetNumNodeGroups(); - for (uint32 i = 0; i < numNodeGroups; ++i) + const size_t numNodeGroups = m_animGraph->GetNumNodeGroups(); + for (size_t i = 0; i < numNodeGroups; ++i) { - EMotionFX::AnimGraphNodeGroup* nodeGroup = mAnimGraph->GetNodeGroup(i); + EMotionFX::AnimGraphNodeGroup* nodeGroup = m_animGraph->GetNodeGroup(i); if (nodeGroup->GetNameString() == convertedNewName) { - //mErrorMsg->setVisible(true); - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); return; } } // no duplicate name found - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } } @@ -135,11 +132,11 @@ namespace EMStudio { // Execute the command AZStd::string outResult; - const AZStd::string convertedNewName = FromQtString(mLineEdit->text()); + const AZStd::string convertedNewName = FromQtString(m_lineEdit->text()); auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), - mAnimGraph->GetID(), - /*name = */ mNodeGroup, + m_animGraph->GetID(), + /*name = */ m_nodeGroup, /*visible = */ AZStd::nullopt, /*newName = */ convertedNewName ); @@ -156,27 +153,25 @@ namespace EMStudio NodeGroupWindow::NodeGroupWindow(AnimGraphPlugin* plugin) : QWidget() { - mPlugin = plugin; - mTableWidget = nullptr; - mAddAction = nullptr; - - mWidgetTable.SetMemoryCategory(MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); + m_plugin = plugin; + m_tableWidget = nullptr; + m_addAction = nullptr; // create and register the command callbacks - mCreateCallback = new CommandAnimGraphAddNodeGroupCallback(false); - mRemoveCallback = new CommandAnimGraphRemoveNodeGroupCallback(false); - mAdjustCallback = new CommandAnimGraphAdjustNodeGroupCallback(false); - GetCommandManager()->RegisterCommandCallback("AnimGraphAddNodeGroup", mCreateCallback); - GetCommandManager()->RegisterCommandCallback("AnimGraphRemoveNodeGroup", mRemoveCallback); - GetCommandManager()->RegisterCommandCallback(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName.data(), mAdjustCallback); + m_createCallback = new CommandAnimGraphAddNodeGroupCallback(false); + m_removeCallback = new CommandAnimGraphRemoveNodeGroupCallback(false); + m_adjustCallback = new CommandAnimGraphAdjustNodeGroupCallback(false); + GetCommandManager()->RegisterCommandCallback("AnimGraphAddNodeGroup", m_createCallback); + GetCommandManager()->RegisterCommandCallback("AnimGraphRemoveNodeGroup", m_removeCallback); + GetCommandManager()->RegisterCommandCallback(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName.data(), m_adjustCallback); // add the add button - mAddAction = new QAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Plus.svg"), tr("Add new node group"), this); - connect(mAddAction, &QAction::triggered, this, &NodeGroupWindow::OnAddNodeGroup); + m_addAction = new QAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Plus.svg"), tr("Add new node group"), this); + connect(m_addAction, &QAction::triggered, this, &NodeGroupWindow::OnAddNodeGroup); // add the buttons to add, remove and clear the motions QToolBar* toolBar = new QToolBar(); - toolBar->addAction(mAddAction); + toolBar->addAction(m_addAction); toolBar->addSeparator(); @@ -186,59 +181,57 @@ namespace EMStudio toolBar->addWidget(m_searchWidget); // create the table widget - mTableWidget = new QTableWidget(); - mTableWidget->setAlternatingRowColors(true); - mTableWidget->setCornerButtonEnabled(false); - mTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); - mTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); - mTableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); - connect(mTableWidget, &QTableWidget::itemSelectionChanged, this, &NodeGroupWindow::UpdateInterface); - //connect( mTableWidget, SIGNAL(cellChanged(int, int)), this, SLOT(OnCellChanged(int, int)) ); - //connect( mTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(OnNameEdited(QTableWidgetItem*)) ); + m_tableWidget = new QTableWidget(); + m_tableWidget->setAlternatingRowColors(true); + m_tableWidget->setCornerButtonEnabled(false); + m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); + connect(m_tableWidget, &QTableWidget::itemSelectionChanged, this, &NodeGroupWindow::UpdateInterface); // set the column count - mTableWidget->setColumnCount(3); + m_tableWidget->setColumnCount(3); // set header items for the table QTableWidgetItem* headerItem = new QTableWidgetItem("Vis"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(0, headerItem); + m_tableWidget->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem("Color"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(1, headerItem); + m_tableWidget->setHorizontalHeaderItem(1, headerItem); headerItem = new QTableWidgetItem("Name"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(2, headerItem); + m_tableWidget->setHorizontalHeaderItem(2, headerItem); // set the column params - mTableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); - mTableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed); - mTableWidget->setColumnWidth(0, 25); - mTableWidget->setColumnWidth(1, 41); - mTableWidget->horizontalHeader()->setVisible(false); + m_tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); + m_tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Fixed); + m_tableWidget->setColumnWidth(0, 25); + m_tableWidget->setColumnWidth(1, 41); + m_tableWidget->horizontalHeader()->setVisible(false); - mTableWidget->setShowGrid(false); + m_tableWidget->setShowGrid(false); - AzQtComponents::CheckBox::setVisibilityMode(mTableWidget, true); - connect(mTableWidget, &QTableWidget::itemChanged, this, &NodeGroupWindow::OnItemChanged); + AzQtComponents::CheckBox::setVisibilityMode(m_tableWidget, true); + connect(m_tableWidget, &QTableWidget::itemChanged, this, &NodeGroupWindow::OnItemChanged); // ser the horizontal header params - QHeaderView* horizontalHeader = mTableWidget->horizontalHeader(); + QHeaderView* horizontalHeader = m_tableWidget->horizontalHeader(); horizontalHeader->setSortIndicator(2, Qt::AscendingOrder); horizontalHeader->setStretchLastSection(true); // hide the vertical header - QHeaderView* verticalHeader = mTableWidget->verticalHeader(); + QHeaderView* verticalHeader = m_tableWidget->verticalHeader(); verticalHeader->setVisible(false); // create the vertical layout - mVerticalLayout = new QVBoxLayout(); - mVerticalLayout->setSpacing(2); - mVerticalLayout->setMargin(3); - mVerticalLayout->setAlignment(Qt::AlignTop); - mVerticalLayout->addWidget(toolBar); - mVerticalLayout->addWidget(mTableWidget); + m_verticalLayout = new QVBoxLayout(); + m_verticalLayout->setSpacing(2); + m_verticalLayout->setMargin(3); + m_verticalLayout->setAlignment(Qt::AlignTop); + m_verticalLayout->addWidget(toolBar); + m_verticalLayout->addWidget(m_tableWidget); // set the object name setObjectName("StyledWidget"); @@ -246,7 +239,7 @@ namespace EMStudio // create the fake widget and layout QWidget* fakeWidget = new QWidget(); fakeWidget->setObjectName("StyledWidget"); - fakeWidget->setLayout(mVerticalLayout); + fakeWidget->setLayout(m_verticalLayout); QVBoxLayout* fakeLayout = new QVBoxLayout(); fakeLayout->setMargin(0); @@ -267,12 +260,12 @@ namespace EMStudio NodeGroupWindow::~NodeGroupWindow() { // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mCreateCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustCallback, false); - delete mCreateCallback; - delete mRemoveCallback; - delete mAdjustCallback; + GetCommandManager()->RemoveCommandCallback(m_createCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustCallback, false); + delete m_createCallback; + delete m_removeCallback; + delete m_adjustCallback; } @@ -280,58 +273,58 @@ namespace EMStudio void NodeGroupWindow::Init() { // selected node groups array - MCore::Array selectedNodeGroups; + AZStd::vector selectedNodeGroups; // get the current selection - const QList selectedItems = mTableWidget->selectedItems(); + const QList selectedItems = m_tableWidget->selectedItems(); // get the number of selected items - const uint32 numSelectedItems = selectedItems.count(); + const int numSelectedItems = selectedItems.count(); // filter the items - selectedNodeGroups.Reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + selectedNodeGroups.reserve(numSelectedItems); + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[i]->row(); - const AZStd::string nodeGroupName = FromQtString(mTableWidget->item(rowIndex, 2)->text()); - if (selectedNodeGroups.Find(nodeGroupName) == MCORE_INVALIDINDEX32) + const int rowIndex = selectedItems[i]->row(); + const AZStd::string nodeGroupName = FromQtString(m_tableWidget->item(rowIndex, 2)->text()); + if (AZStd::find(begin(selectedNodeGroups), end(selectedNodeGroups), nodeGroupName) == end(selectedNodeGroups)) { - selectedNodeGroups.Add(nodeGroupName); + selectedNodeGroups.emplace_back(nodeGroupName); } } // clear the lookup array - mWidgetTable.Clear(false); + m_widgetTable.clear(); // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { - mTableWidget->setRowCount(0); + m_tableWidget->setRowCount(0); UpdateInterface(); return; } // disable signals - mTableWidget->blockSignals(true); + m_tableWidget->blockSignals(true); // get the number of node groups - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); + const int numNodeGroups = aznumeric_caster(animGraph->GetNumNodeGroups()); // set table size and add header items - mTableWidget->setRowCount(numNodeGroups); + m_tableWidget->setRowCount(numNodeGroups); // disable the sorting - mTableWidget->setSortingEnabled(false); + m_tableWidget->setSortingEnabled(false); // add each node group - for (uint32 i = 0; i < numNodeGroups; ++i) + for (int i = 0; i < numNodeGroups; ++i) { // get a pointer to the node group EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(i); // check if the node group is selected - const bool itemSelected = selectedNodeGroups.Find(nodeGroup->GetNameString().c_str()) != MCORE_INVALIDINDEX32; + const bool itemSelected = AZStd::find(begin(selectedNodeGroups), end(selectedNodeGroups), nodeGroup->GetNameString()) != end(selectedNodeGroups); // get the color and convert to Qt color AZ::Color color; @@ -343,13 +336,13 @@ namespace EMStudio visibilityCheckboxItem->setData(Qt::CheckStateRole, nodeGroup->GetIsVisible() ? Qt::Checked : Qt::Unchecked); // add the item, it's needed to have the background color + the widget - mTableWidget->setItem(i, 0, visibilityCheckboxItem); + m_tableWidget->setItem(i, 0, visibilityCheckboxItem); // create the color item QTableWidgetItem* colorItem = new QTableWidgetItem(); // add the item, it's needed to have the background color + the widget - mTableWidget->setItem(i, 1, colorItem); + m_tableWidget->setItem(i, 1, colorItem); // create the color widget AzQtComponents::ColorLabel* colorWidget = new AzQtComponents::ColorLabel(color); @@ -365,15 +358,15 @@ namespace EMStudio colorLayout->addWidget(colorWidget); colorLayoutWidget->setLayout(colorLayout); - mWidgetTable.Add(WidgetLookup(colorWidget, i)); + m_widgetTable.emplace_back(WidgetLookup{colorWidget, i}); connect(colorWidget, &AzQtComponents::ColorLabel::colorChanged, this, &NodeGroupWindow::OnColorChanged); // add the color label in the table - mTableWidget->setCellWidget(i, 1, colorLayoutWidget); + m_tableWidget->setCellWidget(i, 1, colorLayoutWidget); // create the node group name label QTableWidgetItem* nameItem = new QTableWidgetItem(nodeGroup->GetName()); - mTableWidget->setItem(i, 2, nameItem); + m_tableWidget->setItem(i, 2, nameItem); // set the item selected visibilityCheckboxItem->setSelected(itemSelected); @@ -381,24 +374,24 @@ namespace EMStudio nameItem->setSelected(itemSelected); // set the row height - mTableWidget->setRowHeight(i, 21); + m_tableWidget->setRowHeight(i, 21); // check if the current item contains the find text if (QString(nodeGroup->GetName()).contains(m_searchWidgetText.c_str(), Qt::CaseInsensitive)) { - mTableWidget->showRow(i); + m_tableWidget->showRow(i); } else { - mTableWidget->hideRow(i); + m_tableWidget->hideRow(i); } } // enable the sorting - mTableWidget->setSortingEnabled(true); + m_tableWidget->setSortingEnabled(true); // enable signals - mTableWidget->blockSignals(false); + m_tableWidget->blockSignals(false); // update the interface UpdateInterface(); @@ -416,7 +409,7 @@ namespace EMStudio void NodeGroupWindow::OnAddNodeGroup() { // add the parameter - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { MCore::LogWarning("NodeGroupWindow::OnAddNodeGroup() - No AnimGraph active!"); @@ -439,12 +432,12 @@ namespace EMStudio { // select the new node group EMotionFX::AnimGraphNodeGroup* lastNodeGroup = animGraph->GetNodeGroup(animGraph->GetNumNodeGroups() - 1); - const int numRows = mTableWidget->rowCount(); + const int numRows = m_tableWidget->rowCount(); for (int i = 0; i < numRows; ++i) { - if (mTableWidget->item(i, 2)->text() == QString(lastNodeGroup->GetName())) + if (m_tableWidget->item(i, 2)->text() == QString(lastNodeGroup->GetName())) { - mTableWidget->selectRow(i); + m_tableWidget->selectRow(i); break; } } @@ -453,34 +446,28 @@ namespace EMStudio // find the index for the given widget - uint32 NodeGroupWindow::FindGroupIndexByWidget(QObject* widget) const + int NodeGroupWindow::FindGroupIndexByWidget(QObject* widget) const { - // for all table entries - const uint32 numWidgets = mWidgetTable.GetLength(); - for (uint32 i = 0; i < numWidgets; ++i) + const auto foundGroup = AZStd::find_if(begin(m_widgetTable), end(m_widgetTable), [widget](const auto& tableEntry) { - if (mWidgetTable[i].mWidget == widget) // this is button we search for - { - return mWidgetTable[i].mGroupIndex; - } - } - - return MCORE_INVALIDINDEX32; + return tableEntry.m_widget == widget; + }); + return foundGroup != end(m_widgetTable) ? foundGroup->m_groupIndex : MCore::InvalidIndexT; } void NodeGroupWindow::OnIsVisible(int state, int row) { // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { return; } // get the node group index by checking the widget lookup table - const uint32 groupIndex = row; - assert(groupIndex != MCORE_INVALIDINDEX32); + const int groupIndex = row; + assert(groupIndex != MCore::InvalidIndexT); // get a pointer to the node group EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(groupIndex); @@ -510,15 +497,15 @@ namespace EMStudio void NodeGroupWindow::OnColorChanged(const AZ::Color& color) { // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { return; } // get the node group index by checking the widget lookup table - const uint32 groupIndex = FindGroupIndexByWidget(sender()); - assert(groupIndex != MCORE_INVALIDINDEX32); + const int groupIndex = FindGroupIndexByWidget(sender()); + assert(groupIndex != MCore::InvalidIndexT); // get a pointer to the node group EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(groupIndex); @@ -550,14 +537,14 @@ namespace EMStudio void NodeGroupWindow::UpdateInterface() { // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { - mAddAction->setEnabled(false); + m_addAction->setEnabled(false); return; } - mAddAction->setEnabled(true); + m_addAction->setEnabled(true); } @@ -565,40 +552,40 @@ namespace EMStudio void NodeGroupWindow::OnRemoveSelectedGroups() { // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { return; } // get the current selection - const QList selectedItems = mTableWidget->selectedItems(); + const QList selectedItems = m_tableWidget->selectedItems(); // get the number of selected items - const uint32 numSelectedItems = selectedItems.count(); - if (numSelectedItems == 0) + const int numSelectedItems = selectedItems.count(); + if (selectedItems.empty()) { return; } // filter the items - MCore::Array rowIndices; - rowIndices.Reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + AZStd::vector rowIndices; + rowIndices.reserve(numSelectedItems); + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[i]->row(); - if (rowIndices.Find(rowIndex) == MCORE_INVALIDINDEX32) + const int rowIndex = selectedItems[i]->row(); + if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { - rowIndices.Add(rowIndex); + rowIndices.emplace_back(rowIndex); } } // sort the rows // it's used to select the next row - rowIndices.Sort(); + AZStd::sort(begin(rowIndices), end(rowIndices)); // get the number of selected rows - const uint32 numRowIndices = rowIndices.GetLength(); + const size_t numRowIndices = rowIndices.size(); // set the command group name AZStd::string commandGroupName; @@ -608,7 +595,7 @@ namespace EMStudio } else { - commandGroupName = AZStd::string::format("Remove %d node groups", numRowIndices); + commandGroupName = AZStd::string::format("Remove %zu node groups", numRowIndices); } // create the command group @@ -616,9 +603,9 @@ namespace EMStudio // Add each command AZStd::string tempString; - for (uint32 i = 0; i < numRowIndices; ++i) + for (size_t i = 0; i < numRowIndices; ++i) { - const AZStd::string nodeGroupName = FromQtString(mTableWidget->item(rowIndices[i], 2)->text()); + const AZStd::string nodeGroupName = FromQtString(m_tableWidget->item(rowIndices[i], 2)->text()); if (i == 0 || i == numRowIndices - 1) { tempString = AZStd::string::format("AnimGraphRemoveNodeGroup -animGraphID %i -name \"%s\"", animGraph->GetID(), nodeGroupName.c_str()); @@ -637,13 +624,13 @@ namespace EMStudio } // selected the next row - if (rowIndices[0] > ((uint32)mTableWidget->rowCount() - 1)) + if (rowIndices[0] > (m_tableWidget->rowCount() - 1)) { - mTableWidget->selectRow(rowIndices[0] - 1); + m_tableWidget->selectRow(rowIndices[0] - 1); } else { - mTableWidget->selectRow(rowIndices[0]); + m_tableWidget->selectRow(rowIndices[0]); } } @@ -652,11 +639,11 @@ namespace EMStudio void NodeGroupWindow::OnRenameSelectedNodeGroup() { // take the item of the name column - const QList selectedItems = mTableWidget->selectedItems(); - QTableWidgetItem* item = mTableWidget->item(selectedItems[0]->row(), 2); + const QList selectedItems = m_tableWidget->selectedItems(); + QTableWidgetItem* item = m_tableWidget->item(selectedItems[0]->row(), 2); // show the rename window - NodeGroupRenameWindow nodeGroupRenameWindow(this, mPlugin->GetActiveAnimGraph(), FromQtString(item->text())); + NodeGroupRenameWindow nodeGroupRenameWindow(this, m_plugin->GetActiveAnimGraph(), FromQtString(item->text())); nodeGroupRenameWindow.exec(); } @@ -664,7 +651,7 @@ namespace EMStudio void NodeGroupWindow::OnClearNodeGroups() { // get the anim graph - EMotionFX::AnimGraph* animGraph = mPlugin->GetActiveAnimGraph(); + EMotionFX::AnimGraph* animGraph = m_plugin->GetActiveAnimGraph(); if (animGraph == nullptr) { return; @@ -721,24 +708,24 @@ namespace EMStudio void NodeGroupWindow::contextMenuEvent(QContextMenuEvent* event) { // get the current selection - const QList selectedItems = mTableWidget->selectedItems(); + const QList selectedItems = m_tableWidget->selectedItems(); // get the number of selected items - const uint32 numSelectedItems = selectedItems.count(); - if (numSelectedItems == 0) + const int numSelectedItems = selectedItems.count(); + if (selectedItems.empty()) { return; } // filter the items - MCore::Array rowIndices; - rowIndices.Reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + AZStd::vector rowIndices; + rowIndices.reserve(numSelectedItems); + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[i]->row(); - if (rowIndices.Find(rowIndex) == MCORE_INVALIDINDEX32) + const int rowIndex = selectedItems[i]->row(); + if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { - rowIndices.Add(rowIndex); + rowIndices.emplace_back(rowIndex); } } @@ -746,14 +733,14 @@ namespace EMStudio QMenu menu(this); // add rename if only one selected - if (rowIndices.GetLength() == 1) + if (rowIndices.size() == 1) { QAction* renameAction = menu.addAction("Rename Selected Node Group"); connect(renameAction, &QAction::triggered, this, &NodeGroupWindow::OnRenameSelectedNodeGroup); } // at least one selected, remove action is possible - if (rowIndices.GetLength() > 0) + if (!rowIndices.empty()) { menu.addSeparator(); QAction* removeAction = menu.addAction("Remove Selected Node Groups"); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.h index 4dd55a733f..69255ce9b4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.h @@ -10,7 +10,7 @@ #if !defined(Q_MOC_RUN) #include -#include +#include #include @@ -54,10 +54,10 @@ namespace EMStudio void Accepted(); private: - EMotionFX::AnimGraph* mAnimGraph; - AZStd::string mNodeGroup; - QLineEdit* mLineEdit; - QPushButton* mOKButton; + EMotionFX::AnimGraph* m_animGraph; + AZStd::string m_nodeGroup; + QLineEdit* m_lineEdit; + QPushButton* m_okButton; }; class NodeGroupWindow @@ -91,36 +91,29 @@ namespace EMStudio void contextMenuEvent(QContextMenuEvent* event) override; - uint32 FindGroupIndexByWidget(QObject* widget) const; + int FindGroupIndexByWidget(QObject* widget) const; //bool ValidateName(EMotionFX::AnimGraphNodeGroup* nodeGroup, const char* newName) const; MCORE_DEFINECOMMANDCALLBACK(CommandAnimGraphAddNodeGroupCallback); MCORE_DEFINECOMMANDCALLBACK(CommandAnimGraphAdjustNodeGroupCallback); MCORE_DEFINECOMMANDCALLBACK(CommandAnimGraphRemoveNodeGroupCallback); - CommandAnimGraphAddNodeGroupCallback* mCreateCallback; - CommandAnimGraphAdjustNodeGroupCallback* mAdjustCallback; - CommandAnimGraphRemoveNodeGroupCallback* mRemoveCallback; + CommandAnimGraphAddNodeGroupCallback* m_createCallback; + CommandAnimGraphAdjustNodeGroupCallback* m_adjustCallback; + CommandAnimGraphRemoveNodeGroupCallback* m_removeCallback; struct WidgetLookup { - MCORE_MEMORYOBJECTCATEGORY(NodeGroupWindow::WidgetLookup, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - QObject* mWidget; - uint32 mGroupIndex; - - WidgetLookup(QObject* widget, uint32 index) - { - mWidget = widget; - mGroupIndex = index; - } + QObject* m_widget; + int m_groupIndex; }; - AnimGraphPlugin* mPlugin; - QTableWidget* mTableWidget; - QVBoxLayout* mVerticalLayout; - QAction* mAddAction; + AnimGraphPlugin* m_plugin; + QTableWidget* m_tableWidget; + QVBoxLayout* m_verticalLayout; + QAction* m_addAction; AzQtComponents::FilteredSearchWidget* m_searchWidget; AZStd::string m_searchWidgetText; - MCore::Array mWidgetTable; + AZStd::vector m_widgetTable; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.cpp index a0ee45be0b..bd55ce2905 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.cpp @@ -287,23 +287,23 @@ namespace EMStudio } NodePaletteWidget::EventHandler::EventHandler(NodePaletteWidget* widget) - : mWidget(widget) + : m_widget(widget) {} void NodePaletteWidget::EventHandler::OnCreatedNode(EMotionFX::AnimGraph* animGraph, EMotionFX::AnimGraphNode* node) { - if (mWidget->mNode && node->GetParentNode() == mWidget->mNode) + if (m_widget->m_node && node->GetParentNode() == m_widget->m_node) { - mWidget->Init(animGraph, mWidget->mNode); + m_widget->Init(animGraph, m_widget->m_node); } } void NodePaletteWidget::EventHandler::OnRemovedChildNode(EMotionFX::AnimGraph* animGraph, EMotionFX::AnimGraphNode* parentNode) { - if (mWidget->mNode && parentNode && parentNode == mWidget->mNode) + if (m_widget->m_node && parentNode && parentNode == m_widget->m_node) { - mWidget->Init(animGraph, mWidget->mNode); + m_widget->Init(animGraph, m_widget->m_node); } } @@ -311,52 +311,52 @@ namespace EMStudio // constructor NodePaletteWidget::NodePaletteWidget(AnimGraphPlugin* plugin) : QWidget() - , mPlugin(plugin) - , mModel(new NodePaletteModel(plugin, this)) + , m_plugin(plugin) + , m_model(new NodePaletteModel(plugin, this)) { - mNode = nullptr; + m_node = nullptr; // create the default layout - mLayout = new QVBoxLayout(); - mLayout->setMargin(0); - mLayout->setSpacing(0); + m_layout = new QVBoxLayout(); + m_layout->setMargin(0); + m_layout->setSpacing(0); // create the initial text - mInitialText = new QLabel("Create and activate a Anim Graph first.
Then drag and drop items from the
palette into the Anim Graph window.
"); - mInitialText->setAlignment(Qt::AlignCenter); - mInitialText->setTextFormat(Qt::RichText); - mInitialText->setMaximumSize(10000, 10000); - mInitialText->setMargin(0); - mInitialText->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); + m_initialText = new QLabel("Create and activate a Anim Graph first.
Then drag and drop items from the
palette into the Anim Graph window.
"); + m_initialText->setAlignment(Qt::AlignCenter); + m_initialText->setTextFormat(Qt::RichText); + m_initialText->setMaximumSize(10000, 10000); + m_initialText->setMargin(0); + m_initialText->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum); // add the initial text in the layout - mLayout->addWidget(mInitialText); + m_layout->addWidget(m_initialText); // create the tree view - mTreeView = new QTreeView(this); - mTreeView->setHeaderHidden(true); - mTreeView->setModel(mModel); - mTreeView->setDragDropMode(QAbstractItemView::DragOnly); + m_treeView = new QTreeView(this); + m_treeView->setHeaderHidden(true); + m_treeView->setModel(m_model); + m_treeView->setDragDropMode(QAbstractItemView::DragOnly); // add the tree view in the layout - mLayout->addWidget(mTreeView); + m_layout->addWidget(m_treeView); // set the default layout - setLayout(mLayout); + setLayout(m_layout); // register the event handler - mEventHandler = aznew NodePaletteWidget::EventHandler(this); - EMotionFX::GetEventManager().AddEventHandler(mEventHandler); + m_eventHandler = aznew NodePaletteWidget::EventHandler(this); + EMotionFX::GetEventManager().AddEventHandler(m_eventHandler); - connect(&mPlugin->GetAnimGraphModel(), &AnimGraphModel::FocusChanged, this, &NodePaletteWidget::OnFocusChanged); + connect(&m_plugin->GetAnimGraphModel(), &AnimGraphModel::FocusChanged, this, &NodePaletteWidget::OnFocusChanged); } // destructor NodePaletteWidget::~NodePaletteWidget() { - EMotionFX::GetEventManager().RemoveEventHandler(mEventHandler); - delete mEventHandler; + EMotionFX::GetEventManager().RemoveEventHandler(m_eventHandler); + delete m_eventHandler; } @@ -364,33 +364,33 @@ namespace EMStudio void NodePaletteWidget::Init(EMotionFX::AnimGraph* animGraph, EMotionFX::AnimGraphNode* node) { // set the node - mNode = node; + m_node = node; // check if the anim graph is not valid // on this case we show a message to say no one anim graph is activated if (animGraph == nullptr) { // set the layout params - mLayout->setMargin(0); - mLayout->setSpacing(0); + m_layout->setMargin(0); + m_layout->setSpacing(0); // set the widget visible or not - mInitialText->setVisible(true); - mTreeView->setVisible(false); + m_initialText->setVisible(true); + m_treeView->setVisible(false); } else { // set the layout params - mLayout->setMargin(2); - mLayout->setSpacing(2); + m_layout->setMargin(2); + m_layout->setSpacing(2); // set the widget visible or not - mInitialText->setVisible(false); - mTreeView->setVisible(true); + m_initialText->setVisible(false); + m_treeView->setVisible(true); } SaveExpandStates(); - mModel->setNode(mNode); + m_model->setNode(m_node); RestoreExpandStates(); } @@ -398,16 +398,16 @@ namespace EMStudio void NodePaletteWidget::SaveExpandStates() { m_expandedCatagory.clear(); - const auto& catagoryNames = mModel->GetCategoryNames(); + const auto& catagoryNames = m_model->GetCategoryNames(); // Save the expand state. for (const auto& categoryName : catagoryNames) { const QString& str = categoryName.second; - const QModelIndexList items = mModel->match(mModel->index(0, 0), Qt::DisplayRole, QVariant::fromValue(str)); + const QModelIndexList items = m_model->match(m_model->index(0, 0), Qt::DisplayRole, QVariant::fromValue(str)); if (!items.isEmpty()) { - if (mTreeView->isExpanded(items.first())) + if (m_treeView->isExpanded(items.first())) { m_expandedCatagory.emplace(categoryName.first); } @@ -418,7 +418,7 @@ namespace EMStudio void NodePaletteWidget::RestoreExpandStates() { - const auto& catagoryNames = mModel->GetCategoryNames(); + const auto& catagoryNames = m_model->GetCategoryNames(); // Restore the expand state. for (const auto& categoryName : catagoryNames) @@ -430,10 +430,10 @@ namespace EMStudio } const QString& str = categoryName.second; - const QModelIndexList items = mModel->match(mModel->index(0, 0), Qt::DisplayRole, QVariant::fromValue(str)); + const QModelIndexList items = m_model->match(m_model->index(0, 0), Qt::DisplayRole, QVariant::fromValue(str)); if (!items.isEmpty()) { - mTreeView->setExpanded(items.first(), true); + m_treeView->setExpanded(items.first(), true); } } m_expandedCatagory.clear(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.h index be6d17bc12..2ca1a85f74 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodePaletteWidget.h @@ -48,7 +48,7 @@ namespace EMStudio void OnRemovedChildNode(EMotionFX::AnimGraph* animGraph, EMotionFX::AnimGraphNode* parentNode) override; private: - NodePaletteWidget* mWidget; + NodePaletteWidget* m_widget; }; NodePaletteWidget(AnimGraphPlugin* plugin); @@ -65,13 +65,13 @@ namespace EMStudio void SaveExpandStates(); void RestoreExpandStates(); - AnimGraphPlugin* mPlugin; - NodePaletteModel* mModel; - QTreeView* mTreeView; - EMotionFX::AnimGraphNode* mNode; - EventHandler* mEventHandler; - QVBoxLayout* mLayout; - QLabel* mInitialText; + AnimGraphPlugin* m_plugin; + NodePaletteModel* m_model; + QTreeView* m_treeView; + EMotionFX::AnimGraphNode* m_node; + EventHandler* m_eventHandler; + QVBoxLayout* m_layout; + QLabel* m_initialText; // Cache the expanded states. AZStd::unordered_set m_expandedCatagory; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.cpp index f93e72821c..eb4696ef23 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.cpp @@ -25,7 +25,7 @@ namespace EMStudio { - int ParameterCreateEditDialog::m_parameterEditorMinWidth = 300; + int ParameterCreateEditDialog::s_parameterEditorMinWidth = 300; ParameterCreateEditDialog::ParameterCreateEditDialog(AnimGraphPlugin* plugin, QWidget* parent, const EMotionFX::Parameter* editParameter) : QDialog(parent) @@ -74,7 +74,7 @@ namespace EMStudio m_parameterEditorWidget->setSizePolicy(QSizePolicy::Policy::MinimumExpanding, QSizePolicy::Policy::MinimumExpanding); m_parameterEditorWidget->SetSizeHintOffset(QSize(0, 0)); m_parameterEditorWidget->SetLeafIndentation(0); - m_parameterEditorWidget->setMinimumWidth(m_parameterEditorMinWidth); + m_parameterEditorWidget->setMinimumWidth(s_parameterEditorMinWidth); mainLayout->addWidget(m_parameterEditorWidget); // Add the preview information diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.h index 75b0777269..941ee53727 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterCreateEditDialog.h @@ -78,6 +78,6 @@ namespace EMStudio AZStd::unique_ptr m_parameter; AZStd::string m_originalName; - static int m_parameterEditorMinWidth; + static int s_parameterEditorMinWidth; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterEditor/ColorParameterEditor.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterEditor/ColorParameterEditor.cpp index 0302bb66ee..047de95f15 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterEditor/ColorParameterEditor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterEditor/ColorParameterEditor.cpp @@ -63,7 +63,7 @@ namespace EMStudio if (!m_attributes.empty()) { MCore::AttributeColor* attribute = static_cast(m_attributes[0]); - m_currentValue = AZ::Color(attribute->GetValue().r, attribute->GetValue().g, attribute->GetValue().b, attribute->GetValue().a); + m_currentValue = AZ::Color(attribute->GetValue().m_r, attribute->GetValue().m_g, attribute->GetValue().m_b, attribute->GetValue().m_a); } else { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.cpp index 6b17148fe4..51a47a47bf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.cpp @@ -24,32 +24,32 @@ namespace EMStudio ParameterSelectionWindow::ParameterSelectionWindow(QWidget* parent, bool useSingleSelection) : QDialog(parent) { - mAccepted = false; + m_accepted = false; setWindowTitle("Parameter Selection Window"); QVBoxLayout* layout = new QVBoxLayout(); - mParameterWidget = new ParameterWidget(this, useSingleSelection); + m_parameterWidget = new ParameterWidget(this, useSingleSelection); // create the ok and cancel buttons QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mCancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); + m_okButton = new QPushButton("OK"); + m_cancelButton = new QPushButton("Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); - layout->addWidget(mParameterWidget); + layout->addWidget(m_parameterWidget); layout->addLayout(buttonLayout); setLayout(layout); - connect(mOKButton, &QPushButton::clicked, this, &ParameterSelectionWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &ParameterSelectionWindow::reject); + connect(m_okButton, &QPushButton::clicked, this, &ParameterSelectionWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &ParameterSelectionWindow::reject); connect(this, &ParameterSelectionWindow::accepted, this, &ParameterSelectionWindow::OnAccept); - connect(mParameterWidget, &ParameterWidget::OnDoubleClicked, this, &ParameterSelectionWindow::OnDoubleClicked); + connect(m_parameterWidget, &ParameterWidget::OnDoubleClicked, this, &ParameterSelectionWindow::OnDoubleClicked); // set the selection mode - mParameterWidget->SetSelectionMode(useSingleSelection); - mUseSingleSelection = useSingleSelection; + m_parameterWidget->SetSelectionMode(useSingleSelection); + m_useSingleSelection = useSingleSelection; } @@ -67,7 +67,7 @@ namespace EMStudio void ParameterSelectionWindow::OnAccept() { - mParameterWidget->FireSelectionDoneSignal(); + m_parameterWidget->FireSelectionDoneSignal(); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.h index 6e0bad9d10..cb8e28c476 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterSelectionWindow.h @@ -26,9 +26,9 @@ namespace EMStudio * 2. Use the itemSelectionChanged() signal of the GetNodeHierarchyWidget()->GetTreeWidget() to detect when the user adjusts the selection in the node hierarchy widget. * 3. Use the OnSelectionDone() in the GetNodeHierarchyWidget() to detect when the user finished selecting and pressed the OK button. * Example: - * connect( mParameterSelectionWindow, SIGNAL(rejected()), this, SLOT(UserWantsToCancel_1()) ); - * connect( mParameterSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged_2()) ); - * connect( mParameterSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(MCore::Array)), this, SLOT(FinishedSelectionAndPressedOK_3(MCore::Array)) ); + * connect( m_parameterSelectionWindow, SIGNAL(rejected()), this, SLOT(UserWantsToCancel_1()) ); + * connect( m_parameterSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), SIGNAL(itemSelectionChanged()), this, SLOT(SelectionChanged_2()) ); + * connect( m_parameterSelectionWindow->GetNodeHierarchyWidget(), SIGNAL(OnSelectionDone(AZStd::vector)), this, SLOT(FinishedSelectionAndPressedOK_3(AZStd::vector)) ); */ class ParameterSelectionWindow : public QDialog @@ -40,18 +40,18 @@ namespace EMStudio ParameterSelectionWindow(QWidget* parent, bool useSingleSelection); virtual ~ParameterSelectionWindow(); - MCORE_INLINE ParameterWidget* GetParameterWidget() { return mParameterWidget; } - void Update(EMotionFX::AnimGraph* animGraph, const AZStd::vector& selectedParameters) { mParameterWidget->Update(animGraph, selectedParameters); } + MCORE_INLINE ParameterWidget* GetParameterWidget() { return m_parameterWidget; } + void Update(EMotionFX::AnimGraph* animGraph, const AZStd::vector& selectedParameters) { m_parameterWidget->Update(animGraph, selectedParameters); } public slots: void OnAccept(); void OnDoubleClicked(const AZStd::string& item); private: - ParameterWidget* mParameterWidget; - QPushButton* mOKButton; - QPushButton* mCancelButton; - bool mUseSingleSelection; - bool mAccepted; + ParameterWidget* m_parameterWidget; + QPushButton* m_okButton; + QPushButton* m_cancelButton; + bool m_useSingleSelection; + bool m_accepted; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.cpp index 87f9782c95..3c96367d1f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.cpp @@ -36,32 +36,32 @@ namespace EMStudio layout->setMargin(0); // create the tree widget - mTreeWidget = new QTreeWidget(); + m_treeWidget = new QTreeWidget(); // create header items - mTreeWidget->setColumnCount(1); + m_treeWidget->setColumnCount(1); QStringList headerList; headerList.append("Name"); - mTreeWidget->setHeaderLabels(headerList); + m_treeWidget->setHeaderLabels(headerList); // set optical stuff for the tree - mTreeWidget->setSortingEnabled(false); - mTreeWidget->setSelectionMode(QAbstractItemView::SingleSelection); - mTreeWidget->setMinimumWidth(620); - mTreeWidget->setMinimumHeight(500); - mTreeWidget->setAlternatingRowColors(true); - mTreeWidget->setExpandsOnDoubleClick(true); - mTreeWidget->setAnimated(true); + m_treeWidget->setSortingEnabled(false); + m_treeWidget->setSelectionMode(QAbstractItemView::SingleSelection); + m_treeWidget->setMinimumWidth(620); + m_treeWidget->setMinimumHeight(500); + m_treeWidget->setAlternatingRowColors(true); + m_treeWidget->setExpandsOnDoubleClick(true); + m_treeWidget->setAnimated(true); // disable the move of section to have column order fixed - mTreeWidget->header()->setSectionsMovable(false); + m_treeWidget->header()->setSectionsMovable(false); layout->addWidget(m_searchWidget); - layout->addWidget(mTreeWidget); + layout->addWidget(m_treeWidget); setLayout(layout); - connect(mTreeWidget, &QTreeWidget::itemSelectionChanged, this, &ParameterWidget::UpdateSelection); - connect(mTreeWidget, &QTreeWidget::itemDoubleClicked, this, &ParameterWidget::ItemDoubleClicked); + connect(m_treeWidget, &QTreeWidget::itemSelectionChanged, this, &ParameterWidget::UpdateSelection); + connect(m_treeWidget, &QTreeWidget::itemDoubleClicked, this, &ParameterWidget::ItemDoubleClicked); // set the selection mode SetSelectionMode(useSingleSelection); @@ -75,9 +75,9 @@ namespace EMStudio void ParameterWidget::Update(EMotionFX::AnimGraph* animGraph, const AZStd::vector& selectedParameters) { - mAnimGraph = animGraph; - mSelectedParameters = selectedParameters; - mOldSelectedParameters = selectedParameters; + m_animGraph = animGraph; + m_selectedParameters = selectedParameters; + m_oldSelectedParameters = selectedParameters; Update(); } @@ -102,15 +102,15 @@ namespace EMStudio } else { - item = new QTreeWidgetItem(mTreeWidget); - mTreeWidget->addTopLevelItem(item); + item = new QTreeWidgetItem(m_treeWidget); + m_treeWidget->addTopLevelItem(item); } item->setText(0, parameter->GetName().c_str()); item->setExpanded(true); // check if the given parameter is selected - if (AZStd::find(mOldSelectedParameters.begin(), mOldSelectedParameters.end(), parameter->GetName()) != mOldSelectedParameters.end()) + if (AZStd::find(m_oldSelectedParameters.begin(), m_oldSelectedParameters.end(), parameter->GetName()) != m_oldSelectedParameters.end()) { item->setSelected(true); } @@ -120,39 +120,39 @@ namespace EMStudio void ParameterWidget::Update() { - mTreeWidget->clear(); - mTreeWidget->blockSignals(true); + m_treeWidget->clear(); + m_treeWidget->blockSignals(true); // add all parameters that belong to no group parameter - const EMotionFX::ValueParameterVector childValueParameters = mAnimGraph->GetChildValueParameters(); + const EMotionFX::ValueParameterVector childValueParameters = m_animGraph->GetChildValueParameters(); for (const EMotionFX::ValueParameter* parameter : childValueParameters) { - AddParameterToInterface(mAnimGraph, parameter, nullptr); + AddParameterToInterface(m_animGraph, parameter, nullptr); } // get all group parameters and iterate through them AZStd::string tempString; - const EMotionFX::GroupParameterVector groupParameters = mAnimGraph->RecursivelyGetGroupParameters(); + const EMotionFX::GroupParameterVector groupParameters = m_animGraph->RecursivelyGetGroupParameters(); for (const EMotionFX::GroupParameter* groupParameter : groupParameters) { // add the group item to the tree widget - QTreeWidgetItem* groupItem = new QTreeWidgetItem(mTreeWidget); + QTreeWidgetItem* groupItem = new QTreeWidgetItem(m_treeWidget); groupItem->setText(0, groupParameter->GetName().c_str()); groupItem->setExpanded(true); const EMotionFX::ValueParameterVector childValueParameters2 = groupParameter->GetChildValueParameters(); tempString = AZStd::string::format("%zu Parameters", childValueParameters2.size()); groupItem->setToolTip(1, tempString.c_str()); - mTreeWidget->addTopLevelItem(groupItem); + m_treeWidget->addTopLevelItem(groupItem); // add all parameters that belong to the given group bool groupSelected = !childValueParameters2.empty(); for (const EMotionFX::ValueParameter* valueParameter : childValueParameters2) { - AddParameterToInterface(mAnimGraph, valueParameter, groupItem); + AddParameterToInterface(m_animGraph, valueParameter, groupItem); // check if the given parameter is selected - if (groupSelected && AZStd::find(mOldSelectedParameters.begin(), mOldSelectedParameters.end(), valueParameter->GetName()) == mOldSelectedParameters.end()) + if (groupSelected && AZStd::find(m_oldSelectedParameters.begin(), m_oldSelectedParameters.end(), valueParameter->GetName()) == m_oldSelectedParameters.end()) { groupSelected = false; } @@ -161,18 +161,18 @@ namespace EMStudio groupItem->setSelected(groupSelected); } - mTreeWidget->blockSignals(false); + m_treeWidget->blockSignals(false); UpdateSelection(); } void ParameterWidget::UpdateSelection() { - QList selectedItems = mTreeWidget->selectedItems(); + QList selectedItems = m_treeWidget->selectedItems(); - mSelectedParameters.clear(); + m_selectedParameters.clear(); const uint32 numSelectedItems = selectedItems.count(); - mSelectedParameters.reserve(numSelectedItems); + m_selectedParameters.reserve(numSelectedItems); // Iterate through the selected items in the tree widget. AZStd::string itemName; @@ -183,7 +183,7 @@ namespace EMStudio // Get the parameter by name. // Skip elements that we can't find as they also shouldn't be selectable. - const EMotionFX::Parameter* parameter = mAnimGraph->FindParameterByName(itemName); + const EMotionFX::Parameter* parameter = m_animGraph->FindParameterByName(itemName); if (!parameter) { continue; @@ -192,9 +192,9 @@ namespace EMStudio // check if the selected item is a parameter if (azrtti_typeid(parameter) != azrtti_typeid()) { - if (AZStd::find(mSelectedParameters.begin(), mSelectedParameters.end(), itemName) == mSelectedParameters.end()) + if (AZStd::find(m_selectedParameters.begin(), m_selectedParameters.end(), itemName) == m_selectedParameters.end()) { - mSelectedParameters.emplace_back(itemName); + m_selectedParameters.emplace_back(itemName); } } // selected item is a group @@ -205,9 +205,9 @@ namespace EMStudio const EMotionFX::ValueParameterVector valueParameters = groupParameter->RecursivelyGetChildValueParameters(); for (const EMotionFX::ValueParameter* valueParameter : valueParameters) { - if (AZStd::find(mSelectedParameters.begin(), mSelectedParameters.end(), valueParameter->GetName()) == mSelectedParameters.end()) + if (AZStd::find(m_selectedParameters.begin(), m_selectedParameters.end(), valueParameter->GetName()) == m_selectedParameters.end()) { - mSelectedParameters.emplace_back(valueParameter->GetName()); + m_selectedParameters.emplace_back(valueParameter->GetName()); } } } @@ -219,14 +219,14 @@ namespace EMStudio { if (useSingleSelection) { - mTreeWidget->setSelectionMode(QAbstractItemView::SingleSelection); + m_treeWidget->setSelectionMode(QAbstractItemView::SingleSelection); } else { - mTreeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); } - mUseSingleSelection = useSingleSelection; + m_useSingleSelection = useSingleSelection; } void ParameterWidget::SetFilterTypes(const AZStd::vector& filterTypes) @@ -240,9 +240,9 @@ namespace EMStudio MCORE_UNUSED(column); UpdateSelection(); - if (!mSelectedParameters.empty()) + if (!m_selectedParameters.empty()) { - emit OnDoubleClicked(mSelectedParameters[0]); + emit OnDoubleClicked(m_selectedParameters[0]); } } @@ -257,7 +257,7 @@ namespace EMStudio void ParameterWidget::FireSelectionDoneSignal() { - emit OnSelectionDone(mSelectedParameters); + emit OnSelectionDone(m_selectedParameters); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.h index ed2bd1c4e9..9f0601243b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWidget.h @@ -45,11 +45,11 @@ namespace EMStudio void SetFilterTypes(const AZStd::vector& filterTypes); void Update(EMotionFX::AnimGraph* animGraph, const AZStd::vector& selectedParameters); void FireSelectionDoneSignal(); - MCORE_INLINE QTreeWidget* GetTreeWidget() { return mTreeWidget; } + MCORE_INLINE QTreeWidget* GetTreeWidget() { return m_treeWidget; } MCORE_INLINE AzQtComponents::FilteredSearchWidget* GetSearchWidget() { return m_searchWidget; } // this calls UpdateSelection() and then returns the member array containing the selected items - AZStd::vector& GetSelectedParameters() { UpdateSelection(); return mSelectedParameters; } + AZStd::vector& GetSelectedParameters() { UpdateSelection(); return m_selectedParameters; } signals: void OnSelectionDone(const AZStd::vector& selectedItems); @@ -65,13 +65,13 @@ namespace EMStudio private: void AddParameterToInterface(EMotionFX::AnimGraph* animGraph, const EMotionFX::Parameter* parameter, QTreeWidgetItem* groupParameterItem); - EMotionFX::AnimGraph* mAnimGraph; - QTreeWidget* mTreeWidget; + EMotionFX::AnimGraph* m_animGraph; + QTreeWidget* m_treeWidget; AzQtComponents::FilteredSearchWidget* m_searchWidget; AZStd::string m_searchWidgetText; AZStd::vector m_filterTypes; - AZStd::vector mSelectedParameters; - AZStd::vector mOldSelectedParameters; - bool mUseSingleSelection; + AZStd::vector m_selectedParameters; + AZStd::vector m_oldSelectedParameters; + bool m_useSingleSelection; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp index f470b061c5..c93d358c07 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.cpp @@ -47,7 +47,7 @@ namespace EMStudio { - int ParameterWindow::m_contextMenuWidth = 100; + int ParameterWindow::s_contextMenuWidth = 100; // constructor ParameterCreateRenameWindow::ParameterCreateRenameWindow(const char* windowTitle, const char* topText, const char* defaultName, const char* oldName, const AZStd::vector& invalidNames, QWidget* parent) @@ -56,8 +56,8 @@ namespace EMStudio setObjectName("EMFX.ParameterCreateRenameDialog"); // store values - mOldName = oldName; - mInvalidNames = invalidNames; + m_oldName = oldName; + m_invalidNames = invalidNames; // update title of the about dialog setWindowTitle(windowTitle); @@ -75,27 +75,27 @@ namespace EMStudio } // add the line edit - mLineEdit = new QLineEdit(defaultName); - connect(mLineEdit, &QLineEdit::textChanged, this, &ParameterCreateRenameWindow::NameEditChanged); - mLineEdit->selectAll(); + m_lineEdit = new QLineEdit(defaultName); + connect(m_lineEdit, &QLineEdit::textChanged, this, &ParameterCreateRenameWindow::NameEditChanged); + m_lineEdit->selectAll(); // create the button layout QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); - mCancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); - buttonLayout->addWidget(mCancelButton); + m_okButton = new QPushButton("OK"); + m_cancelButton = new QPushButton("Cancel"); + buttonLayout->addWidget(m_okButton); + buttonLayout->addWidget(m_cancelButton); // set the layout - layout->addWidget(mLineEdit); + layout->addWidget(m_lineEdit); layout->addLayout(buttonLayout); setLayout(layout); // connect the buttons - connect(mOKButton, &QPushButton::clicked, this, &ParameterCreateRenameWindow::accept); - connect(mCancelButton, &QPushButton::clicked, this, &ParameterCreateRenameWindow::reject); + connect(m_okButton, &QPushButton::clicked, this, &ParameterCreateRenameWindow::accept); + connect(m_cancelButton, &QPushButton::clicked, this, &ParameterCreateRenameWindow::reject); - mOKButton->setDefault(true); + m_okButton->setDefault(true); } // check for duplicate names upon editing @@ -104,44 +104,44 @@ namespace EMStudio const AZStd::string convertedNewName = text.toUtf8().data(); if (text.isEmpty()) { - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); } - else if (mOldName == convertedNewName) + else if (m_oldName == convertedNewName) { - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } else { // Check if the name has invalid characters. if (!EMotionFX::Parameter::IsNameValid(convertedNewName, nullptr)) { - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); return; } // Is there a parameter with the given name already? - if (AZStd::find(mInvalidNames.begin(), mInvalidNames.end(), convertedNewName) != mInvalidNames.end()) + if (AZStd::find(m_invalidNames.begin(), m_invalidNames.end(), convertedNewName) != m_invalidNames.end()) { - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); return; } // no duplicate name found - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } } ParameterWindow::ParameterWindow(AnimGraphPlugin* plugin) : QWidget() { - mPlugin = plugin; - mEnsureVisibility = false; - mLockSelection = false; + m_plugin = plugin; + m_ensureVisibility = false; + m_lockSelection = false; // add the add button QToolBar* toolBar = new QToolBar(this); @@ -182,55 +182,55 @@ namespace EMStudio toolBar->addWidget(m_searchWidget); // create the parameter tree widget - mTreeWidget = new ParameterWindowTreeWidget(); - mTreeWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mTreeWidget->setObjectName("AnimGraphParamWindow"); - mTreeWidget->header()->setVisible(false); + m_treeWidget = new ParameterWindowTreeWidget(); + m_treeWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_treeWidget->setObjectName("AnimGraphParamWindow"); + m_treeWidget->header()->setVisible(false); // adjust selection mode and enable some other helpful things - mTreeWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTreeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); - mTreeWidget->setExpandsOnDoubleClick(true); - mTreeWidget->setColumnCount(3); - mTreeWidget->setUniformRowHeights(true); - mTreeWidget->setIndentation(10); - mTreeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); - mTreeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - mTreeWidget->header()->setSectionResizeMode(2, QHeaderView::Stretch); + m_treeWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_treeWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_treeWidget->setExpandsOnDoubleClick(true); + m_treeWidget->setColumnCount(3); + m_treeWidget->setUniformRowHeights(true); + m_treeWidget->setIndentation(10); + m_treeWidget->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); + m_treeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); + m_treeWidget->header()->setSectionResizeMode(2, QHeaderView::Stretch); // enable drag and drop - mTreeWidget->setDragEnabled(true); - mTreeWidget->setDragDropMode(QAbstractItemView::InternalMove); + m_treeWidget->setDragEnabled(true); + m_treeWidget->setDragDropMode(QAbstractItemView::InternalMove); // connect the tree widget - connect(mTreeWidget, &QTreeWidget::itemSelectionChanged, this, &ParameterWindow::OnSelectionChanged); - connect(mTreeWidget, &QTreeWidget::itemCollapsed, this, &ParameterWindow::OnGroupCollapsed); - connect(mTreeWidget, &QTreeWidget::itemExpanded, this, &ParameterWindow::OnGroupExpanded); - connect(mTreeWidget, &ParameterWindowTreeWidget::ParameterMoved, this, &ParameterWindow::OnMoveParameterTo); - connect(mTreeWidget, &ParameterWindowTreeWidget::DragEnded, this, [this]() + connect(m_treeWidget, &QTreeWidget::itemSelectionChanged, this, &ParameterWindow::OnSelectionChanged); + connect(m_treeWidget, &QTreeWidget::itemCollapsed, this, &ParameterWindow::OnGroupCollapsed); + connect(m_treeWidget, &QTreeWidget::itemExpanded, this, &ParameterWindow::OnGroupExpanded); + connect(m_treeWidget, &ParameterWindowTreeWidget::ParameterMoved, this, &ParameterWindow::OnMoveParameterTo); + connect(m_treeWidget, &ParameterWindowTreeWidget::DragEnded, this, [this]() { Reinit(/*forceReinit*/true); }); // create and fill the vertical layout - mVerticalLayout = new QVBoxLayout(); - mVerticalLayout->setObjectName("StyledWidget"); - mVerticalLayout->setSpacing(2); - mVerticalLayout->setMargin(0); - mVerticalLayout->setAlignment(Qt::AlignTop); - mVerticalLayout->addWidget(toolBar); - mVerticalLayout->addWidget(mTreeWidget); + m_verticalLayout = new QVBoxLayout(); + m_verticalLayout->setObjectName("StyledWidget"); + m_verticalLayout->setSpacing(2); + m_verticalLayout->setMargin(0); + m_verticalLayout->setAlignment(Qt::AlignTop); + m_verticalLayout->addWidget(toolBar); + m_verticalLayout->addWidget(m_treeWidget); // set the object name setObjectName("StyledWidget"); - setLayout(mVerticalLayout); + setLayout(m_verticalLayout); // set the focus policy setFocusPolicy(Qt::ClickFocus); // Force reinitialize in case e.g. a parameter got added or removed. - connect(&mPlugin->GetAnimGraphModel(), &AnimGraphModel::ParametersChanged, [this](EMotionFX::AnimGraph* animGraph) + connect(&m_plugin->GetAnimGraphModel(), &AnimGraphModel::ParametersChanged, [this](EMotionFX::AnimGraph* animGraph) { if (animGraph == m_animGraph) { @@ -238,7 +238,7 @@ namespace EMStudio } }); - connect(&mPlugin->GetAnimGraphModel(), &AnimGraphModel::FocusChanged, this, &ParameterWindow::OnFocusChanged); + connect(&m_plugin->GetAnimGraphModel(), &AnimGraphModel::FocusChanged, this, &ParameterWindow::OnFocusChanged); // Trigger actions are processed from EMotionFX worker threads, which // are not allowed to update the UI. Use a QueuedConnection to force @@ -267,7 +267,7 @@ namespace EMStudio // get access to the game controller and check if it is valid bool isGameControllerValid = false; #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - GameControllerWindow* gameControllerWindow = mPlugin->GetGameControllerWindow(); + GameControllerWindow* gameControllerWindow = m_plugin->GetGameControllerWindow(); if (gameControllerWindow) { isGameControllerValid = gameControllerWindow->GetIsGameControllerValid(); @@ -318,7 +318,7 @@ namespace EMStudio bool isGameControllerValid = false; #if AZ_TRAIT_EMOTIONFX_HAS_GAME_CONTROLLER - GameControllerWindow* gameControllerWindow = mPlugin->GetGameControllerWindow(); + GameControllerWindow* gameControllerWindow = m_plugin->GetGameControllerWindow(); if (gameControllerWindow) { isGameControllerValid = gameControllerWindow->GetIsGameControllerValid(); @@ -343,9 +343,9 @@ namespace EMStudio void ParameterWindow::AddParameterToInterface(EMotionFX::AnimGraph* animGraph, const EMotionFX::Parameter* parameter, QTreeWidgetItem* parentWidgetItem) { // Only filter value parameters - if (!mFilterString.empty() + if (!m_filterString.empty() && azrtti_typeid(parameter) != azrtti_typeid() - && AzFramework::StringFunc::Find(parameter->GetName().c_str(), mFilterString.c_str()) == AZStd::string::npos) + && AzFramework::StringFunc::Find(parameter->GetName().c_str(), m_filterString.c_str()) == AZStd::string::npos) { return; } @@ -360,10 +360,10 @@ namespace EMStudio if (GetIsParameterSelected(parameter->GetName())) { widgetItem->setSelected(true); - if (mEnsureVisibility) + if (m_ensureVisibility) { - mTreeWidget->scrollToItem(widgetItem); - mEnsureVisibility = false; + m_treeWidget->scrollToItem(widgetItem); + m_ensureVisibility = false; } } @@ -405,7 +405,7 @@ namespace EMStudio AZ_Error("EMotionFX", false, "Can't get serialize context from component application."); return; } - parameterWidget.m_propertyEditor = aznew AzToolsFramework::ReflectedPropertyEditor(mTreeWidget); + parameterWidget.m_propertyEditor = aznew AzToolsFramework::ReflectedPropertyEditor(m_treeWidget); parameterWidget.m_propertyEditor->SetSizeHintOffset(QSize(0, 0)); parameterWidget.m_propertyEditor->SetAutoResizeLabels(false); parameterWidget.m_propertyEditor->SetLeafIndentation(0); @@ -419,7 +419,7 @@ namespace EMStudio parameterWidget.m_propertyEditor->ExpandAll(); parameterWidget.m_propertyEditor->InvalidateAll(); - mTreeWidget->setItemWidget(widgetItem, 2, parameterWidget.m_propertyEditor); + m_treeWidget->setItemWidget(widgetItem, 2, parameterWidget.m_propertyEditor); // create the gizmo widget in case the parameter is currently not being controlled by the gamepad QWidget* gizmoWidget = nullptr; @@ -445,8 +445,8 @@ namespace EMStudio } if (gizmoWidget) { - mTreeWidget->setItemWidget(widgetItem, 1, gizmoWidget); - mTreeWidget->setColumnWidth(1, 20); + m_treeWidget->setItemWidget(widgetItem, 1, gizmoWidget); + m_treeWidget->setColumnWidth(1, 20); } auto insertIt = m_parameterWidgets.emplace(parameter, AZStd::move(parameterWidget)); @@ -520,7 +520,7 @@ namespace EMStudio QAction* editAction = menu->addAction("Edit"); connect(editAction, &QAction::triggered, this, &ParameterWindow::OnEditButton); } - if (!mSelectedParameterNames.empty()) + if (!m_selectedParameterNames.empty()) { menu->addSeparator(); @@ -561,7 +561,7 @@ namespace EMStudio && AZStd::find(groupParametersInCurrentParameter.begin(), groupParametersInCurrentParameter.end(), groupParameter) == groupParametersInCurrentParameter.end() - && AZStd::find(mSelectedParameterNames.begin(), mSelectedParameterNames.end(), groupParameter->GetName()) == mSelectedParameterNames.end()) + && AZStd::find(m_selectedParameterNames.begin(), m_selectedParameterNames.end(), groupParameter->GetName()) == m_selectedParameterNames.end()) { QAction* groupAction = groupMenu->addAction(groupParameter->GetName().c_str()); groupAction->setCheckable(true); @@ -586,7 +586,7 @@ namespace EMStudio menu->addSeparator(); // remove action - if (!mSelectedParameterNames.empty()) + if (!m_selectedParameterNames.empty()) { QAction* removeAction = menu->addAction("Remove"); connect(removeAction, &QAction::triggered, this, &ParameterWindow::OnRemoveSelected); @@ -676,29 +676,29 @@ namespace EMStudio void ParameterWindow::Reinit(bool forceReinit) { - mLockSelection = true; + m_lockSelection = true; // Early out in case we're already showing the parameters from the focused anim graph. - if (!forceReinit && m_animGraph == mPlugin->GetAnimGraphModel().GetFocusedAnimGraph()) + if (!forceReinit && m_animGraph == m_plugin->GetAnimGraphModel().GetFocusedAnimGraph()) { UpdateAttributesForParameterWidgets(); UpdateInterface(); - mLockSelection = false; + m_lockSelection = false; return; } - m_animGraph = mPlugin->GetAnimGraphModel().GetFocusedAnimGraph(); - qobject_cast(mTreeWidget)->SetAnimGraph(m_animGraph); + m_animGraph = m_plugin->GetAnimGraphModel().GetFocusedAnimGraph(); + qobject_cast(m_treeWidget)->SetAnimGraph(m_animGraph); // First clear the parameter widgets array and then the actual tree widget. // Don't change the order here as the tree widget clear call calls an on selection changed which uses the parameter widget array. m_parameterWidgets.clear(); - mTreeWidget->clear(); + m_treeWidget->clear(); if (!m_animGraph) { UpdateInterface(); - mLockSelection = false; + m_lockSelection = false; return; } @@ -706,10 +706,10 @@ namespace EMStudio const EMotionFX::ParameterVector& childParameters = m_animGraph->GetChildParameters(); for (const EMotionFX::Parameter* parameter : childParameters) { - AddParameterToInterface(m_animGraph, parameter, mTreeWidget->invisibleRootItem()); + AddParameterToInterface(m_animGraph, parameter, m_treeWidget->invisibleRootItem()); } - mLockSelection = false; + m_lockSelection = false; UpdateAttributesForParameterWidgets(); UpdateInterface(); @@ -718,11 +718,11 @@ namespace EMStudio void ParameterWindow::SingleSelectGroupParameter(const char* groupName, bool ensureVisibility, bool updateInterface) { - mSelectedParameterNames.clear(); + m_selectedParameterNames.clear(); - mSelectedParameterNames.push_back(groupName); + m_selectedParameterNames.push_back(groupName); - mEnsureVisibility = ensureVisibility; + m_ensureVisibility = ensureVisibility; if (updateInterface) { @@ -732,10 +732,10 @@ namespace EMStudio void ParameterWindow::SelectParameters(const AZStd::vector& parameterNames, bool updateInterface) { - mTreeWidget->clearSelection(); + m_treeWidget->clearSelection(); for (const AZStd::string& parameterName : parameterNames) { - const QList foundItems = mTreeWidget->findItems(parameterName.c_str(), Qt::MatchFixedString); + const QList foundItems = m_treeWidget->findItems(parameterName.c_str(), Qt::MatchFixedString); for (QTreeWidgetItem* foundItem : foundItems) { foundItem->setSelected(true); @@ -753,7 +753,7 @@ namespace EMStudio void ParameterWindow::OnTextFilterChanged(const QString& text) { - mFilterString = text.toUtf8().data(); + m_filterString = text.toUtf8().data(); Reinit(/*forceReinit=*/true); } @@ -829,7 +829,7 @@ namespace EMStudio // disable the remove and edit buttton if we dont have any parameter selected m_editAction->setEnabled(true); - if (mSelectedParameterNames.empty()) + if (m_selectedParameterNames.empty()) { m_editAction->setEnabled(false); } @@ -838,7 +838,7 @@ namespace EMStudio bool moveUpPossible, moveDownPossible; CanMove(&moveUpPossible, &moveDownPossible); - bool isAnimGraphActive = mPlugin->IsAnimGraphActive(m_animGraph); + bool isAnimGraphActive = m_plugin->IsAnimGraphActive(m_animGraph); // Make the parameter widgets read-only in case they are either controlled by the gamepad or the anim graph is not running on an actor instance. for (const auto& iterator : m_parameterWidgets) @@ -865,14 +865,14 @@ namespace EMStudio AZStd::vector result; const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { const EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); const EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); if (animGraphInstance && animGraphInstance->GetAnimGraph() == m_animGraph) { - result.emplace_back(animGraphInstance->GetParameterValue(static_cast(parameterIndex))); + result.emplace_back(animGraphInstance->GetParameterValue(parameterIndex)); } } @@ -912,7 +912,7 @@ namespace EMStudio return; } - ParameterCreateEditDialog* createEditParameterDialog = new ParameterCreateEditDialog(mPlugin, this); + ParameterCreateEditDialog* createEditParameterDialog = new ParameterCreateEditDialog(m_plugin, this); createEditParameterDialog->Init(); EMStudio::ParameterCreateEditDialog::connect(createEditParameterDialog, &QDialog::finished, [=](int resultCode) @@ -930,7 +930,7 @@ namespace EMStudio // Construct the create parameter command and add it to the command group. const AZStd::unique_ptr& parameter = createEditParameterDialog->GetParameter(); - CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph, parameter.get(), MCORE_INVALIDINDEX32); + CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph, parameter.get()); commandGroup.AddCommandString(commandString); const EMotionFX::GroupParameter* parentGroup = nullptr; @@ -988,7 +988,7 @@ namespace EMStudio const AZStd::string oldName = parameter->GetName(); // create and init the dialog - ParameterCreateEditDialog* dialog = new ParameterCreateEditDialog(mPlugin, this, parameter); + ParameterCreateEditDialog* dialog = new ParameterCreateEditDialog(m_plugin, this, parameter); dialog->Init(); // We cannot use exec here as we need to access it from the tests EMStudio::ParameterCreateEditDialog::connect(dialog, &QDialog::finished, [=](int resultCode) @@ -1023,7 +1023,7 @@ namespace EMStudio EMotionFX::AnimGraphNode::Port newPort; if (const EMotionFX::ValueParameter* valueParameter = azrtti_cast(editedParameter.get())) { - newPort.mCompatibleTypes[0] = valueParameter->GetType(); + newPort.m_compatibleTypes[0] = valueParameter->GetType(); } // Get the list of all parameter nodes @@ -1033,7 +1033,7 @@ namespace EMStudio { // Get the list of connections from the port whose type is // being changed - const uint32 sourcePortIndex = parameterNode->FindOutputPortIndex(parameter->GetName().c_str()); + const size_t sourcePortIndex = parameterNode->FindOutputPortIndex(parameter->GetName().c_str()); AZStd::vector> outgoingConnectionsFromThisPort; parameterNode->CollectOutgoingConnections(outgoingConnectionsFromThisPort, sourcePortIndex); @@ -1107,13 +1107,13 @@ namespace EMStudio void ParameterWindow::UpdateSelectionArrays() { // only update the selection in case it is not locked - if (mLockSelection) + if (m_lockSelection) { return; } // clear the selection - mSelectedParameterNames.clear(); + m_selectedParameterNames.clear(); if (!m_animGraph) { @@ -1121,14 +1121,14 @@ namespace EMStudio } // make sure we only have exactly one selected item - QList selectedItems = mTreeWidget->selectedItems(); + QList selectedItems = m_treeWidget->selectedItems(); int32 numSelectedItems = selectedItems.count(); for (int32 i = 0; i < numSelectedItems; ++i) { // get the selected item QTreeWidgetItem* selectedItem = selectedItems[i]; - mSelectedParameterNames.emplace_back(selectedItem->data(0, Qt::UserRole).toString().toUtf8().data()); + m_selectedParameterNames.emplace_back(selectedItem->data(0, Qt::UserRole).toString().toUtf8().data()); } } @@ -1136,7 +1136,7 @@ namespace EMStudio // get the index of the selected parameter const EMotionFX::Parameter* ParameterWindow::GetSingleSelectedParameter() const { - if (mSelectedParameterNames.size() != 1) + if (m_selectedParameterNames.size() != 1) { return nullptr; } @@ -1147,7 +1147,7 @@ namespace EMStudio } // find and return the index of the parameter in the anim graph - return m_animGraph->FindParameterByName(mSelectedParameterNames[0]); + return m_animGraph->FindParameterByName(m_selectedParameterNames[0]); } @@ -1167,8 +1167,8 @@ namespace EMStudio } const EMotionFX::GroupParameterVector groupParameters = m_animGraph->RecursivelyGetGroupParameters(); const size_t logNumGroups = groupParameters.size(); - MCore::LogInfo("Group parameters: (%i)", logNumGroups); - for (uint32 g = 0; g < logNumGroups; ++g) + MCore::LogInfo("Group parameters: (%zu)", logNumGroups); + for (size_t g = 0; g < logNumGroups; ++g) { const EMotionFX::GroupParameter* groupParam = groupParameters[g]; MCore::LogInfo("Group parameter #%i: Name='%s'", g, groupParam->GetName().c_str()); @@ -1192,7 +1192,7 @@ namespace EMStudio AZStd::vector selectedValueParameters; // get the number of selected parameters and iterate through them - for (const AZStd::string& selectedParameter : mSelectedParameterNames) + for (const AZStd::string& selectedParameter : m_selectedParameterNames) { const EMotionFX::Parameter* parameter = m_animGraph->FindParameterByName(selectedParameter); if (!parameter) @@ -1211,7 +1211,7 @@ namespace EMStudio for (const EMotionFX::Parameter* parameter2 : parametersInGroup) { const AZStd::string& parameterName = parameter2->GetName(); - if (AZStd::find(mSelectedParameterNames.begin(), mSelectedParameterNames.end(), parameterName) == mSelectedParameterNames.end()) + if (AZStd::find(m_selectedParameterNames.begin(), m_selectedParameterNames.end(), parameterName) == m_selectedParameterNames.end()) { paramsOfSelectedGroup.push_back(parameterName); } @@ -1294,7 +1294,7 @@ namespace EMStudio int ParameterWindow::GetTopLevelItemCount() const { - return mTreeWidget->topLevelItemCount(); + return m_treeWidget->topLevelItemCount(); } // move parameter under a specific parent, at a determined index @@ -1345,7 +1345,7 @@ namespace EMStudio } // get the number of selected parameters and return directly in case there aren't any selected - const size_t numSelectedParameters = mSelectedParameterNames.size(); + const size_t numSelectedParameters = m_selectedParameterNames.size(); if (numSelectedParameters == 0) { return; @@ -1364,7 +1364,7 @@ namespace EMStudio const EMotionFX::GroupParameter* groupParameter = m_animGraph->FindGroupParameterByName(groupParameterName); AZStd::string parameterNames; - AZ::StringFunc::Join(parameterNames, begin(mSelectedParameterNames), end(mSelectedParameterNames), ";"); + AZ::StringFunc::Join(parameterNames, begin(m_selectedParameterNames), end(m_selectedParameterNames), ";"); if (groupParameter) { commandString = AZStd::string::format(R"(AnimGraphAdjustGroupParameter -animGraphID %d -name "%s" -parameterNames "%s" -action "add")", @@ -1426,7 +1426,7 @@ namespace EMStudio const AZ::Outcome valueParameterIndex = m_animGraph->FindValueParameterIndex(valueParameter); if (valueParameterIndex.IsSuccess()) { - MCore::Attribute* instanceValue = animGraphInstance->GetParameterValue(static_cast(valueParameterIndex.GetValue())); + MCore::Attribute* instanceValue = animGraphInstance->GetParameterValue(valueParameterIndex.GetValue()); valueParameter->SetDefaultValueFromAttribute(instanceValue); m_animGraph->SetDirtyFlag(true); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.h index 3d53469c16..66cb62f0a5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ParameterWindow.h @@ -63,18 +63,18 @@ namespace EMStudio AZStd::string GetName() const { - return mLineEdit->text().toUtf8().data(); + return m_lineEdit->text().toUtf8().data(); } private slots: void NameEditChanged(const QString& text); private: - AZStd::string mOldName; - AZStd::vector mInvalidNames; - QPushButton* mOKButton; - QPushButton* mCancelButton; - QLineEdit* mLineEdit; + AZStd::string m_oldName; + AZStd::vector m_invalidNames; + QPushButton* m_okButton; + QPushButton* m_cancelButton; + QLineEdit* m_lineEdit; }; class ParameterWindow @@ -96,7 +96,7 @@ namespace EMStudio bool GetIsParameterSelected(const AZStd::string& parameterName) { - if (AZStd::find(mSelectedParameterNames.begin(), mSelectedParameterNames.end(), parameterName) == mSelectedParameterNames.end()) + if (AZStd::find(m_selectedParameterNames.begin(), m_selectedParameterNames.end(), parameterName) == m_selectedParameterNames.end()) { return false; } @@ -192,21 +192,21 @@ namespace EMStudio // toolbar buttons QAction* m_addAction; - static int m_contextMenuWidth; + static int s_contextMenuWidth; QAction* m_editAction; - AZStd::vector mSelectedParameterNames; - bool mEnsureVisibility; - bool mLockSelection; + AZStd::vector m_selectedParameterNames; + bool m_ensureVisibility; + bool m_lockSelection; - AZStd::string mFilterString; - AnimGraphPlugin* mPlugin; - ParameterWindowTreeWidget* mTreeWidget; + AZStd::string m_filterString; + AnimGraphPlugin* m_plugin; + ParameterWindowTreeWidget* m_treeWidget; AzQtComponents::FilteredSearchWidget* m_searchWidget; - QVBoxLayout* mVerticalLayout; - QScrollArea* mScrollArea; - AZStd::string mNameString; + QVBoxLayout* m_verticalLayout; + QScrollArea* m_scrollArea; + AZStd::string m_nameString; struct ParameterWidget { AZStd::unique_ptr m_valueParameterEditor; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.cpp index 3a43d640e0..846dd45c07 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.cpp @@ -33,16 +33,16 @@ namespace EMStudio setLayout(mainLayout); mainLayout->setAlignment(Qt::AlignTop); - mTableWidget = new QTableWidget(); - mTableWidget->setAlternatingRowColors(true); - mTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); - mTableWidget->horizontalHeader()->setStretchLastSection(true); - mTableWidget->setCornerButtonEnabled(false); - mTableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); - connect(mTableWidget, &QTableWidget::itemSelectionChanged, this, &StateFilterSelectionWindow::OnSelectionChanged); + m_tableWidget = new QTableWidget(); + m_tableWidget->setAlternatingRowColors(true); + m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_tableWidget->horizontalHeader()->setStretchLastSection(true); + m_tableWidget->setCornerButtonEnabled(false); + m_tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); + connect(m_tableWidget, &QTableWidget::itemSelectionChanged, this, &StateFilterSelectionWindow::OnSelectionChanged); - mainLayout->addWidget(mTableWidget); + mainLayout->addWidget(m_tableWidget); QHBoxLayout* buttonLayout = new QHBoxLayout(); mainLayout->addLayout(buttonLayout); @@ -69,25 +69,25 @@ namespace EMStudio void StateFilterSelectionWindow::ReInit(EMotionFX::AnimGraphStateMachine* stateMachine, const AZStd::vector& oldNodeSelection, const AZStd::vector& oldGroupSelection) { m_stateMachine = stateMachine; - mSelectedGroupNames = oldGroupSelection; + m_selectedGroupNames = oldGroupSelection; m_selectedNodeIds = oldNodeSelection; // clear the table widget - mWidgetTable.clear(); - mTableWidget->clear(); - mTableWidget->setColumnCount(2); + m_widgetTable.clear(); + m_tableWidget->clear(); + m_tableWidget->setColumnCount(2); // set header items for the table QTableWidgetItem* headerItem = new QTableWidgetItem("Name"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(0, headerItem); + m_tableWidget->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem("Type"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(1, headerItem); + m_tableWidget->setHorizontalHeaderItem(1, headerItem); - mTableWidget->resizeColumnsToContents(); - QHeaderView* horizontalHeader = mTableWidget->horizontalHeader(); + m_tableWidget->resizeColumnsToContents(); + QHeaderView* horizontalHeader = m_tableWidget->horizontalHeader(); horizontalHeader->setStretchLastSection(true); if (!m_stateMachine) @@ -98,15 +98,15 @@ namespace EMStudio const EMotionFX::AnimGraph* animGraph = m_stateMachine->GetAnimGraph(); // get the number of nodes inside the active node, the number node groups and set table size and add header items - const uint32 numNodeGroups = animGraph->GetNumNodeGroups(); - const uint32 numNodes = m_stateMachine->GetNumChildNodes(); - const uint32 numRows = numNodeGroups + numNodes; - mTableWidget->setRowCount(numRows); + const size_t numNodeGroups = animGraph->GetNumNodeGroups(); + const size_t numNodes = m_stateMachine->GetNumChildNodes(); + const int numRows = aznumeric_caster(numNodeGroups + numNodes); + m_tableWidget->setRowCount(numRows); // Block signals for the table widget to not reach OnSelectionChanged() when adding rows as that // clears m_selectedNodeIds and thus breaks the 'is node selected' check in the following loop. { - QSignalBlocker signalBlocker(mTableWidget); + QSignalBlocker signalBlocker(m_tableWidget); // iterate the nodes and add them all uint32 currentRowIndex = 0; @@ -161,9 +161,9 @@ namespace EMStudio } // resize to contents and adjust header - QHeaderView* verticalHeader = mTableWidget->verticalHeader(); + QHeaderView* verticalHeader = m_tableWidget->verticalHeader(); verticalHeader->setVisible(false); - mTableWidget->resizeColumnsToContents(); + m_tableWidget->resizeColumnsToContents(); horizontalHeader->setStretchLastSection(true); } @@ -185,10 +185,10 @@ namespace EMStudio nameItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); // add the name item in the table - mTableWidget->setItem(rowIndex, 0, nameItem); + m_tableWidget->setItem(rowIndex, 0, nameItem); // add a lookup - mWidgetTable.emplace_back(WidgetLookup(nameItem, name, isGroup)); + m_widgetTable.emplace_back(WidgetLookup(nameItem, name, isGroup)); // create the type item QTableWidgetItem* typeItem = nullptr; @@ -205,10 +205,10 @@ namespace EMStudio typeItem->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); // add the type item in the table - mTableWidget->setItem(rowIndex, 1, typeItem); + m_tableWidget->setItem(rowIndex, 1, typeItem); // add a lookup - mWidgetTable.emplace_back(WidgetLookup(typeItem, name, isGroup)); + m_widgetTable.emplace_back(WidgetLookup(typeItem, name, isGroup)); // set backgroundcolor of the row if (isGroup) @@ -227,7 +227,7 @@ namespace EMStudio } // set the row height - mTableWidget->setRowHeight(rowIndex, 21); + m_tableWidget->setRowHeight(rowIndex, 21); } @@ -242,12 +242,12 @@ namespace EMStudio const EMotionFX::AnimGraph* animGraph = m_stateMachine->GetAnimGraph(); // for all table entries - const size_t numWidgets = mWidgetTable.size(); + const size_t numWidgets = m_widgetTable.size(); for (size_t i = 0; i < numWidgets; ++i) { - if (mWidgetTable[i].mIsGroup && mWidgetTable[i].mWidget == widget) + if (m_widgetTable[i].m_isGroup && m_widgetTable[i].m_widget == widget) { - return animGraph->FindNodeGroupByName(mWidgetTable[i].mName.c_str()); + return animGraph->FindNodeGroupByName(m_widgetTable[i].m_name.c_str()); } } @@ -267,12 +267,12 @@ namespace EMStudio const EMotionFX::AnimGraph* animGraph = m_stateMachine->GetAnimGraph(); // for all table entries - const size_t numWidgets = mWidgetTable.size(); + const size_t numWidgets = m_widgetTable.size(); for (size_t i = 0; i < numWidgets; ++i) { - if (mWidgetTable[i].mIsGroup == false && mWidgetTable[i].mWidget == widget) + if (m_widgetTable[i].m_isGroup == false && m_widgetTable[i].m_widget == widget) { - return animGraph->RecursiveFindNodeByName(mWidgetTable[i].mName.c_str()); + return animGraph->RecursiveFindNodeByName(m_widgetTable[i].m_name.c_str()); } } @@ -285,11 +285,11 @@ namespace EMStudio void StateFilterSelectionWindow::OnSelectionChanged() { // reset the selection arrays - mSelectedGroupNames.clear(); + m_selectedGroupNames.clear(); m_selectedNodeIds.clear(); // get the selected items and the number of them - QList selectedItems = mTableWidget->selectedItems(); + QList selectedItems = m_tableWidget->selectedItems(); const int numSelectedItems = selectedItems.count(); // iterate through the selected items @@ -311,9 +311,9 @@ namespace EMStudio if (nodeGroup) { // add the node group name in case it is not in yet - if (AZStd::find(mSelectedGroupNames.begin(), mSelectedGroupNames.end(), nodeGroup->GetName()) == mSelectedGroupNames.end()) + if (AZStd::find(m_selectedGroupNames.begin(), m_selectedGroupNames.end(), nodeGroup->GetName()) == m_selectedGroupNames.end()) { - mSelectedGroupNames.emplace_back(nodeGroup->GetName()); + m_selectedGroupNames.emplace_back(nodeGroup->GetName()); } } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.h index 0ebf063703..1789ff77cb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateFilterSelectionWindow.h @@ -38,7 +38,7 @@ namespace EMStudio void ReInit(EMotionFX::AnimGraphStateMachine* stateMachine, const AZStd::vector& oldNodeSelection, const AZStd::vector& oldGroupSelection); const AZStd::vector GetSelectedNodeIds() const { return m_selectedNodeIds; } - const AZStd::vector& GetSelectedGroupNames() const { return mSelectedGroupNames; } + const AZStd::vector& GetSelectedGroupNames() const { return m_selectedGroupNames; } protected slots: void OnSelectionChanged(); @@ -47,15 +47,15 @@ namespace EMStudio struct WidgetLookup { MCORE_MEMORYOBJECTCATEGORY(StateFilterSelectionWindow::WidgetLookup, EMFX_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS_ANIMGRAPH); - QTableWidgetItem* mWidget; - AZStd::string mName; - bool mIsGroup; + QTableWidgetItem* m_widget; + AZStd::string m_name; + bool m_isGroup; WidgetLookup(QTableWidgetItem* widget, const char* name, bool isGroup) { - mWidget = widget; - mName = name; - mIsGroup = isGroup; + m_widget = widget; + m_name = name; + m_isGroup = isGroup; } }; @@ -63,10 +63,10 @@ namespace EMStudio EMotionFX::AnimGraphNode* FindNodeByWidget(QTableWidgetItem* widget) const; void AddRow(uint32 rowIndex, const char* name, bool isGroup, bool isSelected, const QColor& color = QColor(255, 255, 255)); - AZStd::vector mWidgetTable; - AZStd::vector mSelectedGroupNames; + AZStd::vector m_widgetTable; + AZStd::vector m_selectedGroupNames; AZStd::vector m_selectedNodeIds; - QTableWidget* mTableWidget; + QTableWidget* m_tableWidget; EMotionFX::AnimGraphStateMachine* m_stateMachine; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.cpp index 2cb9b8334d..319f2c5b4f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.cpp @@ -28,8 +28,8 @@ namespace EMStudio StateConnection::StateConnection(NodeGraph* parentGraph, const QModelIndex& modelIndex, GraphNode* sourceNode, GraphNode* targetNode, bool isWildcardConnection) : NodeConnection(parentGraph, modelIndex, targetNode, 0, sourceNode, 0) { - mColor = StateMachineColors::s_transitionColor; - mIsWildcardConnection = isWildcardConnection; + m_color = StateMachineColors::s_transitionColor; + m_isWildcardConnection = isWildcardConnection; } @@ -49,7 +49,7 @@ namespace EMStudio CalcStartAndEndPoints(start, end); // Adjust the start and end points in case this is a wildcard transition. - if (mIsWildcardConnection) + if (m_isWildcardConnection) { start = end - QPoint(WILDCARDTRANSITION_SIZE, WILDCARDTRANSITION_SIZE); end += QPoint(3, 3); @@ -130,7 +130,7 @@ namespace EMStudio } } - QColor color = mColor; + QColor color = m_color; if (GetIsSelected()) { @@ -140,26 +140,26 @@ namespace EMStudio { color = StateMachineColors::s_interruptionCandidateColor; } - else if (mIsSynced) + else if (m_isSynced) { color.setRgb(115, 125, 200); } // darken the color in case the transition is disabled - if (mIsDisabled) + if (m_isDisabled) { color = color.darker(165); } // lighten the color in case the transition is highlighted - if (mIsHighlighted) + if (m_isHighlighted) { color = color.lighter(150); painter.setOpacity(1.0); } // lighten the color in case the transition is connected to the currently selected node - if (mIsConnectedHighlighted) + if (m_isConnectedHighlighted) { pen->setWidth(2); color = color.lighter(150); @@ -186,12 +186,12 @@ namespace EMStudio RenderTransition(painter, *brush, *pen, start, end, color, activeColor, - isSelected, /*isDashed=*/mIsDisabled, + isSelected, /*isDashed=*/m_isDisabled, showBlendState, blendWeight, - /*highlightHead=*/mIsHeadHighlighted && mIsWildcardConnection == false, + /*highlightHead=*/m_isHeadHighlighted && m_isWildcardConnection == false, /*gradientActiveIndicator=*/!gotInterrupted); - if (mIsHeadHighlighted) + if (m_isHeadHighlighted) { brush->setColor(color); painter.setBrush(*brush); @@ -251,7 +251,7 @@ namespace EMStudio } // darken the color in case the transition is disabled - if (mIsDisabled) + if (m_isDisabled) { conditionColor = conditionColor.darker(185); } @@ -268,7 +268,7 @@ namespace EMStudio QColor actionColor = Qt::yellow; // darken the color in case the transition is disabled - if (mIsDisabled) + if (m_isDisabled) { actionColor = actionColor.darker(185); } @@ -299,7 +299,7 @@ namespace EMStudio CalcStartAndEndPoints(start, end); // check if we are dealing with a wildcard transition - if (mIsWildcardConnection) + if (m_isWildcardConnection) { start = end - QPoint(WILDCARDTRANSITION_SIZE, WILDCARDTRANSITION_SIZE); end += QPoint(3, 3); @@ -394,10 +394,10 @@ namespace EMStudio const QPoint endOffset = QPoint(transition->GetVisualEndOffsetX(), transition->GetVisualEndOffsetY()); QPoint start = startOffset; - QPoint end = mTargetNode->GetRect().topLeft() + endOffset; - if (mSourceNode) + QPoint end = m_targetNode->GetRect().topLeft() + endOffset; + if (m_sourceNode) { - start += mSourceNode->GetRect().topLeft(); + start += m_sourceNode->GetRect().topLeft(); } else { @@ -405,12 +405,12 @@ namespace EMStudio } QRect sourceRect; - if (mSourceNode) + if (m_sourceNode) { - sourceRect = mSourceNode->GetRect(); + sourceRect = m_sourceNode->GetRect(); } - QRect targetRect = mTargetNode->GetRect(); + QRect targetRect = m_targetNode->GetRect(); targetRect.adjust(-2, -2, 2, 2); // calc the real start point @@ -647,10 +647,8 @@ namespace EMStudio ResetBorderColor(); SetCreateConFromOutputOnly(true); - // mTextOptions.setAlignment( Qt::AlignCenter ); - - mInputPorts.Resize(1); - mOutputPorts.Resize(4); + m_inputPorts.resize(1); + m_outputPorts.resize(4); } StateGraphNode::~StateGraphNode() @@ -661,16 +659,16 @@ namespace EMStudio { AnimGraphVisualNode::Sync(); - EMotionFX::AnimGraphStateMachine* parentStateMachine = static_cast(mEMFXNode->GetParentNode()); - if (parentStateMachine->GetEntryState() == mEMFXNode) + EMotionFX::AnimGraphStateMachine* parentStateMachine = static_cast(m_emfxNode->GetParentNode()); + if (parentStateMachine->GetEntryState() == m_emfxNode) { - mParentGraph->SetEntryNode(this); + m_parentGraph->SetEntryNode(this); } } void StateGraphNode::Render(QPainter& painter, QPen* pen, bool renderShadow) { - if (!mIsVisible) + if (!m_isVisible) { return; } @@ -684,13 +682,13 @@ namespace EMStudio bool isActive = false; bool gotInterrupted = false; - if (animGraphInstance && mEMFXNode && animGraphInstance->GetAnimGraph() == mEMFXNode->GetAnimGraph()) + if (animGraphInstance && m_emfxNode && animGraphInstance->GetAnimGraph() == m_emfxNode->GetAnimGraph()) { - AZ_Assert(azrtti_typeid(mEMFXNode->GetParentNode()) == azrtti_typeid(), "Expected a valid state machine."); - const EMotionFX::AnimGraphStateMachine* stateMachine = static_cast(mEMFXNode->GetParentNode()); + AZ_Assert(azrtti_typeid(m_emfxNode->GetParentNode()) == azrtti_typeid(), "Expected a valid state machine."); + const EMotionFX::AnimGraphStateMachine* stateMachine = static_cast(m_emfxNode->GetParentNode()); const AZStd::vector& activeStates = stateMachine->GetActiveStates(animGraphInstance); - if (AZStd::find(activeStates.begin(), activeStates.end(), mEMFXNode) != activeStates.end()) + if (AZStd::find(activeStates.begin(), activeStates.end(), m_emfxNode) != activeStates.end()) { isActive = true; @@ -698,7 +696,7 @@ namespace EMStudio const EMotionFX::AnimGraphStateTransition* latestActiveTransition = stateMachine->GetLatestActiveTransition(animGraphInstance); for (const EMotionFX::AnimGraphStateTransition* activeTransition : activeTransitions) { - if (activeTransition != latestActiveTransition && activeTransition->GetTargetNode() == mEMFXNode) + if (activeTransition != latestActiveTransition && activeTransition->GetTargetNode() == m_emfxNode) { gotInterrupted = true; break; @@ -707,14 +705,14 @@ namespace EMStudio } } - mBorderColor.setRgb(0, 0, 0); + m_borderColor.setRgb(0, 0, 0); if (isActive) { - mBorderColor = StateMachineColors::s_activeColor; + m_borderColor = StateMachineColors::s_activeColor; } if (gotInterrupted) { - mBorderColor = StateMachineColors::s_interruptedColor; + m_borderColor = StateMachineColors::s_interruptedColor; } QColor borderColor; @@ -727,7 +725,7 @@ namespace EMStudio } else { - borderColor = mBorderColor; + borderColor = m_borderColor; } // background color @@ -738,16 +736,16 @@ namespace EMStudio } else { - bgColor = mBaseColor; + bgColor = m_baseColor; } // blinking red error color const bool hasError = GetHasError(); if (hasError && !isSelected) { - if (mParentGraph->GetUseAnimation()) + if (m_parentGraph->GetUseAnimation()) { - borderColor = mParentGraph->GetErrorBlinkColor(); + borderColor = m_parentGraph->GetErrorBlinkColor(); } else { @@ -761,18 +759,15 @@ namespace EMStudio QColor textColor = isSelected ? Qt::black : Qt::white; // is highlighted/hovered (on-mouse-over effect) - if (mIsHighlighted) + if (m_isHighlighted) { bgColor = bgColor.lighter(120); bgColor2 = bgColor2.lighter(120); } // draw the main rect - // check if we need to color all nodes or not - //const bool colorAllNodes = GetAlwaysColor(); - //if (mIsProcessed || colorAllNodes || mIsSelected==true) { - QLinearGradient bgGradient(0, mRect.top(), 0, mRect.bottom()); + QLinearGradient bgGradient(0, m_rect.top(), 0, m_rect.bottom()); bgGradient.setColorAt(0.0f, bgColor); bgGradient.setColorAt(1.0f, bgColor2); painter.setBrush(bgGradient); @@ -780,19 +775,19 @@ namespace EMStudio } // add 4px to have empty space for the visualize button - painter.drawRoundedRect(mRect, BORDER_RADIUS, BORDER_RADIUS); + painter.drawRoundedRect(m_rect, BORDER_RADIUS, BORDER_RADIUS); // if the scale is so small that we can still see the small things - if (mParentGraph->GetScale() > 0.3f) + if (m_parentGraph->GetScale() > 0.3f) { // draw the visualize area - if (mCanVisualize) + if (m_canVisualize) { RenderVisualizeRect(painter, bgColor, bgColor2); } // render the tracks etc - if (mEMFXNode->GetHasOutputPose() && mIsProcessed) + if (m_emfxNode->GetHasOutputPose() && m_isProcessed) { RenderTracks(painter, bgColor, bgColor2, 3); } @@ -804,14 +799,12 @@ namespace EMStudio painter.setClipping(false); // render the text overlay with the pre-baked node name and port names etc. - const float textOpacity = MCore::Clamp(mParentGraph->GetScale() * mParentGraph->GetScale() * 1.5f, 0.0f, 1.0f); + const float textOpacity = MCore::Clamp(m_parentGraph->GetScale() * m_parentGraph->GetScale() * 1.5f, 0.0f, 1.0f); painter.setOpacity(textOpacity); - painter.setFont(mHeaderFont); + painter.setFont(m_headerFont); painter.setBrush(Qt::NoBrush); painter.setPen(textColor); - //painter.drawStaticText(mRect.left(), mRect.center().y()-6, mTitleText); - painter.drawStaticText(mRect.left(), aznumeric_cast(mRect.center().y() - mTitleText.size().height() / 2), mTitleText); - // painter.drawPixmap( mRect, mTextPixmap ); + painter.drawStaticText(m_rect.left(), aznumeric_cast(m_rect.center().y() - m_titleText.size().height() / 2), m_titleText); painter.setOpacity(1.0f); RenderDebugInfo(painter); @@ -824,39 +817,38 @@ namespace EMStudio int32 StateGraphNode::CalcRequiredWidth() { - const uint32 headerWidth = mHeaderFontMetrics->horizontalAdvance(mElidedName) + 40; + const uint32 headerWidth = m_headerFontMetrics->horizontalAdvance(m_elidedName) + 40; // make sure the node is at least 100 units in width return MCore::Max(headerWidth, 100); } - QRect StateGraphNode::CalcInputPortRect(uint32 portNr) + QRect StateGraphNode::CalcInputPortRect(AZ::u16 portNr) { MCORE_UNUSED(portNr); - return mRect.adjusted(10, 10, -10, -10); + return m_rect.adjusted(10, 10, -10, -10); } - QRect StateGraphNode::CalcOutputPortRect(uint32 portNr) + QRect StateGraphNode::CalcOutputPortRect(AZ::u16 portNr) { switch (portNr) { case 0: - return QRect(mRect.left(), mRect.top(), mRect.width(), 8); + return QRect(m_rect.left(), m_rect.top(), m_rect.width(), 8); break; // top case 1: - return QRect(mRect.left(), mRect.bottom() - 8, mRect.width(), 9); + return QRect(m_rect.left(), m_rect.bottom() - 8, m_rect.width(), 9); break; // bottom case 2: - return QRect(mRect.left(), mRect.top(), 8, mRect.height()); + return QRect(m_rect.left(), m_rect.top(), 8, m_rect.height()); break; // left case 3: - return QRect(mRect.right() - 8, mRect.top(), 9, mRect.height()); + return QRect(m_rect.right() - 8, m_rect.top(), 9, m_rect.height()); break; // right default: MCORE_ASSERT(false); return QRect(); } - ; //MCore::LOG("CalcOutputPortRect: (%i, %i, %i, %i)", rect.top(), rect.left(), rect.bottom(), rect.right()); } @@ -865,7 +857,7 @@ namespace EMStudio MCORE_UNUSED(bgColor2); QColor vizBorder; - if (mVisualize) + if (m_visualize) { vizBorder = Qt::black; } @@ -874,26 +866,26 @@ namespace EMStudio vizBorder = bgColor.darker(225); } - painter.setPen(mVisualizeHighlighted ? StateMachineColors::s_selectedColor : vizBorder); + painter.setPen(m_visualizeHighlighted ? StateMachineColors::s_selectedColor : vizBorder); if (!GetIsSelected()) { - painter.setBrush(mVisualize ? mVisualizeColor : bgColor); + painter.setBrush(m_visualize ? m_visualizeColor : bgColor); } else { - painter.setBrush(mVisualize ? StateMachineColors::s_selectedColor : bgColor); + painter.setBrush(m_visualize ? StateMachineColors::s_selectedColor : bgColor); } - painter.drawRect(mVisualizeRect); + painter.drawRect(m_visualizeRect); } void StateGraphNode::UpdateTextPixmap() { - mTitleText.setTextOption(mTextOptionsCenter); - mTitleText.setTextFormat(Qt::PlainText); - mTitleText.setPerformanceHint(QStaticText::AggressiveCaching); - mTitleText.setTextWidth(mRect.width()); - mTitleText.setText(mElidedName); - mTitleText.prepare(QTransform(), mHeaderFont); + m_titleText.setTextOption(m_textOptionsCenter); + m_titleText.setTextFormat(Qt::PlainText); + m_titleText.setPerformanceHint(QStaticText::AggressiveCaching); + m_titleText.setTextWidth(m_rect.width()); + m_titleText.setText(m_elidedName); + m_titleText.prepare(QTransform(), m_headerFont); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.h index cf0f883199..6a7549e876 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/StateGraphNode.h @@ -54,11 +54,11 @@ namespace EMStudio bool CheckIfIsCloseToHead(const QPoint& point) const override; bool CheckIfIsCloseToTail(const QPoint& point) const override; - uint32 GetType() override { return TYPE_ID; } + uint32 GetType() const override { return TYPE_ID; } EMotionFX::AnimGraphTransitionCondition* FindCondition(const QPoint& mousePos); - bool GetIsWildcardTransition() const override { return mIsWildcardConnection; } + bool GetIsWildcardTransition() const override { return m_isWildcardConnection; } static void RenderTransition(QPainter& painter, QBrush& brush, QPen& pen, QPoint start, QPoint end, @@ -70,7 +70,7 @@ namespace EMStudio private: void RenderConditionsAndActions(EMotionFX::AnimGraphInstance* animGraphInstance, QPainter* painter, QPen* pen, QBrush* brush, QPoint& start, QPoint& end); - bool mIsWildcardConnection; + bool m_isWildcardConnection; }; @@ -98,8 +98,8 @@ namespace EMStudio int32 CalcRequiredHeight() const override; int32 CalcRequiredWidth() override; - QRect CalcInputPortRect(uint32 portNr) override; - QRect CalcOutputPortRect(uint32 portNr) override; + QRect CalcInputPortRect(AZ::u16 portNr) override; + QRect CalcOutputPortRect(AZ::u16 portNr) override; void UpdateTextPixmap() override; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.cpp index 2cf03ca998..be1feb93fc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.cpp @@ -9,6 +9,7 @@ // inlude required headers #include "AttachmentNodesWindow.h" #include "../../../../EMStudioSDK/Source/EMStudioManager.h" +#include "AzCore/std/limits.h" #include #include @@ -31,9 +32,9 @@ namespace EMStudio AttachmentNodesWindow::AttachmentNodesWindow(QWidget* parent) : QWidget(parent) { - mNodeTable = nullptr; - mSelectNodesButton = nullptr; - mNodeAction = ""; + m_nodeTable = nullptr; + m_selectNodesButton = nullptr; + m_nodeAction = ""; // init the widget Init(); @@ -50,49 +51,49 @@ namespace EMStudio void AttachmentNodesWindow::Init() { // create the node groups table - mNodeTable = new QTableWidget(0, 1, 0); + m_nodeTable = new QTableWidget(0, 1, 0); // create the table widget - mNodeTable->setMinimumHeight(125); - mNodeTable->setAlternatingRowColors(true); - mNodeTable->setCornerButtonEnabled(false); - mNodeTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mNodeTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_nodeTable->setMinimumHeight(125); + m_nodeTable->setAlternatingRowColors(true); + m_nodeTable->setCornerButtonEnabled(false); + m_nodeTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_nodeTable->setContextMenuPolicy(Qt::DefaultContextMenu); // set the table to row selection - mNodeTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_nodeTable->setSelectionBehavior(QAbstractItemView::SelectRows); // make the table items read only - mNodeTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_nodeTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // set header items for the table QTableWidgetItem* nameHeaderItem = new QTableWidgetItem("Nodes"); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); + m_nodeTable->setHorizontalHeaderItem(0, nameHeaderItem); - QHeaderView* horizontalHeader = mNodeTable->horizontalHeader(); + QHeaderView* horizontalHeader = m_nodeTable->horizontalHeader(); horizontalHeader->setStretchLastSection(true); // create the node selection window - mNodeSelectionWindow = new NodeSelectionWindow(this, false); + m_nodeSelectionWindow = new NodeSelectionWindow(this, false); // create the selection buttons - mSelectNodesButton = new QToolButton(); - mAddNodesButton = new QToolButton(); - mRemoveNodesButton = new QToolButton(); + m_selectNodesButton = new QToolButton(); + m_addNodesButton = new QToolButton(); + m_removeNodesButton = new QToolButton(); - EMStudioManager::MakeTransparentButton(mSelectNodesButton, "Images/Icons/Plus.svg", "Select nodes and replace the current selection"); - EMStudioManager::MakeTransparentButton(mAddNodesButton, "Images/Icons/Plus.svg", "Select nodes and add them to the current selection"); - EMStudioManager::MakeTransparentButton(mRemoveNodesButton, "Images/Icons/Minus.svg", "Remove selected nodes from the list"); + EMStudioManager::MakeTransparentButton(m_selectNodesButton, "Images/Icons/Plus.svg", "Select nodes and replace the current selection"); + EMStudioManager::MakeTransparentButton(m_addNodesButton, "Images/Icons/Plus.svg", "Select nodes and add them to the current selection"); + EMStudioManager::MakeTransparentButton(m_removeNodesButton, "Images/Icons/Minus.svg", "Remove selected nodes from the list"); // create the buttons layout QHBoxLayout* buttonLayout = new QHBoxLayout(); buttonLayout->setSpacing(0); buttonLayout->setAlignment(Qt::AlignLeft); - buttonLayout->addWidget(mSelectNodesButton); - buttonLayout->addWidget(mAddNodesButton); - buttonLayout->addWidget(mRemoveNodesButton); + buttonLayout->addWidget(m_selectNodesButton); + buttonLayout->addWidget(m_addNodesButton); + buttonLayout->addWidget(m_removeNodesButton); // create the layouts QVBoxLayout* layout = new QVBoxLayout(); @@ -100,18 +101,18 @@ namespace EMStudio layout->setSpacing(2); layout->addLayout(buttonLayout); - layout->addWidget(mNodeTable); + layout->addWidget(m_nodeTable); // set the main layout setLayout(layout); // connect controls to the slots - connect(mSelectNodesButton, &QToolButton::clicked, this, &AttachmentNodesWindow::SelectNodesButtonPressed); - connect(mAddNodesButton, &QToolButton::clicked, this, &AttachmentNodesWindow::SelectNodesButtonPressed); - connect(mRemoveNodesButton, &QToolButton::clicked, this, &AttachmentNodesWindow::RemoveNodesButtonPressed); - connect(mNodeTable, &QTableWidget::itemSelectionChanged, this, &AttachmentNodesWindow::OnItemSelectionChanged); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnSelectionDone), this, &AttachmentNodesWindow::NodeSelectionFinished); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnDoubleClicked), this, &AttachmentNodesWindow::NodeSelectionFinished); + connect(m_selectNodesButton, &QToolButton::clicked, this, &AttachmentNodesWindow::SelectNodesButtonPressed); + connect(m_addNodesButton, &QToolButton::clicked, this, &AttachmentNodesWindow::SelectNodesButtonPressed); + connect(m_removeNodesButton, &QToolButton::clicked, this, &AttachmentNodesWindow::RemoveNodesButtonPressed); + connect(m_nodeTable, &QTableWidget::itemSelectionChanged, this, &AttachmentNodesWindow::OnItemSelectionChanged); + connect(m_nodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &AttachmentNodesWindow::NodeSelectionFinished); + connect(m_nodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnDoubleClicked, this, &AttachmentNodesWindow::NodeSelectionFinished); } @@ -119,13 +120,13 @@ namespace EMStudio void AttachmentNodesWindow::UpdateInterface() { // clear the table widget - mNodeTable->clear(); + m_nodeTable->clear(); // check if the current actor exists - if (mActor == nullptr) + if (m_actor == nullptr) { // set the column count - mNodeTable->setColumnCount(0); + m_nodeTable->setColumnCount(0); // disable the widgets SetWidgetDisabled(true); @@ -135,23 +136,23 @@ namespace EMStudio } // set the column count - mNodeTable->setColumnCount(1); + m_nodeTable->setColumnCount(1); // enable the widget SetWidgetDisabled(false); // set the remove nodes button enabled or not based on selection - mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); + m_removeNodesButton->setEnabled((m_nodeTable->rowCount() != 0) && (m_nodeTable->selectedItems().size() != 0)); // counter for attachment nodes - uint16 numAttachmentNodes = 0; + int numAttachmentNodes = 0; // set the row count - const uint16 numNodes = mActor->GetNumNodes(); - for (uint16 i = 0; i < numNodes; ++i) + const int numNodes = aznumeric_caster(m_actor->GetNumNodes()); + for (int i = 0; i < numNodes; ++i) { // get the nodegroup - EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(i); if (node->GetIsAttachmentNode()) { numAttachmentNodes++; @@ -159,19 +160,19 @@ namespace EMStudio } // set the row count - mNodeTable->setRowCount(numAttachmentNodes); + m_nodeTable->setRowCount(numAttachmentNodes); // set header items for the table - QTableWidgetItem* nameHeaderItem = new QTableWidgetItem(AZStd::string::format("Attachment Nodes (%i / %i)", numAttachmentNodes, mActor->GetNumNodes()).c_str()); + QTableWidgetItem* nameHeaderItem = new QTableWidgetItem(AZStd::string::format("Attachment Nodes (%d / %zu)", numAttachmentNodes, m_actor->GetNumNodes()).c_str()); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignCenter); - mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); + m_nodeTable->setHorizontalHeaderItem(0, nameHeaderItem); // fill the table with content uint16 currentRow = 0; for (uint16 i = 0; i < numNodes; ++i) { // get the nodegroup - EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(i); // continue if node does not exist if (node == nullptr || node->GetIsAttachmentNode() == false) @@ -181,24 +182,24 @@ namespace EMStudio // create table items QTableWidgetItem* tableItemNodeName = new QTableWidgetItem(node->GetName()); - mNodeTable->setItem(currentRow, 0, tableItemNodeName); + m_nodeTable->setItem(currentRow, 0, tableItemNodeName); // set the row height and increase row counter - mNodeTable->setRowHeight(currentRow, 21); + m_nodeTable->setRowHeight(currentRow, 21); ++currentRow; } // resize to contents and adjust header - QHeaderView* verticalHeader = mNodeTable->verticalHeader(); + QHeaderView* verticalHeader = m_nodeTable->verticalHeader(); verticalHeader->setVisible(false); - mNodeTable->resizeColumnsToContents(); - mNodeTable->horizontalHeader()->setStretchLastSection(true); + m_nodeTable->resizeColumnsToContents(); + m_nodeTable->horizontalHeader()->setStretchLastSection(true); // set table size - mNodeTable->setColumnWidth(0, 37); - mNodeTable->setColumnWidth(3, 0); - mNodeTable->setColumnHidden(3, true); - mNodeTable->sortItems(3); + m_nodeTable->setColumnWidth(0, 37); + m_nodeTable->setColumnWidth(3, 0); + m_nodeTable->setColumnHidden(3, true); + m_nodeTable->sortItems(3); // toggle enabled state of the remove button OnItemSelectionChanged(); @@ -209,7 +210,7 @@ namespace EMStudio void AttachmentNodesWindow::SetActor(EMotionFX::Actor* actor) { // set the new actor - mActor = actor; + m_actor = actor; // update the interface UpdateInterface(); @@ -220,20 +221,20 @@ namespace EMStudio void AttachmentNodesWindow::SelectNodesButtonPressed() { // check if actor is set - if (mActor == nullptr) + if (m_actor == nullptr) { return; } // set the action for the selected nodes QWidget* senderWidget = (QWidget*)sender(); - if (senderWidget == mAddNodesButton) + if (senderWidget == m_addNodesButton) { - mNodeAction = "add"; + m_nodeAction = "add"; } else { - mNodeAction = "select"; + m_nodeAction = "select"; } // get the selected actorinstance @@ -247,23 +248,23 @@ namespace EMStudio } // create selection list for the current nodes within the group - mNodeSelectionList.Clear(); - if (senderWidget == mSelectNodesButton) + m_nodeSelectionList.Clear(); + if (senderWidget == m_selectNodesButton) { - const uint32 numNodes = mActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(i); if (node->GetIsAttachmentNode()) { - mNodeSelectionList.AddNode(node); + m_nodeSelectionList.AddNode(node); } } } // show the node selection window - mNodeSelectionWindow->Update(actorInstance->GetID(), &mNodeSelectionList); - mNodeSelectionWindow->show(); + m_nodeSelectionWindow->Update(actorInstance->GetID(), &m_nodeSelectionList); + m_nodeSelectionWindow->show(); } @@ -272,12 +273,12 @@ namespace EMStudio { // generate node list string AZStd::string nodeList; - uint32 lowestSelectedRow = MCORE_INVALIDINDEX32; - const uint32 numTableRows = mNodeTable->rowCount(); - for (uint32 i = 0; i < numTableRows; ++i) + int lowestSelectedRow = AZStd::numeric_limits::max(); + const int numTableRows = m_nodeTable->rowCount(); + for (int i = 0; i < numTableRows; ++i) { // get the current table item - QTableWidgetItem* item = mNodeTable->item(i, 0); + QTableWidgetItem* item = m_nodeTable->item(i, 0); if (item == nullptr) { continue; @@ -287,9 +288,9 @@ namespace EMStudio if (item->isSelected()) { nodeList += AZStd::string::format("%s;", FromQtString(item->text()).c_str()); - if ((uint32)item->row() < lowestSelectedRow) + if (item->row() < lowestSelectedRow) { - lowestSelectedRow = (uint32)item->row(); + lowestSelectedRow = item->row(); } } } @@ -303,29 +304,28 @@ namespace EMStudio // call command for adjusting disable on default flag AZStd::string outResult; AZStd::string command; - command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"remove\" -attachmentNodes \"%s\"", mActor->GetID(), nodeList.c_str()); + command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"remove\" -attachmentNodes \"%s\"", m_actor->GetID(), nodeList.c_str()); if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) { MCore::LogError(outResult.c_str()); } // selected the next row - if (lowestSelectedRow > ((uint32)mNodeTable->rowCount() - 1)) + if (lowestSelectedRow > m_nodeTable->rowCount() - 1) { - mNodeTable->selectRow(lowestSelectedRow - 1); + m_nodeTable->selectRow(lowestSelectedRow - 1); } else { - mNodeTable->selectRow(lowestSelectedRow); + m_nodeTable->selectRow(lowestSelectedRow); } } // add / select nodes - void AttachmentNodesWindow::NodeSelectionFinished(MCore::Array selectionList) + void AttachmentNodesWindow::NodeSelectionFinished(AZStd::vector selectionList) { - // return if no nodes are selected - if (selectionList.GetLength() == 0) + if (selectionList.empty()) { return; } @@ -333,17 +333,16 @@ namespace EMStudio // generate node list string AZStd::string nodeList; nodeList.reserve(16384); - const uint32 numSelectedNodes = selectionList.GetLength(); - for (uint32 i = 0; i < numSelectedNodes; ++i) + for (const SelectionItem& i : selectionList) { - nodeList += AZStd::string::format("%s;", selectionList[i].GetNodeName()); + nodeList += AZStd::string::format("%s;", i.GetNodeName()); } AzFramework::StringFunc::Strip(nodeList, MCore::CharacterConstants::semiColon, true /* case sensitive */, false /* beginning */, true /* ending */); // call command for adjusting disable on default flag AZStd::string outResult; AZStd::string command; - command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"%s\" -attachmentNodes \"%s\"", mActor->GetID(), mNodeAction.c_str(), nodeList.c_str()); + command = AZStd::string::format("AdjustActor -actorID %i -nodeAction \"%s\" -attachmentNodes \"%s\"", m_actor->GetID(), m_nodeAction.c_str(), nodeList.c_str()); if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) { MCore::LogError(outResult.c_str()); @@ -354,17 +353,17 @@ namespace EMStudio // enable/disable the dialog void AttachmentNodesWindow::SetWidgetDisabled(bool disabled) { - mNodeTable->setDisabled(disabled); - mSelectNodesButton->setDisabled(disabled); - mAddNodesButton->setDisabled(disabled); - mRemoveNodesButton->setDisabled(disabled); + m_nodeTable->setDisabled(disabled); + m_selectNodesButton->setDisabled(disabled); + m_addNodesButton->setDisabled(disabled); + m_removeNodesButton->setDisabled(disabled); } // handle item selection changes of the node table void AttachmentNodesWindow::OnItemSelectionChanged() { - mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); + m_removeNodesButton->setEnabled((m_nodeTable->rowCount() != 0) && (!m_nodeTable->selectedItems().empty())); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.h index 89bc06be7f..1743db3ab9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentNodesWindow.h @@ -57,7 +57,7 @@ namespace EMStudio // the slots void SelectNodesButtonPressed(); void RemoveNodesButtonPressed(); - void NodeSelectionFinished(MCore::Array selectionList); + void NodeSelectionFinished(AZStd::vector selectionList); void OnItemSelectionChanged(); private: @@ -66,18 +66,18 @@ namespace EMStudio private: // the current actor - EMotionFX::Actor* mActor; + EMotionFX::Actor* m_actor; // the node selection window and node group - NodeSelectionWindow* mNodeSelectionWindow; - CommandSystem::SelectionList mNodeSelectionList; - AZStd::string mNodeAction; + NodeSelectionWindow* m_nodeSelectionWindow; + CommandSystem::SelectionList m_nodeSelectionList; + AZStd::string m_nodeAction; // widgets - QTableWidget* mNodeTable; - QToolButton* mSelectNodesButton; - QToolButton* mAddNodesButton; - QToolButton* mRemoveNodesButton; + QTableWidget* m_nodeTable; + QToolButton* m_selectNodesButton; + QToolButton* m_addNodesButton; + QToolButton* m_removeNodesButton; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.cpp index d7fd6727f8..5bdb61dea5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.cpp @@ -24,7 +24,7 @@ namespace EMStudio AttachmentsHierarchyWindow::AttachmentsHierarchyWindow(QWidget* parent) : QWidget(parent) { - mHierarchy = nullptr; + m_hierarchy = nullptr; } @@ -40,27 +40,27 @@ namespace EMStudio verticalLayout->setMargin(0); setLayout(verticalLayout); - mHierarchy = new QTreeWidget(); - verticalLayout->addWidget(mHierarchy); - mHierarchy->setColumnCount(1); - mHierarchy->setHeaderHidden(true); + m_hierarchy = new QTreeWidget(); + verticalLayout->addWidget(m_hierarchy); + m_hierarchy->setColumnCount(1); + m_hierarchy->setHeaderHidden(true); // set optical stuff for the tree - mHierarchy->setColumnWidth(0, 200); - mHierarchy->setColumnWidth(1, 20); - mHierarchy->setColumnWidth(1, 100); - mHierarchy->setSortingEnabled(false); - mHierarchy->setSelectionMode(QAbstractItemView::NoSelection); - mHierarchy->setMinimumWidth(150); - mHierarchy->setMinimumHeight(125); - mHierarchy->setAlternatingRowColors(true); - mHierarchy->setExpandsOnDoubleClick(true); - mHierarchy->setAnimated(true); + m_hierarchy->setColumnWidth(0, 200); + m_hierarchy->setColumnWidth(1, 20); + m_hierarchy->setColumnWidth(1, 100); + m_hierarchy->setSortingEnabled(false); + m_hierarchy->setSelectionMode(QAbstractItemView::NoSelection); + m_hierarchy->setMinimumWidth(150); + m_hierarchy->setMinimumHeight(125); + m_hierarchy->setAlternatingRowColors(true); + m_hierarchy->setExpandsOnDoubleClick(true); + m_hierarchy->setAnimated(true); // disable the move of section to have column order fixed - mHierarchy->header()->setSectionsMovable(false); + m_hierarchy->header()->setSectionsMovable(false); - verticalLayout->addWidget(mHierarchy); + verticalLayout->addWidget(m_hierarchy); ReInit(); } @@ -69,11 +69,11 @@ namespace EMStudio void AttachmentsHierarchyWindow::ReInit() { // clear the tree - mHierarchy->clear(); + m_hierarchy->clear(); // get the number of actor instances and iterate through them - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); @@ -88,16 +88,16 @@ namespace EMStudio // check if we are dealing with a root actor instance if (attachedTo == nullptr) { - QTreeWidgetItem* item = new QTreeWidgetItem(mHierarchy); + QTreeWidgetItem* item = new QTreeWidgetItem(m_hierarchy); AZStd::string actorFilename; AzFramework::StringFunc::Path::GetFileName(actor->GetFileNameString().c_str(), actorFilename); item->setText(0, QString("%1 (ID:%2)").arg(actorFilename.c_str()).arg(actorInstance->GetID())); item->setExpanded(true); - mHierarchy->addTopLevelItem(item); + m_hierarchy->addTopLevelItem(item); // get the number of attachments and iterate through them - const uint32 numAttachments = actorInstance->GetNumAttachments(); - for (uint32 j = 0; j < numAttachments; ++j) + const size_t numAttachments = actorInstance->GetNumAttachments(); + for (size_t j = 0; j < numAttachments; ++j) { EMotionFX::Attachment* attachment = actorInstance->GetAttachment(j); MCORE_ASSERT(actorInstance == attachment->GetAttachToActorInstance()); @@ -124,8 +124,8 @@ namespace EMStudio parent->addChild(item); // get the number of attachments and iterate through them - const uint32 numAttachments = actorInstance->GetNumAttachments(); - for (uint32 i = 0; i < numAttachments; ++i) + const size_t numAttachments = actorInstance->GetNumAttachments(); + for (size_t i = 0; i < numAttachments; ++i) { EMotionFX::Attachment* attachment = actorInstance->GetAttachment(i); MCORE_ASSERT(actorInstance == attachment->GetAttachToActorInstance()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.h index 5621cb9bdd..92a55668e8 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsHierarchyWindow.h @@ -39,7 +39,7 @@ namespace EMStudio private: void RecursivelyAddAttachments(QTreeWidgetItem* parent, EMotionFX::ActorInstance* actorInstance); - QTreeWidget* mHierarchy; + QTreeWidget* m_hierarchy; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp index 738879e96e..401945647e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.cpp @@ -20,16 +20,16 @@ namespace EMStudio AttachmentsPlugin::AttachmentsPlugin() : EMStudio::DockWidgetPlugin() { - mDialogStack = nullptr; - mSelectCallback = nullptr; - mUnselectCallback = nullptr; - mClearSelectionCallback = nullptr; - mAddAttachmentCallback = nullptr; - mAddDeformableAttachmentCallback = nullptr; - mRemoveAttachmentCallback = nullptr; - mClearAttachmentsCallback = nullptr; - mAdjustActorCallback = nullptr; - mAttachmentNodesWindow = nullptr; + m_dialogStack = nullptr; + m_selectCallback = nullptr; + m_unselectCallback = nullptr; + m_clearSelectionCallback = nullptr; + m_addAttachmentCallback = nullptr; + m_addDeformableAttachmentCallback = nullptr; + m_removeAttachmentCallback = nullptr; + m_clearAttachmentsCallback = nullptr; + m_adjustActorCallback = nullptr; + m_attachmentNodesWindow = nullptr; } @@ -37,23 +37,23 @@ namespace EMStudio AttachmentsPlugin::~AttachmentsPlugin() { // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - GetCommandManager()->RemoveCommandCallback(mAddAttachmentCallback, false); - GetCommandManager()->RemoveCommandCallback(mAddDeformableAttachmentCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveAttachmentCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearAttachmentsCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustActorCallback, false); - - delete mSelectCallback; - delete mUnselectCallback; - delete mClearSelectionCallback; - delete mAddAttachmentCallback; - delete mAddDeformableAttachmentCallback; - delete mRemoveAttachmentCallback; - delete mClearAttachmentsCallback; - delete mAdjustActorCallback; + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_addAttachmentCallback, false); + GetCommandManager()->RemoveCommandCallback(m_addDeformableAttachmentCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeAttachmentCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearAttachmentsCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustActorCallback, false); + + delete m_selectCallback; + delete m_unselectCallback; + delete m_clearSelectionCallback; + delete m_addAttachmentCallback; + delete m_addDeformableAttachmentCallback; + delete m_removeAttachmentCallback; + delete m_clearAttachmentsCallback; + delete m_adjustActorCallback; } @@ -70,52 +70,52 @@ namespace EMStudio //LogInfo("Initializing attachments window."); // create the dialog stack - assert(mDialogStack == nullptr); - mDialogStack = new MysticQt::DialogStack(mDock); - mDock->setWidget(mDialogStack); + assert(m_dialogStack == nullptr); + m_dialogStack = new MysticQt::DialogStack(m_dock); + m_dock->setWidget(m_dialogStack); // create the attachments window - mAttachmentsWindow = new AttachmentsWindow(mDialogStack); - mAttachmentsWindow->Init(); - mDialogStack->Add(mAttachmentsWindow, "Selected Actor Instance", false, true, true, false); + m_attachmentsWindow = new AttachmentsWindow(m_dialogStack); + m_attachmentsWindow->Init(); + m_dialogStack->Add(m_attachmentsWindow, "Selected Actor Instance", false, true, true, false); // create the attachment hierarchy window - mAttachmentsHierarchyWindow = new AttachmentsHierarchyWindow(mDialogStack); - mAttachmentsHierarchyWindow->Init(); - mDialogStack->Add(mAttachmentsHierarchyWindow, "Hierarchy", false, true, true, false); + m_attachmentsHierarchyWindow = new AttachmentsHierarchyWindow(m_dialogStack); + m_attachmentsHierarchyWindow->Init(); + m_dialogStack->Add(m_attachmentsHierarchyWindow, "Hierarchy", false, true, true, false); // create the attachment nodes window - mAttachmentNodesWindow = new AttachmentNodesWindow(mDialogStack); - mDialogStack->Add(mAttachmentNodesWindow, "Attachment Nodes", false, true); + m_attachmentNodesWindow = new AttachmentNodesWindow(m_dialogStack); + m_dialogStack->Add(m_attachmentNodesWindow, "Attachment Nodes", false, true); // create and register the command callbacks only (only execute this code once for all plugins) - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); - mClearSelectionCallback = new CommandClearSelectionCallback(false); - - mAddAttachmentCallback = new CommandAddAttachmentCallback(false); - mAddDeformableAttachmentCallback = new CommandAddDeformableAttachmentCallback(false); - mRemoveAttachmentCallback = new CommandRemoveAttachmentCallback(false); - mClearAttachmentsCallback = new CommandClearAttachmentsCallback(false); - mAdjustActorCallback = new CommandAdjustActorCallback(false); - mRemoveActorInstanceCallback = new CommandRemoveActorInstanceCallback(false); - - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); - - GetCommandManager()->RegisterCommandCallback("AddAttachment", mAddAttachmentCallback); - GetCommandManager()->RegisterCommandCallback("AddDeformableAttachment", mAddDeformableAttachmentCallback); - GetCommandManager()->RegisterCommandCallback("RemoveAttachment", mRemoveAttachmentCallback); - GetCommandManager()->RegisterCommandCallback("ClearAttachments", mClearAttachmentsCallback); - GetCommandManager()->RegisterCommandCallback("AdjustActor", mAdjustActorCallback); - GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", mRemoveActorInstanceCallback); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); + m_clearSelectionCallback = new CommandClearSelectionCallback(false); + + m_addAttachmentCallback = new CommandAddAttachmentCallback(false); + m_addDeformableAttachmentCallback = new CommandAddDeformableAttachmentCallback(false); + m_removeAttachmentCallback = new CommandRemoveAttachmentCallback(false); + m_clearAttachmentsCallback = new CommandClearAttachmentsCallback(false); + m_adjustActorCallback = new CommandAdjustActorCallback(false); + m_removeActorInstanceCallback = new CommandRemoveActorInstanceCallback(false); + + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); + + GetCommandManager()->RegisterCommandCallback("AddAttachment", m_addAttachmentCallback); + GetCommandManager()->RegisterCommandCallback("AddDeformableAttachment", m_addDeformableAttachmentCallback); + GetCommandManager()->RegisterCommandCallback("RemoveAttachment", m_removeAttachmentCallback); + GetCommandManager()->RegisterCommandCallback("ClearAttachments", m_clearAttachmentsCallback); + GetCommandManager()->RegisterCommandCallback("AdjustActor", m_adjustActorCallback); + GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", m_removeActorInstanceCallback); // reinit the dialog ReInit(); // connect the window activation signal to refresh if reactivated - connect(mDock, &QDockWidget::visibilityChanged, this, &AttachmentsPlugin::WindowReInit); + connect(m_dock, &QDockWidget::visibilityChanged, this, &AttachmentsPlugin::WindowReInit); return true; } @@ -124,8 +124,8 @@ namespace EMStudio // function to reinit the window void AttachmentsPlugin::ReInit() { - mAttachmentsWindow->ReInit(); - mAttachmentsHierarchyWindow->ReInit(); + m_attachmentsWindow->ReInit(); + m_attachmentsHierarchyWindow->ReInit(); // get the current actor const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); @@ -139,7 +139,7 @@ namespace EMStudio } // set the actor of the attachment nodes window - mAttachmentNodesWindow->SetActor(actor); + m_attachmentNodesWindow->SetActor(actor); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.h index 63ce91e187..d59d0d1b93 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsPlugin.h @@ -58,7 +58,7 @@ namespace EMStudio bool Init() override; EMStudioPlugin* Clone() override; void ReInit(); - AttachmentsWindow* GetAttachmentsWindow() const { return mAttachmentsWindow; } + AttachmentsWindow* GetAttachmentsWindow() const { return m_attachmentsWindow; } public slots: void WindowReInit(bool visible); @@ -75,21 +75,21 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandAdjustActorCallback); MCORE_DEFINECOMMANDCALLBACK(CommandRemoveActorInstanceCallback); - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; - CommandClearSelectionCallback* mClearSelectionCallback; - CommandAddAttachmentCallback* mAddAttachmentCallback; - CommandAddDeformableAttachmentCallback* mAddDeformableAttachmentCallback; - CommandRemoveAttachmentCallback* mRemoveAttachmentCallback; - CommandClearAttachmentsCallback* mClearAttachmentsCallback; - CommandAdjustActorCallback* mAdjustActorCallback; - CommandRemoveActorInstanceCallback* mRemoveActorInstanceCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; + CommandClearSelectionCallback* m_clearSelectionCallback; + CommandAddAttachmentCallback* m_addAttachmentCallback; + CommandAddDeformableAttachmentCallback* m_addDeformableAttachmentCallback; + CommandRemoveAttachmentCallback* m_removeAttachmentCallback; + CommandClearAttachmentsCallback* m_clearAttachmentsCallback; + CommandAdjustActorCallback* m_adjustActorCallback; + CommandRemoveActorInstanceCallback* m_removeActorInstanceCallback; - QWidget* mNoSelectionWidget; - MysticQt::DialogStack* mDialogStack; - AttachmentsWindow* mAttachmentsWindow; - AttachmentsHierarchyWindow* mAttachmentsHierarchyWindow; - AttachmentNodesWindow* mAttachmentNodesWindow; + QWidget* m_noSelectionWidget; + MysticQt::DialogStack* m_dialogStack; + AttachmentsWindow* m_attachmentsWindow; + AttachmentsHierarchyWindow* m_attachmentsHierarchyWindow; + AttachmentNodesWindow* m_attachmentNodesWindow; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.cpp index 2498ec1b0e..9d25eeb41b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.cpp @@ -8,6 +8,8 @@ // include required headers #include "AttachmentsWindow.h" +#include "AzCore/std/limits.h" +#include "MCore/Source/Config.h" #include #include #include @@ -38,12 +40,12 @@ namespace EMStudio AttachmentsWindow::AttachmentsWindow(QWidget* parent, bool deformable) : QWidget(parent) { - mTableWidget = nullptr; - mActorInstance = nullptr; - mNodeSelectionWindow = nullptr; - mWaitingForAttachment = false; - mIsDeformableAttachment = deformable; - mEscapeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); + m_tableWidget = nullptr; + m_actorInstance = nullptr; + m_nodeSelectionWindow = nullptr; + m_waitingForAttachment = false; + m_isDeformableAttachment = deformable; + m_escapeShortcut = new QShortcut(QKeySequence(Qt::Key_Escape), this); } @@ -56,54 +58,54 @@ namespace EMStudio // init the geometry lod window void AttachmentsWindow::Init() { - mTempString.reserve(16384); + m_tempString.reserve(16384); setObjectName("StackFrameOnlyBG"); setAcceptDrops(true); // create the lod information table - mTableWidget = new QTableWidget(); + m_tableWidget = new QTableWidget(); // set the alternating row colors - mTableWidget->setAlternatingRowColors(true); + m_tableWidget->setAlternatingRowColors(true); // set the table to row single selection - mTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); // make the table items read only - mTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); // set the minimum size and the resizing policy - mTableWidget->setMinimumHeight(125); - mTableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_tableWidget->setMinimumHeight(125); + m_tableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); // automatically adjust the size of the last entry to make it always fitting the table widget size - QHeaderView* horizontalHeader = mTableWidget->horizontalHeader(); + QHeaderView* horizontalHeader = m_tableWidget->horizontalHeader(); horizontalHeader->setStretchLastSection(true); // disable the corner button between the row and column selection thingies - mTableWidget->setCornerButtonEnabled(false); + m_tableWidget->setCornerButtonEnabled(false); // enable the custom context menu for the motion table - mTableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); + m_tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); // set the column count - mTableWidget->setColumnCount(6); + m_tableWidget->setColumnCount(6); // set header items for the table - mTableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Vis")); - mTableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("ID")); - mTableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Name")); - mTableWidget->setHorizontalHeaderItem(3, new QTableWidgetItem("IsSkin")); - mTableWidget->setHorizontalHeaderItem(4, new QTableWidgetItem("Node")); - mTableWidget->setHorizontalHeaderItem(5, new QTableWidgetItem("Nodes")); + m_tableWidget->setHorizontalHeaderItem(0, new QTableWidgetItem("Vis")); + m_tableWidget->setHorizontalHeaderItem(1, new QTableWidgetItem("ID")); + m_tableWidget->setHorizontalHeaderItem(2, new QTableWidgetItem("Name")); + m_tableWidget->setHorizontalHeaderItem(3, new QTableWidgetItem("IsSkin")); + m_tableWidget->setHorizontalHeaderItem(4, new QTableWidgetItem("Node")); + m_tableWidget->setHorizontalHeaderItem(5, new QTableWidgetItem("Nodes")); // set the horizontal header alignement horizontalHeader->setDefaultAlignment(Qt::AlignVCenter | Qt::AlignLeft); // set the vertical header not visible - QHeaderView* verticalHeader = mTableWidget->verticalHeader(); + QHeaderView* verticalHeader = m_tableWidget->verticalHeader(); verticalHeader->setVisible(false); // set the vis fast updates and IsSkin columns fixed @@ -112,103 +114,103 @@ namespace EMStudio horizontalHeader->setSectionResizeMode(5, QHeaderView::Fixed); // set the width of the other columns - mTableWidget->setColumnWidth(0, 25); - mTableWidget->setColumnWidth(1, 25); - mTableWidget->setColumnWidth(2, 100); - mTableWidget->setColumnWidth(3, 44); - mTableWidget->setColumnWidth(4, 100); - mTableWidget->setColumnWidth(5, 32); + m_tableWidget->setColumnWidth(0, 25); + m_tableWidget->setColumnWidth(1, 25); + m_tableWidget->setColumnWidth(2, 100); + m_tableWidget->setColumnWidth(3, 44); + m_tableWidget->setColumnWidth(4, 100); + m_tableWidget->setColumnWidth(5, 32); // create buttons for the attachments dialog - mOpenAttachmentButton = new QToolButton(); - mOpenDeformableAttachmentButton = new QToolButton(); - mRemoveButton = new QToolButton(); - mClearButton = new QToolButton(); - mCancelSelectionButton = new QToolButton(); - - EMStudioManager::MakeTransparentButton(mOpenAttachmentButton, "Images/Icons/Open.svg", "Open actor from file and add it as regular attachment"); - EMStudioManager::MakeTransparentButton(mOpenDeformableAttachmentButton, "Images/Icons/Open.svg", "Open actor from file and add it as skin attachment"); - EMStudioManager::MakeTransparentButton(mRemoveButton, "Images/Icons/Minus.svg", "Remove selected attachments"); - EMStudioManager::MakeTransparentButton(mClearButton, "Images/Icons/Clear.svg", "Remove all attachments"); - EMStudioManager::MakeTransparentButton(mCancelSelectionButton, "Images/Icons/Remove.svg", "Cancel attachment selection"); + m_openAttachmentButton = new QToolButton(); + m_openDeformableAttachmentButton = new QToolButton(); + m_removeButton = new QToolButton(); + m_clearButton = new QToolButton(); + m_cancelSelectionButton = new QToolButton(); + + EMStudioManager::MakeTransparentButton(m_openAttachmentButton, "Images/Icons/Open.svg", "Open actor from file and add it as regular attachment"); + EMStudioManager::MakeTransparentButton(m_openDeformableAttachmentButton, "Images/Icons/Open.svg", "Open actor from file and add it as skin attachment"); + EMStudioManager::MakeTransparentButton(m_removeButton, "Images/Icons/Minus.svg", "Remove selected attachments"); + EMStudioManager::MakeTransparentButton(m_clearButton, "Images/Icons/Clear.svg", "Remove all attachments"); + EMStudioManager::MakeTransparentButton(m_cancelSelectionButton, "Images/Icons/Remove.svg", "Cancel attachment selection"); // create the buttons layout QHBoxLayout* buttonLayout = new QHBoxLayout(); buttonLayout->setSpacing(0); buttonLayout->setAlignment(Qt::AlignLeft); - buttonLayout->addWidget(mOpenAttachmentButton); - buttonLayout->addWidget(mOpenDeformableAttachmentButton); - buttonLayout->addWidget(mRemoveButton); - buttonLayout->addWidget(mClearButton); + buttonLayout->addWidget(m_openAttachmentButton); + buttonLayout->addWidget(m_openDeformableAttachmentButton); + buttonLayout->addWidget(m_removeButton); + buttonLayout->addWidget(m_clearButton); // create the buttons layout for selection mode QHBoxLayout* buttonLayoutSelectionMode = new QHBoxLayout(); buttonLayoutSelectionMode->setSpacing(0); buttonLayoutSelectionMode->setAlignment(Qt::AlignLeft); - buttonLayoutSelectionMode->addWidget(mCancelSelectionButton); + buttonLayoutSelectionMode->addWidget(m_cancelSelectionButton); // create info widgets - mWaitingForAttachmentWidget = new QWidget(); - mNoSelectionWidget = new QWidget(); - mWaitingForAttachmentLayout = new QVBoxLayout(); - mNoSelectionLayout = new QVBoxLayout(); + m_waitingForAttachmentWidget = new QWidget(); + m_noSelectionWidget = new QWidget(); + m_waitingForAttachmentLayout = new QVBoxLayout(); + m_noSelectionLayout = new QVBoxLayout(); QLabel* waitingForAttachmentLabel = new QLabel("Please select an actor instance."); QLabel* noSelectionLabel = new QLabel("No attachments to show."); - mWaitingForAttachmentLayout->addLayout(buttonLayoutSelectionMode); - mWaitingForAttachmentLayout->addWidget(waitingForAttachmentLabel); - mWaitingForAttachmentLayout->setAlignment(waitingForAttachmentLabel, Qt::AlignCenter); - mWaitingForAttachmentWidget->setLayout(mWaitingForAttachmentLayout); - mWaitingForAttachmentWidget->setHidden(true); + m_waitingForAttachmentLayout->addLayout(buttonLayoutSelectionMode); + m_waitingForAttachmentLayout->addWidget(waitingForAttachmentLabel); + m_waitingForAttachmentLayout->setAlignment(waitingForAttachmentLabel, Qt::AlignCenter); + m_waitingForAttachmentWidget->setLayout(m_waitingForAttachmentLayout); + m_waitingForAttachmentWidget->setHidden(true); - mNoSelectionLayout->addWidget(noSelectionLabel); - mNoSelectionLayout->setAlignment(noSelectionLabel, Qt::AlignCenter); - mNoSelectionWidget->setLayout(mNoSelectionLayout); - mNoSelectionWidget->setHidden(true); + m_noSelectionLayout->addWidget(noSelectionLabel); + m_noSelectionLayout->setAlignment(noSelectionLabel, Qt::AlignCenter); + m_noSelectionWidget->setLayout(m_noSelectionLayout); + m_noSelectionWidget->setHidden(true); // create the layouts - mAttachmentsWidget = new QWidget(); - mAttachmentsLayout = new QVBoxLayout(); - mMainLayout = new QVBoxLayout(); - mMainLayout->setMargin(0); - mMainLayout->setSpacing(2); - mAttachmentsLayout->setMargin(0); - mAttachmentsLayout->setSpacing(2); + m_attachmentsWidget = new QWidget(); + m_attachmentsLayout = new QVBoxLayout(); + m_mainLayout = new QVBoxLayout(); + m_mainLayout->setMargin(0); + m_mainLayout->setSpacing(2); + m_attachmentsLayout->setMargin(0); + m_attachmentsLayout->setSpacing(2); // fill the attachments layout - mAttachmentsLayout->addLayout(buttonLayout); - mAttachmentsLayout->addWidget(mTableWidget); - mAttachmentsWidget->setLayout(mAttachmentsLayout); - mAttachmentsWidget->setObjectName("StackFrameOnlyBG"); + m_attachmentsLayout->addLayout(buttonLayout); + m_attachmentsLayout->addWidget(m_tableWidget); + m_attachmentsWidget->setLayout(m_attachmentsLayout); + m_attachmentsWidget->setObjectName("StackFrameOnlyBG"); // settings for the selection mode widgets - mWaitingForAttachmentWidget->setObjectName("StackFrameOnlyBG"); - mWaitingForAttachmentWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mWaitingForAttachmentLayout->setSpacing(0); - mWaitingForAttachmentLayout->setMargin(0); - mNoSelectionWidget->setObjectName("StackFrameOnlyBG"); - mNoSelectionWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_waitingForAttachmentWidget->setObjectName("StackFrameOnlyBG"); + m_waitingForAttachmentWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_waitingForAttachmentLayout->setSpacing(0); + m_waitingForAttachmentLayout->setMargin(0); + m_noSelectionWidget->setObjectName("StackFrameOnlyBG"); + m_noSelectionWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); // fill the main layout - mMainLayout->addWidget(mAttachmentsWidget); - mMainLayout->addWidget(mWaitingForAttachmentWidget); - mMainLayout->addWidget(mNoSelectionWidget); - setLayout(mMainLayout); + m_mainLayout->addWidget(m_attachmentsWidget); + m_mainLayout->addWidget(m_waitingForAttachmentWidget); + m_mainLayout->addWidget(m_noSelectionWidget); + setLayout(m_mainLayout); // create the node selection window - mNodeSelectionWindow = new NodeSelectionWindow(this, true); + m_nodeSelectionWindow = new NodeSelectionWindow(this, true); // connect the controls to the slots - connect(mTableWidget, &QTableWidget::itemSelectionChanged, this, &AttachmentsWindow::OnSelectionChanged); - connect(mOpenAttachmentButton, &QToolButton::clicked, this, &AttachmentsWindow::OnOpenAttachmentButtonClicked); - connect(mOpenDeformableAttachmentButton, &QToolButton::clicked, this, &AttachmentsWindow::OnOpenDeformableAttachmentButtonClicked); - connect(mRemoveButton, &QToolButton::clicked, this, &AttachmentsWindow::OnRemoveButtonClicked); - connect(mClearButton, &QToolButton::clicked, this, &AttachmentsWindow::OnClearButtonClicked); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnSelectionDone), this, &AttachmentsWindow::OnAttachmentNodesSelected); - connect(mNodeSelectionWindow, &NodeSelectionWindow::rejected, this, &AttachmentsWindow::OnCancelAttachmentNodeSelection); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), &QTreeWidget::itemSelectionChanged, this, &AttachmentsWindow::OnNodeChanged); - connect(mEscapeShortcut, &QShortcut::activated, this, &AttachmentsWindow::OnEscapeButtonPressed); - connect(mCancelSelectionButton, &QToolButton::clicked, this, &AttachmentsWindow::OnEscapeButtonPressed); + connect(m_tableWidget, &QTableWidget::itemSelectionChanged, this, &AttachmentsWindow::OnSelectionChanged); + connect(m_openAttachmentButton, &QToolButton::clicked, this, &AttachmentsWindow::OnOpenAttachmentButtonClicked); + connect(m_openDeformableAttachmentButton, &QToolButton::clicked, this, &AttachmentsWindow::OnOpenDeformableAttachmentButtonClicked); + connect(m_removeButton, &QToolButton::clicked, this, &AttachmentsWindow::OnRemoveButtonClicked); + connect(m_clearButton, &QToolButton::clicked, this, &AttachmentsWindow::OnClearButtonClicked); + connect(m_nodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &AttachmentsWindow::OnAttachmentNodesSelected); + connect(m_nodeSelectionWindow, &NodeSelectionWindow::rejected, this, &AttachmentsWindow::OnCancelAttachmentNodeSelection); + connect(m_nodeSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), &QTreeWidget::itemSelectionChanged, this, &AttachmentsWindow::OnNodeChanged); + connect(m_escapeShortcut, &QShortcut::activated, this, &AttachmentsWindow::OnEscapeButtonPressed); + connect(m_cancelSelectionButton, &QToolButton::clicked, this, &AttachmentsWindow::OnEscapeButtonPressed); // reinit the window ReInit(); @@ -220,13 +222,13 @@ namespace EMStudio { // get the selected actor instance const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - mActorInstance = selection.GetSingleActorInstance(); + m_actorInstance = selection.GetSingleActorInstance(); // disable controls if no actor instance is selected - if (mActorInstance == nullptr) + if (m_actorInstance == nullptr) { // set the row count - mTableWidget->setRowCount(0); + m_tableWidget->setRowCount(0); // update the interface UpdateInterface(); @@ -236,15 +238,15 @@ namespace EMStudio } // the number of existing attachments - const uint32 numAttachments = mActorInstance->GetNumAttachments(); + const int numAttachments = aznumeric_caster(m_actorInstance->GetNumAttachments()); // set table size and add header items - mTableWidget->setRowCount(numAttachments); + m_tableWidget->setRowCount(numAttachments); // loop trough all attachments and add them to the table - for (uint32 i = 0; i < numAttachments; ++i) + for (int i = 0; i < numAttachments; ++i) { - EMotionFX::Attachment* attachment = mActorInstance->GetAttachment(i); + EMotionFX::Attachment* attachment = m_actorInstance->GetAttachment(i); if (attachment == nullptr) { continue; @@ -252,29 +254,22 @@ namespace EMStudio EMotionFX::ActorInstance* attachmentInstance = attachment->GetAttachmentActorInstance(); EMotionFX::Actor* attachmentActor = attachmentInstance->GetActor(); - EMotionFX::Actor* attachedToActor = mActorInstance->GetActor(); - uint32 attachedToNodeIndex = MCORE_INVALIDINDEX32; - EMotionFX::Node* attachedToNode = nullptr; - - if (!attachment->GetIsInfluencedByMultipleJoints()) - { - attachedToNodeIndex = static_cast(attachment)->GetAttachToNodeIndex(); - } - - if (attachedToNodeIndex != MCORE_INVALIDINDEX32) - { - attachedToNode = attachedToActor->GetSkeleton()->GetNode(attachedToNodeIndex); - } + EMotionFX::Actor* attachedToActor = m_actorInstance->GetActor(); + EMotionFX::Node* attachedToNode = + !attachment->GetIsInfluencedByMultipleJoints() + ? attachedToNode = attachedToActor->GetSkeleton()->GetNode( + static_cast(attachment)->GetAttachToNodeIndex()) + : nullptr; // create table items - mTempString = AZStd::string::format("%i", attachmentInstance->GetID()); - QTableWidgetItem* tableItemID = new QTableWidgetItem(mTempString.c_str()); - AzFramework::StringFunc::Path::GetFileName(attachmentActor->GetFileNameString().c_str(), mTempString); - QTableWidgetItem* tableItemName = new QTableWidgetItem(mTempString.c_str()); - mTempString = attachment->GetIsInfluencedByMultipleJoints() ? "Yes" : "No"; - QTableWidgetItem* tableItemDeformable = new QTableWidgetItem(mTempString.c_str()); - mTempString = AZStd::string::format("%i", attachmentInstance->GetNumNodes()); - QTableWidgetItem* tableItemNumNodes = new QTableWidgetItem(mTempString.c_str()); + m_tempString = AZStd::string::format("%i", attachmentInstance->GetID()); + QTableWidgetItem* tableItemID = new QTableWidgetItem(m_tempString.c_str()); + AzFramework::StringFunc::Path::GetFileName(attachmentActor->GetFileNameString().c_str(), m_tempString); + QTableWidgetItem* tableItemName = new QTableWidgetItem(m_tempString.c_str()); + m_tempString = attachment->GetIsInfluencedByMultipleJoints() ? "Yes" : "No"; + QTableWidgetItem* tableItemDeformable = new QTableWidgetItem(m_tempString.c_str()); + m_tempString = AZStd::string::format("%zu", attachmentInstance->GetNumNodes()); + QTableWidgetItem* tableItemNumNodes = new QTableWidgetItem(m_tempString.c_str()); QTableWidgetItem* tableItemNodeName = new QTableWidgetItem(""); // set node name if exists if (attachedToNode) @@ -284,7 +279,7 @@ namespace EMStudio auto nodeSelectionButton = new AzQtComponents::BrowseEdit(); nodeSelectionButton->setPlaceholderText(attachedToNode->GetName()); nodeSelectionButton->setStyleSheet("text-align: left;"); - mTableWidget->setCellWidget(i, 4, nodeSelectionButton); + m_tableWidget->setCellWidget(i, 4, nodeSelectionButton); connect(nodeSelectionButton, &AzQtComponents::BrowseEdit::attachedButtonTriggered, this, &AttachmentsWindow::OnSelectNodeButtonClicked); } @@ -295,18 +290,18 @@ namespace EMStudio isVisibleCheckBox->setChecked(true); // add table items to the current row - mTableWidget->setCellWidget(i, 0, isVisibleCheckBox); - mTableWidget->setItem(i, 1, tableItemID); - mTableWidget->setItem(i, 2, tableItemName); - mTableWidget->setItem(i, 3, tableItemDeformable); - mTableWidget->setItem(i, 4, tableItemNodeName); - mTableWidget->setItem(i, 5, tableItemNumNodes); + m_tableWidget->setCellWidget(i, 0, isVisibleCheckBox); + m_tableWidget->setItem(i, 1, tableItemID); + m_tableWidget->setItem(i, 2, tableItemName); + m_tableWidget->setItem(i, 3, tableItemDeformable); + m_tableWidget->setItem(i, 4, tableItemNodeName); + m_tableWidget->setItem(i, 5, tableItemNumNodes); // connect the controls to the functions connect(isVisibleCheckBox, &QCheckBox::stateChanged, this, &AttachmentsWindow::OnVisibilityChanged); // set the row height - mTableWidget->setRowHeight(i, 21); + m_tableWidget->setRowHeight(i, 21); } // update the interface @@ -317,8 +312,8 @@ namespace EMStudio // update the enabled state of the remove/clear button depending on the table entries void AttachmentsWindow::OnUpdateButtonsEnabled() { - mRemoveButton->setEnabled(mTableWidget->selectedItems().size() != 0); - mClearButton->setEnabled(mTableWidget->rowCount() != 0); + m_removeButton->setEnabled(m_tableWidget->selectedItems().size() != 0); + m_clearButton->setEnabled(m_tableWidget->rowCount() != 0); } @@ -326,8 +321,8 @@ namespace EMStudio void AttachmentsWindow::UpdateInterface() { // enable/disable widgets, based on the selection state - mAttachmentsWidget->setHidden(mWaitingForAttachment); - mWaitingForAttachmentWidget->setHidden((mWaitingForAttachment == false)); + m_attachmentsWidget->setHidden(m_waitingForAttachment); + m_waitingForAttachmentWidget->setHidden((m_waitingForAttachment == false)); // update remove/clear buttons OnUpdateButtonsEnabled(); @@ -345,8 +340,8 @@ namespace EMStudio const QList urls = mimeData->urls(); // clear the drop filenames - mDropFileNames.clear(); - mDropFileNames.reserve(urls.count()); + m_dropFileNames.clear(); + m_dropFileNames.reserve(urls.count()); // get the number of urls and iterate over them AZStd::string filename; @@ -360,12 +355,12 @@ namespace EMStudio if (extension == "actor") { - mDropFileNames.push_back(filename); + m_dropFileNames.push_back(filename); } } // get the number of dropped sound files - if (mDropFileNames.empty()) + if (m_dropFileNames.empty()) { MCore::LogWarning("Drag and drop failed. No valid actor file dropped."); } @@ -416,13 +411,13 @@ namespace EMStudio MCore::CommandGroup commandGroup("Add attachments"); // skip adding if no actor instance is selected - if (mActorInstance == nullptr) + if (m_actorInstance == nullptr) { return; } // get name of the first node - EMotionFX::Actor* actor = mActorInstance->GetActor(); + EMotionFX::Actor* actor = m_actorInstance->GetActor(); if (actor == nullptr) { return; @@ -436,10 +431,10 @@ namespace EMStudio { EBUS_EVENT(AzFramework::ApplicationRequests::Bus, NormalizePathKeepCase, filename); - const uint32 actorIndex = EMotionFX::GetActorManager().FindActorIndexByFileName(filename.c_str()); + const size_t actorIndex = EMotionFX::GetActorManager().FindActorIndexByFileName(filename.c_str()); // create instance for the attachment - if (actorIndex == MCORE_INVALIDINDEX32) + if (actorIndex == InvalidIndex) { commandGroup.AddCommandString(AZStd::string::format("ImportActor -filename \"%s\"", filename.c_str()).c_str()); commandGroup.AddCommandString("CreateActorInstance -actorID %LASTRESULT%"); @@ -452,19 +447,19 @@ namespace EMStudio } // add the attachment - if (mIsDeformableAttachment == false) + if (m_isDeformableAttachment == false) { - commandGroup.AddCommandString(AZStd::string::format("AddAttachment -attachmentID %%LASTRESULT%% -attachToID %i -attachToNode \"%s\"", mActorInstance->GetID(), nodeName).c_str()); + commandGroup.AddCommandString(AZStd::string::format("AddAttachment -attachmentID %%LASTRESULT%% -attachToID %i -attachToNode \"%s\"", m_actorInstance->GetID(), nodeName).c_str()); } else { - commandGroup.AddCommandString(AZStd::string::format("AddDeformableAttachment -attachmentID %%LASTRESULT%% -attachToID %i", mActorInstance->GetID()).c_str()); + commandGroup.AddCommandString(AZStd::string::format("AddDeformableAttachment -attachmentID %%LASTRESULT%% -attachToID %i", m_actorInstance->GetID()).c_str()); } } // select the old actorinstance commandGroup.AddCommandString("Unselect -actorInstanceID SELECT_ALL -actorID SELECT_ALL"); - commandGroup.AddCommandString(AZStd::string::format("Select -actorinstanceID %i", mActorInstance->GetID()).c_str()); + commandGroup.AddCommandString(AZStd::string::format("Select -actorinstanceID %i", m_actorInstance->GetID()).c_str()); // execute the command group GetCommandManager()->ExecuteCommandGroup(commandGroup, outString); @@ -479,20 +474,18 @@ namespace EMStudio MCore::CommandGroup group(AZStd::string("Remove Attachment Actor").c_str()); // iterate trough all selected items - const uint32 numItems = items.length(); - for (uint32 i = 0; i < numItems; ++i) + for (const QTableWidgetItem* item : items) { - QTableWidgetItem* item = items[i]; if (item == nullptr || item->column() != 1) { continue; } // the attachment id - const uint32 id = GetIDFromTableRow(item->row()); + const int id = GetIDFromTableRow(item->row()); const AZStd::string nodeName = GetNodeNameFromTableRow(item->row()); - group.AddCommandString(AZStd::string::format("RemoveAttachment -attachmentID %i -attachToID %i -attachToNode \"%s\"", id, mActorInstance->GetID(), nodeName.c_str()).c_str()); + group.AddCommandString(AZStd::string::format("RemoveAttachment -attachmentID %d -attachToID %i -attachToNode \"%s\"", id, m_actorInstance->GetID(), nodeName.c_str()).c_str()); } // execute the group command @@ -506,33 +499,33 @@ namespace EMStudio // called if an actor has been dropped for normal attachments void AttachmentsWindow::OnDroppedAttachmentsActors() { - mIsDeformableAttachment = false; + m_isDeformableAttachment = false; // add attachments to the selected actorinstance - AddAttachments(mDropFileNames); + AddAttachments(m_dropFileNames); // clear the attachments array - mDropFileNames.clear(); + m_dropFileNames.clear(); } // called if an actor has been dropped for deformable attachments void AttachmentsWindow::OnDroppedDeformableActors() { - mIsDeformableAttachment = true; + m_isDeformableAttachment = true; // add attachments to the selected actorinstance - AddAttachments(mDropFileNames); + AddAttachments(m_dropFileNames); // clear the attachments array - mDropFileNames.clear(); + m_dropFileNames.clear(); } // connects two selected actor instances void AttachmentsWindow::OnAttachmentSelected() { - if (mWaitingForAttachment == false) + if (m_waitingForAttachment == false) { return; } @@ -541,13 +534,13 @@ namespace EMStudio const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); EMotionFX::ActorInstance* attachmentInstance = selection.GetSingleActorInstance(); - if (mActorInstance == nullptr || attachmentInstance == nullptr) + if (m_actorInstance == nullptr || attachmentInstance == nullptr) { return; } // get name of the first node - EMotionFX::Actor* actor = mActorInstance->GetActor(); + EMotionFX::Actor* actor = m_actorInstance->GetActor(); if (actor == nullptr) { return; @@ -557,28 +550,28 @@ namespace EMStudio const char* nodeName = actor->GetSkeleton()->GetNode(0)->GetName(); // remove the attachment in case it is already attached - mActorInstance->RemoveAttachment(attachmentInstance); + m_actorInstance->RemoveAttachment(attachmentInstance); // execute command for the attachment AZStd::string outResult; MCore::CommandGroup commandGroup("Add Attachment"); // add the attachment - if (mIsDeformableAttachment == false) + if (m_isDeformableAttachment == false) { - commandGroup.AddCommandString(AZStd::string::format("AddAttachment -attachToID %i -attachmentID %i -attachToNode \"%s\"", mActorInstance->GetID(), attachmentInstance->GetID(), nodeName).c_str()); + commandGroup.AddCommandString(AZStd::string::format("AddAttachment -attachToID %i -attachmentID %i -attachToNode \"%s\"", m_actorInstance->GetID(), attachmentInstance->GetID(), nodeName).c_str()); } else { - commandGroup.AddCommandString(AZStd::string::format("AddDeformableAttachment -attachToID %i -attachmentID %i", mActorInstance->GetID(), attachmentInstance->GetID()).c_str()); + commandGroup.AddCommandString(AZStd::string::format("AddDeformableAttachment -attachToID %i -attachmentID %i", m_actorInstance->GetID(), attachmentInstance->GetID()).c_str()); } // clear selection and select the actor instance the attachment is attached to commandGroup.AddCommandString(AZStd::string::format("ClearSelection")); - commandGroup.AddCommandString(AZStd::string::format("Select -actorInstanceID %i", mActorInstance->GetID())); + commandGroup.AddCommandString(AZStd::string::format("Select -actorInstanceID %i", m_actorInstance->GetID())); // reset the state for selection - mWaitingForAttachment = false; + m_waitingForAttachment = false; // execute the command group EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, outResult); @@ -590,14 +583,14 @@ namespace EMStudio void AttachmentsWindow::OnNodeChanged() { - NodeHierarchyWidget* hierarchyWidget = mNodeSelectionWindow->GetNodeHierarchyWidget(); + NodeHierarchyWidget* hierarchyWidget = m_nodeSelectionWindow->GetNodeHierarchyWidget(); AZStd::vector& selectedItems = hierarchyWidget->GetSelectedItems(); if (selectedItems.size() != 1) { return; } - const uint32 actorInstanceID = selectedItems[0].mActorInstanceID; + const uint32 actorInstanceID = selectedItems[0].m_actorInstanceId; const char* nodeName = selectedItems[0].GetNodeName(); EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); if (actorInstance == nullptr) @@ -605,7 +598,7 @@ namespace EMStudio return; } - assert(actorInstance == mActorInstance); + assert(actorInstance == m_actorInstance); EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(nodeName); @@ -622,18 +615,18 @@ namespace EMStudio } // reapply the attachment - mActorInstance->RemoveAttachment(attachment); + m_actorInstance->RemoveAttachment(attachment); // create and add the new attachment - EMotionFX::AttachmentNode* newAttachment = EMotionFX::AttachmentNode::Create(mActorInstance, node->GetNodeIndex(), attachment); - mActorInstance->AddAttachment(newAttachment); + EMotionFX::AttachmentNode* newAttachment = EMotionFX::AttachmentNode::Create(m_actorInstance, node->GetNodeIndex(), attachment); + m_actorInstance->AddAttachment(newAttachment); } EMotionFX::ActorInstance* AttachmentsWindow::GetSelectedAttachment() { // get the attachment id - const QList selectedTableItems = mTableWidget->selectedItems(); + const QList selectedTableItems = m_tableWidget->selectedItems(); if (selectedTableItems.length() < 1) { return nullptr; @@ -660,16 +653,15 @@ namespace EMStudio return; } - mActorInstance->RemoveAttachment(attachment); + m_actorInstance->RemoveAttachment(attachment); - EMotionFX::Actor* actor = mActorInstance->GetActor(); - EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(mNodeBeforeSelectionWindow.c_str()); + EMotionFX::Actor* actor = m_actorInstance->GetActor(); + EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(m_nodeBeforeSelectionWindow.c_str()); if (node) { - EMotionFX::AttachmentNode* newAttachment = EMotionFX::AttachmentNode::Create(mActorInstance, node->GetNodeIndex(), attachment); - mActorInstance->AddAttachment(newAttachment); - //mActorInstance->AddAttachment(node->GetNodeIndex(), attachment); + EMotionFX::AttachmentNode* newAttachment = EMotionFX::AttachmentNode::Create(m_actorInstance, node->GetNodeIndex(), attachment); + m_actorInstance->AddAttachment(newAttachment); } } @@ -677,7 +669,7 @@ namespace EMStudio void AttachmentsWindow::OnOpenAttachmentButtonClicked() { // set to normal attachment - mIsDeformableAttachment = false; + m_isDeformableAttachment = false; AZStd::vector filenames = GetMainWindow()->GetFileManager()->LoadActorsFileDialog(this); if (filenames.empty()) @@ -693,7 +685,7 @@ namespace EMStudio void AttachmentsWindow::OnOpenDeformableAttachmentButtonClicked() { // set to skin attachment - mIsDeformableAttachment = true; + m_isDeformableAttachment = true; AZStd::vector filenames = GetMainWindow()->GetFileManager()->LoadActorsFileDialog(this); if (filenames.empty()) @@ -708,26 +700,25 @@ namespace EMStudio // remove selected attachments void AttachmentsWindow::OnRemoveButtonClicked() { - uint32 lowestSelectedRow = MCORE_INVALIDINDEX32; - const QList selectedItems = mTableWidget->selectedItems(); - const int numSelectedItems = selectedItems.size(); - for (int i = 0; i < numSelectedItems; ++i) + int lowestSelectedRow = AZStd::numeric_limits::max(); + const QList selectedItems = m_tableWidget->selectedItems(); + for (const QTableWidgetItem* selectedItem : selectedItems) { - if ((uint32)selectedItems[i]->row() < lowestSelectedRow) + if (selectedItem->row() < lowestSelectedRow) { - lowestSelectedRow = (uint32)selectedItems[i]->row(); + lowestSelectedRow = selectedItem->row(); } } RemoveTableItems(selectedItems); - if (lowestSelectedRow > ((uint32)mTableWidget->rowCount() - 1)) + if (lowestSelectedRow > (m_tableWidget->rowCount() - 1)) { - mTableWidget->selectRow(lowestSelectedRow - 1); + m_tableWidget->selectRow(lowestSelectedRow - 1); } else { - mTableWidget->selectRow(lowestSelectedRow); + m_tableWidget->selectRow(lowestSelectedRow); } } @@ -735,8 +726,8 @@ namespace EMStudio // remove all attachments void AttachmentsWindow::OnClearButtonClicked() { - mTableWidget->selectAll(); - RemoveTableItems(mTableWidget->selectedItems()); + m_tableWidget->selectAll(); + RemoveTableItems(m_tableWidget->selectedItems()); } @@ -754,28 +745,28 @@ namespace EMStudio const int row = GetRowContainingWidget(widget); if (row != -1) { - mTableWidget->selectRow(row); + m_tableWidget->selectRow(row); } - mNodeBeforeSelectionWindow = GetSelectedNodeName(); + m_nodeBeforeSelectionWindow = GetSelectedNodeName(); // show the node selection window - mNodeSelectionWindow->Update(mActorInstance->GetID()); - mNodeSelectionWindow->show(); + m_nodeSelectionWindow->Update(m_actorInstance->GetID()); + m_nodeSelectionWindow->show(); } // called when the node selection is done - void AttachmentsWindow::OnAttachmentNodesSelected(MCore::Array selection) + void AttachmentsWindow::OnAttachmentNodesSelected(AZStd::vector selection) { // check if selection is valid - if (selection.GetLength() != 1) + if (selection.size() != 1) { MCore::LogDebug("No valid attachment selected."); return; } - const uint32 actorInstanceID = selection[0].mActorInstanceID; + const uint32 actorInstanceID = selection[0].m_actorInstanceId; const char* nodeName = selection[0].GetNodeName(); if (EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID) == nullptr) { @@ -796,8 +787,8 @@ namespace EMStudio AZStd::string oldNodeName = GetSelectedNodeName(); // remove and readd the attachment - commandGroup.AddCommandString(AZStd::string::format("RemoveAttachment -attachmentID %i -attachToID %i -attachToNode \"%s\"", attachment->GetID(), mActorInstance->GetID(), oldNodeName.c_str()).c_str()); - commandGroup.AddCommandString(AZStd::string::format("AddAttachment -attachToID %i -attachmentID %i -attachToNode \"%s\"", mActorInstance->GetID(), attachment->GetID(), nodeName).c_str()); + commandGroup.AddCommandString(AZStd::string::format("RemoveAttachment -attachmentID %i -attachToID %i -attachToNode \"%s\"", attachment->GetID(), m_actorInstance->GetID(), oldNodeName.c_str()).c_str()); + commandGroup.AddCommandString(AZStd::string::format("AddAttachment -attachToID %i -attachmentID %i -attachToNode \"%s\"", m_actorInstance->GetID(), attachment->GetID(), nodeName).c_str()); // execute the command group GetCommandManager()->ExecuteCommandGroup(commandGroup, outResult); @@ -807,8 +798,8 @@ namespace EMStudio // get the selected node name AZStd::string AttachmentsWindow::GetSelectedNodeName() { - const QList items = mTableWidget->selectedItems(); - const uint32 numItems = items.length(); + const QList items = m_tableWidget->selectedItems(); + const size_t numItems = items.length(); if (numItems < 1) { return AZStd::string(); @@ -842,10 +833,10 @@ namespace EMStudio // extracts the actor instance id from a given row int AttachmentsWindow::GetIDFromTableRow(int row) { - QTableWidgetItem* item = mTableWidget->item(row, 1); + QTableWidgetItem* item = m_tableWidget->item(row, 1); if (item == nullptr) { - return MCORE_INVALIDINDEX32; + return MCore::InvalidIndexT; } AZStd::string id; @@ -858,10 +849,10 @@ namespace EMStudio // extracts the node name from a given row AZStd::string AttachmentsWindow::GetNodeNameFromTableRow(int row) { - QTableWidgetItem* item = mTableWidget->item(row, 4); + QTableWidgetItem* item = m_tableWidget->item(row, 4); if (item == nullptr) { - return AZStd::string(); + return {}; } return FromQtString(item->whatsThis()); @@ -872,13 +863,13 @@ namespace EMStudio int AttachmentsWindow::GetRowContainingWidget(const QWidget* widget) { // loop trough the table items and search for widget - const uint32 numRows = mTableWidget->rowCount(); - const uint32 numCols = mTableWidget->columnCount(); - for (uint32 i = 0; i < numRows; ++i) + const int numRows = m_tableWidget->rowCount(); + const int numCols = m_tableWidget->columnCount(); + for (int i = 0; i < numRows; ++i) { - for (uint32 j = 0; j < numCols; ++j) + for (int j = 0; j < numCols; ++j) { - if (mTableWidget->cellWidget(i, j) == widget) + if (m_tableWidget->cellWidget(i, j) == widget) { return i; } @@ -899,7 +890,7 @@ namespace EMStudio // cancel selection of escape button is pressed void AttachmentsWindow::OnEscapeButtonPressed() { - mWaitingForAttachment = false; + m_waitingForAttachment = false; UpdateInterface(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.h index dd00ae6cb0..9d3cb2d0f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/Attachments/AttachmentsWindow.h @@ -56,7 +56,7 @@ namespace EMStudio void AddAttachments(const AZStd::vector& filenames); void OnAttachmentSelected(); - bool GetIsWaitingForAttachment() const { return mWaitingForAttachment; } + bool GetIsWaitingForAttachment() const { return m_waitingForAttachment; } EMotionFX::ActorInstance* GetSelectedAttachment(); AZStd::string GetSelectedNodeName(); @@ -78,7 +78,7 @@ namespace EMStudio void OnDroppedAttachmentsActors(); void OnDroppedDeformableActors(); void OnVisibilityChanged(int visibility); - void OnAttachmentNodesSelected(MCore::Array selection); + void OnAttachmentNodesSelected(AZStd::vector selection); void OnCancelAttachmentNodeSelection(); void OnEscapeButtonPressed(); void OnUpdateButtonsEnabled(); @@ -89,35 +89,35 @@ namespace EMStudio AZStd::string GetNodeNameFromTableRow(int row); int GetRowContainingWidget(const QWidget* widget); - bool mWaitingForAttachment; - bool mIsDeformableAttachment; + bool m_waitingForAttachment; + bool m_isDeformableAttachment; - QVBoxLayout* mWaitingForAttachmentLayout; - QVBoxLayout* mNoSelectionLayout; - QVBoxLayout* mMainLayout; - QVBoxLayout* mAttachmentsLayout; + QVBoxLayout* m_waitingForAttachmentLayout; + QVBoxLayout* m_noSelectionLayout; + QVBoxLayout* m_mainLayout; + QVBoxLayout* m_attachmentsLayout; - QWidget* mAttachmentsWidget; - QWidget* mWaitingForAttachmentWidget; - QWidget* mNoSelectionWidget; + QWidget* m_attachmentsWidget; + QWidget* m_waitingForAttachmentWidget; + QWidget* m_noSelectionWidget; - QShortcut* mEscapeShortcut; + QShortcut* m_escapeShortcut; - QTableWidget* mTableWidget; - EMotionFX::ActorInstance* mActorInstance; - AZStd::vector mAttachments; - AZStd::string mNodeBeforeSelectionWindow; + QTableWidget* m_tableWidget; + EMotionFX::ActorInstance* m_actorInstance; + AZStd::vector m_attachments; + AZStd::string m_nodeBeforeSelectionWindow; - QToolButton* mOpenAttachmentButton; - QToolButton* mOpenDeformableAttachmentButton; - QToolButton* mRemoveButton; - QToolButton* mClearButton; - QToolButton* mCancelSelectionButton; + QToolButton* m_openAttachmentButton; + QToolButton* m_openDeformableAttachmentButton; + QToolButton* m_removeButton; + QToolButton* m_clearButton; + QToolButton* m_cancelSelectionButton; - NodeSelectionWindow* mNodeSelectionWindow; + NodeSelectionWindow* m_nodeSelectionWindow; - AZStd::vector mDropFileNames; - AZStd::string mTempString; + AZStd::vector m_dropFileNames; + AZStd::string m_tempString; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBar/CommandBarPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBar/CommandBarPlugin.cpp index f06dedfc67..80577de3b4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBar/CommandBarPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBar/CommandBarPlugin.cpp @@ -91,11 +91,11 @@ namespace EMStudio m_commandEdit = new QLineEdit(); m_commandEdit->setPlaceholderText("Enter command"); connect(m_commandEdit, &QLineEdit::returnPressed, this, &CommandBarPlugin::OnEnter); - m_commandEditAction = mBar->addWidget(m_commandEdit); + m_commandEditAction = m_bar->addWidget(m_commandEdit); m_resultEdit = new QLineEdit(); m_resultEdit->setReadOnly(true); - m_commandResultAction = mBar->addWidget(m_resultEdit); + m_commandResultAction = m_bar->addWidget(m_resultEdit); m_globalSimSpeedSlider = new AzQtComponents::SliderDouble(Qt::Horizontal); m_globalSimSpeedSlider->setMaximumWidth(80); @@ -104,9 +104,9 @@ namespace EMStudio m_globalSimSpeedSlider->setValue(1.0); m_globalSimSpeedSlider->setToolTip("The global simulation speed factor.\nA value of 1.0 means the normal speed, which is when the slider handle is in the center.\nPress the button on the right of this slider to reset to the normal speed."); connect(m_globalSimSpeedSlider, &AzQtComponents::SliderDouble::valueChanged, this, &CommandBarPlugin::OnGlobalSimSpeedChanged); - m_globalSimSpeedSliderAction = mBar->addWidget(m_globalSimSpeedSlider); + m_globalSimSpeedSliderAction = m_bar->addWidget(m_globalSimSpeedSlider); - m_globalSimSpeedResetAction = mBar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Reset.svg"), + m_globalSimSpeedResetAction = m_bar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Reset.svg"), tr("Reset the global simulation speed factor to its normal speed"), this, &CommandBarPlugin::ResetGlobalSimSpeed); @@ -114,7 +114,7 @@ namespace EMStudio m_progressText->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); m_progressText->setAlignment(Qt::AlignRight); m_progressText->setStyleSheet("padding-right: 1px; color: rgb(140, 140, 140);"); - m_progressTextAction = mBar->addWidget(m_progressText); + m_progressTextAction = m_bar->addWidget(m_progressText); m_progressTextAction->setVisible(false); m_progressBar = new QProgressBar(); @@ -122,10 +122,10 @@ namespace EMStudio m_progressBar->setValue(0); m_progressBar->setMaximumWidth(300); m_progressBar->setStyleSheet("padding-right: 2px;"); - m_progressBarAction = mBar->addWidget(m_progressBar); + m_progressBarAction = m_bar->addWidget(m_progressBar); m_progressBarAction->setVisible(false); - m_lockSelectionAction = mBar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Reset.svg"), + m_lockSelectionAction = m_bar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Reset.svg"), tr("Lock or unlock the selection of actor instances"), this, &CommandBarPlugin::OnLockSelectionButton); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.cpp deleted file mode 100644 index 2a8a8f99bc..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -/* - -// include required headers -#include "CommandBrowserPlugin.h" -#include "../../../../EMStudioSDK/Source/EMStudioManager.h" -#include - - -namespace EMStudio -{ - -// constructor -CommandBrowserPlugin::CommandBrowserPlugin() : EMStudio::DockWidgetPlugin() -{ - mWebView = nullptr; -} - - -// destructor -CommandBrowserPlugin::~CommandBrowserPlugin() -{ -} - - -// clone the log window -EMStudioPlugin* CommandBrowserPlugin::Clone() -{ - CommandBrowserPlugin* newPlugin = new CommandBrowserPlugin(); - return newPlugin; -} - - -// init after the parent dock window has been created -bool CommandBrowserPlugin::Init() -{ - //LogInfo("Initializing command browser window."); - //QWebSettings::globalSettings()->setAttribute(QWebSettings::JavascriptEnabled, true); - mWebView = new QWebView( mDock ); - mWebView->setObjectName( "QWebView" ); - mWebView->settings()->setAttribute(QWebSettings::JavascriptEnabled, true); - mWebView->settings()->setAttribute(QWebSettings::JavascriptCanOpenWindows, true ); - mDock->SetContents( mWebView ); - GenerateCommandList(); - return true; -} - - -void CommandBrowserPlugin::GenerateCommandList() -{ - CommandSystem::CommandManager* manager = GetCommandManager(); - - uint32 i; - const uint32 numCommands = manager->GetNumRegisteredCommands(); - - // generate the html header - QString html; - html = ""; - html += ""; - html += "\n"; - - html += "\n"; - html += "\n"; - html += "\n"; - - // init all commands as closed - html += "\n"; - - // write the alphabet - html += "\n"; - MCore::Command* prevCommand = nullptr; - for (i=0; iGetCommand(i); - - // find out if we need to show the leading character - bool newFirstCharacter = false; - if (prevCommand == nullptr) - newFirstCharacter = true; - else - if (prevCommand->GetName()[0] != command->GetName()[0]) - newFirstCharacter = true; - - // display the first character as link - if (newFirstCharacter) - { - const char character = command->GetName()[0]; - QString newString; - newString.sprintf("%c ", character, character); - html += newString; - } - - prevCommand = command; - } - html += ""; - html += "
"; - html += "
"; - html += "
\n"; - - - // show all commands as links - prevCommand = nullptr; - for (i=0; iGetCommand(i); - - // find out if we need to show the leading character - bool newFirstCharacter = false; - if (prevCommand == nullptr) - newFirstCharacter = true; - else - if (prevCommand->GetName()[0] != command->GetName()[0]) - newFirstCharacter = true; - - if (newFirstCharacter) - { - // if this isn't the first command - if (i != 0) - { - html += "
"; - //html += "
"; - html += "
"; - } - - QString newString; - newString.sprintf("", command->GetName()[0]); - html += newString; - - html += "\n"; - html += (char)command->GetName()[0]; - html += ""; - - html += "
"; - html += "
"; - //html += "
"; - //html += "
"; - } - - QString newString; - newString.sprintf("
%s
\n", command->GetName(), command->GetName()); - html += newString; - newString.sprintf("
\n", command->GetName()); - html += newString; - - prevCommand = command; - } - html += "\n"; - - - // set the html code - mWebView->setHtml( html ); -} - -} // namespace EMStudio -*/ diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.h deleted file mode 100644 index b4aa695ce5..0000000000 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/CommandBrowser/CommandBrowserPlugin.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#ifndef __EMSTUDIO_COMMANDBROWSERPLUGIN_H -#define __EMSTUDIO_COMMANDBROWSERPLUGIN_H -/* -// include MCore -//#include #include "LogWindowCallback.h" #include #include @@ -26,7 +27,7 @@ namespace EMStudio qRegisterMetaType(); // init the max second column width - mMaxSecondColumnWidth = 0; + m_maxSecondColumnWidth = 0; // init the table setColumnCount(2); @@ -46,9 +47,9 @@ namespace EMStudio // set the filter #ifdef AZ_DEBUG_BUILD - mFilter = LOGLEVEL_FATAL | LOGLEVEL_ERROR | LOGLEVEL_WARNING | LOGLEVEL_INFO | LOGLEVEL_DETAILEDINFO | LOGLEVEL_DEBUG; + m_filter = LOGLEVEL_FATAL | LOGLEVEL_ERROR | LOGLEVEL_WARNING | LOGLEVEL_INFO | LOGLEVEL_DETAILEDINFO | LOGLEVEL_DEBUG; #else - mFilter = LOGLEVEL_FATAL | LOGLEVEL_ERROR | LOGLEVEL_WARNING | LOGLEVEL_INFO; + m_filter = LOGLEVEL_FATAL | LOGLEVEL_ERROR | LOGLEVEL_WARNING | LOGLEVEL_INFO; #endif connect(this, &LogWindowCallback::DoLog, this, &LogWindowCallback::LogImpl, Qt::QueuedConnection); @@ -112,17 +113,17 @@ namespace EMStudio setItem(newRowIndex, 1, messageItem); // check the filter, if the filter is not enabled, it's not needed to test the find value - if ((mFilter & (int)logLevel) != 0) + if ((m_filter & (int)logLevel) != 0) { // check the find value, set the row not visible if the text is not found - if (messageItem->text().contains(mFind, Qt::CaseInsensitive)) + if (messageItem->text().contains(m_find, Qt::CaseInsensitive)) { // set the row not hidden setRowHidden(newRowIndex, false); // custom resize of the column to be efficient const int itemWidth = itemDelegate()->sizeHint(viewOptions(), indexFromItem(messageItem)).width(); - mMaxSecondColumnWidth = qMax(mMaxSecondColumnWidth, itemWidth); + m_maxSecondColumnWidth = qMax(m_maxSecondColumnWidth, itemWidth); SetColumnWidthToTakeWholeSpace(); } else @@ -144,10 +145,10 @@ namespace EMStudio void LogWindowCallback::SetFind(const QString& find) { // store the new find - mFind = find; + m_find = find; // init the max second column width - mMaxSecondColumnWidth = 0; + m_maxSecondColumnWidth = 0; // test each row with the new find const int numRows = rowCount(); @@ -158,17 +159,17 @@ namespace EMStudio const int logLevel = messageItem->data(Qt::UserRole).toInt(); // check the filter, if the filter is not enabled, it's not needed to test the find value - if ((mFilter & logLevel) != 0) + if ((m_filter & logLevel) != 0) { // check the find value, set the row not visible if the text is not found - if (messageItem->text().contains(mFind, Qt::CaseInsensitive)) + if (messageItem->text().contains(m_find, Qt::CaseInsensitive)) { // set the row not hidden setRowHidden(i, false); // update the new column width to keep the maximum const int itemWidth = itemDelegate()->sizeHint(viewOptions(), indexFromItem(messageItem)).width(); - mMaxSecondColumnWidth = qMax(mMaxSecondColumnWidth, itemWidth); + m_maxSecondColumnWidth = qMax(m_maxSecondColumnWidth, itemWidth); } else { @@ -190,10 +191,10 @@ namespace EMStudio void LogWindowCallback::SetFilter(uint32 filter) { // store the new filter - mFilter = filter; + m_filter = filter; // init the max second column width - mMaxSecondColumnWidth = 0; + m_maxSecondColumnWidth = 0; // test each row with the new find const int numRows = rowCount(); @@ -204,17 +205,17 @@ namespace EMStudio const int logLevel = messageItem->data(Qt::UserRole).toInt(); // check the filter, if the filter is not enabled, it's not needed to test the find value - if ((mFilter & logLevel) != 0) + if ((m_filter & logLevel) != 0) { // check the find value, set the row not visible if the text is not found - if (messageItem->text().contains(mFind, Qt::CaseInsensitive)) + if (messageItem->text().contains(m_find, Qt::CaseInsensitive)) { // set the row not hidden setRowHidden(i, false); // update the new column width to keep the maximum const int itemWidth = itemDelegate()->sizeHint(viewOptions(), indexFromItem(messageItem)).width(); - mMaxSecondColumnWidth = qMax(mMaxSecondColumnWidth, itemWidth); + m_maxSecondColumnWidth = qMax(m_maxSecondColumnWidth, itemWidth); } else { @@ -262,13 +263,13 @@ namespace EMStudio { const int firstColumnWidth = columnWidth(0); const int widthWihoutFirstColumnWidth = qMax(0, viewport()->width() - firstColumnWidth); - if (mMaxSecondColumnWidth < widthWihoutFirstColumnWidth) + if (m_maxSecondColumnWidth < widthWihoutFirstColumnWidth) { setColumnWidth(1, widthWihoutFirstColumnWidth); } else { - setColumnWidth(1, mMaxSecondColumnWidth); + setColumnWidth(1, m_maxSecondColumnWidth); } } @@ -280,7 +281,7 @@ namespace EMStudio const QList items = selectedItems(); // get the number of selected items - const uint32 numSelectedItems = items.count(); + const int numSelectedItems = items.count(); // check if nothing needed to be copied if (numSelectedItems == 0) @@ -289,27 +290,27 @@ namespace EMStudio } // filter the items - MCore::Array rowIndices; - rowIndices.Reserve(numSelectedItems); - for (uint32 i = 0; i < numSelectedItems; ++i) + AZStd::vector rowIndices; + rowIndices.reserve(numSelectedItems); + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = items[i]->row(); - if (rowIndices.Find(rowIndex) == MCORE_INVALIDINDEX32) + const int rowIndex = items[i]->row(); + if (AZStd::find(begin(rowIndices), end(rowIndices), rowIndex) == end(rowIndices)) { - rowIndices.Add(rowIndex); + rowIndices.emplace_back(rowIndex); } } // sort the array to copy the item in order - rowIndices.Sort(); + AZStd::sort(begin(rowIndices), end(rowIndices)); // get the number of selected rows - const uint32 numSelectedRows = rowIndices.GetLength(); + const size_t numSelectedRows = rowIndices.size(); // genereate the clipboard text QString clipboardText; - const uint32 lastIndex = numSelectedRows - 1; - for (uint32 i = 0; i < numSelectedRows; ++i) + const size_t lastIndex = numSelectedRows - 1; + for (size_t i = 0; i < numSelectedRows; ++i) { const QString time = item(rowIndices[i], 0)->text(); const QString message = item(rowIndices[i], 1)->text(); @@ -344,7 +345,7 @@ namespace EMStudio { setRowCount(0); setColumnWidth(1, 0); - mMaxSecondColumnWidth = 0; + m_maxSecondColumnWidth = 0; } @@ -359,7 +360,7 @@ namespace EMStudio QMenu menu(this); // add actions - if (items.size() > 0) + if (!items.empty()) { QAction* copyAction = menu.addAction("Copy"); connect(copyAction, &QAction::triggered, this, &LogWindowCallback::Copy); @@ -369,7 +370,7 @@ namespace EMStudio QAction* selectAllAction = menu.addAction("Select All"); connect(selectAllAction, &QAction::triggered, this, &LogWindowCallback::SelectAll); } - if (items.size() > 0) + if (!items.empty()) { QAction* UnselectAllAction = menu.addAction("Unselect All"); connect(UnselectAllAction, &QAction::triggered, this, &LogWindowCallback::UnselectAll); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.h index 3a1598e120..2e319e1dfa 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowCallback.h @@ -40,13 +40,13 @@ namespace EMStudio void SetFind(const QString& find); QString GetFind() const { - return mFind; + return m_find; } void SetFilter(uint32 filter); uint32 GetFilter() const { - return mFilter; + return m_filter; } protected: @@ -70,9 +70,9 @@ namespace EMStudio void SetColumnWidthToTakeWholeSpace(); private: - QString mFind; - uint32 mFilter; - int mMaxSecondColumnWidth; + QString m_find; + uint32 m_filter; + int m_maxSecondColumnWidth; bool m_scrollToBottom; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.cpp index 49bf04bf3b..8fd80bb584 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.cpp @@ -20,7 +20,7 @@ namespace EMStudio LogWindowPlugin::LogWindowPlugin() : EMStudio::DockWidgetPlugin() { - mLogCallback = nullptr; + m_logCallback = nullptr; } @@ -28,8 +28,8 @@ namespace EMStudio LogWindowPlugin::~LogWindowPlugin() { // remove the callback from the log manager (automatically deletes from memory as well) - const uint32 index = MCore::GetLogManager().FindLogCallback(mLogCallback); - if (index != MCORE_INVALIDINDEX32) + const size_t index = MCore::GetLogManager().FindLogCallback(m_logCallback); + if (index != InvalidIndex) { MCore::GetLogManager().RemoveLogCallback(index); } @@ -83,7 +83,7 @@ namespace EMStudio bool LogWindowPlugin::Init() { // create the widget - QWidget* windowWidget = new QWidget(mDock); + QWidget* windowWidget = new QWidget(m_dock); // create the layout QVBoxLayout* windowWidgetLayout = new QVBoxLayout(); @@ -91,7 +91,7 @@ namespace EMStudio windowWidgetLayout->setMargin(3); // create the find widget - mSearchWidget = new AzQtComponents::FilteredSearchWidget(windowWidget); + m_searchWidget = new AzQtComponents::FilteredSearchWidget(windowWidget); AddFilter(tr("Fatal"), MCore::LogCallback::LOGLEVEL_FATAL, true); AddFilter(tr("Error"), MCore::LogCallback::LOGLEVEL_ERROR, true); AddFilter(tr("Warning"), MCore::LogCallback::LOGLEVEL_WARNING, true); @@ -103,13 +103,13 @@ namespace EMStudio AddFilter(tr("Detailed Info"), MCore::LogCallback::LOGLEVEL_DETAILEDINFO, false); AddFilter(tr("Debug"), MCore::LogCallback::LOGLEVEL_DEBUG, false); #endif - connect(mSearchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, this, &LogWindowPlugin::OnTextFilterChanged); - connect(mSearchWidget, &AzQtComponents::FilteredSearchWidget::TypeFilterChanged, this, &LogWindowPlugin::OnTypeFilterChanged); + connect(m_searchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, this, &LogWindowPlugin::OnTextFilterChanged); + connect(m_searchWidget, &AzQtComponents::FilteredSearchWidget::TypeFilterChanged, this, &LogWindowPlugin::OnTypeFilterChanged); // create the filter layout QHBoxLayout* topLayout = new QHBoxLayout(); topLayout->addWidget(new QLabel("Filter:")); - topLayout->addWidget(mSearchWidget); + topLayout->addWidget(m_searchWidget); topLayout->addStretch(); topLayout->setSpacing(6); @@ -117,18 +117,18 @@ namespace EMStudio windowWidgetLayout->addLayout(topLayout); // create and add the table and callback - mLogCallback = new LogWindowCallback(nullptr); - windowWidgetLayout->addWidget(mLogCallback); + m_logCallback = new LogWindowCallback(nullptr); + windowWidgetLayout->addWidget(m_logCallback); // set the layout windowWidget->setLayout(windowWidgetLayout); // set the table as content - mDock->setWidget(windowWidget); + m_dock->setWidget(windowWidget); // create the callback - mLogCallback->SetLogLevels(MCore::LogCallback::LOGLEVEL_ALL); - MCore::GetLogManager().AddLogCallback(mLogCallback); + m_logCallback->SetLogLevels(MCore::LogCallback::LOGLEVEL_ALL); + MCore::GetLogManager().AddLogCallback(m_logCallback); // return true because the plugin is correctly initialized return true; @@ -138,7 +138,7 @@ namespace EMStudio // find changed void LogWindowPlugin::OnTextFilterChanged(const QString& text) { - mLogCallback->SetFind(text); + m_logCallback->SetFind(text); } @@ -150,7 +150,7 @@ namespace EMStudio { newFilter |= filter.metadata.toInt(); } - mLogCallback->SetFilter(newFilter); + m_logCallback->SetFilter(newFilter); } @@ -159,7 +159,7 @@ namespace EMStudio AzQtComponents::SearchTypeFilter filter(tr("Level"), name); filter.metadata = static_cast(level); filter.enabled = enabled; - mSearchWidget->AddTypeFilter(filter); + m_searchWidget->AddTypeFilter(filter); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.h index 1b40b3fa2a..61b6ab4b8c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/LogWindow/LogWindowPlugin.h @@ -61,8 +61,8 @@ namespace EMStudio private: void AddFilter(const QString& name, MCore::LogCallback::ELogLevel level, bool enabled); - LogWindowCallback* mLogCallback; - AzQtComponents::FilteredSearchWidget* mSearchWidget; + LogWindowCallback* m_logCallback; + AzQtComponents::FilteredSearchWidget* m_searchWidget; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.cpp index 278159e4d0..7a38b0813d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.cpp @@ -21,11 +21,11 @@ namespace EMStudio : QDialog(parent) { // keep values - mActorInstance = actorInstance; - mMorphTarget = morphTarget; + m_actorInstance = actorInstance; + m_morphTarget = morphTarget; // init the phoneme selection window - mPhonemeSelectionWindow = nullptr; + m_phonemeSelectionWindow = nullptr; // set the window name setWindowTitle(QString("Edit Morph Target: %1").arg(morphTarget->GetName())); @@ -35,35 +35,35 @@ namespace EMStudio layout->setAlignment(Qt::AlignVCenter); // get the morph target range min/max - const float morphTargetRangeMin = mMorphTarget->GetRangeMin(); - const float morphTargetRangeMax = mMorphTarget->GetRangeMax(); + const float morphTargetRangeMin = m_morphTarget->GetRangeMin(); + const float morphTargetRangeMax = m_morphTarget->GetRangeMax(); // create the range min label QLabel* rangeMinLabel = new QLabel("Range Min"); // create the range min double spinbox - mRangeMin = new AzQtComponents::DoubleSpinBox(); - mRangeMin->setSingleStep(0.1); - mRangeMin->setRange(std::numeric_limits::lowest(), morphTargetRangeMax); - mRangeMin->setValue(morphTargetRangeMin); - connect(mRangeMin, qOverload(&QDoubleSpinBox::valueChanged), this, &MorphTargetEditWindow::MorphTargetRangeMinValueChanged); + m_rangeMin = new AzQtComponents::DoubleSpinBox(); + m_rangeMin->setSingleStep(0.1); + m_rangeMin->setRange(std::numeric_limits::lowest(), morphTargetRangeMax); + m_rangeMin->setValue(morphTargetRangeMin); + connect(m_rangeMin, qOverload(&QDoubleSpinBox::valueChanged), this, &MorphTargetEditWindow::MorphTargetRangeMinValueChanged); // create the range max label QLabel* rangeMaxLabel = new QLabel("Range Max"); // create the range max double spinbox - mRangeMax = new AzQtComponents::DoubleSpinBox(); - mRangeMax->setSingleStep(0.1); - mRangeMax->setRange(morphTargetRangeMin, std::numeric_limits::max()); - mRangeMax->setValue(morphTargetRangeMax); - connect(mRangeMax, qOverload(&QDoubleSpinBox::valueChanged), this, &MorphTargetEditWindow::MorphTargetRangeMaxValueChanged); + m_rangeMax = new AzQtComponents::DoubleSpinBox(); + m_rangeMax->setSingleStep(0.1); + m_rangeMax->setRange(morphTargetRangeMin, std::numeric_limits::max()); + m_rangeMax->setValue(morphTargetRangeMax); + connect(m_rangeMax, qOverload(&QDoubleSpinBox::valueChanged), this, &MorphTargetEditWindow::MorphTargetRangeMaxValueChanged); // create the grid layout QGridLayout* gridLayout = new QGridLayout(); gridLayout->addWidget(rangeMinLabel, 0, 0); - gridLayout->addWidget(mRangeMin, 0, 1); + gridLayout->addWidget(m_rangeMin, 0, 1); gridLayout->addWidget(rangeMaxLabel, 1, 0); - gridLayout->addWidget(mRangeMax, 1, 1); + gridLayout->addWidget(m_rangeMax, 1, 1); // create the buttons layout QHBoxLayout* buttonsLayout = new QHBoxLayout(); @@ -95,36 +95,36 @@ namespace EMStudio MorphTargetEditWindow::~MorphTargetEditWindow() { - delete mPhonemeSelectionWindow; + delete m_phonemeSelectionWindow; } void MorphTargetEditWindow::UpdateInterface() { // get the morph target range min/max - const float morphTargetRangeMin = mMorphTarget->GetRangeMin(); - const float morphTargetRangeMax = mMorphTarget->GetRangeMax(); + const float morphTargetRangeMin = m_morphTarget->GetRangeMin(); + const float morphTargetRangeMax = m_morphTarget->GetRangeMax(); // disable signals - mRangeMin->blockSignals(true); - mRangeMax->blockSignals(true); + m_rangeMin->blockSignals(true); + m_rangeMax->blockSignals(true); // update the range min - mRangeMin->setRange(std::numeric_limits::lowest(), morphTargetRangeMax); - mRangeMin->setValue(morphTargetRangeMin); + m_rangeMin->setRange(std::numeric_limits::lowest(), morphTargetRangeMax); + m_rangeMin->setValue(morphTargetRangeMin); // update the range max - mRangeMax->setRange(morphTargetRangeMin, std::numeric_limits::max()); - mRangeMax->setValue(morphTargetRangeMax); + m_rangeMax->setRange(morphTargetRangeMin, std::numeric_limits::max()); + m_rangeMax->setValue(morphTargetRangeMax); // enable signals - mRangeMin->blockSignals(false); - mRangeMax->blockSignals(false); + m_rangeMin->blockSignals(false); + m_rangeMax->blockSignals(false); // update the phoneme selection window - if (mPhonemeSelectionWindow) + if (m_phonemeSelectionWindow) { - mPhonemeSelectionWindow->UpdateInterface(); + m_phonemeSelectionWindow->UpdateInterface(); } } @@ -132,24 +132,24 @@ namespace EMStudio void MorphTargetEditWindow::MorphTargetRangeMinValueChanged(double value) { const float rangeMin = (float)value; - mRangeMax->setRange(rangeMin, std::numeric_limits::max()); + m_rangeMax->setRange(rangeMin, std::numeric_limits::max()); } void MorphTargetEditWindow::MorphTargetRangeMaxValueChanged(double value) { const float rangeMax = (float)value; - mRangeMin->setRange(std::numeric_limits::lowest(), rangeMax); + m_rangeMin->setRange(std::numeric_limits::lowest(), rangeMax); } void MorphTargetEditWindow::Accepted() { - const float rangeMin = (float)mRangeMin->value(); - const float rangeMax = (float)mRangeMax->value(); + const float rangeMin = (float)m_rangeMin->value(); + const float rangeMax = (float)m_rangeMax->value(); AZStd::string result; - AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %i -name \"%s\" -rangeMin %f -rangeMax %f", mActorInstance->GetID(), mActorInstance->GetLODLevel(), mMorphTarget->GetNameString().c_str(), rangeMin, rangeMax); + AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %zu -name \"%s\" -rangeMin %f -rangeMax %f", m_actorInstance->GetID(), m_actorInstance->GetLODLevel(), m_morphTarget->GetNameString().c_str(), rangeMin, rangeMax); if (EMStudio::GetCommandManager()->ExecuteCommand(command, result) == false) { AZ_Error("EMotionFX", false, result.c_str()); @@ -161,9 +161,9 @@ namespace EMStudio void MorphTargetEditWindow::EditPhonemeButtonClicked() { - delete mPhonemeSelectionWindow; - mPhonemeSelectionWindow = new PhonemeSelectionWindow(mActorInstance->GetActor(), mActorInstance->GetLODLevel(), mMorphTarget, this); - mPhonemeSelectionWindow->exec(); + delete m_phonemeSelectionWindow; + m_phonemeSelectionWindow = new PhonemeSelectionWindow(m_actorInstance->GetActor(), m_actorInstance->GetLODLevel(), m_morphTarget, this); + m_phonemeSelectionWindow->exec(); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.h index e5f6d59055..9439c9d84c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetEditWindow.h @@ -31,7 +31,7 @@ namespace EMStudio ~MorphTargetEditWindow(); void UpdateInterface(); - EMotionFX::MorphTarget* GetMorphTarget() { return mMorphTarget; } + EMotionFX::MorphTarget* GetMorphTarget() { return m_morphTarget; } public slots: void Accepted(); @@ -40,10 +40,10 @@ namespace EMStudio void EditPhonemeButtonClicked(); private: - EMotionFX::ActorInstance* mActorInstance; - EMotionFX::MorphTarget* mMorphTarget; - AzQtComponents::DoubleSpinBox* mRangeMin; - AzQtComponents::DoubleSpinBox* mRangeMax; - PhonemeSelectionWindow* mPhonemeSelectionWindow; + EMotionFX::ActorInstance* m_actorInstance; + EMotionFX::MorphTarget* m_morphTarget; + AzQtComponents::DoubleSpinBox* m_rangeMin; + AzQtComponents::DoubleSpinBox* m_rangeMax; + PhonemeSelectionWindow* m_phonemeSelectionWindow; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.cpp index 9d75f648b1..2fec1f424f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.cpp @@ -23,11 +23,11 @@ namespace EMStudio : QWidget(parent) { // keep values - mName = name; - mActorInstance = actorInstance; + m_name = name; + m_actorInstance = actorInstance; // init the edit window to nullptr - mEditWindow = nullptr; + m_editWindow = nullptr; // create the layout QVBoxLayout* layout = new QVBoxLayout(); @@ -35,9 +35,9 @@ namespace EMStudio layout->setMargin(0); // checkbox to enable/disable manual mode for all morph targets - mSelectAll = new QCheckBox("Select All"); - mSelectAll->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); - connect(mSelectAll, &QCheckBox::stateChanged, this, &MorphTargetGroupWidget::SetManualModeForAll); + m_selectAll = new QCheckBox("Select All"); + m_selectAll->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); + connect(m_selectAll, &QCheckBox::stateChanged, this, &MorphTargetGroupWidget::SetManualModeForAll); // button for resetting all morph targets QPushButton* resetAll = new QPushButton("Reset All"); @@ -46,7 +46,7 @@ namespace EMStudio // add controls to the top layout QHBoxLayout* topControlLayout = new QHBoxLayout(); - topControlLayout->addWidget(mSelectAll); + topControlLayout->addWidget(m_selectAll); topControlLayout->addWidget(resetAll); topControlLayout->setSpacing(5); topControlLayout->setMargin(0); @@ -60,13 +60,13 @@ namespace EMStudio gridLayout->setVerticalSpacing(2); const size_t numMorphTargets = morphTargets.size(); - mMorphTargets.resize(numMorphTargets); + m_morphTargets.resize(numMorphTargets); for (size_t i=0; iaddWidget(numberLabel, intIndex, 0); // add the manual mode checkbox - mMorphTargets[i].mManualMode = new QCheckBox(); - mMorphTargets[i].mManualMode->setMaximumWidth(15); - mMorphTargets[i].mManualMode->setProperty("MorphTargetIndex", intIndex); - mMorphTargets[i].mManualMode->setStyleSheet("QCheckBox{ spacing: 0px; }"); - gridLayout->addWidget(mMorphTargets[i].mManualMode, intIndex, 1); - connect(mMorphTargets[i].mManualMode, &QCheckBox::clicked, this, &MorphTargetGroupWidget::ManualModeClicked); + m_morphTargets[i].m_manualMode = new QCheckBox(); + m_morphTargets[i].m_manualMode->setMaximumWidth(15); + m_morphTargets[i].m_manualMode->setProperty("MorphTargetIndex", intIndex); + m_morphTargets[i].m_manualMode->setStyleSheet("QCheckBox{ spacing: 0px; }"); + gridLayout->addWidget(m_morphTargets[i].m_manualMode, intIndex, 1); + connect(m_morphTargets[i].m_manualMode, &QCheckBox::clicked, this, &MorphTargetGroupWidget::ManualModeClicked); // create slider to adjust the morph target - mMorphTargets[i].mSliderWeight = new AzQtComponents::SliderDoubleCombo(); - mMorphTargets[i].mSliderWeight->setMinimumWidth(50); - mMorphTargets[i].mSliderWeight->setProperty("MorphTargetIndex", intIndex); - mMorphTargets[i].mSliderWeight->spinbox()->setMinimumWidth(40); - mMorphTargets[i].mSliderWeight->spinbox()->setMaximumWidth(40); - gridLayout->addWidget(mMorphTargets[i].mSliderWeight, intIndex, 2); - connect(mMorphTargets[i].mSliderWeight, &AzQtComponents::SliderDoubleCombo::valueChanged, this, &MorphTargetGroupWidget::SliderWeightMoved); - connect(mMorphTargets[i].mSliderWeight, &AzQtComponents::SliderDoubleCombo::editingFinished, this, &MorphTargetGroupWidget::SliderWeightReleased); + m_morphTargets[i].m_sliderWeight = new AzQtComponents::SliderDoubleCombo(); + m_morphTargets[i].m_sliderWeight->setMinimumWidth(50); + m_morphTargets[i].m_sliderWeight->setProperty("MorphTargetIndex", intIndex); + m_morphTargets[i].m_sliderWeight->spinbox()->setMinimumWidth(40); + m_morphTargets[i].m_sliderWeight->spinbox()->setMaximumWidth(40); + gridLayout->addWidget(m_morphTargets[i].m_sliderWeight, intIndex, 2); + connect(m_morphTargets[i].m_sliderWeight, &AzQtComponents::SliderDoubleCombo::valueChanged, this, &MorphTargetGroupWidget::SliderWeightMoved); + connect(m_morphTargets[i].m_sliderWeight, &AzQtComponents::SliderDoubleCombo::editingFinished, this, &MorphTargetGroupWidget::SliderWeightReleased); // create the name label QLabel* nameLabel = new QLabel(morphTargets[i]->GetName()); @@ -116,7 +116,7 @@ namespace EMStudio // the destructor MorphTargetGroupWidget::~MorphTargetGroupWidget() { - delete mEditWindow; + delete m_editWindow; } @@ -128,12 +128,12 @@ namespace EMStudio AZStd::string command; // loop trough all morph targets and enable/disable manual mode - const size_t numMorphTargets = mMorphTargets.size(); + const size_t numMorphTargets = m_morphTargets.size(); for (size_t i = 0; i < numMorphTargets; ++i) { - EMotionFX::MorphTarget* morphTarget = mMorphTargets[i].mMorphTarget; + EMotionFX::MorphTarget* morphTarget = m_morphTargets[i].m_morphTarget; - command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %i -name \"%s\" -manualMode ", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName()); + command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %zu -name \"%s\" -manualMode ", m_actorInstance->GetID(), m_actorInstance->GetLODLevel(), morphTarget->GetName()); command += AZStd::to_string(value == Qt::Checked); commandGroup.AddCommandString(command); } @@ -154,12 +154,12 @@ namespace EMStudio AZStd::string command; // loop trough all morph targets and enable/disable manual mode - const size_t numMorphTargets = mMorphTargets.size(); + const size_t numMorphTargets = m_morphTargets.size(); for (size_t i = 0; i < numMorphTargets; ++i) { - EMotionFX::MorphTarget* morphTarget = mMorphTargets[i].mMorphTarget; + EMotionFX::MorphTarget* morphTarget = m_morphTargets[i].m_morphTarget; - command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %i -name \"%s\" -weight %f", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName(), morphTarget->CalcZeroInfluenceWeight()); + command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %zu -name \"%s\" -weight %f", m_actorInstance->GetID(), m_actorInstance->GetLODLevel(), morphTarget->GetName(), morphTarget->CalcZeroInfluenceWeight()); commandGroup.AddCommandString(command); } @@ -176,12 +176,12 @@ namespace EMStudio { QCheckBox* checkBox = static_cast(sender()); const int morphTargetIndex = checkBox->property("MorphTargetIndex").toInt(); - EMotionFX::MorphTarget* morphTarget = mMorphTargets[morphTargetIndex].mMorphTarget; + EMotionFX::MorphTarget* morphTarget = m_morphTargets[morphTargetIndex].m_morphTarget; AZStd::string result; - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %i -name \"%s\" -weight %f -manualMode %s", - mActorInstance->GetID(), - mActorInstance->GetLODLevel(), + const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %zu -name \"%s\" -weight %f -manualMode %s", + m_actorInstance->GetID(), + m_actorInstance->GetLODLevel(), morphTarget->GetName(), 0.0f, AZStd::to_string(checkBox->isChecked()).c_str()); @@ -198,7 +198,7 @@ namespace EMStudio // get the morph target AzQtComponents::SliderDoubleCombo* floatSlider = static_cast(sender()); const int morphTargetIndex = floatSlider->property("MorphTargetIndex").toInt(); - EMotionFX::MorphSetupInstance::MorphTarget* morphTargetInstance = mMorphTargets[morphTargetIndex].mMorphTargetInstance; + EMotionFX::MorphSetupInstance::MorphTarget* morphTargetInstance = m_morphTargets[morphTargetIndex].m_morphTargetInstance; // update the weight morphTargetInstance->SetWeight(aznumeric_cast(floatSlider->value())); @@ -211,22 +211,22 @@ namespace EMStudio // get the morph target and the morph target instance AzQtComponents::SliderDoubleCombo* floatSlider = static_cast(sender()); const int morphTargetIndex = floatSlider->property("MorphTargetIndex").toInt(); - EMotionFX::MorphTarget* morphTarget = mMorphTargets[morphTargetIndex].mMorphTarget; - EMotionFX::MorphSetupInstance::MorphTarget* morphTargetInstance = mMorphTargets[morphTargetIndex].mMorphTargetInstance; + EMotionFX::MorphTarget* morphTarget = m_morphTargets[morphTargetIndex].m_morphTarget; + EMotionFX::MorphSetupInstance::MorphTarget* morphTargetInstance = m_morphTargets[morphTargetIndex].m_morphTargetInstance; // set the old weight to have the undo correct - morphTargetInstance->SetWeight(mMorphTargets[morphTargetIndex].mOldWeight); + morphTargetInstance->SetWeight(m_morphTargets[morphTargetIndex].m_oldWeight); // execute command AZStd::string result; - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %i -name \"%s\" -weight %f", mActorInstance->GetID(), mActorInstance->GetLODLevel(), morphTarget->GetName(), floatSlider->value()); + const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorInstanceID %i -lodLevel %zu -name \"%s\" -weight %f", m_actorInstance->GetID(), m_actorInstance->GetLODLevel(), morphTarget->GetName(), floatSlider->value()); if (EMStudio::GetCommandManager()->ExecuteCommand(command, result) == false) { AZ_Error("EMotionFX", false, result.c_str()); } // set the new old weight value - mMorphTargets[morphTargetIndex].mOldWeight = aznumeric_cast(floatSlider->value()); + m_morphTargets[morphTargetIndex].m_oldWeight = aznumeric_cast(floatSlider->value()); } @@ -236,12 +236,12 @@ namespace EMStudio // get the morph target QPushButton* button = static_cast(sender()); const int morphTargetIndex = button->property("MorphTargetIndex").toInt(); - EMotionFX::MorphTarget* morphTarget = mMorphTargets[morphTargetIndex].mMorphTarget; + EMotionFX::MorphTarget* morphTarget = m_morphTargets[morphTargetIndex].m_morphTarget; // show the edit window - delete mEditWindow; - mEditWindow = new MorphTargetEditWindow(mActorInstance, morphTarget, this); - mEditWindow->exec(); + delete m_editWindow; + m_editWindow = new MorphTargetEditWindow(m_actorInstance, morphTarget, this); + m_editWindow->exec(); } @@ -250,13 +250,13 @@ namespace EMStudio { bool selectAllChecked = true; - const size_t numMorphTargets = mMorphTargets.size(); + const size_t numMorphTargets = m_morphTargets.size(); for (size_t i = 0; i < numMorphTargets; ++i) { - const float rangeMin = mMorphTargets[i].mMorphTarget->GetRangeMin(); - const float rangeMax = mMorphTargets[i].mMorphTarget->GetRangeMax(); - const float weight = mMorphTargets[i].mMorphTargetInstance->GetWeight(); - const bool manualMode = mMorphTargets[i].mMorphTargetInstance->GetIsInManualMode(); + const float rangeMin = m_morphTargets[i].m_morphTarget->GetRangeMin(); + const float rangeMax = m_morphTargets[i].m_morphTarget->GetRangeMax(); + const float weight = m_morphTargets[i].m_morphTargetInstance->GetWeight(); + const bool manualMode = m_morphTargets[i].m_morphTargetInstance->GetIsInManualMode(); // check if the select all should not be checked if (manualMode == false) @@ -265,82 +265,82 @@ namespace EMStudio } // disable signals - QSignalBlocker sb(mMorphTargets[i].mSliderWeight); - mMorphTargets[i].mManualMode->blockSignals(true); + QSignalBlocker sb(m_morphTargets[i].m_sliderWeight); + m_morphTargets[i].m_manualMode->blockSignals(true); // update the manual mode - mMorphTargets[i].mManualMode->setChecked(manualMode); + m_morphTargets[i].m_manualMode->setChecked(manualMode); // update the slider weight - mMorphTargets[i].mSliderWeight->setDisabled(!manualMode); - mMorphTargets[i].mSliderWeight->setRange(rangeMin, rangeMax); + m_morphTargets[i].m_sliderWeight->setDisabled(!manualMode); + m_morphTargets[i].m_sliderWeight->setRange(rangeMin, rangeMax); // enforce single step of 0.1 - mMorphTargets[i].mSliderWeight->slider()->setNumSteps(aznumeric_cast((rangeMax - rangeMin) / 0.1)); - mMorphTargets[i].mSliderWeight->setValue(weight); + m_morphTargets[i].m_sliderWeight->slider()->setNumSteps(aznumeric_cast((rangeMax - rangeMin) / 0.1)); + m_morphTargets[i].m_sliderWeight->setValue(weight); // enable signals - mMorphTargets[i].mManualMode->blockSignals(false); + m_morphTargets[i].m_manualMode->blockSignals(false); // store the current weight // the weight is updated in realtime but before to execute the adjust command it has to be reset to have the undo correct - mMorphTargets[i].mOldWeight = weight; + m_morphTargets[i].m_oldWeight = weight; } // update the select all - mSelectAll->blockSignals(true); - mSelectAll->setChecked(selectAllChecked); - mSelectAll->blockSignals(false); + m_selectAll->blockSignals(true); + m_selectAll->setChecked(selectAllChecked); + m_selectAll->blockSignals(false); // update the edit window - if (mEditWindow) + if (m_editWindow) { - mEditWindow->UpdateInterface(); + m_editWindow->UpdateInterface(); } } void MorphTargetGroupWidget::UpdateMorphTarget(const char* name) { // update the row - const size_t numMorphTargets = mMorphTargets.size(); + const size_t numMorphTargets = m_morphTargets.size(); for (size_t i = 0; i < numMorphTargets; ++i) { // continue of the name is not the same - if (mMorphTargets[i].mMorphTarget->GetNameString() != name) + if (m_morphTargets[i].m_morphTarget->GetNameString() != name) { continue; } // get values - const float rangeMin = mMorphTargets[i].mMorphTarget->GetRangeMin(); - const float rangeMax = mMorphTargets[i].mMorphTarget->GetRangeMax(); - const float weight = mMorphTargets[i].mMorphTargetInstance->GetWeight(); - const bool manualMode = mMorphTargets[i].mMorphTargetInstance->GetIsInManualMode(); + const float rangeMin = m_morphTargets[i].m_morphTarget->GetRangeMin(); + const float rangeMax = m_morphTargets[i].m_morphTarget->GetRangeMax(); + const float weight = m_morphTargets[i].m_morphTargetInstance->GetWeight(); + const bool manualMode = m_morphTargets[i].m_morphTargetInstance->GetIsInManualMode(); // disable signals - QSignalBlocker sb(mMorphTargets[i].mSliderWeight); - mMorphTargets[i].mManualMode->blockSignals(true); + QSignalBlocker sb(m_morphTargets[i].m_sliderWeight); + m_morphTargets[i].m_manualMode->blockSignals(true); // update the manual mode - mMorphTargets[i].mManualMode->setChecked(manualMode); + m_morphTargets[i].m_manualMode->setChecked(manualMode); // update the slider weight - mMorphTargets[i].mSliderWeight->setDisabled(!manualMode); - mMorphTargets[i].mSliderWeight->setRange(rangeMin, rangeMax); + m_morphTargets[i].m_sliderWeight->setDisabled(!manualMode); + m_morphTargets[i].m_sliderWeight->setRange(rangeMin, rangeMax); // enforce single step of 0.1 - mMorphTargets[i].mSliderWeight->slider()->setNumSteps(aznumeric_cast((rangeMax - rangeMin) / 0.1)); - mMorphTargets[i].mSliderWeight->setValue(weight); + m_morphTargets[i].m_sliderWeight->slider()->setNumSteps(aznumeric_cast((rangeMax - rangeMin) / 0.1)); + m_morphTargets[i].m_sliderWeight->setValue(weight); // enable signals - mMorphTargets[i].mManualMode->blockSignals(false); + m_morphTargets[i].m_manualMode->blockSignals(false); // store the current weight // the weight is updated in realtime but before to execute the adjust command it has to be reset to have the undo correct - mMorphTargets[i].mOldWeight = weight; + m_morphTargets[i].m_oldWeight = weight; // update edit window in case it's the edit of this morph target - if (mEditWindow && mEditWindow->GetMorphTarget() == mMorphTargets[i].mMorphTarget) + if (m_editWindow && m_editWindow->GetMorphTarget() == m_morphTargets[i].m_morphTarget) { - mEditWindow->UpdateInterface(); + m_editWindow->UpdateInterface(); } // stop here because we found it @@ -351,15 +351,15 @@ namespace EMStudio bool selectAllChecked = true; for (uint32 i = 0; i < numMorphTargets; ++i) { - if (mMorphTargets[i].mMorphTargetInstance->GetIsInManualMode() == false) + if (m_morphTargets[i].m_morphTargetInstance->GetIsInManualMode() == false) { selectAllChecked = false; break; } } - mSelectAll->blockSignals(true); - mSelectAll->setChecked(selectAllChecked); - mSelectAll->blockSignals(false); + m_selectAll->blockSignals(true); + m_selectAll->setChecked(selectAllChecked); + m_selectAll->blockSignals(false); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.h index 7a4bdb40b6..5e8519afcc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetGroupWidget.h @@ -39,16 +39,16 @@ namespace EMStudio struct MorphTarget { - EMotionFX::MorphTarget* mMorphTarget; - EMotionFX::MorphSetupInstance::MorphTarget* mMorphTargetInstance; - QCheckBox* mManualMode; - AzQtComponents::SliderDoubleCombo* mSliderWeight = nullptr; - float mOldWeight; + EMotionFX::MorphTarget* m_morphTarget; + EMotionFX::MorphSetupInstance::MorphTarget* m_morphTargetInstance; + QCheckBox* m_manualMode; + AzQtComponents::SliderDoubleCombo* m_sliderWeight = nullptr; + float m_oldWeight; }; void UpdateInterface(); void UpdateMorphTarget(const char* name); - const MorphTarget* GetMorphTarget(size_t index){ return &mMorphTargets[index]; } + const MorphTarget* GetMorphTarget(size_t index){ return &m_morphTargets[index]; } public slots: void SetManualModeForAll(int value); @@ -59,10 +59,10 @@ namespace EMStudio void ResetAll(); private: - AZStd::string mName; - EMotionFX::ActorInstance* mActorInstance; - QCheckBox* mSelectAll; - AZStd::vector mMorphTargets; - MorphTargetEditWindow* mEditWindow; + AZStd::string m_name; + EMotionFX::ActorInstance* m_actorInstance; + QCheckBox* m_selectAll; + AZStd::vector m_morphTargets; + MorphTargetEditWindow* m_editWindow; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.cpp index ce8de9483a..1ceeb155fa 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.cpp @@ -22,9 +22,9 @@ namespace EMStudio MorphTargetsWindowPlugin::MorphTargetsWindowPlugin() : EMStudio::DockWidgetPlugin() { - mDialogStack = nullptr; - mCurrentActorInstance = nullptr; - mStaticTextWidget = nullptr; + m_dialogStack = nullptr; + m_currentActorInstance = nullptr; + m_staticTextWidget = nullptr; EMotionFX::ActorInstanceNotificationBus::Handler::BusConnect(); } @@ -43,7 +43,7 @@ namespace EMStudio Clear(); // delete the dialog stack - delete mDialogStack; + delete m_dialogStack; } @@ -59,19 +59,19 @@ namespace EMStudio bool MorphTargetsWindowPlugin::Init() { // create the static text layout - mStaticTextWidget = new QWidget(); - mStaticTextLayout = new QVBoxLayout(); - mStaticTextWidget->setLayout(mStaticTextLayout); + m_staticTextWidget = new QWidget(); + m_staticTextLayout = new QVBoxLayout(); + m_staticTextWidget->setLayout(m_staticTextLayout); QLabel* label = new QLabel("No morph targets to show."); - mStaticTextLayout->addWidget(label); - mStaticTextLayout->setAlignment(label, Qt::AlignCenter); + m_staticTextLayout->addWidget(label); + m_staticTextLayout->setAlignment(label, Qt::AlignCenter); // create the dialog stack - assert(mDialogStack == nullptr); - mDialogStack = new MysticQt::DialogStack(); - mDock->setMinimumWidth(300); - mDock->setMinimumHeight(100); - mDock->setWidget(mStaticTextWidget); + assert(m_dialogStack == nullptr); + m_dialogStack = new MysticQt::DialogStack(); + m_dock->setMinimumWidth(300); + m_dock->setMinimumHeight(100); + m_dock->setWidget(m_staticTextWidget); GetCommandManager()->RegisterCommandCallback("Select", m_callbacks, false); GetCommandManager()->RegisterCommandCallback("Unselect", m_callbacks, false); @@ -83,7 +83,7 @@ namespace EMStudio ReInit(); // connect the window activation signal to refresh if reactivated - connect(mDock, &QDockWidget::visibilityChanged, this, &MorphTargetsWindowPlugin::WindowReInit); + connect(m_dock, &QDockWidget::visibilityChanged, this, &MorphTargetsWindowPlugin::WindowReInit); // done return true; @@ -93,18 +93,18 @@ namespace EMStudio // clear the morph target window void MorphTargetsWindowPlugin::Clear() { - if (mDock) + if (m_dock) { - mDock->setWidget(mStaticTextWidget); + m_dock->setWidget(m_staticTextWidget); } // clear the dialog stack - if (mDialogStack) + if (m_dialogStack) { - mDialogStack->Clear(); + m_dialogStack->Clear(); } - mMorphTargetGroups.clear(); + m_morphTargetGroups.clear(); } // reinit the morph target dialog, e.g. if selection changes @@ -121,13 +121,13 @@ namespace EMStudio if (actorInstance == nullptr) { // set the dock contents - mDock->setWidget(mStaticTextWidget); + m_dock->setWidget(m_staticTextWidget); // clear dialog and reset the current actor instance as we cleared the window - if (mCurrentActorInstance) + if (m_currentActorInstance) { Clear(); - mCurrentActorInstance = nullptr; + m_currentActorInstance = nullptr; } // done @@ -135,10 +135,10 @@ namespace EMStudio } // only reinit the morph targets if actor instance changed - if (mCurrentActorInstance != actorInstance || forceReInit) + if (m_currentActorInstance != actorInstance || forceReInit) { // set the current actor instance in any case - mCurrentActorInstance = actorInstance; + m_currentActorInstance = actorInstance; // arrays for the default morph targets and the phonemes AZStd::vector phonemes; @@ -150,7 +150,7 @@ namespace EMStudio EMotionFX::MorphSetup* morphSetup = actor->GetMorphSetup(actorInstance->GetLODLevel()); if (morphSetup == nullptr) { - mDock->setWidget(mStaticTextWidget); + m_dock->setWidget(m_staticTextWidget); return; } @@ -158,7 +158,7 @@ namespace EMStudio EMotionFX::MorphSetupInstance* morphSetupInstance = actorInstance->GetMorphSetupInstance(); if (morphSetupInstance == nullptr) { - mDock->setWidget(mStaticTextWidget); + m_dock->setWidget(m_staticTextWidget); return; } @@ -217,11 +217,11 @@ namespace EMStudio // create static text if no morph targets are available if (defaultMorphTargets.empty() && phonemes.empty()) { - mDock->setWidget(mStaticTextWidget); + m_dock->setWidget(m_staticTextWidget); } else { - mDock->setWidget(mDialogStack); + m_dock->setWidget(m_dialogStack); } // adjust the slider values to the correct weights of the selected actor instance @@ -237,11 +237,11 @@ namespace EMStudio return; } - MorphTargetGroupWidget* morphTargetGroup = new MorphTargetGroupWidget(name, mCurrentActorInstance, morphTargets, morphTargetInstances, mDialogStack); + MorphTargetGroupWidget* morphTargetGroup = new MorphTargetGroupWidget(name, m_currentActorInstance, morphTargets, morphTargetInstances, m_dialogStack); morphTargetGroup->setObjectName("EMFX.MorphTargetsWindowPlugin.MorphTargetGroupWidget"); - mMorphTargetGroups.push_back(morphTargetGroup); + m_morphTargetGroups.push_back(morphTargetGroup); - mDialogStack->Add(morphTargetGroup, name); + m_dialogStack->Add(morphTargetGroup, name); } @@ -258,7 +258,7 @@ namespace EMStudio // update the interface void MorphTargetsWindowPlugin::UpdateInterface() { - for (MorphTargetGroupWidget* group : mMorphTargetGroups) + for (MorphTargetGroupWidget* group : m_morphTargetGroups) { group->UpdateInterface(); } @@ -268,7 +268,7 @@ namespace EMStudio // update the morph target void MorphTargetsWindowPlugin::UpdateMorphTarget(const char* name) { - for (MorphTargetGroupWidget* group : mMorphTargetGroups) + for (MorphTargetGroupWidget* group : m_morphTargetGroups) { group->UpdateMorphTarget(name); } @@ -276,7 +276,7 @@ namespace EMStudio void MorphTargetsWindowPlugin::OnActorInstanceDestroyed(EMotionFX::ActorInstance* actorInstance) { - if (mCurrentActorInstance == actorInstance) + if (m_currentActorInstance == actorInstance) { ReInit(/*actorInstance=*/nullptr); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.h index 4e81a24b39..d2295fcd9c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/MorphTargetsWindowPlugin.h @@ -60,7 +60,7 @@ namespace EMStudio // creates a new group with several morph targets void CreateGroup(const char* name, const AZStd::vector& morphTargets, const AZStd::vector& morphTargetInstances); - EMotionFX::ActorInstance* GetActorInstance() const { return mCurrentActorInstance; } + EMotionFX::ActorInstance* GetActorInstance() const { return m_currentActorInstance; } void UpdateInterface(); void UpdateMorphTarget(const char* name); @@ -82,15 +82,15 @@ namespace EMStudio AZStd::vector m_callbacks; // holds the generated groups for the morph targets - AZStd::vector mMorphTargetGroups; + AZStd::vector m_morphTargetGroups; // holds the currently selected actor instance - EMotionFX::ActorInstance* mCurrentActorInstance; + EMotionFX::ActorInstance* m_currentActorInstance; // some qt stuff - QVBoxLayout* mStaticTextLayout; - QWidget* mStaticTextWidget; - MysticQt::DialogStack* mDialogStack; - QLabel* mInfoText; + QVBoxLayout* m_staticTextLayout; + QWidget* m_staticTextWidget; + MysticQt::DialogStack* m_dialogStack; + QLabel* m_infoText; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp index 704351a4bb..4f1aa5b42b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.cpp @@ -34,25 +34,25 @@ namespace EMStudio VisimeWidget::VisimeWidget(const AZStd::string& filename) { // set the file name and size hints - mFileName = filename; - mSelected = false; - mMouseWithinWidget = false; + m_fileName = filename; + m_selected = false; + m_mouseWithinWidget = false; setMinimumHeight(60); setMaximumHeight(60); setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); // extract the pure filename - AzFramework::StringFunc::Path::GetFileName(filename.c_str(), mFileNameWithoutExt); + AzFramework::StringFunc::Path::GetFileName(filename.c_str(), m_fileNameWithoutExt); // load the pixmap - mPixmap = new QPixmap(filename.c_str()); + m_pixmap = new QPixmap(filename.c_str()); } // destructor VisimeWidget::~VisimeWidget() { - delete mPixmap; + delete m_pixmap; } @@ -82,11 +82,11 @@ namespace EMStudio painter.setPen(QColor(66, 66, 66)); // draw selection border - if (mSelected) + if (m_selected) { painter.setBrush(QBrush(QColor(244, 156, 28))); } - else if (mMouseWithinWidget) + else if (m_mouseWithinWidget) { painter.setBrush(QBrush(QColor(153, 160, 178))); } @@ -98,11 +98,11 @@ namespace EMStudio painter.drawRoundedRect(0, 2, width(), height() - 4, 5.0, 5.0); // draw background - if (mSelected) + if (m_selected) { painter.setBrush(QBrush(QColor(56, 65, 72))); } - else if (mMouseWithinWidget) + else if (m_mouseWithinWidget) { painter.setBrush(QBrush(QColor(134, 142, 150))); } @@ -115,10 +115,10 @@ namespace EMStudio painter.drawRoundedRect(2, 4, width() - 4, height() - 8, 5.0, 5.0); // draw visime image - painter.drawPixmap(5, 5, height() - 10, height() - 10, *mPixmap); + painter.drawPixmap(5, 5, height() - 10, height() - 10, *m_pixmap); // draw visime name - if (mSelected) + if (m_selected) { painter.setPen(QColor(244, 156, 28)); } @@ -128,23 +128,23 @@ namespace EMStudio } //painter.setFont( QFont("MS Shell Dlg 2", 8) ); - painter.drawText(70, (height() / 2) + 4, mFileNameWithoutExt.c_str()); + painter.drawText(70, (height() / 2) + 4, m_fileNameWithoutExt.c_str()); } // constructor - PhonemeSelectionWindow::PhonemeSelectionWindow(EMotionFX::Actor* actor, uint32 lodLevel, EMotionFX::MorphTarget* morphTarget, QWidget* parent) + PhonemeSelectionWindow::PhonemeSelectionWindow(EMotionFX::Actor* actor, size_t lodLevel, EMotionFX::MorphTarget* morphTarget, QWidget* parent) : QDialog(parent) { // set the initial size setMinimumWidth(800); setMinimumHeight(450); - mActor = actor; - mMorphTarget = morphTarget; - mLODLevel = lodLevel; - mMorphSetup = actor->GetMorphSetup(lodLevel); - mDirtyFlag = false; + m_actor = actor; + m_morphTarget = morphTarget; + m_lodLevel = lodLevel; + m_morphSetup = actor->GetMorphSetup(lodLevel); + m_dirtyFlag = false; // init the dialog Init(); @@ -165,49 +165,49 @@ namespace EMStudio setSizeGripEnabled(false); // buttons to add / remove / clear phonemes - mAddPhonemesButton = new QPushButton(""); - mAddPhonemesButtonArrow = new QPushButton(""); - mRemovePhonemesButton = new QPushButton(""); - mRemovePhonemesButtonArrow = new QPushButton(""); - mClearPhonemesButton = new QPushButton(""); - - EMStudioManager::MakeTransparentButton(mAddPhonemesButtonArrow, "Images/Icons/PlayForward.svg", "Assign the selected phonemes to the morph target."); - EMStudioManager::MakeTransparentButton(mRemovePhonemesButtonArrow, "Images/Icons/PlayBackward.svg", "Unassign the selected phonemes from the morph target."); - EMStudioManager::MakeTransparentButton(mAddPhonemesButton, "Images/Icons/Plus.svg", "Assign the selected phonemes to the morph target."); - EMStudioManager::MakeTransparentButton(mRemovePhonemesButton, "Images/Icons/Minus.svg", "Unassign the selected phonemes from the morph target."); - EMStudioManager::MakeTransparentButton(mClearPhonemesButton, "Images/Icons/Clear.svg", "Unassign all phonemes from the morph target."); + m_addPhonemesButton = new QPushButton(""); + m_addPhonemesButtonArrow = new QPushButton(""); + m_removePhonemesButton = new QPushButton(""); + m_removePhonemesButtonArrow = new QPushButton(""); + m_clearPhonemesButton = new QPushButton(""); + + EMStudioManager::MakeTransparentButton(m_addPhonemesButtonArrow, "Images/Icons/PlayForward.svg", "Assign the selected phonemes to the morph target."); + EMStudioManager::MakeTransparentButton(m_removePhonemesButtonArrow, "Images/Icons/PlayBackward.svg", "Unassign the selected phonemes from the morph target."); + EMStudioManager::MakeTransparentButton(m_addPhonemesButton, "Images/Icons/Plus.svg", "Assign the selected phonemes to the morph target."); + EMStudioManager::MakeTransparentButton(m_removePhonemesButton, "Images/Icons/Minus.svg", "Unassign the selected phonemes from the morph target."); + EMStudioManager::MakeTransparentButton(m_clearPhonemesButton, "Images/Icons/Clear.svg", "Unassign all phonemes from the morph target."); // init the visime tables - mPossiblePhonemeSetsTable = new DragTableWidget(0, 1); - mSelectedPhonemeSetsTable = new DragTableWidget(0, 1); - mPossiblePhonemeSetsTable->setCornerButtonEnabled(false); - mPossiblePhonemeSetsTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mPossiblePhonemeSetsTable->setContextMenuPolicy(Qt::DefaultContextMenu); - mSelectedPhonemeSetsTable->setCornerButtonEnabled(false); - mSelectedPhonemeSetsTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mSelectedPhonemeSetsTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_possiblePhonemeSetsTable = new DragTableWidget(0, 1); + m_selectedPhonemeSetsTable = new DragTableWidget(0, 1); + m_possiblePhonemeSetsTable->setCornerButtonEnabled(false); + m_possiblePhonemeSetsTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_possiblePhonemeSetsTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_selectedPhonemeSetsTable->setCornerButtonEnabled(false); + m_selectedPhonemeSetsTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_selectedPhonemeSetsTable->setContextMenuPolicy(Qt::DefaultContextMenu); // set the table to row single selection - mPossiblePhonemeSetsTable->setSelectionBehavior(QAbstractItemView::SelectRows); - mSelectedPhonemeSetsTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_possiblePhonemeSetsTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_selectedPhonemeSetsTable->setSelectionBehavior(QAbstractItemView::SelectRows); // make the table items read only - mPossiblePhonemeSetsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - mSelectedPhonemeSetsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_possiblePhonemeSetsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_selectedPhonemeSetsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // resize to contents and adjust header - QHeaderView* verticalHeaderPossible = mPossiblePhonemeSetsTable->verticalHeader(); - QHeaderView* verticalHeaderSelected = mSelectedPhonemeSetsTable->verticalHeader(); - QHeaderView* horizontalHeaderPossible = mPossiblePhonemeSetsTable->horizontalHeader(); - QHeaderView* horizontalHeaderSelected = mSelectedPhonemeSetsTable->horizontalHeader(); + QHeaderView* verticalHeaderPossible = m_possiblePhonemeSetsTable->verticalHeader(); + QHeaderView* verticalHeaderSelected = m_selectedPhonemeSetsTable->verticalHeader(); + QHeaderView* horizontalHeaderPossible = m_possiblePhonemeSetsTable->horizontalHeader(); + QHeaderView* horizontalHeaderSelected = m_selectedPhonemeSetsTable->horizontalHeader(); verticalHeaderPossible->setVisible(false); verticalHeaderSelected->setVisible(false); horizontalHeaderPossible->setVisible(false); horizontalHeaderSelected->setVisible(false); // create the dialog stacks - mPossiblePhonemeSets = new MysticQt::DialogStack(this); - mSelectedPhonemeSets = new MysticQt::DialogStack(this); + m_possiblePhonemeSets = new MysticQt::DialogStack(this); + m_selectedPhonemeSets = new MysticQt::DialogStack(this); // create and fill the main layout QHBoxLayout* layout = new QHBoxLayout(); @@ -232,10 +232,10 @@ namespace EMStudio QHBoxLayout* buttonLayout = new QHBoxLayout(); buttonLayout->setSpacing(0); buttonLayout->setAlignment(Qt::AlignLeft); - buttonLayout->addWidget(mAddPhonemesButton); + buttonLayout->addWidget(m_addPhonemesButton); leftLayout->addLayout(buttonLayout); - leftLayout->addWidget(mPossiblePhonemeSetsTable); + leftLayout->addWidget(m_possiblePhonemeSetsTable); leftLayout->addWidget(labelHelperWidgetAdd); // the center layout @@ -244,8 +244,8 @@ namespace EMStudio // fill the center layout centerLayout->addWidget(seperatorLineTop); - centerLayout->addWidget(mAddPhonemesButtonArrow); - centerLayout->addWidget(mRemovePhonemesButtonArrow); + centerLayout->addWidget(m_addPhonemesButtonArrow); + centerLayout->addWidget(m_removePhonemesButtonArrow); centerLayout->addWidget(seperatorLineBottom); // the right layout and info label @@ -262,12 +262,12 @@ namespace EMStudio buttonLayout = new QHBoxLayout(); buttonLayout->setSpacing(0); buttonLayout->setAlignment(Qt::AlignLeft); - buttonLayout->addWidget(mRemovePhonemesButton); - buttonLayout->addWidget(mClearPhonemesButton); + buttonLayout->addWidget(m_removePhonemesButton); + buttonLayout->addWidget(m_clearPhonemesButton); // fill the right layozt rightLayout->addLayout(buttonLayout); - rightLayout->addWidget(mSelectedPhonemeSetsTable); + rightLayout->addWidget(m_selectedPhonemeSetsTable); rightLayout->addWidget(labelHelperWidgetRemove); @@ -285,13 +285,13 @@ namespace EMStudio helperWidgetRight->setLayout(rightLayout); // add helper widgets to the dialog stacks - mPossiblePhonemeSets->Add(helperWidgetLeft, "Possible Phoneme Sets", false, true, false); - mSelectedPhonemeSets->Add(helperWidgetRight, "Selected Phoneme Sets", false, true, false); + m_possiblePhonemeSets->Add(helperWidgetLeft, "Possible Phoneme Sets", false, true, false); + m_selectedPhonemeSets->Add(helperWidgetRight, "Selected Phoneme Sets", false, true, false); // add sublayouts to the main layout - layout->addWidget(mPossiblePhonemeSets); + layout->addWidget(m_possiblePhonemeSets); layout->addLayout(centerLayout); - layout->addWidget(mSelectedPhonemeSets); + layout->addWidget(m_selectedPhonemeSets); // set the main layout setLayout(layout); @@ -300,43 +300,43 @@ namespace EMStudio UpdateInterface(); // connect signals to the slots - connect(mPossiblePhonemeSetsTable, &DragTableWidget::itemSelectionChanged, this, &PhonemeSelectionWindow::PhonemeSelectionChanged); - connect(mSelectedPhonemeSetsTable, &DragTableWidget::itemSelectionChanged, this, &PhonemeSelectionWindow::PhonemeSelectionChanged); - connect(mPossiblePhonemeSetsTable, &DragTableWidget::dataDropped, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); - connect(mRemovePhonemesButton, &QPushButton::clicked, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); - connect(mRemovePhonemesButtonArrow, &QPushButton::clicked, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); - connect(mAddPhonemesButton, &QPushButton::clicked, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); - connect(mAddPhonemesButtonArrow, &QPushButton::clicked, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); - connect(mSelectedPhonemeSetsTable, &DragTableWidget::dataDropped, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); - connect(mClearPhonemesButton, &QPushButton::clicked, this, &PhonemeSelectionWindow::ClearSelectedPhonemeSets); - connect(mPossiblePhonemeSetsTable, &DragTableWidget::itemDoubleClicked, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); - connect(mSelectedPhonemeSetsTable, &DragTableWidget::itemDoubleClicked, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); + connect(m_possiblePhonemeSetsTable, &DragTableWidget::itemSelectionChanged, this, &PhonemeSelectionWindow::PhonemeSelectionChanged); + connect(m_selectedPhonemeSetsTable, &DragTableWidget::itemSelectionChanged, this, &PhonemeSelectionWindow::PhonemeSelectionChanged); + connect(m_possiblePhonemeSetsTable, &DragTableWidget::dataDropped, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); + connect(m_removePhonemesButton, &QPushButton::clicked, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); + connect(m_removePhonemesButtonArrow, &QPushButton::clicked, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); + connect(m_addPhonemesButton, &QPushButton::clicked, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); + connect(m_addPhonemesButtonArrow, &QPushButton::clicked, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); + connect(m_selectedPhonemeSetsTable, &DragTableWidget::dataDropped, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); + connect(m_clearPhonemesButton, &QPushButton::clicked, this, &PhonemeSelectionWindow::ClearSelectedPhonemeSets); + connect(m_possiblePhonemeSetsTable, &DragTableWidget::itemDoubleClicked, this, &PhonemeSelectionWindow::AddSelectedPhonemeSets); + connect(m_selectedPhonemeSetsTable, &DragTableWidget::itemDoubleClicked, this, &PhonemeSelectionWindow::RemoveSelectedPhonemeSets); } void PhonemeSelectionWindow::UpdateInterface() { // return if morph setup is not valid - if (mMorphSetup == nullptr) + if (m_morphSetup == nullptr) { return; } // clear the tables - mPossiblePhonemeSetsTable->clear(); - mSelectedPhonemeSetsTable->clear(); + m_possiblePhonemeSetsTable->clear(); + m_selectedPhonemeSetsTable->clear(); // get number of morph targets - const uint32 numMorphTargets = mMorphSetup->GetNumMorphTargets(); - const uint32 numPhonemeSets = mMorphTarget->GetNumAvailablePhonemeSets(); - uint32 insertPosition = 0; - for (uint32 i = 1; i < numPhonemeSets; ++i) + const size_t numMorphTargets = m_morphSetup->GetNumMorphTargets(); + const uint32 numPhonemeSets = m_morphTarget->GetNumAvailablePhonemeSets(); + int insertPosition = 0; + for (int i = 1; i < numPhonemeSets; ++i) { // check if another morph target already has this phoneme set. bool phonemeSetFound = false; - for (uint32 j = 0; j < numMorphTargets; ++j) + for (size_t j = 0; j < numMorphTargets; ++j) { - EMotionFX::MorphTarget* morphTarget = mMorphSetup->GetMorphTarget(j); + EMotionFX::MorphTarget* morphTarget = m_morphSetup->GetMorphTarget(j); if (morphTarget->GetIsPhonemeSetEnabled((EMotionFX::MorphTarget::EPhonemeSet)(1 << i))) { phonemeSetFound = true; @@ -352,69 +352,69 @@ namespace EMStudio // get the phoneme set name EMotionFX::MorphTarget::EPhonemeSet phonemeSet = (EMotionFX::MorphTarget::EPhonemeSet)(1 << i); - const AZStd::string phonemeSetName = mMorphTarget->GetPhonemeSetString(phonemeSet).c_str(); + const AZStd::string phonemeSetName = m_morphTarget->GetPhonemeSetString(phonemeSet).c_str(); // set the row count for the possible phoneme sets table - mPossiblePhonemeSetsTable->setRowCount(insertPosition + 1); + m_possiblePhonemeSetsTable->setRowCount(insertPosition + 1); // create dummy table widget item. QTableWidgetItem* item = new QTableWidgetItem(phonemeSetName.c_str()); item->setToolTip(GetPhonemeSetExample(phonemeSet)); - mPossiblePhonemeSetsTable->setItem(insertPosition, 0, item); + m_possiblePhonemeSetsTable->setItem(insertPosition, 0, item); // create the visime widget and add it to the table const AZStd::string filename = AZStd::string::format("%s/Images/Visimes/%s.png", MysticQt::GetDataDir().c_str(), phonemeSetName.c_str()); VisimeWidget* visimeWidget = new VisimeWidget(filename); - mPossiblePhonemeSetsTable->setCellWidget(insertPosition, 0, visimeWidget); + m_possiblePhonemeSetsTable->setCellWidget(insertPosition, 0, visimeWidget); // set row and column properties - mPossiblePhonemeSetsTable->setRowHeight(insertPosition, visimeWidget->height() + 2); + m_possiblePhonemeSetsTable->setRowHeight(insertPosition, visimeWidget->height() + 2); // increase insert position ++insertPosition; } // fill the table with the selected phoneme sets - const AZStd::string selectedPhonemeSets = mMorphTarget->GetPhonemeSetString(mMorphTarget->GetPhonemeSets()); + const AZStd::string selectedPhonemeSets = m_morphTarget->GetPhonemeSetString(m_morphTarget->GetPhonemeSets()); AZStd::vector splittedPhonemeSets; AzFramework::StringFunc::Tokenize(selectedPhonemeSets.c_str(), splittedPhonemeSets, MCore::CharacterConstants::comma, true /* keep empty strings */, true /* keep space strings */); - const uint32 numSelectedPhonemeSets = static_cast(splittedPhonemeSets.size()); - mSelectedPhonemeSetsTable->setRowCount(numSelectedPhonemeSets); - for (uint32 i = 0; i < numSelectedPhonemeSets; ++i) + const int numSelectedPhonemeSets = aznumeric_caster(splittedPhonemeSets.size()); + m_selectedPhonemeSetsTable->setRowCount(numSelectedPhonemeSets); + for (int i = 0; i < numSelectedPhonemeSets; ++i) { // create dummy table widget item. - const EMotionFX::MorphTarget::EPhonemeSet phonemeSet = mMorphTarget->FindPhonemeSet(splittedPhonemeSets[i].c_str()); + const EMotionFX::MorphTarget::EPhonemeSet phonemeSet = m_morphTarget->FindPhonemeSet(splittedPhonemeSets[i].c_str()); QTableWidgetItem* item = new QTableWidgetItem(splittedPhonemeSets[i].c_str()); item->setToolTip(GetPhonemeSetExample(phonemeSet)); - mSelectedPhonemeSetsTable->setItem(i, 0, item); + m_selectedPhonemeSetsTable->setItem(i, 0, item); // create the visime widget and add it to the table const AZStd::string filename = AZStd::string::format("%s/Images/Visimes/%s.png", MysticQt::GetDataDir().c_str(), splittedPhonemeSets[i].c_str()); VisimeWidget* visimeWidget = new VisimeWidget(filename); - mSelectedPhonemeSetsTable->setCellWidget(i, 0, visimeWidget); + m_selectedPhonemeSetsTable->setCellWidget(i, 0, visimeWidget); // set row and column properties - mSelectedPhonemeSetsTable->setRowHeight(i, visimeWidget->height() + 2); + m_selectedPhonemeSetsTable->setRowHeight(i, visimeWidget->height() + 2); } // stretch last section of the tables and disable horizontal header - QHeaderView* horizontalHeaderSelected = mSelectedPhonemeSetsTable->horizontalHeader(); + QHeaderView* horizontalHeaderSelected = m_selectedPhonemeSetsTable->horizontalHeader(); horizontalHeaderSelected->setVisible(false); horizontalHeaderSelected->setStretchLastSection(true); - QHeaderView* horizontalHeaderPossible = mPossiblePhonemeSetsTable->horizontalHeader(); + QHeaderView* horizontalHeaderPossible = m_possiblePhonemeSetsTable->horizontalHeader(); horizontalHeaderPossible->setVisible(false); horizontalHeaderPossible->setStretchLastSection(true); // disable/enable buttons upon reinit of the tables - mAddPhonemesButton->setDisabled(true); - mAddPhonemesButtonArrow->setDisabled(true); - mRemovePhonemesButton->setDisabled(true); - mRemovePhonemesButtonArrow->setDisabled(true); - mClearPhonemesButton->setDisabled(mSelectedPhonemeSetsTable->rowCount() == 0); + m_addPhonemesButton->setDisabled(true); + m_addPhonemesButtonArrow->setDisabled(true); + m_removePhonemesButton->setDisabled(true); + m_removePhonemesButtonArrow->setDisabled(true); + m_clearPhonemesButton->setDisabled(m_selectedPhonemeSetsTable->rowCount() == 0); } @@ -425,21 +425,21 @@ namespace EMStudio QTableWidget* table = (QTableWidget*)sender(); // disable/enable buttons - bool selected = (table->selectedItems().size() > 0); - if (table == mPossiblePhonemeSetsTable) + bool selected = !table->selectedItems().empty(); + if (table == m_possiblePhonemeSetsTable) { - mAddPhonemesButton->setDisabled(!selected); - mAddPhonemesButtonArrow->setDisabled(!selected); + m_addPhonemesButton->setDisabled(!selected); + m_addPhonemesButtonArrow->setDisabled(!selected); } else { - mRemovePhonemesButton->setDisabled(!selected); - mRemovePhonemesButtonArrow->setDisabled(!selected); + m_removePhonemesButton->setDisabled(!selected); + m_removePhonemesButtonArrow->setDisabled(!selected); } // adjust selection state of the cell widgetsmActor - const uint32 numRows = table->rowCount(); - for (uint32 i = 0; i < numRows; ++i) + const int numRows = table->rowCount(); + for (int i = 0; i < numRows; ++i) { // get the table widget item and check if it exists QTableWidgetItem* item = table->item(i, 0); @@ -461,22 +461,21 @@ namespace EMStudio // removes the selected phoneme sets void PhonemeSelectionWindow::RemoveSelectedPhonemeSets() { - QList selectedItems = mSelectedPhonemeSetsTable->selectedItems(); - const uint32 numSelectedItems = selectedItems.size(); - if (numSelectedItems == 0) + QList selectedItems = m_selectedPhonemeSetsTable->selectedItems(); + if (selectedItems.empty()) { return; } // create phoneme sets string from the selected phoneme sets AZStd::string phonemeSets; - for (uint32 i = 0; i < numSelectedItems; ++i) + for (const QTableWidgetItem* selectedItem : selectedItems) { - phonemeSets += AZStd::string::format("%s,", selectedItems[i]->text().toUtf8().data()); + phonemeSets += AZStd::string::format("%s,", selectedItem->text().toUtf8().data()); } // call command to remove selected the phoneme sets - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %i -name \"%s\" -phonemeAction \"remove\" -phonemeSets \"%s\"", mActor->GetID(), mLODLevel, mMorphTarget->GetName(), phonemeSets.c_str()); + const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %zu -name \"%s\" -phonemeAction \"remove\" -phonemeSets \"%s\"", m_actor->GetID(), m_lodLevel, m_morphTarget->GetName(), phonemeSets.c_str()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) @@ -485,7 +484,7 @@ namespace EMStudio } else { - mDirtyFlag = true; + m_dirtyFlag = true; } } @@ -493,22 +492,21 @@ namespace EMStudio // adds the selected phoneme sets void PhonemeSelectionWindow::AddSelectedPhonemeSets() { - QList selectedItems = mSelectedPhonemeSetsTable->selectedItems(); - const uint32 numSelectedItems = selectedItems.size(); - if (numSelectedItems == 0) + QList selectedItems = m_selectedPhonemeSetsTable->selectedItems(); + if (selectedItems.empty()) { return; } // create phoneme sets string from the selected phoneme sets AZStd::string phonemeSets; - for (uint32 i = 0; i < numSelectedItems; ++i) + for (const QTableWidgetItem* selectedItem : selectedItems) { - phonemeSets += AZStd::string::format("%s,", selectedItems[i]->text().toUtf8().data()); + phonemeSets += AZStd::string::format("%s,", selectedItem->text().toUtf8().data()); } // call command to add the selected phoneme sets - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %i -name \"%s\" -phonemeAction \"add\" -phonemeSets \"%s\"", mActor->GetID(), mLODLevel, mMorphTarget->GetName(), phonemeSets.c_str()); + const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %zu -name \"%s\" -phonemeAction \"add\" -phonemeSets \"%s\"", m_actor->GetID(), m_lodLevel, m_morphTarget->GetName(), phonemeSets.c_str()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) @@ -517,7 +515,7 @@ namespace EMStudio } else { - mDirtyFlag = true; + m_dirtyFlag = true; } } @@ -525,7 +523,7 @@ namespace EMStudio // clear the selected phoneme sets void PhonemeSelectionWindow::ClearSelectedPhonemeSets() { - const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %i -name \"%s\" -phonemeAction \"clear\"", mActor->GetID(), mLODLevel, mMorphTarget->GetName()); + const AZStd::string command = AZStd::string::format("AdjustMorphTarget -actorID %i -lodLevel %zu -name \"%s\" -phonemeAction \"clear\"", m_actor->GetID(), m_lodLevel, m_morphTarget->GetName()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) @@ -534,7 +532,7 @@ namespace EMStudio } else { - mDirtyFlag = true; + m_dirtyFlag = true; } } @@ -592,7 +590,7 @@ namespace EMStudio MCORE_UNUSED(event); // check if something changed - if (mDirtyFlag == false) + if (m_dirtyFlag == false) { return; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.h index 70ce72a281..80f0d9b19e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MorphTargetsWindow/PhonemeSelectionWindow.h @@ -91,19 +91,19 @@ namespace EMStudio VisimeWidget(const AZStd::string& filename); virtual ~VisimeWidget(); - void SetSelected(bool selected = true) { mSelected = selected; } + void SetSelected(bool selected = true) { m_selected = selected; } void UpdateInterface(); void paintEvent(QPaintEvent* event) override; - void enterEvent(QEvent* event) override { MCORE_UNUSED(event); mMouseWithinWidget = true; repaint(); } - void leaveEvent(QEvent* event) override { MCORE_UNUSED(event); mMouseWithinWidget = false; repaint(); } + void enterEvent(QEvent* event) override { MCORE_UNUSED(event); m_mouseWithinWidget = true; repaint(); } + void leaveEvent(QEvent* event) override { MCORE_UNUSED(event); m_mouseWithinWidget = false; repaint(); } private: - AZStd::string mFileName; - AZStd::string mFileNameWithoutExt; - QPixmap* mPixmap; - bool mSelected; - bool mMouseWithinWidget; + AZStd::string m_fileName; + AZStd::string m_fileNameWithoutExt; + QPixmap* m_pixmap; + bool m_selected; + bool m_mouseWithinWidget; }; @@ -117,7 +117,7 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(PhonemeSelectionWindow, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_EMSTUDIOSDK) public: - PhonemeSelectionWindow(EMotionFX::Actor* actor, uint32 lodLevel, EMotionFX::MorphTarget* morphTarget, QWidget* parent = nullptr); + PhonemeSelectionWindow(EMotionFX::Actor* actor, size_t lodLevel, EMotionFX::MorphTarget* morphTarget, QWidget* parent = nullptr); virtual ~PhonemeSelectionWindow(); void Init(); @@ -138,23 +138,23 @@ namespace EMStudio private: // the morph target - EMotionFX::Actor* mActor; - EMotionFX::MorphTarget* mMorphTarget; - uint32 mLODLevel; - EMotionFX::MorphSetup* mMorphSetup; + EMotionFX::Actor* m_actor; + EMotionFX::MorphTarget* m_morphTarget; + size_t m_lodLevel; + EMotionFX::MorphSetup* m_morphSetup; // the dialogstacks - MysticQt::DialogStack* mPossiblePhonemeSets; - MysticQt::DialogStack* mSelectedPhonemeSets; - DragTableWidget* mPossiblePhonemeSetsTable; - DragTableWidget* mSelectedPhonemeSetsTable; - - QPushButton* mAddPhonemesButton; - QPushButton* mRemovePhonemesButton; - QPushButton* mClearPhonemesButton; - QPushButton* mAddPhonemesButtonArrow; - QPushButton* mRemovePhonemesButtonArrow; - - bool mDirtyFlag; + MysticQt::DialogStack* m_possiblePhonemeSets; + MysticQt::DialogStack* m_selectedPhonemeSets; + DragTableWidget* m_possiblePhonemeSetsTable; + DragTableWidget* m_selectedPhonemeSetsTable; + + QPushButton* m_addPhonemesButton; + QPushButton* m_removePhonemesButton; + QPushButton* m_clearPhonemesButton; + QPushButton* m_addPhonemesButtonArrow; + QPushButton* m_removePhonemesButtonArrow; + + bool m_dirtyFlag; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.cpp index 9432ad1d78..e0e9455770 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.cpp @@ -33,7 +33,7 @@ namespace EMStudio { MotionEventPresetsWidget::MotionEventPresetsWidget(QWidget* parent, MotionEventsPlugin* plugin) : QWidget(parent) - , mPlugin(plugin) + , m_plugin(plugin) { Init(); } @@ -48,17 +48,17 @@ namespace EMStudio layout->setSpacing(2); // create the table widget - mTableWidget = new DragTableWidget(0, 2, nullptr); - mTableWidget->setCornerButtonEnabled(false); - mTableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mTableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); - mTableWidget->setShowGrid(false); + m_tableWidget = new DragTableWidget(0, 2, nullptr); + m_tableWidget->setCornerButtonEnabled(false); + m_tableWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_tableWidget->setContextMenuPolicy(Qt::DefaultContextMenu); + m_tableWidget->setShowGrid(false); // set the table to row single selection - mTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); - QHeaderView* horizontalHeader = mTableWidget->horizontalHeader(); + QHeaderView* horizontalHeader = m_tableWidget->horizontalHeader(); horizontalHeader->setStretchLastSection(true); horizontalHeader->setVisible(false); @@ -89,15 +89,15 @@ namespace EMStudio } layout->addWidget(toolBar); - layout->addWidget(mTableWidget); + layout->addWidget(m_tableWidget); layout->addLayout(ioButtonsLayout); // set the main layout setLayout(layout); // connect the signals and the slots - connect(mTableWidget, &MotionEventPresetsWidget::DragTableWidget::itemSelectionChanged, this, &MotionEventPresetsWidget::SelectionChanged); - connect(mTableWidget, &QTableWidget::cellDoubleClicked, this, [this](int row, int column) + connect(m_tableWidget, &MotionEventPresetsWidget::DragTableWidget::itemSelectionChanged, this, &MotionEventPresetsWidget::SelectionChanged); + connect(m_tableWidget, &QTableWidget::cellDoubleClicked, this, [this](int row, int column) { AZ_UNUSED(column); MotionEventPreset* preset = GetEventPresetManager()->GetPreset(row); @@ -108,7 +108,7 @@ namespace EMStudio GetEventPresetManager()->SetDirtyFlag(true); ReInit(); - mPlugin->FireColorChangedSignal(); + m_plugin->FireColorChangedSignal(); } }); @@ -116,14 +116,14 @@ namespace EMStudio // initialize everything ReInit(); UpdateInterface(); - mPlugin->ReInit(); + m_plugin->ReInit(); } void MotionEventPresetsWidget::ReInit() { // Remember selected items - QList selectedItems = mTableWidget->selectedItems(); + QList selectedItems = m_tableWidget->selectedItems(); AZStd::vector selectedRows; selectedRows.reserve(selectedItems.size()); for (const QTableWidgetItem* selectedItem : selectedItems) @@ -133,11 +133,11 @@ namespace EMStudio } // clear the table widget - mTableWidget->clear(); - mTableWidget->setColumnCount(2); + m_tableWidget->clear(); + m_tableWidget->setColumnCount(2); const size_t numEventPresets = GetEventPresetManager()->GetNumPresets(); - mTableWidget->setRowCount(static_cast(numEventPresets)); + m_tableWidget->setRowCount(static_cast(numEventPresets)); // set header items for the table QTableWidgetItem* colorHeaderItem = new QTableWidgetItem("Color"); @@ -145,11 +145,11 @@ namespace EMStudio colorHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); presetNameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mTableWidget->setHorizontalHeaderItem(0, colorHeaderItem); - mTableWidget->setHorizontalHeaderItem(1, presetNameHeaderItem); + m_tableWidget->setHorizontalHeaderItem(0, colorHeaderItem); + m_tableWidget->setHorizontalHeaderItem(1, presetNameHeaderItem); - mTableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); - mTableWidget->setColumnWidth(0, 39); + m_tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); + m_tableWidget->setColumnWidth(0, 39); for (AZ::u32 i = 0; i < numEventPresets; ++i) { @@ -173,8 +173,8 @@ namespace EMStudio tableItemColor->setWhatsThis(whatsThisString.c_str()); tableItemPresetName->setWhatsThis(whatsThisString.c_str()); - mTableWidget->setItem(i, 0, tableItemColor); - mTableWidget->setItem(i, 1, tableItemPresetName); + m_tableWidget->setItem(i, 0, tableItemColor); + m_tableWidget->setItem(i, 1, tableItemPresetName); // Editing will be handled in the double click signal handler tableItemPresetName->setFlags(tableItemPresetName->flags() ^ Qt::ItemIsEditable); @@ -188,23 +188,23 @@ namespace EMStudio } // set the vertical header not visible - QHeaderView* verticalHeader = mTableWidget->verticalHeader(); + QHeaderView* verticalHeader = m_tableWidget->verticalHeader(); verticalHeader->setVisible(false); - mTableWidget->resizeColumnToContents(1); - mTableWidget->resizeColumnToContents(2); + m_tableWidget->resizeColumnToContents(1); + m_tableWidget->resizeColumnToContents(2); - if (mTableWidget->columnWidth(1) < 36) + if (m_tableWidget->columnWidth(1) < 36) { - mTableWidget->setColumnWidth(1, 36); + m_tableWidget->setColumnWidth(1, 36); } - if (mTableWidget->columnWidth(2) < 70) + if (m_tableWidget->columnWidth(2) < 70) { - mTableWidget->setColumnWidth(2, 70); + m_tableWidget->setColumnWidth(2, 70); } - mTableWidget->horizontalHeader()->setStretchLastSection(true); + m_tableWidget->horizontalHeader()->setStretchLastSection(true); // update the interface UpdateInterface(); @@ -243,7 +243,7 @@ namespace EMStudio void MotionEventPresetsWidget::RemoveSelectedMotionEventPresets() { - QList selectedItems = mTableWidget->selectedItems(); + QList selectedItems = m_tableWidget->selectedItems(); if (selectedItems.isEmpty()) { ClearMotionEventPresetsButton(); @@ -272,13 +272,13 @@ namespace EMStudio ReInit(); // selected the next row - if (firstSelectedRow > (mTableWidget->rowCount() - 1)) + if (firstSelectedRow > (m_tableWidget->rowCount() - 1)) { - mTableWidget->selectRow(firstSelectedRow - 1); + m_tableWidget->selectRow(firstSelectedRow - 1); } else { - mTableWidget->selectRow(firstSelectedRow); + m_tableWidget->selectRow(firstSelectedRow); } } @@ -303,7 +303,7 @@ namespace EMStudio void MotionEventPresetsWidget::ClearMotionEventPresets() { - mTableWidget->selectAll(); + m_tableWidget->selectAll(); RemoveSelectedMotionEventPresets(); UpdateInterface(); } @@ -329,7 +329,7 @@ namespace EMStudio ReInit(); UpdateInterface(); - mPlugin->ReInit(); + m_plugin->ReInit(); } @@ -366,7 +366,7 @@ namespace EMStudio void MotionEventPresetsWidget::contextMenuEvent(QContextMenuEvent* event) { - QList selectedItems = mTableWidget->selectedItems(); + QList selectedItems = m_tableWidget->selectedItems(); if (selectedItems.isEmpty()) { return; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.h index 331780fe19..8d36f57c25 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventPresetsWidget.h @@ -46,7 +46,7 @@ namespace EMStudio void Init(); void UpdateInterface(); - QTableWidget* GetMotionEventPresetsTable() { return mTableWidget; } + QTableWidget* GetMotionEventPresetsTable() { return m_tableWidget; } public slots: void ReInit(); @@ -93,12 +93,12 @@ namespace EMStudio } }; - DragTableWidget* mTableWidget = nullptr; + DragTableWidget* m_tableWidget = nullptr; QAction* m_addAction = nullptr; QAction* m_saveMenuAction = nullptr; QAction* m_saveAction = nullptr; QAction* m_saveAsAction = nullptr; QAction* m_loadAction = nullptr; - MotionEventsPlugin* mPlugin = nullptr; + MotionEventsPlugin* m_plugin = nullptr; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.cpp index 193fbec9e3..316b2017cc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.cpp @@ -25,34 +25,34 @@ namespace EMStudio { MotionEventsPlugin::MotionEventsPlugin() : EMStudio::DockWidgetPlugin() - , mAdjustMotionCallback(nullptr) - , mSelectCallback(nullptr) - , mUnselectCallback(nullptr) - , mClearSelectionCallback(nullptr) - , mDialogStack(nullptr) - , mMotionEventPresetsWidget(nullptr) - , mMotionEventWidget(nullptr) - , mMotionTable(nullptr) - , mTimeViewPlugin(nullptr) - , mTrackHeaderWidget(nullptr) - , mTrackDataWidget(nullptr) - , mMotionWindowPlugin(nullptr) - , mMotionListWindow(nullptr) - , mMotion(nullptr) + , m_adjustMotionCallback(nullptr) + , m_selectCallback(nullptr) + , m_unselectCallback(nullptr) + , m_clearSelectionCallback(nullptr) + , m_dialogStack(nullptr) + , m_motionEventPresetsWidget(nullptr) + , m_motionEventWidget(nullptr) + , m_motionTable(nullptr) + , m_timeViewPlugin(nullptr) + , m_trackHeaderWidget(nullptr) + , m_trackDataWidget(nullptr) + , m_motionWindowPlugin(nullptr) + , m_motionListWindow(nullptr) + , m_motion(nullptr) { } MotionEventsPlugin::~MotionEventsPlugin() { - GetCommandManager()->RemoveCommandCallback(mAdjustMotionCallback, false); - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - delete mAdjustMotionCallback; - delete mSelectCallback; - delete mUnselectCallback; - delete mClearSelectionCallback; + GetCommandManager()->RemoveCommandCallback(m_adjustMotionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + delete m_adjustMotionCallback; + delete m_selectCallback; + delete m_unselectCallback; + delete m_clearSelectionCallback; } @@ -74,12 +74,12 @@ namespace EMStudio { if (classID == TimeViewPlugin::CLASS_ID) { - mTimeViewPlugin = nullptr; + m_timeViewPlugin = nullptr; } if (classID == MotionWindowPlugin::CLASS_ID) { - mMotionWindowPlugin = nullptr; + m_motionWindowPlugin = nullptr; } } @@ -91,28 +91,28 @@ namespace EMStudio GetEventPresetManager()->Load(); // create callbacks - mAdjustMotionCallback = new CommandAdjustMotionCallback(false); - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); - mClearSelectionCallback = new CommandClearSelectionCallback(false); - GetCommandManager()->RegisterCommandCallback("AdjustMotion", mAdjustMotionCallback); - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); + m_adjustMotionCallback = new CommandAdjustMotionCallback(false); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); + m_clearSelectionCallback = new CommandClearSelectionCallback(false); + GetCommandManager()->RegisterCommandCallback("AdjustMotion", m_adjustMotionCallback); + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); // create the dialog stack - assert(mDialogStack == nullptr); - mDialogStack = new MysticQt::DialogStack(mDock); - mDock->setWidget(mDialogStack); + assert(m_dialogStack == nullptr); + m_dialogStack = new MysticQt::DialogStack(m_dock); + m_dock->setWidget(m_dialogStack); // create the motion event presets widget - mMotionEventPresetsWidget = new MotionEventPresetsWidget(mDialogStack, this); - mDialogStack->Add(mMotionEventPresetsWidget, "Motion Event Presets", false, true); - connect(mDock, &QDockWidget::visibilityChanged, this, &MotionEventsPlugin::WindowReInit); + m_motionEventPresetsWidget = new MotionEventPresetsWidget(m_dialogStack, this); + m_dialogStack->Add(m_motionEventPresetsWidget, "Motion Event Presets", false, true); + connect(m_dock, &QDockWidget::visibilityChanged, this, &MotionEventsPlugin::WindowReInit); // create the motion event properties widget - mMotionEventWidget = new MotionEventWidget(mDialogStack); - mDialogStack->Add(mMotionEventWidget, "Motion Event Properties", false, true); + m_motionEventWidget = new MotionEventWidget(m_dialogStack); + m_dialogStack->Add(m_motionEventWidget, "Motion Event Properties", false, true); ValidatePluginLinks(); UpdateMotionEventWidget(); @@ -123,30 +123,30 @@ namespace EMStudio void MotionEventsPlugin::ValidatePluginLinks() { - if (!mTimeViewPlugin) + if (!m_timeViewPlugin) { EMStudioPlugin* timeViewBasePlugin = EMStudio::GetPluginManager()->FindActivePlugin(TimeViewPlugin::CLASS_ID); if (timeViewBasePlugin) { - mTimeViewPlugin = (TimeViewPlugin*)timeViewBasePlugin; - mTrackDataWidget = mTimeViewPlugin->GetTrackDataWidget(); - mTrackHeaderWidget = mTimeViewPlugin->GetTrackHeaderWidget(); + m_timeViewPlugin = (TimeViewPlugin*)timeViewBasePlugin; + m_trackDataWidget = m_timeViewPlugin->GetTrackDataWidget(); + m_trackHeaderWidget = m_timeViewPlugin->GetTrackHeaderWidget(); - connect(mTrackDataWidget, &TrackDataWidget::MotionEventPresetsDropped, this, &MotionEventsPlugin::OnEventPresetDropped); - connect(mTimeViewPlugin, &TimeViewPlugin::SelectionChanged, this, &MotionEventsPlugin::UpdateMotionEventWidget); - connect(this, &MotionEventsPlugin::OnColorChanged, mTimeViewPlugin, &TimeViewPlugin::ReInit); + connect(m_trackDataWidget, &TrackDataWidget::MotionEventPresetsDropped, this, &MotionEventsPlugin::OnEventPresetDropped); + connect(m_timeViewPlugin, &TimeViewPlugin::SelectionChanged, this, &MotionEventsPlugin::UpdateMotionEventWidget); + connect(this, &MotionEventsPlugin::OnColorChanged, m_timeViewPlugin, &TimeViewPlugin::ReInit); } } - if (!mMotionWindowPlugin) + if (!m_motionWindowPlugin) { EMStudioPlugin* motionBasePlugin = EMStudio::GetPluginManager()->FindActivePlugin(MotionWindowPlugin::CLASS_ID); if (motionBasePlugin) { - mMotionWindowPlugin = (MotionWindowPlugin*)motionBasePlugin; - mMotionListWindow = mMotionWindowPlugin->GetMotionListWindow(); + m_motionWindowPlugin = (MotionWindowPlugin*)motionBasePlugin; + m_motionListWindow = m_motionWindowPlugin->GetMotionListWindow(); - connect(mMotionListWindow, &MotionListWindow::MotionSelectionChanged, this, &MotionEventsPlugin::MotionSelectionChanged); + connect(m_motionListWindow, &MotionListWindow::MotionSelectionChanged, this, &MotionEventsPlugin::MotionSelectionChanged); } } } @@ -155,9 +155,9 @@ namespace EMStudio void MotionEventsPlugin::MotionSelectionChanged() { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); - if (mMotion != motion) + if (m_motion != motion) { - mMotion = motion; + m_motion = motion; ReInit(); } } @@ -185,7 +185,7 @@ namespace EMStudio bool MotionEventsPlugin::CheckIfIsPresetReadyToDrop() { // get the motion event presets table - QTableWidget* eventPresetsTable = mMotionEventPresetsWidget->GetMotionEventPresetsTable(); + QTableWidget* eventPresetsTable = m_motionEventPresetsWidget->GetMotionEventPresetsTable(); if (eventPresetsTable == nullptr) { return false; @@ -210,18 +210,17 @@ namespace EMStudio void MotionEventsPlugin::OnEventPresetDropped(QPoint position) { // calculate the start time for the motion event - double dropTimeInSeconds = mTimeViewPlugin->PixelToTime(position.x()); - //mTimeViewPlugin->CalcTime( position.x(), &dropTimeInSeconds, nullptr, nullptr, nullptr, nullptr ); + double dropTimeInSeconds = m_timeViewPlugin->PixelToTime(position.x()); // get the time track on which we dropped the preset - TimeTrack* timeTrack = mTimeViewPlugin->GetTrackAt(position.y()); - if (!timeTrack || !mMotion) + TimeTrack* timeTrack = m_timeViewPlugin->GetTrackAt(position.y()); + if (!timeTrack || !m_motion) { return; } // get the corresponding motion event track - EMotionFX::MotionEventTable* eventTable = mMotion->GetEventTable(); + EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable(); EMotionFX::MotionEventTrack* eventTrack = eventTable->FindTrackByName(timeTrack->GetName()); if (eventTrack == nullptr) { @@ -229,7 +228,7 @@ namespace EMStudio } // get the motion event presets table - QTableWidget* eventPresetsTable = mMotionEventPresetsWidget->GetMotionEventPresetsTable(); + QTableWidget* eventPresetsTable = m_motionEventPresetsWidget->GetMotionEventPresetsTable(); if (eventPresetsTable == nullptr) { return; @@ -246,7 +245,7 @@ namespace EMStudio if (itemName->isSelected()) { CommandSystem::CommandCreateMotionEvent* createMotionEventCommand = aznew CommandSystem::CommandCreateMotionEvent(); - createMotionEventCommand->SetMotionID(mMotion->GetID()); + createMotionEventCommand->SetMotionID(m_motion->GetID()); createMotionEventCommand->SetEventTrackName(eventTrack->GetName()); createMotionEventCommand->SetStartTime(aznumeric_cast(dropTimeInSeconds)); createMotionEventCommand->SetEndTime(aznumeric_cast(dropTimeInSeconds)); @@ -263,20 +262,20 @@ namespace EMStudio void MotionEventsPlugin::UpdateMotionEventWidget() { - if (!mMotionEventWidget || !mTimeViewPlugin) + if (!m_motionEventWidget || !m_timeViewPlugin) { return; } - mTimeViewPlugin->UpdateSelection(); - if (mTimeViewPlugin->GetNumSelectedEvents() != 1) + m_timeViewPlugin->UpdateSelection(); + if (m_timeViewPlugin->GetNumSelectedEvents() != 1) { - mMotionEventWidget->ReInit(); + m_motionEventWidget->ReInit(); } else { - EventSelectionItem selectionItem = mTimeViewPlugin->GetSelectedEvent(0); - mMotionEventWidget->ReInit(selectionItem.mMotion, selectionItem.GetMotionEvent()); + EventSelectionItem selectionItem = m_timeViewPlugin->GetSelectedEvent(0); + m_motionEventWidget->ReInit(selectionItem.m_motion, selectionItem.GetMotionEvent()); } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.h index 7f3e821f8d..7cd34e4bca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionEvents/MotionEventsPlugin.h @@ -56,7 +56,7 @@ namespace EMStudio void OnBeforeRemovePlugin(uint32 classID) override; - MotionEventPresetsWidget* GetPresetsWidget() const { return mMotionEventPresetsWidget; } + MotionEventPresetsWidget* GetPresetsWidget() const { return m_motionEventPresetsWidget; } void ValidatePluginLinks(); @@ -78,21 +78,21 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandSelectCallback); MCORE_DEFINECOMMANDCALLBACK(CommandUnselectCallback); MCORE_DEFINECOMMANDCALLBACK(CommandClearSelectionCallback); - CommandAdjustMotionCallback* mAdjustMotionCallback; - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; - CommandClearSelectionCallback* mClearSelectionCallback; - - MysticQt::DialogStack* mDialogStack; - MotionEventPresetsWidget* mMotionEventPresetsWidget; - MotionEventWidget* mMotionEventWidget; - - QTableWidget* mMotionTable; - TimeViewPlugin* mTimeViewPlugin; - TrackHeaderWidget* mTrackHeaderWidget; - TrackDataWidget* mTrackDataWidget; - MotionWindowPlugin* mMotionWindowPlugin; - MotionListWindow* mMotionListWindow; - EMotionFX::Motion* mMotion; + CommandAdjustMotionCallback* m_adjustMotionCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; + CommandClearSelectionCallback* m_clearSelectionCallback; + + MysticQt::DialogStack* m_dialogStack; + MotionEventPresetsWidget* m_motionEventPresetsWidget; + MotionEventWidget* m_motionEventWidget; + + QTableWidget* m_motionTable; + TimeViewPlugin* m_timeViewPlugin; + TrackHeaderWidget* m_trackHeaderWidget; + TrackDataWidget* m_trackDataWidget; + MotionWindowPlugin* m_motionWindowPlugin; + MotionListWindow* m_motionListWindow; + EMotionFX::Motion* m_motion; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.cpp index 53b60c715f..ca62d6d927 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.cpp @@ -6,6 +6,8 @@ * */ +#include "AzCore/std/algorithm.h" +#include "AzCore/std/iterator.h" #include #include #include @@ -33,7 +35,7 @@ namespace EMStudio { - MotionSetManagementRemoveMotionsFailedWindow::MotionSetManagementRemoveMotionsFailedWindow(QWidget* parent, const MCore::Array& motions) + MotionSetManagementRemoveMotionsFailedWindow::MotionSetManagementRemoveMotionsFailedWindow(QWidget* parent, const AZStd::vector& motions) : QDialog(parent) { // set the window title @@ -70,11 +72,11 @@ namespace EMStudio tableWidget->verticalHeader()->setVisible(false); // set the number of rows - const uint32 numMotions = motions.GetLength(); + const int numMotions = aznumeric_caster(motions.size()); tableWidget->setRowCount(numMotions); // add each motion in the table - for (uint32 i = 0; i < numMotions; ++i) + for (int i = 0; i < numMotions; ++i) { // get the motion EMotionFX::Motion* motion = motions[i]; @@ -118,7 +120,7 @@ namespace EMStudio : QDialog(parent) { // store the motion set - mMotionSet = motionSet; + m_motionSet = motionSet; // set the window title setWindowTitle("Enter new motion set name"); @@ -130,33 +132,27 @@ namespace EMStudio QVBoxLayout* layout = new QVBoxLayout(); // add the line edit - mLineEdit = new QLineEdit(); - connect(mLineEdit, &QLineEdit::textEdited, this, &MotionSetManagementRenameWindow::TextEdited); - layout->addWidget(mLineEdit); + m_lineEdit = new QLineEdit(); + connect(m_lineEdit, &QLineEdit::textEdited, this, &MotionSetManagementRenameWindow::TextEdited); + layout->addWidget(m_lineEdit); // set the current name and select all - mLineEdit->setText(motionSet->GetName()); - mLineEdit->selectAll(); - - // create add the error message - /*mErrorMsg = new QLabel("Error: Duplicate name found"); - mErrorMsg->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mErrorMsg->setVisible(false);*/ + m_lineEdit->setText(motionSet->GetName()); + m_lineEdit->selectAll(); // create the button layout QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); + m_okButton = new QPushButton("OK"); QPushButton* cancelButton = new QPushButton("Cancel"); - //buttonLayout->addWidget(mErrorMsg); - buttonLayout->addWidget(mOKButton); + buttonLayout->addWidget(m_okButton); buttonLayout->addWidget(cancelButton); // Allow pressing the enter key as alternative to pressing the ok button for faster workflow. - mOKButton->setAutoDefault(true); - mOKButton->setDefault(true); + m_okButton->setAutoDefault(true); + m_okButton->setDefault(true); // connect the buttons - connect(mOKButton, &QPushButton::clicked, this, &MotionSetManagementRenameWindow::Accepted); + connect(m_okButton, &QPushButton::clicked, this, &MotionSetManagementRenameWindow::Accepted); connect(cancelButton, &QPushButton::clicked, this, &MotionSetManagementRenameWindow::reject); // set the new layout @@ -169,21 +165,19 @@ namespace EMStudio { if (text.isEmpty()) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); } - else if (text == mMotionSet->GetName()) + else if (text == m_motionSet->GetName()) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } else { // find duplicate name in all motion sets other than this motion set - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -194,24 +188,22 @@ namespace EMStudio if (text == motionSet->GetName()) { - //mErrorMsg->setVisible(true); - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); return; } } // no duplicate name found - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } } void MotionSetManagementRenameWindow::Accepted() { - const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -newName \"%s\"", mMotionSet->GetID(), mLineEdit->text().toUtf8().data()); + const AZStd::string commandString = AZStd::string::format("AdjustMotionSet -motionSetID %i -newName \"%s\"", m_motionSet->GetID(), m_lineEdit->text().toUtf8().data()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(commandString, result)) @@ -227,7 +219,7 @@ namespace EMStudio MotionSetManagementWindow::MotionSetManagementWindow(MotionSetsWindowPlugin* parentPlugin, QWidget* parent) : QWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; } @@ -246,31 +238,31 @@ namespace EMStudio layout->setMargin(0); layout->setSpacing(2); - mMotionSetsTree = new QTreeWidget(); + m_motionSetsTree = new QTreeWidget(); // set the table to row single selection - mMotionSetsTree->setSelectionBehavior(QAbstractItemView::SelectRows); - mMotionSetsTree->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_motionSetsTree->setSelectionBehavior(QAbstractItemView::SelectRows); + m_motionSetsTree->setSelectionMode(QAbstractItemView::ExtendedSelection); // set the minimum size and the resizing policy - mMotionSetsTree->setMinimumHeight(150); - mMotionSetsTree->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - mMotionSetsTree->setColumnCount(1); + m_motionSetsTree->setMinimumHeight(150); + m_motionSetsTree->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + m_motionSetsTree->setColumnCount(1); - mMotionSetsTree->setAlternatingRowColors(true); - mMotionSetsTree->setExpandsOnDoubleClick(true); - mMotionSetsTree->setAnimated(true); - mMotionSetsTree->setObjectName("EMFX.MotionSetManagementWindow.MotionSetsTree"); + m_motionSetsTree->setAlternatingRowColors(true); + m_motionSetsTree->setExpandsOnDoubleClick(true); + m_motionSetsTree->setAnimated(true); + m_motionSetsTree->setObjectName("EMFX.MotionSetManagementWindow.MotionSetsTree"); - connect(mMotionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); + connect(m_motionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); QStringList headerList; headerList.append("Name"); - mMotionSetsTree->setHeaderLabels(headerList); - mMotionSetsTree->header()->setSortIndicator(0, Qt::AscendingOrder); + m_motionSetsTree->setHeaderLabels(headerList); + m_motionSetsTree->header()->setSortIndicator(0, Qt::AscendingOrder); // disable the move of section to have column order fixed - mMotionSetsTree->header()->setSectionsMovable(false); + m_motionSetsTree->header()->setSectionsMovable(false); QToolBar* toolBar = new QToolBar(this); toolBar->setObjectName("MotionSetManagementWindow.ToolBar"); @@ -309,7 +301,7 @@ namespace EMStudio toolBar->addWidget(m_searchWidget); layout->addWidget(toolBar); - layout->addWidget(mMotionSetsTree); + layout->addWidget(m_motionSetsTree); ReInit(); UpdateInterface(); @@ -359,8 +351,8 @@ namespace EMStudio } // Recursively add all child sets. - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { EMotionFX::MotionSet* childSet = motionSet->GetChildSet(i); RecursivelyAddSets(item, childSet, selectedSetIDs); @@ -371,29 +363,28 @@ namespace EMStudio void MotionSetManagementWindow::ReInit() { // Get the selected items in the motion set tree widget.. - const QList selectedItems = mMotionSetsTree->selectedItems(); - const int numSelectedItems = selectedItems.count(); + const QList selectedItems = m_motionSetsTree->selectedItems(); + const int numSelectedItems = selectedItems.size(); // Create and fill an array containing ids of all selected motion sets. AZStd::vector selectedMotionSetIDs; - selectedMotionSetIDs.resize(numSelectedItems); - for (int32 i = 0; i < numSelectedItems; ++i) + selectedMotionSetIDs.reserve(numSelectedItems); + AZStd::transform(selectedItems.begin(), selectedItems.end(), AZStd::back_inserter(selectedMotionSetIDs), [](const QTreeWidgetItem* selectedItem) { - const int motionSetId = AzFramework::StringFunc::ToInt(selectedItems[i]->whatsThis(0).toUtf8().data()); - selectedMotionSetIDs[i] = motionSetId; - } + return selectedItem->whatsThis(0).toUInt(); + }); // Set the sorting disabled to avoid index issues. - mMotionSetsTree->setSortingEnabled(false); + m_motionSetsTree->setSortingEnabled(false); // Clear all old items. - mMotionSetsTree->blockSignals(true); - mMotionSetsTree->clear(); + m_motionSetsTree->blockSignals(true); + m_motionSetsTree->clear(); // Iterate through root motion sets and fill in the table recursively. AZStd::string tempString; - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { // Only process root motion sets. EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -408,7 +399,7 @@ namespace EMStudio } // add the top level item - QTreeWidgetItem* item = new QTreeWidgetItem(mMotionSetsTree); + QTreeWidgetItem* item = new QTreeWidgetItem(m_motionSetsTree); item->setText(0, motionSet->GetName()); item->setData(0, Qt::UserRole, motionSet->GetID()); item->setIcon(0, QIcon(QStringLiteral(":/EMotionFX/MotionSet.svg"))); @@ -417,7 +408,7 @@ namespace EMStudio AZStd::to_string(tempString, motionSet->GetID()); item->setWhatsThis(0, tempString.c_str()); - mMotionSetsTree->addTopLevelItem(item); + m_motionSetsTree->addTopLevelItem(item); // Should the motion set be selected? if (AZStd::find(selectedMotionSetIDs.begin(), selectedMotionSetIDs.end(), motionSet->GetID()) != selectedMotionSetIDs.end()) @@ -446,8 +437,8 @@ namespace EMStudio } // get the number of children and iterate through them - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 j = 0; j < numChildSets; ++j) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t j = 0; j < numChildSets; ++j) { // get the child set EMotionFX::MotionSet* childSet = motionSet->GetChildSet(j); @@ -458,20 +449,20 @@ namespace EMStudio } // enable the tree signals - mMotionSetsTree->blockSignals(false); + m_motionSetsTree->blockSignals(false); // enable the sorting - mMotionSetsTree->setSortingEnabled(true); + m_motionSetsTree->setSortingEnabled(true); } void MotionSetManagementWindow::OnSelectionChanged() { - const QList selectedItems = mMotionSetsTree->selectedItems(); - const uint32 numSelected = selectedItems.count(); + const QList selectedItems = m_motionSetsTree->selectedItems(); + const size_t numSelected = selectedItems.count(); if (numSelected != 1) { - mPlugin->SetSelectedSet(nullptr); + m_plugin->SetSelectedSet(nullptr); } else { @@ -480,7 +471,7 @@ namespace EMStudio if (selectedSet) { - mPlugin->SetSelectedSet(selectedSet); + m_plugin->SetSelectedSet(selectedSet); } } } @@ -497,7 +488,7 @@ namespace EMStudio connect(addAction, &QAction::triggered, this, &MotionSetManagementWindow::OnCreateMotionSet); // get the selected items - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); const int numSelectedItems = selectedItems.count(); // add remove if at least one item selected @@ -536,7 +527,7 @@ namespace EMStudio void MotionSetManagementWindow::OnCreateMotionSet() { - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); const int numSelectedItems = selectedItems.count(); // only add the motion set as child if at least one item selected @@ -547,7 +538,7 @@ namespace EMStudio const AZStd::string uniqueMotionSetName = MCore::GenerateUniqueString("MotionSet", [&](const AZStd::string& value) { - return (EMotionFX::GetMotionManager().FindMotionSetIndexByName(value.c_str()) == MCORE_INVALIDINDEX32); + return (EMotionFX::GetMotionManager().FindMotionSetIndexByName(value.c_str()) == InvalidIndex); }); // Construct the command string. @@ -561,7 +552,7 @@ namespace EMStudio } // Select the new motion set - mMotionSetsTree->clearSelection(); + m_motionSetsTree->clearSelection(); const EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByName(uniqueMotionSetName.c_str()); if (motionSet) { @@ -585,7 +576,7 @@ namespace EMStudio uniqueMotionSetName = MCore::GenerateUniqueString("MotionSet", [&](const AZStd::string& value) { - return (EMotionFX::GetMotionManager().FindMotionSetIndexByName(value.c_str()) == MCORE_INVALIDINDEX32) && + return (EMotionFX::GetMotionManager().FindMotionSetIndexByName(value.c_str()) == InvalidIndex) && (parentMotionSetByName.find(value) == parentMotionSetByName.end()); }); @@ -610,7 +601,7 @@ namespace EMStudio } // Select the new motion sets. - mMotionSetsTree->clearSelection(); + m_motionSetsTree->clearSelection(); for (const AZStd::pair& nameAndParentMotionSet : parentMotionSetByName) { EMotionFX::MotionSet* motionSet = nameAndParentMotionSet.second->RecursiveFindMotionSetByName(nameAndParentMotionSet.first); @@ -623,8 +614,8 @@ namespace EMStudio void MotionSetManagementWindow::SelectItemsById(uint32 motionSetId) { bool selectionChanged = false; - disconnect(mMotionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); - QTreeWidgetItemIterator it(mMotionSetsTree); + disconnect(m_motionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); + QTreeWidgetItemIterator it(m_motionSetsTree); while (*it) { if ((*it)->data(0, Qt::UserRole).toUInt() == motionSetId) @@ -638,7 +629,7 @@ namespace EMStudio } ++it; } - connect(mMotionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); + connect(m_motionSetsTree, &QTreeWidget::itemSelectionChanged, this, &MotionSetManagementWindow::OnSelectionChanged); if (selectionChanged) { OnSelectionChanged(); @@ -648,17 +639,16 @@ namespace EMStudio void MotionSetManagementWindow::GetSelectedMotionSets(AZStd::vector& outSelectedMotionSets) const { // Get the selected items from the motion set tree widget. - const QList selectedItems = mMotionSetsTree->selectedItems(); - const int numSelectedItems = selectedItems.count(); + const QList selectedItems = m_motionSetsTree->selectedItems(); - outSelectedMotionSets.resize(numSelectedItems); + outSelectedMotionSets.resize(selectedItems.size()); // Find the corresponding motion sets and add them to the array. - for (int32 i = 0; i < numSelectedItems; ++i) + AZStd::transform(selectedItems.begin(), selectedItems.end(), outSelectedMotionSets.begin(), [](const QTreeWidgetItem* selectedItem) { - const int motionSetId = AzFramework::StringFunc::ToInt(selectedItems[i]->whatsThis(0).toUtf8().data()); - outSelectedMotionSets[i] = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetId); - } + const uint32 motionSetId = selectedItem->whatsThis(0).toUInt(); + return EMotionFX::GetMotionManager().FindMotionSetByID(motionSetId); + }); } @@ -681,8 +671,8 @@ namespace EMStudio } // Do the same for all child motion sets recursively. - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { EMotionFX::MotionSet* childSet = motionSet->GetChildSet(i); RecursiveIncreaseMotionsReferenceCount(childSet); @@ -693,8 +683,8 @@ namespace EMStudio void MotionSetManagementWindow::RecursiveRemoveMotionsFromSet(EMotionFX::MotionSet* motionSet, MCore::CommandGroup& commandGroup, AZStd::vector& failedRemoveMotions) { // Recursively remove motions from the all entries in the child motion sets. - const uint32 numChildSets = motionSet->GetNumChildSets(); - for (uint32 i = 0; i < numChildSets; ++i) + const size_t numChildSets = motionSet->GetNumChildSets(); + for (size_t i = 0; i < numChildSets; ++i) { EMotionFX::MotionSet* childSet = motionSet->GetChildSet(i); RecursiveRemoveMotionsFromSet(childSet, commandGroup, failedRemoveMotions); @@ -721,23 +711,19 @@ namespace EMStudio void MotionSetManagementWindow::OnRemoveSelectedMotionSets() { - const QList selectedItems = mMotionSetsTree->selectedItems(); - const uint32 numSelected = selectedItems.count(); - if (numSelected <= 0) + const QList selectedItems = m_motionSetsTree->selectedItems(); + if (selectedItems.empty()) { return; } // ask to remove motions - bool removeMotions; - if (QMessageBox::question(this, "Remove Motions From Project?", "Remove the motions from the project entirely? This would also remove them from the motion list. Pressing no will remove them from the motion set but keep them inside the motion list inside the motions window.", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) - { - removeMotions = true; - } - else - { - removeMotions = false; - } + const bool removeMotions = QMessageBox::question( + this, + "Remove Motions From Project?", + "Remove the motions from the project entirely? This would also remove them from the motion list. Pressing no will remove them from the motion set but keep them inside the motion list inside the motions window.", + QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes + ) == QMessageBox::Yes; // create our command group MCore::CommandGroup commandGroup("Remove motion sets"); @@ -747,16 +733,16 @@ namespace EMStudio // get the number of selected motion sets and iterate through them AZStd::set toBeRemoved; - for (int32 i = numSelected - 1; i >= 0; --i) + for (auto selectedItem = selectedItems.crbegin(); selectedItem != selectedItems.crend(); ++selectedItem) { // get the motion set ID - const uint32 motionSetID = AzFramework::StringFunc::ToInt(FromQtString(selectedItems[i]->whatsThis(0)).c_str()); + const uint32 motionSetID = (*selectedItem)->whatsThis(0).toInt(); // get the current motion set and only process the root sets EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetID); // in case we modified the motion set ask if the user wants to save changes it before removing it - mPlugin->SaveDirtyMotionSet(motionSet, nullptr, true, false); + m_plugin->SaveDirtyMotionSet(motionSet, nullptr, true, false); // recursively increase motions reference count RecursiveIncreaseMotionsReferenceCount(motionSet); @@ -789,14 +775,14 @@ namespace EMStudio void MotionSetManagementWindow::OnRenameSelectedMotionSet() { - MotionSetManagementRenameWindow motionSetManagementRenameWindow(this, mPlugin->GetSelectedSet()); + MotionSetManagementRenameWindow motionSetManagementRenameWindow(this, m_plugin->GetSelectedSet()); motionSetManagementRenameWindow.exec(); } void MotionSetManagementWindow::OnClearMotionSets() { // show the save dirty files window before - if (mPlugin->OnSaveDirtyMotionSets() == DirtyFileManager::CANCELED) + if (m_plugin->OnSaveDirtyMotionSets() == DirtyFileManager::CANCELED) { return; } @@ -817,8 +803,8 @@ namespace EMStudio // Increase the reference counter if needed for each motion. AZStd::string commandString; - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -850,7 +836,7 @@ namespace EMStudio if (removeMotions) { AZStd::string motionFileName; - for (uint32 i = 0; i < numMotionSets; ++i) + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -884,7 +870,7 @@ namespace EMStudio void MotionSetManagementWindow::UpdateInterface() { - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); const int numSelectedItems = selectedItems.count(); // remove and save buttons are valid if at least one item is selected @@ -902,7 +888,7 @@ namespace EMStudio rootItem = rootItem->parent(); } - const uint32 motionSetID = AzFramework::StringFunc::ToInt(FromQtString(rootItem->whatsThis(0)).c_str()); + const uint32 motionSetID = rootItem->whatsThis(0).toUInt(); EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetID); if (AZStd::find(selectedRootMotionSets.begin(), selectedRootMotionSets.end(), motionSet) == selectedRootMotionSets.end()) { @@ -919,14 +905,14 @@ namespace EMStudio { AZStd::string filename = GetMainWindow()->GetFileManager()->LoadMotionSetFileDialog(this); GetMainWindow()->activateWindow(); - mPlugin->LoadMotionSet(filename); + m_plugin->LoadMotionSet(filename); } void MotionSetManagementWindow::OnSave() { // get the selected items and the number of selected items - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); const int numSelectedItems = selectedItems.count(); // at leat one item must be selected @@ -948,7 +934,7 @@ namespace EMStudio } // Add the root motion set in the array if not already added. - const uint32 motionSetID = AzFramework::StringFunc::ToInt(FromQtString(rootItem->whatsThis(0)).c_str()); + const uint32 motionSetID = rootItem->whatsThis(0).toUInt(); EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetID); if (AZStd::find(selectedRootMotionSets.begin(), selectedRootMotionSets.end(), motionSet) == selectedRootMotionSets.end()) { @@ -961,12 +947,9 @@ namespace EMStudio commandGroup.SetReturnFalseAfterError(true); // Add each command. - const size_t numSelectedRootMotionSets = selectedRootMotionSets.size(); - for (size_t i = 0; i < numSelectedRootMotionSets; ++i) + for (const EMotionFX::MotionSet* motionSet : selectedRootMotionSets) { - EMotionFX::MotionSet* motionSet = selectedRootMotionSets[i]; - - // Show a file dialog in case the motion set hasn't been saved yet. + // Show a file dialog in case the motion set hasn't been saved yet. AZStd::string filename = motionSet->GetFilename(); if (filename.empty()) { @@ -1003,7 +986,7 @@ namespace EMStudio void MotionSetManagementWindow::OnSaveAs() { // get the selected items and the number of selected items - const QList selectedItems = mMotionSetsTree->selectedItems(); + const QList selectedItems = m_motionSetsTree->selectedItems(); const int numSelectedItems = selectedItems.count(); // filter to only keep the root motion sets from the selected items @@ -1019,7 +1002,7 @@ namespace EMStudio } // Add the root motion set in the array if not already added. - const uint32 motionSetID = AzFramework::StringFunc::ToInt(FromQtString(rootItem->whatsThis(0)).c_str()); + const uint32 motionSetID = rootItem->whatsThis(0).toUInt(); EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(motionSetID); if (AZStd::find(selectedRootMotionSets.begin(), selectedRootMotionSets.end(), motionSet) == selectedRootMotionSets.end()) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.h index f5b354c5a4..ffe5f0f698 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetManagementWindow.h @@ -43,7 +43,7 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(MotionSetManagementRemoveMotionsFailedWindow, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS); public: - MotionSetManagementRemoveMotionsFailedWindow(QWidget* parent, const MCore::Array& motions); + MotionSetManagementRemoveMotionsFailedWindow(QWidget* parent, const AZStd::vector& motions); }; @@ -61,10 +61,9 @@ namespace EMStudio void Accepted(); private: - EMotionFX::MotionSet* mMotionSet; - QLineEdit* mLineEdit; - QPushButton* mOKButton; - //QLabel* mErrorMsg; + EMotionFX::MotionSet* m_motionSet; + QLineEdit* m_lineEdit; + QPushButton* m_okButton; }; @@ -113,8 +112,8 @@ namespace EMStudio void contextMenuEvent(QContextMenuEvent* event) override; private: - QVBoxLayout* mVLayout = nullptr; - QTreeWidget* mMotionSetsTree = nullptr; + QVBoxLayout* m_vLayout = nullptr; + QTreeWidget* m_motionSetsTree = nullptr; QAction* m_addAction = nullptr; QAction* m_openAction = nullptr; QAction* m_saveMenuAction = nullptr; @@ -122,6 +121,6 @@ namespace EMStudio QAction* m_saveAsAction = nullptr; AzQtComponents::FilteredSearchWidget* m_searchWidget = nullptr; AZStd::string m_searchWidgetText; - MotionSetsWindowPlugin* mPlugin = nullptr; + MotionSetsWindowPlugin* m_plugin = nullptr; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.cpp index 10ceb2e43f..6d16ea19b1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.cpp @@ -6,6 +6,7 @@ * */ +#include "AzCore/std/algorithm.h" #include "MotionSetsWindowPlugin.h" #include #include @@ -123,11 +124,11 @@ namespace EMStudio RenameMotionEntryWindow::RenameMotionEntryWindow(QWidget* parent, EMotionFX::MotionSet* motionSet, const AZStd::string& motionId) : QDialog(parent) { - mMotionSet = motionSet; + m_motionSet = motionSet; m_motionId = motionId; // Build a list of unique string id values from all motion set entries. - mMotionSet->BuildIdStringList(m_existingIds); + m_motionSet->BuildIdStringList(m_existingIds); // Set the window title and minimum width. setWindowTitle("Enter new motion ID"); @@ -135,25 +136,25 @@ namespace EMStudio QVBoxLayout* layout = new QVBoxLayout(); - mLineEdit = new QLineEdit(); - connect(mLineEdit, &QLineEdit::textEdited, this, &RenameMotionEntryWindow::TextEdited); - layout->addWidget(mLineEdit); + m_lineEdit = new QLineEdit(); + connect(m_lineEdit, &QLineEdit::textEdited, this, &RenameMotionEntryWindow::TextEdited); + layout->addWidget(m_lineEdit); // Set the old motion id as text and select all so that the user can directly start typing. - mLineEdit->setText(m_motionId.c_str()); - mLineEdit->selectAll(); + m_lineEdit->setText(m_motionId.c_str()); + m_lineEdit->selectAll(); QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); + m_okButton = new QPushButton("OK"); QPushButton* cancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); + buttonLayout->addWidget(m_okButton); buttonLayout->addWidget(cancelButton); // Allow pressing the enter key as alternative to pressing the ok button for faster workflow. - mOKButton->setAutoDefault(true); - mOKButton->setDefault(true); + m_okButton->setAutoDefault(true); + m_okButton->setDefault(true); - connect(mOKButton, &QPushButton::clicked, this, &RenameMotionEntryWindow::Accepted); + connect(m_okButton, &QPushButton::clicked, this, &RenameMotionEntryWindow::Accepted); connect(cancelButton, &QPushButton::clicked, this, &RenameMotionEntryWindow::reject); layout->addLayout(buttonLayout); @@ -168,24 +169,22 @@ namespace EMStudio // Disable the ok button and put the text edit in error state in case the new motion id is either empty or does already exist in the motion set. if (newId.empty() || AZStd::find(m_existingIds.begin(), m_existingIds.end(), newId) != m_existingIds.end()) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); return; } - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } void RenameMotionEntryWindow::Accepted() { AZStd::string commandString = AZStd::string::format("MotionSetAdjustMotion -motionSetID %i -idString \"%s\" -newIDString \"%s\" -updateMotionNodeStringIDs true", - mMotionSet->GetID(), + m_motionSet->GetID(), m_motionId.c_str(), - mLineEdit->text().toUtf8().data()); + m_lineEdit->text().toUtf8().data()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(commandString, result)) @@ -201,7 +200,7 @@ namespace EMStudio MotionSetWindow::MotionSetWindow(MotionSetsWindowPlugin* parentPlugin, QWidget* parent) : QWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; } @@ -252,7 +251,7 @@ namespace EMStudio // left side - m_tableWidget = new MotionSetTableWidget(mPlugin, this); + m_tableWidget = new MotionSetTableWidget(m_plugin, this); m_tableWidget->setObjectName("EMFX.MotionSetWindow.TableWidget"); tableLayout->addWidget(m_tableWidget); m_tableWidget->setAlternatingRowColors(true); @@ -327,11 +326,11 @@ namespace EMStudio void MotionSetWindow::ReInit() { - EMotionFX::MotionSet* selectedSet = mPlugin->GetSelectedSet(); - const uint32 selectedSetIndex = EMotionFX::GetMotionManager().FindMotionSetIndex(selectedSet); - if (selectedSetIndex != MCORE_INVALIDINDEX32) + EMotionFX::MotionSet* selectedSet = m_plugin->GetSelectedSet(); + const size_t selectedSetIndex = EMotionFX::GetMotionManager().FindMotionSetIndex(selectedSet); + if (selectedSetIndex != InvalidIndex) { - UpdateMotionSetTable(m_tableWidget, mPlugin->GetSelectedSet()); + UpdateMotionSetTable(m_tableWidget, m_plugin->GetSelectedSet()); } else { @@ -343,15 +342,11 @@ namespace EMStudio bool MotionSetWindow::AddMotion(EMotionFX::MotionSet* motionSet, EMotionFX::MotionSet::MotionEntry* motionEntry) { // check if the motion set is the one we currently see in the interface, if not there is nothing to do - if (mPlugin->GetSelectedSet() == motionSet) + if (m_plugin->GetSelectedSet() == motionSet) { InsertRow(motionSet, motionEntry, m_tableWidget, false); } - // check if the motion set is the one we currently see in the interface in the right table, if not there is nothing to do - //if (mRightSelectedSet == motionSet) - // InsertRow(motionSet, motionEntry, mMotionSetTableRight, true); - UpdateInterface(); return true; } @@ -372,7 +367,7 @@ namespace EMStudio } // Check if the motion set is the one we currently see in the interface, if not there is nothing to do. - if (mPlugin->GetSelectedSet() == motionSet) + if (m_plugin->GetSelectedSet() == motionSet) { FillRow(motionSet, motionEntry, rowIndex, m_tableWidget, false); } @@ -385,7 +380,7 @@ namespace EMStudio bool MotionSetWindow::RemoveMotion(EMotionFX::MotionSet* motionSet, EMotionFX::MotionSet::MotionEntry* motionEntry) { // Check if the motion set is the one we currently see in the interface, if not there is nothing to do. - if (mPlugin->GetSelectedSet() == motionSet) + if (m_plugin->GetSelectedSet() == motionSet) { RemoveRow(motionSet, motionEntry, m_tableWidget); } @@ -408,16 +403,16 @@ namespace EMStudio commandGroup.AddCommandString("Unselect -motionIndex SELECT_ALL"); - command = AZStd::string::format("Select -motionIndex %d", EMotionFX::GetMotionManager().FindMotionIndexByID(motion->GetID())); + command = AZStd::string::format("Select -motionIndex %zu", EMotionFX::GetMotionManager().FindMotionIndexByID(motion->GetID())); commandGroup.AddCommandString(command); EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo(); if (defaultPlayBackInfo) { // Don't blend in and out of the for previewing animations. We might only see a short bit of it for animations smaller than the blend in/out time. - defaultPlayBackInfo->mBlendInTime = 0.0f; - defaultPlayBackInfo->mBlendOutTime = 0.0f; - defaultPlayBackInfo->mFreezeAtLastFrame = (defaultPlayBackInfo->mNumLoops != EMFX_LOOPFOREVER); + defaultPlayBackInfo->m_blendInTime = 0.0f; + defaultPlayBackInfo->m_blendOutTime = 0.0f; + defaultPlayBackInfo->m_freezeAtLastFrame = (defaultPlayBackInfo->m_numLoops != EMFX_LOOPFOREVER); commandParameters = CommandSystem::CommandPlayMotion::PlayBackInfoToCommandParameters(defaultPlayBackInfo); } @@ -810,7 +805,7 @@ namespace EMStudio void MotionSetWindow::UpdateInterface() { - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); const bool isEnabled = (motionSet != nullptr); m_addAction->setEnabled(isEnabled); @@ -824,7 +819,7 @@ namespace EMStudio } const QList selectedItems = m_tableWidget->selectedItems(); - const uint32 numSelectedItems = selectedItems.count(); + const size_t numSelectedItems = selectedItems.count(); // Get the row indices from the selected items. AZStd::vector rowIndices; @@ -835,7 +830,7 @@ namespace EMStudio m_editAction->setEnabled(hasMotions); // Inform the time view plugin about the motion selection change. - const bool hasSelectedRows = rowIndices.size() > 0; + const bool hasSelectedRows = !rowIndices.empty(); if (hasSelectedRows) { QTableWidgetItem* firstSelectedItem = selectedItems[0]; @@ -847,8 +842,8 @@ namespace EMStudio { MCore::CommandGroup commandGroup("Select motion"); commandGroup.AddCommandString("Unselect -motionIndex SELECT_ALL"); - const AZ::u32 motionIndex = EMotionFX::GetMotionManager().FindMotionIndexByFileName(motion->GetFileName()); - commandGroup.AddCommandString(AZStd::string::format("Select -motionIndex %d", motionIndex)); + const size_t motionIndex = EMotionFX::GetMotionManager().FindMotionIndexByFileName(motion->GetFileName()); + commandGroup.AddCommandString(AZStd::string::format("Select -motionIndex %zu", motionIndex)); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommandGroup(commandGroup, result, false)) @@ -865,7 +860,7 @@ namespace EMStudio void MotionSetWindow::OnAddNewEntry() { - EMotionFX::MotionSet* selectedSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* selectedSet = m_plugin->GetSelectedSet(); if (!selectedSet) { return; @@ -902,7 +897,7 @@ namespace EMStudio void MotionSetWindow::AddMotions(const AZStd::vector& filenames) { - EMotionFX::MotionSet* selectedSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* selectedSet = m_plugin->GetSelectedSet(); if (!selectedSet) { return; @@ -913,7 +908,7 @@ namespace EMStudio // Build a list of unique string id values from all motion set entries. AZStd::vector idStrings; - idStrings.reserve(selectedSet->GetNumMotionEntries() + (uint32)numFileNames); + idStrings.reserve(selectedSet->GetNumMotionEntries() + numFileNames); selectedSet->BuildIdStringList(idStrings); AZStd::string parameterString; @@ -1067,7 +1062,7 @@ namespace EMStudio void MotionSetWindow::OnRemoveMotions() { - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return; @@ -1133,16 +1128,16 @@ namespace EMStudio return; } - for (uint32 i = 0; i < numRowIndices; ++i) + for (const int rowIndex : rowIndices) { - QTableWidgetItem* idItem = m_tableWidget->item(rowIndices[i], 1); + QTableWidgetItem* idItem = m_tableWidget->item(rowIndex, 1); EMotionFX::MotionSet::MotionEntry* motionEntry = motionSet->FindMotionEntryById(idItem->text().toUtf8().data()); // Check if the motion exists in multiple motion sets. - const AZ::u32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - AZ::u32 numMotionSetContainsMotion = 0; + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + size_t numMotionSetContainsMotion = 0; - for (AZ::u32 motionSetId = 0; motionSetId < numMotionSets; motionSetId++) + for (size_t motionSetId = 0; motionSetId < numMotionSets; motionSetId++) { EMotionFX::MotionSet* motionSet2 = EMotionFX::GetMotionManager().GetMotionSet(motionSetId); if (motionSet2->FindMotionEntryById(motionEntry->GetId())) @@ -1181,7 +1176,7 @@ namespace EMStudio if (removeMotion && motionEntry->GetMotion()) { // Calculcate how many motion sets except than the provided one use the given motion. - uint32 numExternalUses = CalcNumMotionEntriesUsingMotionExcluding(motionEntry->GetFilename(), motionSet); + size_t numExternalUses = CalcNumMotionEntriesUsingMotionExcluding(motionEntry->GetFilename(), motionSet); // Remove the motion in case it was only used by the given motion set. if (numExternalUses == 0) @@ -1199,15 +1194,14 @@ namespace EMStudio // Find the lowest row selected. int lowestRowSelected = -1; - for (uint32 i = 0; i < numRowIndices; ++i) + for (int selectedRowIndex : rowIndices) { - if (rowIndices[i] < lowestRowSelected) + if (selectedRowIndex < lowestRowSelected) { - lowestRowSelected = rowIndices[i]; + lowestRowSelected = selectedRowIndex; } } - MCore::CommandGroup commandGroup("Motion set remove motions"); // 1. Remove motion entries from the motion set. @@ -1254,7 +1248,7 @@ namespace EMStudio EMotionFX::MotionSet::MotionEntry* motionEntry = FindMotionEntry(item); // Show the entry renaming window. - RenameMotionEntryWindow window(this, mPlugin->GetSelectedSet(), motionEntry->GetId().c_str()); + RenameMotionEntryWindow window(this, m_plugin->GetSelectedSet(), motionEntry->GetId().c_str()); window.exec(); } @@ -1274,7 +1268,7 @@ namespace EMStudio void MotionSetWindow::OnUnassignMotions() { - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return; @@ -1322,7 +1316,7 @@ namespace EMStudio void MotionSetWindow::OnClearMotions() { - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return; @@ -1371,7 +1365,7 @@ namespace EMStudio } // Calculcate how many motion sets except than the provided one use the given motion. - uint32 numExternalUses = CalcNumMotionEntriesUsingMotionExcluding(motionEntry->GetFilename(), motionSet); + size_t numExternalUses = CalcNumMotionEntriesUsingMotionExcluding(motionEntry->GetFilename(), motionSet); // Remove the motion in case it was only used by the given motion set. if (numExternalUses == 0) @@ -1407,24 +1401,20 @@ namespace EMStudio // get the current selection const QList selectedItems = m_tableWidget->selectedItems(); - // get the number of selected items - const uint32 numSelectedItems = selectedItems.count(); - // Get the row indices from the selected items. AZStd::vector rowIndices; GetRowIndices(selectedItems, rowIndices); // get the selected motion set - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); // generate the motions IDs array AZStd::vector motionIDs; - const size_t numSelectedRows = rowIndices.size(); - if (numSelectedRows > 0) + if (!rowIndices.empty()) { - for (int i = 0; i < numSelectedRows; ++i) + for (const int rowIndex : rowIndices) { - QTableWidgetItem* item = m_tableWidget->item(rowIndices[i], 1); + QTableWidgetItem* item = m_tableWidget->item(rowIndex, 1); motionIDs.push_back(item->text().toUtf8().data()); } } @@ -1446,7 +1436,7 @@ namespace EMStudio void MotionSetWindow::OnEntryDoubleClicked(QTableWidgetItem* item) { - const EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + const EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return; @@ -1556,8 +1546,7 @@ namespace EMStudio const QList selectedItems = m_tableWidget->selectedItems(); // get the number of selected items - const uint32 numSelectedItems = selectedItems.count(); - if (numSelectedItems == 0) + if (selectedItems.empty()) { return; } @@ -1608,7 +1597,7 @@ namespace EMStudio : QTableWidget(parent) { // keep the parent plugin - mPlugin = parentPlugin; + m_plugin = parentPlugin; // enable drop only setAcceptDrops(true); @@ -1625,7 +1614,7 @@ namespace EMStudio void MotionSetTableWidget::dropEvent(QDropEvent* event) { - mPlugin->GetMotionSetWindow()->dropEvent(event); + m_plugin->GetMotionSetWindow()->dropEvent(event); } @@ -1644,7 +1633,7 @@ namespace EMStudio // return the mime data QMimeData* MotionSetTableWidget::mimeData(const QList items) const { - EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (motionSet == nullptr) { return nullptr; @@ -1687,13 +1676,13 @@ namespace EMStudio : QDialog(parent) { // save the motion set and the motion IDs - mMotionSet = motionSet; - mMotionIDs = motionIDs; + m_motionSet = motionSet; + m_motionIDs = motionIDs; // Reserve space. - mValids.reserve(mMotionIDs.size()); - mMotionToModifiedMap.reserve(mMotionIDs.size()); - mModifiedMotionIDs.reserve(motionSet->GetNumMotionEntries()); + m_valids.reserve(m_motionIDs.size()); + m_motionToModifiedMap.reserve(m_motionIDs.size()); + m_modifiedMotionIDs.reserve(motionSet->GetNumMotionEntries()); // set the window title setWindowTitle("Batch Edit Motion IDs"); @@ -1706,113 +1695,113 @@ namespace EMStudio spacerWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); // create the combobox - mComboBox = new QComboBox(); - mComboBox->addItem("Replace All"); - mComboBox->addItem("Replace First"); - mComboBox->addItem("Replace Last"); + m_comboBox = new QComboBox(); + m_comboBox->addItem("Replace All"); + m_comboBox->addItem("Replace First"); + m_comboBox->addItem("Replace Last"); // connect the combobox - connect(mComboBox, static_cast(&QComboBox::currentIndexChanged), this, &MotionEditStringIDWindow::CurrentIndexChanged); + connect(m_comboBox, static_cast(&QComboBox::currentIndexChanged), this, &MotionEditStringIDWindow::CurrentIndexChanged); // create the string line edits - mStringALineEdit = new QLineEdit(); - mStringBLineEdit = new QLineEdit(); + m_stringALineEdit = new QLineEdit(); + m_stringBLineEdit = new QLineEdit(); // connect the line edit - connect(mStringALineEdit, &QLineEdit::textChanged, this, &MotionEditStringIDWindow::StringABChanged); - connect(mStringBLineEdit, &QLineEdit::textChanged, this, &MotionEditStringIDWindow::StringABChanged); + connect(m_stringALineEdit, &QLineEdit::textChanged, this, &MotionEditStringIDWindow::StringABChanged); + connect(m_stringBLineEdit, &QLineEdit::textChanged, this, &MotionEditStringIDWindow::StringABChanged); // add the operation layout QHBoxLayout* operationLayout = new QHBoxLayout(); operationLayout->addWidget(new QLabel("Operation:")); - operationLayout->addWidget(mComboBox); + operationLayout->addWidget(m_comboBox); operationLayout->addWidget(spacerWidget); operationLayout->addWidget(new QLabel("StringA:")); - operationLayout->addWidget(mStringALineEdit); + operationLayout->addWidget(m_stringALineEdit); operationLayout->addWidget(new QLabel("StringB:")); - operationLayout->addWidget(mStringBLineEdit); + operationLayout->addWidget(m_stringBLineEdit); layout->addLayout(operationLayout); // create the table widget - mTableWidget = new QTableWidget(); - mTableWidget->setAlternatingRowColors(true); - mTableWidget->setGridStyle(Qt::SolidLine); - mTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); - mTableWidget->setSelectionMode(QAbstractItemView::SingleSelection); - mTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_tableWidget = new QTableWidget(); + m_tableWidget->setAlternatingRowColors(true); + m_tableWidget->setGridStyle(Qt::SolidLine); + m_tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); + m_tableWidget->setSelectionMode(QAbstractItemView::SingleSelection); + m_tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); // set the table widget columns - mTableWidget->setColumnCount(2); + m_tableWidget->setColumnCount(2); QStringList headerLabels; headerLabels.append("Before"); headerLabels.append("After"); - mTableWidget->setHorizontalHeaderLabels(headerLabels); - mTableWidget->horizontalHeader()->setStretchLastSection(true); - mTableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); - mTableWidget->horizontalHeader()->setSortIndicator(0, Qt::AscendingOrder); + m_tableWidget->setHorizontalHeaderLabels(headerLabels); + m_tableWidget->horizontalHeader()->setStretchLastSection(true); + m_tableWidget->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft); + m_tableWidget->horizontalHeader()->setSortIndicator(0, Qt::AscendingOrder); // Set the row count - const size_t numMotionIDs = mMotionIDs.size(); - mTableWidget->setRowCount(static_cast(numMotionIDs)); + const size_t numMotionIDs = m_motionIDs.size(); + m_tableWidget->setRowCount(static_cast(numMotionIDs)); // disable the sorting - mTableWidget->setSortingEnabled(false); + m_tableWidget->setSortingEnabled(false); // initialize the table for (size_t i = 0; i < numMotionIDs; ++i) { // create the before and after table widget items - QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); - QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); + QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); + QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); // set the text of the row const int row = static_cast(i); - mTableWidget->setItem(row, 0, beforeTableWidgetItem); - mTableWidget->setItem(row, 1, afterTableWidgetItem); + m_tableWidget->setItem(row, 0, beforeTableWidgetItem); + m_tableWidget->setItem(row, 1, afterTableWidgetItem); } - mTableWidget->setSortingEnabled(true); - mTableWidget->resizeColumnToContents(0); - mTableWidget->setCornerButtonEnabled(false); + m_tableWidget->setSortingEnabled(true); + m_tableWidget->resizeColumnToContents(0); + m_tableWidget->setCornerButtonEnabled(false); - layout->addWidget(mTableWidget); + layout->addWidget(m_tableWidget); // create the num motion IDs label // this label never change, it's the total of motion ID in the table - mNumMotionIDsLabel = new QLabel(); - mNumMotionIDsLabel->setAlignment(Qt::AlignLeft); - mNumMotionIDsLabel->setText(QString("Number of motion IDs: %1").arg(numMotionIDs)); + m_numMotionIDsLabel = new QLabel(); + m_numMotionIDsLabel->setAlignment(Qt::AlignLeft); + m_numMotionIDsLabel->setText(QString("Number of motion IDs: %1").arg(numMotionIDs)); // create the num modified IDs label - mNumModifiedIDsLabel = new QLabel(); - mNumModifiedIDsLabel->setAlignment(Qt::AlignCenter); - mNumModifiedIDsLabel->setText("Number of modified IDs: 0"); + m_numModifiedIDsLabel = new QLabel(); + m_numModifiedIDsLabel->setAlignment(Qt::AlignCenter); + m_numModifiedIDsLabel->setText("Number of modified IDs: 0"); // create the num duplicate IDs label - mNumDuplicateIDsLabel = new QLabel(); - mNumDuplicateIDsLabel->setAlignment(Qt::AlignRight); - mNumDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); + m_numDuplicateIDsLabel = new QLabel(); + m_numDuplicateIDsLabel->setAlignment(Qt::AlignRight); + m_numDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); // add the stats layout QHBoxLayout* statsLayout = new QHBoxLayout(); - statsLayout->addWidget(mNumMotionIDsLabel); - statsLayout->addWidget(mNumModifiedIDsLabel); - statsLayout->addWidget(mNumDuplicateIDsLabel); + statsLayout->addWidget(m_numMotionIDsLabel); + statsLayout->addWidget(m_numModifiedIDsLabel); + statsLayout->addWidget(m_numDuplicateIDsLabel); layout->addLayout(statsLayout); // add the bottom buttons QHBoxLayout* buttonLayout = new QHBoxLayout(); - mApplyButton = new QPushButton("Apply"); + m_applyButton = new QPushButton("Apply"); QPushButton* closeButton = new QPushButton("Close"); - buttonLayout->addWidget(mApplyButton); + buttonLayout->addWidget(m_applyButton); buttonLayout->addWidget(closeButton); layout->addLayout(buttonLayout); // apply button is disabled because nothing is changed - mApplyButton->setEnabled(false); + m_applyButton->setEnabled(false); // connect the buttons - connect(mApplyButton, &QPushButton::clicked, this, &MotionEditStringIDWindow::Accepted); + connect(m_applyButton, &QPushButton::clicked, this, &MotionEditStringIDWindow::Accepted); connect(closeButton, &QPushButton::clicked, this, &MotionEditStringIDWindow::reject); setLayout(layout); @@ -1828,14 +1817,13 @@ namespace EMStudio // add each command AZStd::string commandString; - const size_t numValid = mValids.size(); - for (size_t i = 0; i < numValid; ++i) + for (size_t validID : m_valids) { // get the motion ID and the modified ID - AZStd::string& motionID = mMotionIDs[mValids[i]]; - const AZStd::string& modifiedID = mModifiedMotionIDs[mMotionToModifiedMap[mValids[i]]]; + AZStd::string& motionID = m_motionIDs[validID]; + const AZStd::string& modifiedID = m_modifiedMotionIDs[m_motionToModifiedMap[validID]]; - commandString = AZStd::string::format("MotionSetAdjustMotion -motionSetID %i -idString \"%s\" -newIDString \"%s\" -updateMotionNodeStringIDs true", mMotionSet->GetID(), motionID.c_str(), modifiedID.c_str()); + commandString = AZStd::string::format("MotionSetAdjustMotion -motionSetID %i -idString \"%s\" -newIDString \"%s\" -updateMotionNodeStringIDs true", m_motionSet->GetID(), motionID.c_str(), modifiedID.c_str()); motionID = modifiedID; // add the command in the group @@ -1850,46 +1838,46 @@ namespace EMStudio } // block signals for the reset - mStringALineEdit->blockSignals(true); - mStringBLineEdit->blockSignals(true); + m_stringALineEdit->blockSignals(true); + m_stringBLineEdit->blockSignals(true); // reset the string line edits - mStringALineEdit->setText(""); - mStringBLineEdit->setText(""); + m_stringALineEdit->setText(""); + m_stringBLineEdit->setText(""); // enable signals after the reset - mStringALineEdit->blockSignals(false); - mStringBLineEdit->blockSignals(false); + m_stringALineEdit->blockSignals(false); + m_stringBLineEdit->blockSignals(false); // disable the sorting - mTableWidget->setSortingEnabled(false); + m_tableWidget->setSortingEnabled(false); // set the new table using modified motion IDs - const size_t numMotionIDs = mMotionIDs.size(); + const size_t numMotionIDs = m_motionIDs.size(); for (size_t i = 0; i < numMotionIDs; ++i) { // create the before and after table widget items - QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); - QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); + QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); + QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); // set the text of the row const int row = static_cast(i); - mTableWidget->setItem(row, 0, beforeTableWidgetItem); - mTableWidget->setItem(row, 1, afterTableWidgetItem); + m_tableWidget->setItem(row, 0, beforeTableWidgetItem); + m_tableWidget->setItem(row, 1, afterTableWidgetItem); } // enable the sorting - mTableWidget->setSortingEnabled(true); + m_tableWidget->setSortingEnabled(true); // resize before column - mTableWidget->resizeColumnToContents(0); + m_tableWidget->resizeColumnToContents(0); // reset the stats - mNumModifiedIDsLabel->setText("Number of modified IDs: 0"); - mNumDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); + m_numModifiedIDsLabel->setText("Number of modified IDs: 0"); + m_numDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); // apply button is disabled because nothing is changed - mApplyButton->setEnabled(false); + m_applyButton->setEnabled(false); } @@ -1910,10 +1898,10 @@ namespace EMStudio void MotionEditStringIDWindow::UpdateTableAndButton() { // get the number of motion IDs - const size_t numMotionIDs = mMotionIDs.size(); + const size_t numMotionIDs = m_motionIDs.size(); // Remember the selected motion IDs so we can restore selection after swapping the table items. - const QList selectedItems = mTableWidget->selectedItems(); + const QList selectedItems = m_tableWidget->selectedItems(); const int numSelectedItems = selectedItems.size(); QVector selectedMotionIds(numSelectedItems); for (int i = 0; i < numSelectedItems; ++i) @@ -1922,117 +1910,117 @@ namespace EMStudio } // special case where the string A and B are empty, nothing is replaced - if ((mStringALineEdit->text().isEmpty()) && (mStringBLineEdit->text().isEmpty())) + if ((m_stringALineEdit->text().isEmpty()) && (m_stringBLineEdit->text().isEmpty())) { // disable the sorting - mTableWidget->setSortingEnabled(false); + m_tableWidget->setSortingEnabled(false); // reset the table for (size_t i = 0; i < numMotionIDs; ++i) { // create the before and after table widget items - QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); - QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); + QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); + QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); // set the text of the row const int row = static_cast(i); - mTableWidget->setItem(row, 0, beforeTableWidgetItem); - mTableWidget->setItem(row, 1, afterTableWidgetItem); + m_tableWidget->setItem(row, 0, beforeTableWidgetItem); + m_tableWidget->setItem(row, 1, afterTableWidgetItem); } // enable the sorting - mTableWidget->setSortingEnabled(true); + m_tableWidget->setSortingEnabled(true); // reset the stats - mNumModifiedIDsLabel->setText("Number of modified IDs: 0"); - mNumDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); + m_numModifiedIDsLabel->setText("Number of modified IDs: 0"); + m_numDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); // apply button is disabled because nothing is changed - mApplyButton->setEnabled(false); + m_applyButton->setEnabled(false); // stop here return; } - // found flags - uint32 numDuplicateFound = 0; - // Clear the arrays but keep the memory to avoid alloc. - mValids.clear(); - mModifiedMotionIDs.clear(); - mMotionToModifiedMap.clear(); + m_valids.clear(); + m_modifiedMotionIDs.clear(); + m_motionToModifiedMap.clear(); // Copy all motion IDs from the motion set in the modified array. - const EMotionFX::MotionSet::MotionEntries& motionEntries = mMotionSet->GetMotionEntries(); + const EMotionFX::MotionSet::MotionEntries& motionEntries = m_motionSet->GetMotionEntries(); for (const auto& item : motionEntries) { const EMotionFX::MotionSet::MotionEntry* motionEntry = item.second; - mModifiedMotionIDs.push_back(motionEntry->GetId().c_str()); + m_modifiedMotionIDs.push_back(motionEntry->GetId().c_str()); } // Modify each ID using the operation in the modified array. AZStd::string newMotionID; AZStd::string tempString; - for (uint32 i = 0; i < numMotionIDs; ++i) + for (const AZStd::string& motionID : m_motionIDs) { // 0=Replace All, 1=Replace First, 2=Replace Last - const int operationMode = mComboBox->currentIndex(); + const int operationMode = m_comboBox->currentIndex(); // compute the new text switch (operationMode) { case 0: { - tempString = mMotionIDs[i].c_str(); - AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */); + tempString = motionID.c_str(); + AzFramework::StringFunc::Replace(tempString, m_stringALineEdit->text().toUtf8().data(), m_stringBLineEdit->text().toUtf8().data(), true /* case sensitive */); newMotionID = tempString.c_str(); break; } case 1: { - tempString = mMotionIDs[i].c_str(); - AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, true /* replace first */, false /* replace last */); + tempString = motionID.c_str(); + AzFramework::StringFunc::Replace(tempString, m_stringALineEdit->text().toUtf8().data(), m_stringBLineEdit->text().toUtf8().data(), true /* case sensitive */, true /* replace first */, false /* replace last */); newMotionID = tempString.c_str(); break; } case 2: { - tempString = mMotionIDs[i].c_str(); - AzFramework::StringFunc::Replace(tempString, mStringALineEdit->text().toUtf8().data(), mStringBLineEdit->text().toUtf8().data(), true /* case sensitive */, false /* replace first */, true /* replace last */); + tempString = motionID.c_str(); + AzFramework::StringFunc::Replace(tempString, m_stringALineEdit->text().toUtf8().data(), m_stringBLineEdit->text().toUtf8().data(), true /* case sensitive */, false /* replace first */, true /* replace last */); newMotionID = tempString.c_str(); break; } } // change the value in the array and add the mapping motion to modified - auto iterator = AZStd::find(mModifiedMotionIDs.begin(), mModifiedMotionIDs.end(), mMotionIDs[i]); - const size_t modifiedIndex = iterator - mModifiedMotionIDs.begin(); - mModifiedMotionIDs[modifiedIndex] = newMotionID; - mMotionToModifiedMap.push_back(static_cast(modifiedIndex)); + auto iterator = AZStd::find(m_modifiedMotionIDs.begin(), m_modifiedMotionIDs.end(), motionID); + const size_t modifiedIndex = iterator - m_modifiedMotionIDs.begin(); + m_modifiedMotionIDs[modifiedIndex] = newMotionID; + m_motionToModifiedMap.push_back(modifiedIndex); } // disable the sorting - mTableWidget->setSortingEnabled(false); + m_tableWidget->setSortingEnabled(false); + + // found flags + size_t numDuplicateFound = 0; // update each row - for (uint32 i = 0; i < numMotionIDs; ++i) + for (size_t i = 0; i < numMotionIDs; ++i) { // find the index in the motion set - const AZStd::string& modifiedID = mModifiedMotionIDs[mMotionToModifiedMap[i]]; + const AZStd::string& modifiedID = m_modifiedMotionIDs[m_motionToModifiedMap[i]]; // create the before and after table widget items - QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(mMotionIDs[i].c_str()); + QTableWidgetItem* beforeTableWidgetItem = new QTableWidgetItem(m_motionIDs[i].c_str()); QTableWidgetItem* afterTableWidgetItem = new QTableWidgetItem(modifiedID.c_str()); // find duplicate - uint32 itemFoundCounter = 0; - const AZ::u32 numMotionEntries = static_cast(mMotionSet->GetNumMotionEntries()); - for (uint32 k = 0; k < numMotionEntries; ++k) + size_t itemFoundCounter = 0; + const size_t numMotionEntries = m_motionSet->GetNumMotionEntries(); + for (size_t k = 0; k < numMotionEntries; ++k) { - if (mModifiedMotionIDs[k] == modifiedID) + if (m_modifiedMotionIDs[k] == modifiedID) { ++itemFoundCounter; if (itemFoundCounter > 1) @@ -2051,51 +2039,51 @@ namespace EMStudio } else { - if (modifiedID != mMotionIDs[i]) + if (modifiedID != m_motionIDs[i]) { // set the row green beforeTableWidgetItem->setForeground(Qt::green); afterTableWidgetItem->setForeground(Qt::green); // add a valid - mValids.push_back(i); + m_valids.push_back(i); } } // set the text of the row - mTableWidget->setItem(i, 0, beforeTableWidgetItem); - mTableWidget->setItem(i, 1, afterTableWidgetItem); + m_tableWidget->setItem(aznumeric_caster(i), 0, beforeTableWidgetItem); + m_tableWidget->setItem(aznumeric_caster(i), 1, afterTableWidgetItem); } // enable the sorting - mTableWidget->setSortingEnabled(true); + m_tableWidget->setSortingEnabled(true); // update the num modified label - mNumModifiedIDsLabel->setText(QString("Number of modified IDs: %1").arg(mValids.size())); + m_numModifiedIDsLabel->setText(QString("Number of modified IDs: %1").arg(m_valids.size())); // update the num duplicate label // the number is in red if at least one found if (numDuplicateFound > 0) { - mNumDuplicateIDsLabel->setText(QString("Number of duplicate IDs: %1").arg(numDuplicateFound)); + m_numDuplicateIDsLabel->setText(QString("Number of duplicate IDs: %1").arg(numDuplicateFound)); } else { - mNumDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); + m_numDuplicateIDsLabel->setText("Number of duplicate IDs: 0"); } // enable or disable the apply button - mApplyButton->setEnabled((mValids.size() > 0) && (numDuplicateFound == 0)); + m_applyButton->setEnabled((!m_valids.empty()) && (numDuplicateFound == 0)); // Reselect the remembered motions. - mTableWidget->clearSelection(); - const int rowCount = mTableWidget->rowCount(); + m_tableWidget->clearSelection(); + const int rowCount = m_tableWidget->rowCount(); for (int i = 0; i < rowCount; ++i) { - const QTableWidgetItem* item = mTableWidget->item(i, 0); + const QTableWidgetItem* item = m_tableWidget->item(i, 0); if (AZStd::find(selectedMotionIds.begin(), selectedMotionIds.end(), item->text()) != selectedMotionIds.end()) { - mTableWidget->selectRow(i); + m_tableWidget->selectRow(i); } } } @@ -2108,7 +2096,7 @@ namespace EMStudio return nullptr; } - const EMotionFX::MotionSet* motionSet = mPlugin->GetSelectedSet(); + const EMotionFX::MotionSet* motionSet = m_plugin->GetSelectedSet(); if (!motionSet) { return nullptr; @@ -2130,9 +2118,9 @@ namespace EMStudio const int numItems = items.size(); outRowIndices.reserve(numItems); - for (int i = 0; i < numItems; ++i) + for (const QTableWidgetItem* item : items) { - const int rowIndex = items[i]->row(); + const int rowIndex = item->row(); if (AZStd::find(outRowIndices.begin(), outRowIndices.end(), rowIndex) == outRowIndices.end()) { outRowIndices.push_back(rowIndex); @@ -2141,7 +2129,7 @@ namespace EMStudio } - uint32 MotionSetWindow::CalcNumMotionEntriesUsingMotionExcluding(const AZStd::string& motionFilename, EMotionFX::MotionSet* excludedMotionSet) + size_t MotionSetWindow::CalcNumMotionEntriesUsingMotionExcluding(const AZStd::string& motionFilename, EMotionFX::MotionSet* excludedMotionSet) { if (motionFilename.empty()) { @@ -2149,9 +2137,9 @@ namespace EMStudio } // Iterate through all available motion sets and count how many entries are refering to the given motion file. - AZ::u32 counter = 0; - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + size_t counter = 0; + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); if (motionSet->GetIsOwnedByRuntime()) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.h index 1827214e5d..8c1fe04662 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetWindow.h @@ -62,11 +62,11 @@ namespace EMStudio void Accepted(); private: - EMotionFX::MotionSet* mMotionSet; + EMotionFX::MotionSet* m_motionSet; AZStd::vector m_existingIds; AZStd::string m_motionId; - QLineEdit* mLineEdit; - QPushButton* mOKButton; + QLineEdit* m_lineEdit; + QPushButton* m_okButton; }; @@ -88,19 +88,19 @@ namespace EMStudio void UpdateTableAndButton(); private: - EMotionFX::MotionSet* mMotionSet; - AZStd::vector mMotionIDs; - AZStd::vector mModifiedMotionIDs; - AZStd::vector mMotionToModifiedMap; - AZStd::vector mValids; - QTableWidget* mTableWidget; - QLineEdit* mStringALineEdit; - QLineEdit* mStringBLineEdit; - QPushButton* mApplyButton; - QLabel* mNumMotionIDsLabel; - QLabel* mNumModifiedIDsLabel; - QLabel* mNumDuplicateIDsLabel; - QComboBox* mComboBox; + EMotionFX::MotionSet* m_motionSet; + AZStd::vector m_motionIDs; + AZStd::vector m_modifiedMotionIDs; + AZStd::vector m_motionToModifiedMap; + AZStd::vector m_valids; + QTableWidget* m_tableWidget; + QLineEdit* m_stringALineEdit; + QLineEdit* m_stringBLineEdit; + QPushButton* m_applyButton; + QLabel* m_numMotionIDsLabel; + QLabel* m_numModifiedIDsLabel; + QLabel* m_numDuplicateIDsLabel; + QComboBox* m_comboBox; }; @@ -124,7 +124,7 @@ namespace EMStudio void dragEnterEvent(QDragEnterEvent* event) override; void dragMoveEvent(QDragMoveEvent* event) override; - MotionSetsWindowPlugin* mPlugin; + MotionSetsWindowPlugin* m_plugin; }; @@ -184,10 +184,10 @@ namespace EMStudio EMotionFX::MotionSet::MotionEntry* FindMotionEntry(QTableWidgetItem* item) const; void GetRowIndices(const QList& items, AZStd::vector& outRowIndices); - uint32 CalcNumMotionEntriesUsingMotionExcluding(const AZStd::string& motionFilename, EMotionFX::MotionSet* excludedMotionSet); + size_t CalcNumMotionEntriesUsingMotionExcluding(const AZStd::string& motionFilename, EMotionFX::MotionSet* excludedMotionSet); private: - QVBoxLayout* mVLayout = nullptr; + QVBoxLayout* m_vLayout = nullptr; MotionSetTableWidget* m_tableWidget = nullptr; QAction* m_addAction = nullptr; @@ -196,6 +196,6 @@ namespace EMStudio AzQtComponents::FilteredSearchWidget* m_searchWidget = nullptr; AZStd::string m_searchWidgetText; - MotionSetsWindowPlugin* mPlugin = nullptr; + MotionSetsWindowPlugin* m_plugin = nullptr; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.cpp index 21f1eb58cd..bb84dee35d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.cpp @@ -42,7 +42,7 @@ namespace EMStudio public: SaveDirtyMotionSetFilesCallback(MotionSetsWindowPlugin* plugin) - : SaveDirtyFilesCallback() { mPlugin = plugin; } + : SaveDirtyFilesCallback() { m_plugin = plugin; } ~SaveDirtyMotionSetFilesCallback() {} enum @@ -55,8 +55,8 @@ namespace EMStudio void GetDirtyFileNames(AZStd::vector* outFileNames, AZStd::vector* outObjects) override { - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(i); @@ -79,7 +79,7 @@ namespace EMStudio // add the link to the actual object ObjectPointer objPointer; - objPointer.mMotionSet = motionSet; + objPointer.m_motionSet = motionSet; outObjects->push_back(objPointer); } } @@ -94,13 +94,13 @@ namespace EMStudio { // get the current object pointer and skip directly if the type check fails ObjectPointer objPointer = objects[i]; - if (objPointer.mMotionSet == nullptr) + if (objPointer.m_motionSet == nullptr) { continue; } - EMotionFX::MotionSet* motionSet = objPointer.mMotionSet; - if (mPlugin->SaveDirtyMotionSet(motionSet, commandGroup, false) == DirtyFileManager::CANCELED) + EMotionFX::MotionSet* motionSet = objPointer.m_motionSet; + if (m_plugin->SaveDirtyMotionSet(motionSet, commandGroup, false) == DirtyFileManager::CANCELED) { return DirtyFileManager::CANCELED; } @@ -117,7 +117,7 @@ namespace EMStudio } private: - MotionSetsWindowPlugin* mPlugin; + MotionSetsWindowPlugin* m_plugin; }; @@ -125,43 +125,42 @@ namespace EMStudio MotionSetsWindowPlugin::MotionSetsWindowPlugin() : EMStudio::DockWidgetPlugin() { - mDialogStack = nullptr; - mSelectedSet = nullptr; - mCreateMotionSetCallback = nullptr; + m_dialogStack = nullptr; + m_selectedSet = nullptr; + m_createMotionSetCallback = nullptr; m_reinitCallback = nullptr; - mAdjustMotionSetCallback = nullptr; - mMotionSetAddMotionCallback = nullptr; - mMotionSetRemoveMotionCallback = nullptr; - mMotionSetAdjustMotionCallback = nullptr; - mLoadMotionSetCallback = nullptr; - //mStringIDWindow = nullptr; - mMotionSetManagementWindow = nullptr; - mMotionSetWindow = nullptr; - mDirtyFilesCallback = nullptr; + m_adjustMotionSetCallback = nullptr; + m_motionSetAddMotionCallback = nullptr; + m_motionSetRemoveMotionCallback = nullptr; + m_motionSetAdjustMotionCallback = nullptr; + m_loadMotionSetCallback = nullptr; + m_motionSetManagementWindow = nullptr; + m_motionSetWindow = nullptr; + m_dirtyFilesCallback = nullptr; } // destructor MotionSetsWindowPlugin::~MotionSetsWindowPlugin() { - GetCommandManager()->RemoveCommandCallback(mCreateMotionSetCallback, false); + GetCommandManager()->RemoveCommandCallback(m_createMotionSetCallback, false); GetCommandManager()->RemoveCommandCallback(m_reinitCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustMotionSetCallback, false); - GetCommandManager()->RemoveCommandCallback(mMotionSetAddMotionCallback, false); - GetCommandManager()->RemoveCommandCallback(mMotionSetRemoveMotionCallback, false); - GetCommandManager()->RemoveCommandCallback(mMotionSetAdjustMotionCallback, false); - GetCommandManager()->RemoveCommandCallback(mLoadMotionSetCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustMotionSetCallback, false); + GetCommandManager()->RemoveCommandCallback(m_motionSetAddMotionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_motionSetRemoveMotionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_motionSetAdjustMotionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_loadMotionSetCallback, false); - delete mCreateMotionSetCallback; + delete m_createMotionSetCallback; delete m_reinitCallback; - delete mAdjustMotionSetCallback; - delete mMotionSetAddMotionCallback; - delete mMotionSetRemoveMotionCallback; - delete mMotionSetAdjustMotionCallback; - delete mLoadMotionSetCallback; - - GetMainWindow()->GetDirtyFileManager()->RemoveCallback(mDirtyFilesCallback, false); - delete mDirtyFilesCallback; + delete m_adjustMotionSetCallback; + delete m_motionSetAddMotionCallback; + delete m_motionSetRemoveMotionCallback; + delete m_motionSetAdjustMotionCallback; + delete m_loadMotionSetCallback; + + GetMainWindow()->GetDirtyFileManager()->RemoveCallback(m_dirtyFilesCallback, false); + delete m_dirtyFilesCallback; } @@ -176,49 +175,49 @@ namespace EMStudio // init after the parent dock window has been created bool MotionSetsWindowPlugin::Init() { - mCreateMotionSetCallback = new CommandCreateMotionSetCallback(false); + m_createMotionSetCallback = new CommandCreateMotionSetCallback(false); m_reinitCallback = new CommandReinitCallback(false); - mAdjustMotionSetCallback = new CommandAdjustMotionSetCallback(false); - mMotionSetAddMotionCallback = new CommandMotionSetAddMotionCallback(false); - mMotionSetRemoveMotionCallback = new CommandMotionSetRemoveMotionCallback(false); - mMotionSetAdjustMotionCallback = new CommandMotionSetAdjustMotionCallback(false); - mLoadMotionSetCallback = new CommandLoadMotionSetCallback(false); + m_adjustMotionSetCallback = new CommandAdjustMotionSetCallback(false); + m_motionSetAddMotionCallback = new CommandMotionSetAddMotionCallback(false); + m_motionSetRemoveMotionCallback = new CommandMotionSetRemoveMotionCallback(false); + m_motionSetAdjustMotionCallback = new CommandMotionSetAdjustMotionCallback(false); + m_loadMotionSetCallback = new CommandLoadMotionSetCallback(false); - GetCommandManager()->RegisterCommandCallback("CreateMotionSet", mCreateMotionSetCallback); + GetCommandManager()->RegisterCommandCallback("CreateMotionSet", m_createMotionSetCallback); GetCommandManager()->RegisterCommandCallback("RemoveMotionSet", m_reinitCallback); - GetCommandManager()->RegisterCommandCallback("AdjustMotionSet", mAdjustMotionSetCallback); + GetCommandManager()->RegisterCommandCallback("AdjustMotionSet", m_adjustMotionSetCallback); - GetCommandManager()->RegisterCommandCallback("MotionSetAddMotion", mMotionSetAddMotionCallback); - GetCommandManager()->RegisterCommandCallback("MotionSetRemoveMotion", mMotionSetRemoveMotionCallback); - GetCommandManager()->RegisterCommandCallback("MotionSetAdjustMotion", mMotionSetAdjustMotionCallback); - GetCommandManager()->RegisterCommandCallback("LoadMotionSet", mLoadMotionSetCallback); + GetCommandManager()->RegisterCommandCallback("MotionSetAddMotion", m_motionSetAddMotionCallback); + GetCommandManager()->RegisterCommandCallback("MotionSetRemoveMotion", m_motionSetRemoveMotionCallback); + GetCommandManager()->RegisterCommandCallback("MotionSetAdjustMotion", m_motionSetAdjustMotionCallback); + GetCommandManager()->RegisterCommandCallback("LoadMotionSet", m_loadMotionSetCallback); GetCommandManager()->RegisterCommandCallback("RemoveMotion", m_reinitCallback); // create the dialog stack - assert(mDialogStack == nullptr); - mDialogStack = new MysticQt::DialogStack(mDock); - mDock->setWidget(mDialogStack); + assert(m_dialogStack == nullptr); + m_dialogStack = new MysticQt::DialogStack(m_dock); + m_dock->setWidget(m_dialogStack); // connect the window activation signal to refresh if reactivated - connect(mDock, &QDockWidget::visibilityChanged, this, &MotionSetsWindowPlugin::WindowReInit); + connect(m_dock, &QDockWidget::visibilityChanged, this, &MotionSetsWindowPlugin::WindowReInit); // create the set management window - mMotionSetManagementWindow = new MotionSetManagementWindow(this, mDialogStack); - mMotionSetManagementWindow->Init(); - mDialogStack->Add(mMotionSetManagementWindow, "Motion Set Management", false, true, true, false); + m_motionSetManagementWindow = new MotionSetManagementWindow(this, m_dialogStack); + m_motionSetManagementWindow->Init(); + m_dialogStack->Add(m_motionSetManagementWindow, "Motion Set Management", false, true, true, false); // create the motion set properties window - mMotionSetWindow = new MotionSetWindow(this, mDialogStack); - mMotionSetWindow->Init(); - mDialogStack->Add(mMotionSetWindow, "Motion Set", false, true); + m_motionSetWindow = new MotionSetWindow(this, m_dialogStack); + m_motionSetWindow->Init(); + m_dialogStack->Add(m_motionSetWindow, "Motion Set", false, true); ReInit(); SetSelectedSet(nullptr); // initialize the dirty files callback - mDirtyFilesCallback = new SaveDirtyMotionSetFilesCallback(this); - GetMainWindow()->GetDirtyFileManager()->AddCallback(mDirtyFilesCallback); + m_dirtyFilesCallback = new SaveDirtyMotionSetFilesCallback(this); + GetMainWindow()->GetDirtyFileManager()->AddCallback(m_dirtyFilesCallback); return true; } @@ -226,26 +225,26 @@ namespace EMStudio EMotionFX::MotionSet* MotionSetsWindowPlugin::GetSelectedSet() const { - if (EMotionFX::GetMotionManager().FindMotionSetIndex(mSelectedSet) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionSetIndex(m_selectedSet) == InvalidIndex) { return nullptr; } - return mSelectedSet; + return m_selectedSet; } void MotionSetsWindowPlugin::ReInit() { // Validate existence of selected motion set and reset selection in case selection is invalid. - if (EMotionFX::GetMotionManager().FindMotionSetIndex(mSelectedSet) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionSetIndex(m_selectedSet) == InvalidIndex) { - mSelectedSet = nullptr; + m_selectedSet = nullptr; } - SetSelectedSet(mSelectedSet); - mMotionSetManagementWindow->ReInit(); - mMotionSetWindow->ReInit(); + SetSelectedSet(m_selectedSet); + m_motionSetManagementWindow->ReInit(); + m_motionSetWindow->ReInit(); } @@ -334,16 +333,16 @@ namespace EMStudio void MotionSetsWindowPlugin::SetSelectedSet(EMotionFX::MotionSet* motionSet) { - mSelectedSet = motionSet; + m_selectedSet = motionSet; if (motionSet) { - mMotionSetManagementWindow->SelectItemsById(motionSet->GetID()); + m_motionSetManagementWindow->SelectItemsById(motionSet->GetID()); } - mMotionSetManagementWindow->ReInit(); - mMotionSetManagementWindow->UpdateInterface(); - mMotionSetWindow->ReInit(); - mMotionSetWindow->UpdateInterface(); + m_motionSetManagementWindow->ReInit(); + m_motionSetManagementWindow->UpdateInterface(); + m_motionSetWindow->ReInit(); + m_motionSetWindow->UpdateInterface(); } @@ -488,7 +487,7 @@ namespace EMStudio // If motion entry is still not found, look through all motion sets not owned by runtime. const EMotionFX::MotionManager& motionManager = EMotionFX::GetMotionManager(); - for(AZ::u32 i = 0; i < motionManager.GetNumMotionSets(); ++i) + for(size_t i = 0; i < motionManager.GetNumMotionSets(); ++i) { motionSet = motionManager.GetMotionSet(i); if (motionSet->GetIsOwnedByRuntime()) @@ -680,9 +679,9 @@ namespace EMStudio // select the first motion set if (EMotionFX::GetMotionManager().GetNumMotionSets() > 0) { - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); - for (uint32 i = 0; i < numMotionSets; ++i) + for (size_t i = 0; i < numMotionSets; ++i) { EMotionFX::MotionSet* motionSet2 = EMotionFX::GetMotionManager().GetMotionSet(0); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h index 4b7b16f5f5..459118c831 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h @@ -72,8 +72,8 @@ namespace EMStudio void SetSelectedSet(EMotionFX::MotionSet* motionSet); int SaveDirtyMotionSet(EMotionFX::MotionSet* motionSet, MCore::CommandGroup* commandGroup, bool askBeforeSaving, bool showCancelButton = true); - MotionSetManagementWindow* GetManagementWindow() { return mMotionSetManagementWindow; } - MotionSetWindow* GetMotionSetWindow() { return mMotionSetWindow; } + MotionSetManagementWindow* GetManagementWindow() { return m_motionSetManagementWindow; } + MotionSetWindow* GetMotionSetWindow() { return m_motionSetWindow; } int OnSaveDirtyMotionSets(); void LoadMotionSet(AZStd::string filename); @@ -94,22 +94,21 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandMotionSetAdjustMotionCallback); MCORE_DEFINECOMMANDCALLBACK(CommandLoadMotionSetCallback); - CommandCreateMotionSetCallback* mCreateMotionSetCallback; + CommandCreateMotionSetCallback* m_createMotionSetCallback; CommandReinitCallback* m_reinitCallback; - CommandAdjustMotionSetCallback* mAdjustMotionSetCallback; - CommandMotionSetAddMotionCallback* mMotionSetAddMotionCallback; - CommandMotionSetRemoveMotionCallback* mMotionSetRemoveMotionCallback; - CommandMotionSetAdjustMotionCallback* mMotionSetAdjustMotionCallback; - CommandLoadMotionSetCallback* mLoadMotionSetCallback; + CommandAdjustMotionSetCallback* m_adjustMotionSetCallback; + CommandMotionSetAddMotionCallback* m_motionSetAddMotionCallback; + CommandMotionSetRemoveMotionCallback* m_motionSetRemoveMotionCallback; + CommandMotionSetAdjustMotionCallback* m_motionSetAdjustMotionCallback; + CommandLoadMotionSetCallback* m_loadMotionSetCallback; - MotionSetManagementWindow* mMotionSetManagementWindow; - MotionSetWindow* mMotionSetWindow; + MotionSetManagementWindow* m_motionSetManagementWindow; + MotionSetWindow* m_motionSetWindow; - MysticQt::DialogStack* mDialogStack; - //MotionSetStringIDWindow* mStringIDWindow; + MysticQt::DialogStack* m_dialogStack; - EMotionFX::MotionSet* mSelectedSet; + EMotionFX::MotionSet* m_selectedSet; - SaveDirtyMotionSetFilesCallback* mDirtyFilesCallback; + SaveDirtyMotionSetFilesCallback* m_dirtyFilesCallback; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.cpp index 9910384133..de5eb31d92 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.cpp @@ -31,32 +31,32 @@ namespace EMStudio MotionExtractionWindow::MotionExtractionWindow(QWidget* parent, MotionWindowPlugin* motionWindowPlugin) : QWidget(parent) { - mMotionWindowPlugin = motionWindowPlugin; - mSelectCallback = nullptr; - mUnselectCallback = nullptr; - mClearSelectionCallback = nullptr; - mWarningWidget = nullptr; - mMainVerticalLayout = nullptr; - mChildVerticalLayout = nullptr; - mMotionExtractionNodeSelectionWindow= nullptr; - mWarningSelectNodeLink = nullptr; - mAdjustActorCallback = nullptr; - mCaptureHeight = nullptr; - mWarningShowed = false; + m_motionWindowPlugin = motionWindowPlugin; + m_selectCallback = nullptr; + m_unselectCallback = nullptr; + m_clearSelectionCallback = nullptr; + m_warningWidget = nullptr; + m_mainVerticalLayout = nullptr; + m_childVerticalLayout = nullptr; + m_motionExtractionNodeSelectionWindow= nullptr; + m_warningSelectNodeLink = nullptr; + m_adjustActorCallback = nullptr; + m_captureHeight = nullptr; + m_warningShowed = false; } // destructor MotionExtractionWindow::~MotionExtractionWindow() { - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustActorCallback, false); - delete mAdjustActorCallback; - delete mSelectCallback; - delete mUnselectCallback; - delete mClearSelectionCallback; + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustActorCallback, false); + delete m_adjustActorCallback; + delete m_selectCallback; + delete m_unselectCallback; + delete m_clearSelectionCallback; } @@ -65,21 +65,21 @@ namespace EMStudio // Create the flags widget. void MotionExtractionWindow::CreateFlagsWidget() { - mFlagsWidget = new QWidget(); + m_flagsWidget = new QWidget(); - mCaptureHeight = new QCheckBox(); - AzQtComponents::CheckBox::applyToggleSwitchStyle(mCaptureHeight); - connect(mCaptureHeight, &QCheckBox::clicked, this, &MotionExtractionWindow::OnMotionExtractionFlagsUpdated); + m_captureHeight = new QCheckBox(); + AzQtComponents::CheckBox::applyToggleSwitchStyle(m_captureHeight); + connect(m_captureHeight, &QCheckBox::clicked, this, &MotionExtractionWindow::OnMotionExtractionFlagsUpdated); QGridLayout* layout = new QGridLayout(); layout->setAlignment(Qt::AlignTop); layout->setSpacing(3); layout->addWidget(new QLabel(tr("Capture Height Changes")), 0, 0); - layout->addWidget(mCaptureHeight, 0, 1); + layout->addWidget(m_captureHeight, 0, 1); layout->setContentsMargins(0, 0, 0, 0); - mFlagsWidget->setLayout(layout); + m_flagsWidget->setLayout(layout); - mChildVerticalLayout->addWidget(mFlagsWidget); + m_childVerticalLayout->addWidget(m_flagsWidget); } @@ -87,17 +87,17 @@ namespace EMStudio void MotionExtractionWindow::CreateWarningWidget() { // create the warning widget - mWarningWidget = new QWidget(); - mWarningWidget->setMinimumHeight(MOTIONEXTRACTIONWINDOW_HEIGHT); - mWarningWidget->setMaximumHeight(MOTIONEXTRACTIONWINDOW_HEIGHT); + m_warningWidget = new QWidget(); + m_warningWidget->setMinimumHeight(MOTIONEXTRACTIONWINDOW_HEIGHT); + m_warningWidget->setMaximumHeight(MOTIONEXTRACTIONWINDOW_HEIGHT); QLabel* warningLabel = new QLabel("No node has been selected yet to enable Motion Extraction."); warningLabel->setWordWrap(true); warningLabel->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); - mWarningSelectNodeLink = new AzQtComponents::BrowseEdit(mWarningWidget); - mWarningSelectNodeLink->setPlaceholderText("Click here to setup the Motion Extraction node"); - connect(mWarningSelectNodeLink, &AzQtComponents::BrowseEdit::attachedButtonTriggered, this, &MotionExtractionWindow::OnSelectMotionExtractionNode); + m_warningSelectNodeLink = new AzQtComponents::BrowseEdit(m_warningWidget); + m_warningSelectNodeLink->setPlaceholderText("Click here to setup the Motion Extraction node"); + connect(m_warningSelectNodeLink, &AzQtComponents::BrowseEdit::attachedButtonTriggered, this, &MotionExtractionWindow::OnSelectMotionExtractionNode); // create and fill the layout QVBoxLayout* layout = new QVBoxLayout(); @@ -106,12 +106,12 @@ namespace EMStudio layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(warningLabel); - layout->addWidget(mWarningSelectNodeLink); + layout->addWidget(m_warningSelectNodeLink); - mWarningWidget->setLayout(layout); + m_warningWidget->setLayout(layout); // add it to our main layout - mChildVerticalLayout->addWidget(mWarningWidget); + m_childVerticalLayout->addWidget(m_warningWidget); } @@ -119,23 +119,23 @@ namespace EMStudio void MotionExtractionWindow::Init() { // create and register the command callbacks - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); - mClearSelectionCallback = new CommandClearSelectionCallback(false); - mAdjustActorCallback = new CommandAdjustActorCallback(false); - GetCommandManager()->RegisterCommandCallback("AdjustActor", mAdjustActorCallback); - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); + m_clearSelectionCallback = new CommandClearSelectionCallback(false); + m_adjustActorCallback = new CommandAdjustActorCallback(false); + GetCommandManager()->RegisterCommandCallback("AdjustActor", m_adjustActorCallback); + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); // create the node selection windows - mMotionExtractionNodeSelectionWindow = new NodeSelectionWindow(this, true); - connect(mMotionExtractionNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnSelectionDone), this, &MotionExtractionWindow::OnMotionExtractionNodeSelected); + m_motionExtractionNodeSelectionWindow = new NodeSelectionWindow(this, true); + connect(m_motionExtractionNodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &MotionExtractionWindow::OnMotionExtractionNodeSelected); // set some layout for our window - mMainVerticalLayout = new QVBoxLayout(); - mMainVerticalLayout->setSpacing(0); - setLayout(mMainVerticalLayout); + m_mainVerticalLayout = new QVBoxLayout(); + m_mainVerticalLayout->setSpacing(0); + setLayout(m_mainVerticalLayout); QCheckBox* checkBox = new QCheckBox(tr("Motion extraction")); checkBox->setChecked(true); @@ -160,17 +160,17 @@ namespace EMStudio {\ image: url(:/Cards/img/UI20/Cards/caret-right.svg);\ }"); - mMainVerticalLayout->addWidget(checkBox); + m_mainVerticalLayout->addWidget(checkBox); QWidget* childWidget = new QWidget(this); - mMainVerticalLayout->addWidget(childWidget); + m_mainVerticalLayout->addWidget(childWidget); - mChildVerticalLayout = new QVBoxLayout(childWidget); - mChildVerticalLayout->setContentsMargins(28,0,0,0); + m_childVerticalLayout = new QVBoxLayout(childWidget); + m_childVerticalLayout->setContentsMargins(28,0,0,0); connect(checkBox, &QCheckBox::toggled, childWidget, &QWidget::setVisible); // default create the warning widget (this is needed else we're getting a crash when switching layouts as the widget and the flag might be out of sync) CreateWarningWidget(); - mWarningShowed = true; + m_warningShowed = true; // update interface UpdateInterface(); @@ -182,7 +182,7 @@ namespace EMStudio const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); // Check if there actually is any motion selected. - const uint32 numSelectedMotions = selectionList.GetNumSelectedMotions(); + const size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); const bool isEnabled = (numSelectedMotions != 0); EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); @@ -191,9 +191,9 @@ namespace EMStudio EMotionFX::Actor* actor = nullptr; EMotionFX::Node* extractionNode = nullptr; - if (mCaptureHeight) + if (m_captureHeight) { - mCaptureHeight->setEnabled( isEnabled ); + m_captureHeight->setEnabled( isEnabled ); } if (actorInstance) @@ -205,60 +205,60 @@ namespace EMStudio if (extractionNode == nullptr) { // Check if we already show the warning widget, if yes, do nothing. - if (mWarningShowed == false) + if (m_warningShowed == false) { CreateWarningWidget(); - if (mFlagsWidget) + if (m_flagsWidget) { - mFlagsWidget->hide(); - mFlagsWidget->deleteLater(); - mFlagsWidget = nullptr; - mCaptureHeight = nullptr; + m_flagsWidget->hide(); + m_flagsWidget->deleteLater(); + m_flagsWidget = nullptr; + m_captureHeight = nullptr; } } // Disable the link in case no actor is selected. if (actorInstance == nullptr) { - mWarningSelectNodeLink->setEnabled(false); + m_warningSelectNodeLink->setEnabled(false); } else { - mWarningSelectNodeLink->setEnabled(true); + m_warningSelectNodeLink->setEnabled(true); } // Return directly in case we show the warning widget. - mWarningShowed = true; + m_warningShowed = true; return; } else { // Check if we already show the motion extraction flags widget, if yes, do nothing. - if (mWarningShowed) + if (m_warningShowed) { - if (mWarningWidget) + if (m_warningWidget) { - mWarningWidget->hide(); - mWarningWidget->deleteLater(); - mWarningWidget = nullptr; + m_warningWidget->hide(); + m_warningWidget->deleteLater(); + m_warningWidget = nullptr; } CreateFlagsWidget(); } - if (mCaptureHeight) + if (m_captureHeight) { - mCaptureHeight->setEnabled( isEnabled ); + m_captureHeight->setEnabled( isEnabled ); } // Figure out if all selected motions use the same settings. bool allCaptureHeightEqual = true; - uint32 numCaptureHeight = 0; - const uint32 numMotions = selectionList.GetNumSelectedMotions(); + size_t numCaptureHeight = 0; + const size_t numMotions = selectionList.GetNumSelectedMotions(); bool curCaptureHeight = false; - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { EMotionFX::Motion* curMotion = selectionList.GetMotion(i); EMotionFX::Motion* prevMotion = (i>0) ? selectionList.GetMotion(i-1) : nullptr; @@ -280,31 +280,31 @@ namespace EMStudio // Adjust the height capture checkbox, based on the selected motions. const bool triState = (numMotions > 1) && !allCaptureHeightEqual; - mCaptureHeight->setTristate( triState ); + m_captureHeight->setTristate( triState ); if (numMotions > 1) { if (!allCaptureHeightEqual) { - mCaptureHeight->setCheckState( Qt::CheckState::PartiallyChecked ); + m_captureHeight->setCheckState( Qt::CheckState::PartiallyChecked ); } else { - mCaptureHeight->setChecked( curCaptureHeight ); + m_captureHeight->setChecked( curCaptureHeight ); } } else { if (numCaptureHeight > 0) { - mCaptureHeight->setCheckState( Qt::CheckState::Checked ); + m_captureHeight->setCheckState( Qt::CheckState::Checked ); } else { - mCaptureHeight->setCheckState( Qt::CheckState::Unchecked ); + m_captureHeight->setCheckState( Qt::CheckState::Unchecked ); } } - mWarningShowed = false; + m_warningShowed = false; } } @@ -314,7 +314,7 @@ namespace EMStudio { int flags = 0; - if (mCaptureHeight->checkState() == Qt::CheckState::Checked) + if (m_captureHeight->checkState() == Qt::CheckState::Checked) flags |= EMotionFX::MOTIONEXTRACT_CAPTURE_Z; return static_cast(flags); @@ -325,7 +325,7 @@ namespace EMStudio void MotionExtractionWindow::OnMotionExtractionFlagsUpdated() { const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedMotions = selectionList.GetNumSelectedMotions(); + const size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); EMotionFX::ActorInstance* actorInstance = selectionList.GetSingleActorInstance(); // Check if there is at least one motion selected and exactly one actor instance. @@ -353,7 +353,7 @@ namespace EMStudio // Iterate through all selected motions. AZStd::string command; - for (uint32 i = 0; i < numSelectedMotions; ++i) + for (size_t i = 0; i < numSelectedMotions; ++i) { // Get the current selected motion, check if it is a skeletal motion, skip directly elsewise. EMotionFX::Motion* motion = selectionList.GetMotion(i); @@ -388,12 +388,12 @@ namespace EMStudio return; } - mMotionExtractionNodeSelectionWindow->Update(actorInstance->GetID()); - mMotionExtractionNodeSelectionWindow->show(); + m_motionExtractionNodeSelectionWindow->Update(actorInstance->GetID()); + m_motionExtractionNodeSelectionWindow->show(); } - void MotionExtractionWindow::OnMotionExtractionNodeSelected(MCore::Array selection) + void MotionExtractionWindow::OnMotionExtractionNodeSelected(AZStd::vector selection) { // get the selected node name uint32 actorID; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.h index efe89c49dc..5e314df323 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionExtractionWindow.h @@ -53,7 +53,7 @@ namespace EMStudio void OnMotionExtractionFlagsUpdated(); void OnSelectMotionExtractionNode(); - void OnMotionExtractionNodeSelected(MCore::Array selection); + void OnMotionExtractionNodeSelected(AZStd::vector selection); private: // callbacks @@ -61,28 +61,28 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandUnselectCallback); MCORE_DEFINECOMMANDCALLBACK(CommandClearSelectionCallback); MCORE_DEFINECOMMANDCALLBACK(CommandAdjustActorCallback); - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; - CommandClearSelectionCallback* mClearSelectionCallback; - CommandAdjustActorCallback* mAdjustActorCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; + CommandClearSelectionCallback* m_clearSelectionCallback; + CommandAdjustActorCallback* m_adjustActorCallback; // general - MotionWindowPlugin* mMotionWindowPlugin; - QCheckBox* mAutoMode; + MotionWindowPlugin* m_motionWindowPlugin; + QCheckBox* m_autoMode; // flags widget - QWidget* mFlagsWidget; - QCheckBox* mCaptureHeight; + QWidget* m_flagsWidget; + QCheckBox* m_captureHeight; // - QVBoxLayout* mMainVerticalLayout; - QVBoxLayout* mChildVerticalLayout; - QWidget* mWarningWidget; - bool mWarningShowed; + QVBoxLayout* m_mainVerticalLayout; + QVBoxLayout* m_childVerticalLayout; + QWidget* m_warningWidget; + bool m_warningShowed; // motion extraction node selection - NodeSelectionWindow* mMotionExtractionNodeSelectionWindow; - AzQtComponents::BrowseEdit* mWarningSelectNodeLink; + NodeSelectionWindow* m_motionExtractionNodeSelectionWindow; + AzQtComponents::BrowseEdit* m_warningSelectNodeLink; // helper functions void CreateFlagsWidget(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.cpp index c6af7f2149..0940a620e6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.cpp @@ -124,8 +124,8 @@ namespace EMStudio : QWidget(parent) { setObjectName("MotionListWindow"); - mMotionTable = nullptr; - mMotionWindowPlugin = motionWindowPlugin; + m_motionTable = nullptr; + m_motionWindowPlugin = motionWindowPlugin; } @@ -137,77 +137,77 @@ namespace EMStudio void MotionListWindow::Init() { - mVLayout = new QVBoxLayout(); - mVLayout->setMargin(3); - mVLayout->setSpacing(2); - mMotionTable = new MotionTableWidget(mMotionWindowPlugin, this); - mMotionTable->setObjectName("EMFX.MotionListWindow.MotionTable"); - mMotionTable->setAlternatingRowColors(true); - connect(mMotionTable, &MotionTableWidget::cellDoubleClicked, this, &MotionListWindow::cellDoubleClicked); - connect(mMotionTable, &MotionTableWidget::itemSelectionChanged, this, &MotionListWindow::itemSelectionChanged); + m_vLayout = new QVBoxLayout(); + m_vLayout->setMargin(3); + m_vLayout->setSpacing(2); + m_motionTable = new MotionTableWidget(m_motionWindowPlugin, this); + m_motionTable->setObjectName("EMFX.MotionListWindow.MotionTable"); + m_motionTable->setAlternatingRowColors(true); + connect(m_motionTable, &MotionTableWidget::cellDoubleClicked, this, &MotionListWindow::cellDoubleClicked); + connect(m_motionTable, &MotionTableWidget::itemSelectionChanged, this, &MotionListWindow::itemSelectionChanged); // set the table to row single selection - mMotionTable->setSelectionBehavior(QAbstractItemView::SelectRows); - mMotionTable->setSelectionMode(QAbstractItemView::ExtendedSelection); + m_motionTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_motionTable->setSelectionMode(QAbstractItemView::ExtendedSelection); // make the table items read only - mMotionTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_motionTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // disable the corner button between the row and column selection thingies - mMotionTable->setCornerButtonEnabled(false); + m_motionTable->setCornerButtonEnabled(false); // enable the custom context menu for the motion table - mMotionTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_motionTable->setContextMenuPolicy(Qt::DefaultContextMenu); // set the column count - mMotionTable->setColumnCount(5); + m_motionTable->setColumnCount(5); // add the name column QTableWidgetItem* nameHeaderItem = new QTableWidgetItem("Name"); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMotionTable->setHorizontalHeaderItem(0, nameHeaderItem); + m_motionTable->setHorizontalHeaderItem(0, nameHeaderItem); // add the length column QTableWidgetItem* lengthHeaderItem = new QTableWidgetItem("Duration"); lengthHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMotionTable->setHorizontalHeaderItem(1, lengthHeaderItem); + m_motionTable->setHorizontalHeaderItem(1, lengthHeaderItem); // add the sub column QTableWidgetItem* subHeaderItem = new QTableWidgetItem("Joints"); subHeaderItem->setToolTip("Number of joints inside the motion"); subHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMotionTable->setHorizontalHeaderItem(2, subHeaderItem); + m_motionTable->setHorizontalHeaderItem(2, subHeaderItem); // add the msub column QTableWidgetItem* msubHeaderItem = new QTableWidgetItem("Morphs"); msubHeaderItem->setToolTip("Number of morph targets inside the motion"); msubHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMotionTable->setHorizontalHeaderItem(3, msubHeaderItem); + m_motionTable->setHorizontalHeaderItem(3, msubHeaderItem); // add the type column QTableWidgetItem* typeHeaderItem = new QTableWidgetItem("Type"); typeHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMotionTable->setHorizontalHeaderItem(4, typeHeaderItem); + m_motionTable->setHorizontalHeaderItem(4, typeHeaderItem); // set the sorting order on the first column - mMotionTable->horizontalHeader()->setSortIndicator(0, Qt::AscendingOrder); + m_motionTable->horizontalHeader()->setSortIndicator(0, Qt::AscendingOrder); // hide the vertical columns - QHeaderView* verticalHeader = mMotionTable->verticalHeader(); + QHeaderView* verticalHeader = m_motionTable->verticalHeader(); verticalHeader->setVisible(false); // set the last column to take the whole available space - mMotionTable->horizontalHeader()->setStretchLastSection(true); + m_motionTable->horizontalHeader()->setStretchLastSection(true); // set the column width - mMotionTable->setColumnWidth(0, 300); - mMotionTable->setColumnWidth(1, 55); - mMotionTable->setColumnWidth(2, 50); - mMotionTable->setColumnWidth(3, 55); - mMotionTable->setColumnWidth(4, 105); + m_motionTable->setColumnWidth(0, 300); + m_motionTable->setColumnWidth(1, 55); + m_motionTable->setColumnWidth(2, 50); + m_motionTable->setColumnWidth(3, 55); + m_motionTable->setColumnWidth(4, 105); - mVLayout->addWidget(mMotionTable); - setLayout(mVLayout); + m_vLayout->addWidget(m_motionTable); + setLayout(m_vLayout); ReInit(); } @@ -224,7 +224,7 @@ namespace EMStudio bool MotionListWindow::AddMotionByID(uint32 motionID) { // find the motion entry based on the id - MotionWindowPlugin::MotionTableEntry* motionEntry = mMotionWindowPlugin->FindMotionEntryByID(motionID); + MotionWindowPlugin::MotionTableEntry* motionEntry = m_motionWindowPlugin->FindMotionEntryByID(motionID); if (motionEntry == nullptr) { return false; @@ -237,15 +237,15 @@ namespace EMStudio } // get the motion - EMotionFX::Motion* motion = motionEntry->mMotion; + EMotionFX::Motion* motion = motionEntry->m_motion; // disable the sorting - mMotionTable->setSortingEnabled(false); + m_motionTable->setSortingEnabled(false); // insert the new row - const uint32 rowIndex = 0; - mMotionTable->insertRow(rowIndex); - mMotionTable->setRowHeight(rowIndex, 21); + const int rowIndex = 0; + m_motionTable->insertRow(rowIndex); + m_motionTable->setRowHeight(rowIndex, 21); // create the name item QTableWidgetItem* nameTableItem = new QTableWidgetItem(motion->GetName()); @@ -257,7 +257,7 @@ namespace EMStudio nameTableItem->setToolTip(motion->GetFileName()); // set the item in the motion table - mMotionTable->setItem(rowIndex, 0, nameTableItem); + m_motionTable->setItem(rowIndex, 0, nameTableItem); // create the length item AZStd::string length; @@ -265,7 +265,7 @@ namespace EMStudio QTableWidgetItem* lengthTableItem = new QTableWidgetItem(length.c_str()); // set the item in the motion table - mMotionTable->setItem(rowIndex, 1, lengthTableItem); + m_motionTable->setItem(rowIndex, 1, lengthTableItem); // set the sub and msub text AZStd::string sub, msub; @@ -278,12 +278,12 @@ namespace EMStudio QTableWidgetItem* msubTableItem = new QTableWidgetItem(msub.c_str()); // set the items in the motion table - mMotionTable->setItem(rowIndex, 2, subTableItem); - mMotionTable->setItem(rowIndex, 3, msubTableItem); + m_motionTable->setItem(rowIndex, 2, subTableItem); + m_motionTable->setItem(rowIndex, 3, msubTableItem); // create and set the type item QTableWidgetItem* typeTableItem = new QTableWidgetItem(motionData->RTTI_GetTypeName()); - mMotionTable->setItem(rowIndex, 4, typeTableItem); + m_motionTable->setItem(rowIndex, 4, typeTableItem); // set the items italic if the motion is dirty if (motion->GetDirtyFlag()) @@ -301,7 +301,7 @@ namespace EMStudio } // enable the sorting - mMotionTable->setSortingEnabled(true); + m_motionTable->setSortingEnabled(true); // update the interface UpdateInterface(); @@ -314,8 +314,8 @@ namespace EMStudio uint32 MotionListWindow::FindRowByMotionID(uint32 motionID) { // iterate through the rows and compare the motion IDs - const uint32 rowCount = mMotionTable->rowCount(); - for (uint32 i = 0; i < rowCount; ++i) + const int rowCount = m_motionTable->rowCount(); + for (int i = 0; i < rowCount; ++i) { if (GetMotionID(i) == motionID) { @@ -338,7 +338,7 @@ namespace EMStudio } // remove the row - mMotionTable->removeRow(rowIndex); + m_motionTable->removeRow(rowIndex); // update the interface UpdateInterface(); @@ -350,12 +350,12 @@ namespace EMStudio bool MotionListWindow::CheckIfIsMotionVisible(MotionWindowPlugin::MotionTableEntry* entry) { - if (entry->mMotion->GetIsOwnedByRuntime()) + if (entry->m_motion->GetIsOwnedByRuntime()) { return false; } - AZStd::string motionNameLowered = entry->mMotion->GetNameString(); + AZStd::string motionNameLowered = entry->m_motion->GetNameString(); AZStd::to_lower(motionNameLowered.begin(), motionNameLowered.end()); if (m_searchWidgetText.empty() || motionNameLowered.find(m_searchWidgetText) != AZStd::string::npos) { @@ -369,33 +369,33 @@ namespace EMStudio { const CommandSystem::SelectionList selection = GetCommandManager()->GetCurrentSelection(); - size_t numMotions = mMotionWindowPlugin->GetNumMotionEntries(); - mShownMotionEntries.clear(); - mShownMotionEntries.reserve(numMotions); + size_t numMotions = m_motionWindowPlugin->GetNumMotionEntries(); + m_shownMotionEntries.clear(); + m_shownMotionEntries.reserve(numMotions); for (size_t i = 0; i < numMotions; ++i) { - MotionWindowPlugin::MotionTableEntry* entry = mMotionWindowPlugin->GetMotionEntry(i); + MotionWindowPlugin::MotionTableEntry* entry = m_motionWindowPlugin->GetMotionEntry(i); if (CheckIfIsMotionVisible(entry)) { - mShownMotionEntries.push_back(entry); + m_shownMotionEntries.push_back(entry); } } - numMotions = mShownMotionEntries.size(); + numMotions = m_shownMotionEntries.size(); // set the number of rows - mMotionTable->setRowCount(static_cast(numMotions)); + m_motionTable->setRowCount(static_cast(numMotions)); // set the sorting disabled - mMotionTable->setSortingEnabled(false); + m_motionTable->setSortingEnabled(false); // iterate through the motions and fill in the table for (int i = 0; i < numMotions; ++i) { - EMotionFX::Motion* motion = mShownMotionEntries[static_cast(i)]->mMotion; + EMotionFX::Motion* motion = m_shownMotionEntries[static_cast(i)]->m_motion; // set the row height - mMotionTable->setRowHeight(i, 21); + m_motionTable->setRowHeight(i, 21); // create the name item QTableWidgetItem* nameTableItem = new QTableWidgetItem(motion->GetName()); @@ -407,7 +407,7 @@ namespace EMStudio nameTableItem->setToolTip(motion->GetFileName()); // set the item in the motion table - mMotionTable->setItem(i, 0, nameTableItem); + m_motionTable->setItem(i, 0, nameTableItem); // create the length item AZStd::string length; @@ -415,7 +415,7 @@ namespace EMStudio QTableWidgetItem* lengthTableItem = new QTableWidgetItem(length.c_str()); // set the item in the motion table - mMotionTable->setItem(i, 1, lengthTableItem); + m_motionTable->setItem(i, 1, lengthTableItem); // set the sub and msub text AZStd::string sub, msub; @@ -428,12 +428,12 @@ namespace EMStudio QTableWidgetItem* msubTableItem = new QTableWidgetItem(msub.c_str()); // set the items in the motion table - mMotionTable->setItem(i, 2, subTableItem); - mMotionTable->setItem(i, 3, msubTableItem); + m_motionTable->setItem(i, 2, subTableItem); + m_motionTable->setItem(i, 3, msubTableItem); // create and set the type item QTableWidgetItem* typeTableItem = new QTableWidgetItem(motionData->RTTI_GetTypeName()); - mMotionTable->setItem(i, 4, typeTableItem); + m_motionTable->setItem(i, 4, typeTableItem); // set the items italic if the motion is dirty if (motion->GetDirtyFlag()) @@ -452,7 +452,7 @@ namespace EMStudio } // set the sorting enabled - mMotionTable->setSortingEnabled(true); + m_motionTable->setSortingEnabled(true); // set the old selection as before the reinit UpdateSelection(selection); @@ -463,13 +463,13 @@ namespace EMStudio void MotionListWindow::UpdateSelection(const CommandSystem::SelectionList& selectionList) { // block signals to not have the motion table events when selection changed - mMotionTable->blockSignals(true); + m_motionTable->blockSignals(true); // clear the selection - mMotionTable->clearSelection(); + m_motionTable->clearSelection(); // iterate through the selected motions and select the corresponding rows in the table widget - const uint32 numSelectedMotions = selectionList.GetNumSelectedMotions(); + const size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); for (uint32 i = 0; i < numSelectedMotions; ++i) { // get the index of the motion inside the motion manager (which is equal to the row in the motion table) and select the row at the motion index @@ -478,17 +478,17 @@ namespace EMStudio if (row != MCORE_INVALIDINDEX32) { // select the entire row - const int columnCount = mMotionTable->columnCount(); + const int columnCount = m_motionTable->columnCount(); for (int c = 0; c < columnCount; ++c) { - QTableWidgetItem* tableWidgetItem = mMotionTable->item(row, c); + QTableWidgetItem* tableWidgetItem = m_motionTable->item(row, c); tableWidgetItem->setSelected(true); } } } // enable the signals now all rows are selected - mMotionTable->blockSignals(false); + m_motionTable->blockSignals(false); // call the selection changed itemSelectionChanged(); @@ -502,7 +502,7 @@ namespace EMStudio uint32 MotionListWindow::GetMotionID(uint32 rowIndex) { - QTableWidgetItem* tableItem = mMotionTable->item(rowIndex, 0); + QTableWidgetItem* tableItem = m_motionTable->item(rowIndex, 0); if (tableItem) { return tableItem->data(Qt::UserRole).toInt(); @@ -520,7 +520,7 @@ namespace EMStudio if (motion) { - mMotionWindowPlugin->PlayMotion(motion); + m_motionWindowPlugin->PlayMotion(motion); } } @@ -528,17 +528,17 @@ namespace EMStudio void MotionListWindow::itemSelectionChanged() { // get the current selection - const QList selectedItems = mMotionTable->selectedItems(); + const QList selectedItems = m_motionTable->selectedItems(); // get the number of selected items - const uint32 numSelectedItems = selectedItems.count(); + const int numSelectedItems = selectedItems.count(); // filter the items - AZStd::vector rowIndices; + AZStd::vector rowIndices; rowIndices.reserve(numSelectedItems); - for (size_t i = 0; i < numSelectedItems; ++i) + for (int i = 0; i < numSelectedItems; ++i) { - const uint32 rowIndex = selectedItems[static_cast(i)]->row(); + const int rowIndex = selectedItems[i]->row(); if (AZStd::find(rowIndices.begin(), rowIndices.end(), rowIndex) == rowIndices.end()) { rowIndices.push_back(rowIndex); @@ -546,25 +546,23 @@ namespace EMStudio } // clear the selected motion IDs - mSelectedMotionIDs.clear(); + m_selectedMotionIDs.clear(); // get the number of selected items and iterate through them - const size_t numSelectedRows = rowIndices.size(); - mSelectedMotionIDs.reserve(numSelectedRows); - for (size_t i = 0; i < numSelectedRows; ++i) + m_selectedMotionIDs.reserve(rowIndices.size()); + for (const int rowIndex : rowIndices) { - mSelectedMotionIDs.push_back(GetMotionID(rowIndices[i])); + m_selectedMotionIDs.push_back(GetMotionID(rowIndex)); } // unselect all motions GetCommandManager()->GetCurrentSelection().ClearMotionSelection(); // get the number of selected motions and iterate through them - const size_t numSelectedMotions = mSelectedMotionIDs.size(); - for (size_t i = 0; i < numSelectedMotions; ++i) + for (uint32 selectedMotionID : m_selectedMotionIDs) { // find the motion by name in the motion library and select it - EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(mSelectedMotionIDs[i]); + EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(selectedMotionID); if (motion) { GetCommandManager()->GetCurrentSelection().AddMotion(motion); @@ -572,7 +570,7 @@ namespace EMStudio } // update the interface - mMotionWindowPlugin->UpdateInterface(); + m_motionWindowPlugin->UpdateInterface(); // emit signal that tells other windows that the motion selection changed emit MotionSelectionChanged(); @@ -583,7 +581,7 @@ namespace EMStudio { // get the current selection const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedMotions = selection.GetNumSelectedMotions(); + const size_t numSelectedMotions = selection.GetNumSelectedMotions(); if (numSelectedMotions == 0) { return; @@ -607,7 +605,6 @@ namespace EMStudio // Set the command group name based on the number of motions to add. AZStd::string groupName; - const size_t numSelectedMotionSets = selectedMotionSets.size(); if (numSelectedMotions > 1) { groupName = "Add motions in motion sets"; @@ -621,16 +618,14 @@ namespace EMStudio // add in each selected motion set AZStd::string motionName; - for (uint32 m = 0; m < numSelectedMotionSets; ++m) + for (const EMotionFX::MotionSet* motionSet : selectedMotionSets) { - EMotionFX::MotionSet* motionSet = selectedMotionSets[m]; - // Build a list of unique string id values from all motion set entries. AZStd::vector idStrings; motionSet->BuildIdStringList(idStrings); // add each selected motion in the motion set - for (uint32 i = 0; i < numSelectedMotions; ++i) + for (size_t i = 0; i < numSelectedMotions; ++i) { // remove the media root folder from the absolute motion filename so that we get the relative one to the media root folder motionName = selection.GetMotion(i)->GetFileName(); @@ -654,7 +649,7 @@ namespace EMStudio const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); // iterate through the selected motions and show them - for (uint32 i = 0; i < selection.GetNumSelectedMotions(); ++i) + for (size_t i = 0; i < selection.GetNumSelectedMotions(); ++i) { EMotionFX::Motion* motion = selection.GetMotion(i); AzQtComponents::ShowFileOnDesktop(motion->GetFileName()); @@ -753,7 +748,7 @@ namespace EMStudio MotionTableWidget::MotionTableWidget(MotionWindowPlugin* parentPlugin, QWidget* parent) : QTableWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; // enable dragging setDragEnabled(true); @@ -777,8 +772,8 @@ namespace EMStudio // get the number of selected motions and return directly if there are no motions selected AZStd::string textData, command; - const uint32 numMotions = selectionList.GetNumSelectedMotions(); - for (uint32 i = 0; i < numMotions; ++i) + const size_t numMotions = selectionList.GetNumSelectedMotions(); + for (size_t i = 0; i < numMotions; ++i) { EMotionFX::Motion* motion = selectionList.GetMotion(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.h index 89f2dc8f8a..7308ce12e1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionListWindow.h @@ -62,7 +62,7 @@ namespace EMStudio QStringList mimeTypes() const override; Qt::DropActions supportedDropActions() const override; - MotionWindowPlugin* mPlugin; + MotionWindowPlugin* m_plugin; }; @@ -80,7 +80,7 @@ namespace EMStudio void ReInit(); void UpdateInterface(); - QTableWidget* GetMotionTable() { return mMotionTable; } + QTableWidget* GetMotionTable() { return m_motionTable; } bool AddMotionByID(uint32 motionID); bool RemoveMotionByID(uint32 motionID); @@ -108,11 +108,11 @@ namespace EMStudio void UpdateSelection(const CommandSystem::SelectionList& selectionList); private: - AZStd::vector mSelectedMotionIDs; - AZStd::vector mShownMotionEntries; - QVBoxLayout* mVLayout; - MotionTableWidget* mMotionTable; - MotionWindowPlugin* mMotionWindowPlugin; + AZStd::vector m_selectedMotionIDs; + AZStd::vector m_shownMotionEntries; + QVBoxLayout* m_vLayout; + MotionTableWidget* m_motionTable; + MotionWindowPlugin* m_motionWindowPlugin; AZStd::string m_searchWidgetText; }; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.cpp index 5c0ab3d564..d6dbe2c4cc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.cpp @@ -26,9 +26,8 @@ namespace EMStudio MotionRetargetingWindow::MotionRetargetingWindow(QWidget* parent, MotionWindowPlugin* motionWindowPlugin) : QWidget(parent) { - mMotionWindowPlugin = motionWindowPlugin; - mMotionRetargetingButton = nullptr; - //mRenderMotionBindPose = nullptr; + m_motionWindowPlugin = motionWindowPlugin; + m_motionRetargetingButton = nullptr; } @@ -44,18 +43,11 @@ namespace EMStudio QGridLayout* layout = new QGridLayout(); setLayout(layout); - mMotionRetargetingButton = new QCheckBox(); - AzQtComponents::CheckBox::applyToggleSwitchStyle(mMotionRetargetingButton); + m_motionRetargetingButton = new QCheckBox(); + AzQtComponents::CheckBox::applyToggleSwitchStyle(m_motionRetargetingButton); layout->addWidget(new QLabel(tr("Use Motion Retargeting")), 0, 0); - layout->addWidget(mMotionRetargetingButton, 0, 1); - connect(mMotionRetargetingButton, &QCheckBox::clicked, this, &MotionRetargetingWindow::UpdateMotions); - - //mRenderMotionBindPose = new QCheckBox(); - //AzQtComponents::CheckBox::applyToggleSwitchStyle(mRenderMotionBindPose); - //mRenderMotionBindPose->setToolTip("Render motion bind pose of the currently selected motion for the selected actor instances"); - //mRenderMotionBindPose->setChecked(false); - //layout->addWidget(new QLabel(tr("Render Motion Bind Pose")), 1, 0); - //layout->addWidget(mRenderMotionBindPose, 1, 1); + layout->addWidget(m_motionRetargetingButton, 0, 1); + connect(m_motionRetargetingButton, &QCheckBox::clicked, this, &MotionRetargetingWindow::UpdateMotions); } @@ -67,24 +59,24 @@ namespace EMStudio MCore::CommandGroup commandGroup("Adjust default motion instances"); // get the number of selected motions and iterate through them - const uint32 numMotions = selection.GetNumSelectedMotions(); - for (uint32 i = 0; i < numMotions; ++i) + const size_t numMotions = selection.GetNumSelectedMotions(); + for (size_t i = 0; i < numMotions; ++i) { - MotionWindowPlugin::MotionTableEntry* entry = mMotionWindowPlugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()); + MotionWindowPlugin::MotionTableEntry* entry = m_motionWindowPlugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()); if (entry == nullptr) { MCore::LogError("Cannot find motion table entry for the given motion."); continue; } - EMotionFX::Motion* motion = entry->mMotion; + EMotionFX::Motion* motion = entry->m_motion; EMotionFX::PlayBackInfo* playbackInfo = motion->GetDefaultPlayBackInfo(); AZStd::string commandParameters; - if (playbackInfo->mRetarget != mMotionRetargetingButton->isChecked()) + if (playbackInfo->m_retarget != m_motionRetargetingButton->isChecked()) { - commandParameters += AZStd::string::format("-retarget %s ", AZStd::to_string(mMotionRetargetingButton->isChecked()).c_str()); + commandParameters += AZStd::string::format("-retarget %s ", AZStd::to_string(m_motionRetargetingButton->isChecked()).c_str()); } // in case the command parameters are empty it means nothing changed, so we can skip this command @@ -108,11 +100,10 @@ namespace EMStudio const CommandSystem::SelectionList& selection = CommandSystem::GetCommandManager()->GetCurrentSelection(); // check if there actually is any motion selected - const uint32 numSelectedMotions = selection.GetNumSelectedMotions(); + const size_t numSelectedMotions = selection.GetNumSelectedMotions(); const bool isEnabled = (numSelectedMotions != 0); - mMotionRetargetingButton->setEnabled(isEnabled); - //mRenderMotionBindPose->setEnabled(isEnabled); + m_motionRetargetingButton->setEnabled(isEnabled); if (isEnabled == false) { @@ -120,19 +111,19 @@ namespace EMStudio } // iterate through the selected motions - for (uint32 i = 0; i < numSelectedMotions; ++i) + for (size_t i = 0; i < numSelectedMotions; ++i) { - MotionWindowPlugin::MotionTableEntry* entry = mMotionWindowPlugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()); + MotionWindowPlugin::MotionTableEntry* entry = m_motionWindowPlugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()); if (entry == nullptr) { MCore::LogWarning("Cannot find motion table entry for the given motion."); continue; } - EMotionFX::Motion* motion = entry->mMotion; + EMotionFX::Motion* motion = entry->m_motion; EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo(); - mMotionRetargetingButton->setChecked(defaultPlayBackInfo->mRetarget); + m_motionRetargetingButton->setChecked(defaultPlayBackInfo->m_retarget); } } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.h index 3c5d50bc36..a846982eca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionRetargetingWindow.h @@ -47,12 +47,11 @@ namespace EMStudio void UpdateMotions(); private: - MotionWindowPlugin* mMotionWindowPlugin; - QCheckBox* mMotionRetargetingButton; - //QCheckBox* mRenderMotionBindPose; - EMotionFX::ActorInstance* mSelectedActorInstance; - EMotionFX::Actor* mActor; - CommandSystem::SelectionList mSelectionList; + MotionWindowPlugin* m_motionWindowPlugin; + QCheckBox* m_motionRetargetingButton; + EMotionFX::ActorInstance* m_selectedActorInstance; + EMotionFX::Actor* m_actor; + CommandSystem::SelectionList m_selectionList; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.cpp index 0a1fcb3b7a..87c6a601aa 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.cpp @@ -6,6 +6,7 @@ * */ +#include "AzCore/std/limits.h" #include #include #include @@ -39,7 +40,7 @@ namespace EMStudio public: SaveDirtyMotionFilesCallback(MotionWindowPlugin* plugin) - : SaveDirtyFilesCallback() { mPlugin = plugin; } + : SaveDirtyFilesCallback() { m_plugin = plugin; } ~SaveDirtyMotionFilesCallback() {} enum @@ -53,8 +54,8 @@ namespace EMStudio void GetDirtyFileNames(AZStd::vector* outFileNames, AZStd::vector* outObjects) override { // get the number of motions and iterate through them - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); - for (uint32 i = 0; i < numMotions; ++i) + const size_t numMotions = EMotionFX::GetMotionManager().GetNumMotions(); + for (size_t i = 0; i < numMotions; ++i) { EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); @@ -71,7 +72,7 @@ namespace EMStudio // add the link to the actual object ObjectPointer objPointer; - objPointer.mMotion = motion; + objPointer.m_motion = motion; outObjects->push_back(objPointer); } } @@ -86,13 +87,13 @@ namespace EMStudio { // get the current object pointer and skip directly if the type check fails ObjectPointer objPointer = objects[i]; - if (objPointer.mMotion == nullptr) + if (objPointer.m_motion == nullptr) { continue; } - EMotionFX::Motion* motion = objPointer.mMotion; - if (mPlugin->SaveDirtyMotion(motion, commandGroup, false) == DirtyFileManager::CANCELED) + EMotionFX::Motion* motion = objPointer.m_motion; + if (m_plugin->SaveDirtyMotion(motion, commandGroup, false) == DirtyFileManager::CANCELED) { return DirtyFileManager::CANCELED; } @@ -109,31 +110,31 @@ namespace EMStudio } private: - MotionWindowPlugin* mPlugin; + MotionWindowPlugin* m_plugin; }; - AZStd::vector MotionWindowPlugin::mInternalMotionInstanceSelection; + AZStd::vector MotionWindowPlugin::s_internalMotionInstanceSelection; MotionWindowPlugin::MotionWindowPlugin() : EMStudio::DockWidgetPlugin() { - mDialogStack = nullptr; - mMotionListWindow = nullptr; - mMotionPropertiesWindow = nullptr; - mMotionExtractionWindow = nullptr; - mMotionRetargetingWindow = nullptr; - mDirtyFilesCallback = nullptr; - mAddMotionsAction = nullptr; - mSaveAction = nullptr; - mMotionNameLabel = nullptr; + m_dialogStack = nullptr; + m_motionListWindow = nullptr; + m_motionPropertiesWindow = nullptr; + m_motionExtractionWindow = nullptr; + m_motionRetargetingWindow = nullptr; + m_dirtyFilesCallback = nullptr; + m_addMotionsAction = nullptr; + m_saveAction = nullptr; + m_motionNameLabel = nullptr; } MotionWindowPlugin::~MotionWindowPlugin() { - delete mDialogStack; + delete m_dialogStack; ClearMotionEntries(); // unregister the command callbacks and get rid of the memory @@ -143,19 +144,19 @@ namespace EMStudio } m_callbacks.clear(); - GetMainWindow()->GetDirtyFileManager()->RemoveCallback(mDirtyFilesCallback, false); - delete mDirtyFilesCallback; + GetMainWindow()->GetDirtyFileManager()->RemoveCallback(m_dirtyFilesCallback, false); + delete m_dirtyFilesCallback; } void MotionWindowPlugin::ClearMotionEntries() { - const size_t numEntries = mMotionEntries.size(); + const size_t numEntries = m_motionEntries.size(); for (size_t i = 0; i < numEntries; ++i) { - delete mMotionEntries[i]; + delete m_motionEntries[i]; } - mMotionEntries.clear(); + m_motionEntries.clear(); } @@ -179,9 +180,9 @@ namespace EMStudio GetCommandManager()->RegisterCommandCallback("ScaleMotionData", m_callbacks, false); GetCommandManager()->RegisterCommandCallback("Select", m_callbacks, false); - QWidget* container = new QWidget(mDock); + QWidget* container = new QWidget(m_dock); container->setLayout(new QVBoxLayout); - mDock->setWidget(container); + m_dock->setWidget(container); QToolBar* toolBar = new QToolBar(container); container->layout()->addWidget(toolBar); @@ -193,73 +194,73 @@ namespace EMStudio container->layout()->addWidget(splitterWidget); // create the motion list stack window - mMotionListWindow = new MotionListWindow(splitterWidget, this); - mMotionListWindow->Init(); - connect(mMotionListWindow, &MotionListWindow::SaveRequested, this, &MotionWindowPlugin::OnSave); - connect(mMotionListWindow, &MotionListWindow::RemoveMotionsRequested, this, &MotionWindowPlugin::OnRemoveMotions); - splitterWidget->addWidget(mMotionListWindow); + m_motionListWindow = new MotionListWindow(splitterWidget, this); + m_motionListWindow->Init(); + connect(m_motionListWindow, &MotionListWindow::SaveRequested, this, &MotionWindowPlugin::OnSave); + connect(m_motionListWindow, &MotionListWindow::RemoveMotionsRequested, this, &MotionWindowPlugin::OnRemoveMotions); + splitterWidget->addWidget(m_motionListWindow); // reinitialize the motion table entries ReInit(); - mAddMotionsAction = toolBar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Plus.svg"), tr("Load motions"), this, &MotionWindowPlugin::OnAddMotions); - mSaveAction = toolBar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Menu/FileSave.svg"), tr("Save selected motions"), this, &MotionWindowPlugin::OnSave); + m_addMotionsAction = toolBar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Plus.svg"), tr("Load motions"), this, &MotionWindowPlugin::OnAddMotions); + m_saveAction = toolBar->addAction(MysticQt::GetMysticQt()->FindIcon("Images/Menu/FileSave.svg"), tr("Save selected motions"), this, &MotionWindowPlugin::OnSave); toolBar->addSeparator(); AzQtComponents::FilteredSearchWidget* searchWidget = new AzQtComponents::FilteredSearchWidget(toolBar); - connect(searchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, mMotionListWindow, &MotionListWindow::OnTextFilterChanged); + connect(searchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, m_motionListWindow, &MotionListWindow::OnTextFilterChanged); toolBar->addWidget(searchWidget); // create the dialog stack - assert(mDialogStack == nullptr); - mDialogStack = new MysticQt::DialogStack(splitterWidget); - mDialogStack->setMinimumWidth(279); - splitterWidget->addWidget(mDialogStack); + assert(m_dialogStack == nullptr); + m_dialogStack = new MysticQt::DialogStack(splitterWidget); + m_dialogStack->setMinimumWidth(279); + splitterWidget->addWidget(m_dialogStack); // add the motion properties stack window - mMotionPropertiesWindow = new MotionPropertiesWindow(mDialogStack, this); - mMotionPropertiesWindow->Init(); - mDialogStack->Add(mMotionPropertiesWindow, "Motion Properties", false, true); + m_motionPropertiesWindow = new MotionPropertiesWindow(m_dialogStack, this); + m_motionPropertiesWindow->Init(); + m_dialogStack->Add(m_motionPropertiesWindow, "Motion Properties", false, true); // add the motion name label QWidget* motionName = new QWidget(); QBoxLayout* motionNameLayout = new QHBoxLayout(motionName); - mMotionNameLabel = new QLabel(); + m_motionNameLabel = new QLabel(); QLabel* label = new QLabel(tr("Motion name")); motionNameLayout->addWidget(label); - motionNameLayout->addWidget(mMotionNameLabel); + motionNameLayout->addWidget(m_motionNameLabel); motionNameLayout->setStretchFactor(label, 3); - motionNameLayout->setStretchFactor(mMotionNameLabel, 2); - mMotionPropertiesWindow->layout()->addWidget(motionName); + motionNameLayout->setStretchFactor(m_motionNameLabel, 2); + m_motionPropertiesWindow->layout()->addWidget(motionName); // add the motion extraction stack window - mMotionExtractionWindow = new MotionExtractionWindow(mDialogStack, this); - mMotionExtractionWindow->Init(); - mMotionPropertiesWindow->AddSubProperties(mMotionExtractionWindow); + m_motionExtractionWindow = new MotionExtractionWindow(m_dialogStack, this); + m_motionExtractionWindow->Init(); + m_motionPropertiesWindow->AddSubProperties(m_motionExtractionWindow); // add the motion retargeting stack window - mMotionRetargetingWindow = new MotionRetargetingWindow(mDialogStack, this); - mMotionRetargetingWindow->Init(); - mMotionPropertiesWindow->AddSubProperties(mMotionRetargetingWindow); + m_motionRetargetingWindow = new MotionRetargetingWindow(m_dialogStack, this); + m_motionRetargetingWindow->Init(); + m_motionPropertiesWindow->AddSubProperties(m_motionRetargetingWindow); - mMotionPropertiesWindow->FinalizeSubProperties(); + m_motionPropertiesWindow->FinalizeSubProperties(); // connect the window activation signal to refresh if reactivated - connect(mDock, &QDockWidget::visibilityChanged, this, &MotionWindowPlugin::VisibilityChanged); + connect(m_dock, &QDockWidget::visibilityChanged, this, &MotionWindowPlugin::VisibilityChanged); // update the new interface and return success UpdateInterface(); // initialize the dirty files callback - mDirtyFilesCallback = new SaveDirtyMotionFilesCallback(this); - GetMainWindow()->GetDirtyFileManager()->AddCallback(mDirtyFilesCallback); + m_dirtyFilesCallback = new SaveDirtyMotionFilesCallback(this); + GetMainWindow()->GetDirtyFileManager()->AddCallback(m_dirtyFilesCallback); return true; } void MotionWindowPlugin::OnAddMotions() { - const AZStd::vector filenames = GetMainWindow()->GetFileManager()->LoadMotionsFileDialog(mMotionListWindow); + const AZStd::vector filenames = GetMainWindow()->GetFileManager()->LoadMotionsFileDialog(m_motionListWindow); CommandSystem::LoadMotionsCommand(filenames); } @@ -272,11 +273,11 @@ namespace EMStudio } // iterate through the motions and put them into some array - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); + const size_t numMotions = EMotionFX::GetMotionManager().GetNumMotions(); AZStd::vector motionsToRemove; motionsToRemove.reserve(numMotions); - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); if (motion->GetIsOwnedByRuntime()) @@ -293,7 +294,7 @@ namespace EMStudio // show the window if at least one failed remove motion if (!failedRemoveMotions.empty()) { - MotionListRemoveMotionsFailedWindow removeMotionsFailedWindow(mMotionListWindow, failedRemoveMotions); + MotionListRemoveMotionsFailedWindow removeMotionsFailedWindow(m_motionListWindow, failedRemoveMotions); removeMotionsFailedWindow.exec(); } } @@ -303,7 +304,7 @@ namespace EMStudio const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); // get the number of selected motions - const uint32 numMotions = selection.GetNumSelectedMotions(); + const size_t numMotions = selection.GetNumSelectedMotions(); if (numMotions == 0) { return; @@ -327,7 +328,7 @@ namespace EMStudio // Save all dirty motion files. EMotionFX::MotionManager& motionManager = EMotionFX::GetMotionManager(); - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { // Look up the motion by ID, using our backup seleciton list. // So even if our selection list in EMotion FX gets modified, we still iterate over the original selection now. @@ -353,15 +354,11 @@ namespace EMStudio } // find the lowest row selected - uint32 lowestRowSelected = MCORE_INVALIDINDEX32; - const QList selectedItems = mMotionListWindow->GetMotionTable()->selectedItems(); - const int numSelectedItems = selectedItems.size(); - for (int i = 0; i < numSelectedItems; ++i) + int lowestRowSelected = AZStd::numeric_limits::max(); + const QList selectedItems = m_motionListWindow->GetMotionTable()->selectedItems(); + for (const QTableWidgetItem* selectedItem : selectedItems) { - if ((uint32)selectedItems[i]->row() < lowestRowSelected) - { - lowestRowSelected = (uint32)selectedItems[i]->row(); - } + lowestRowSelected = AZStd::min(lowestRowSelected, selectedItem->row()); } // construct the command group and remove the selected motions @@ -369,19 +366,19 @@ namespace EMStudio CommandSystem::RemoveMotions(motionsToRemove, &failedRemoveMotions); // selected the next row - if (lowestRowSelected > ((uint32)mMotionListWindow->GetMotionTable()->rowCount() - 1)) + if (lowestRowSelected > (m_motionListWindow->GetMotionTable()->rowCount() - 1)) { - mMotionListWindow->GetMotionTable()->selectRow(lowestRowSelected - 1); + m_motionListWindow->GetMotionTable()->selectRow(lowestRowSelected - 1); } else { - mMotionListWindow->GetMotionTable()->selectRow(lowestRowSelected); + m_motionListWindow->GetMotionTable()->selectRow(lowestRowSelected); } // show the window if at least one failed remove motion if (!failedRemoveMotions.empty()) { - MotionListRemoveMotionsFailedWindow removeMotionsFailedWindow(mMotionListWindow, failedRemoveMotions); + MotionListRemoveMotionsFailedWindow removeMotionsFailedWindow(m_motionListWindow, failedRemoveMotions); removeMotionsFailedWindow.exec(); } } @@ -389,7 +386,7 @@ namespace EMStudio void MotionWindowPlugin::OnSave() { const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const AZ::u32 numMotions = selectionList.GetNumSelectedMotions(); + const size_t numMotions = selectionList.GetNumSelectedMotions(); if (numMotions == 0) { return; @@ -398,7 +395,7 @@ namespace EMStudio // Collect motion ids of the motion to be saved. AZStd::vector motionIds; motionIds.reserve(numMotions); - for (AZ::u32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { const EMotionFX::Motion* motion = selectionList.GetMotion(i); motionIds.push_back(motion->GetID()); @@ -425,8 +422,8 @@ namespace EMStudio { if (!motion->GetIsOwnedByRuntime()) { - mMotionEntries.push_back(new MotionTableEntry(motion)); - return mMotionListWindow->AddMotionByID(motionID); + m_motionEntries.push_back(new MotionTableEntry(motion)); + return m_motionListWindow->AddMotionByID(motionID); } } } @@ -437,21 +434,21 @@ namespace EMStudio bool MotionWindowPlugin::RemoveMotionByIndex(size_t index) { - const uint32 motionID = mMotionEntries[index]->mMotionID; + const uint32 motionID = m_motionEntries[index]->m_motionId; - delete mMotionEntries[index]; - mMotionEntries.erase(mMotionEntries.begin() + index); + delete m_motionEntries[index]; + m_motionEntries.erase(m_motionEntries.begin() + index); - return mMotionListWindow->RemoveMotionByID(motionID); + return m_motionListWindow->RemoveMotionByID(motionID); } bool MotionWindowPlugin::RemoveMotionById(uint32 motionID) { - const size_t numMotionEntries = mMotionEntries.size(); + const size_t numMotionEntries = m_motionEntries.size(); for (size_t i = 0; i < numMotionEntries; ++i) { - if (mMotionEntries[i]->mMotionID == motionID) + if (m_motionEntries[i]->m_motionId == motionID) { return RemoveMotionByIndex(i); } @@ -462,11 +459,9 @@ namespace EMStudio void MotionWindowPlugin::ReInit() { - uint32 i; - // get the number of motions in the motion library and iterate through them - const uint32 numLibraryMotions = EMotionFX::GetMotionManager().GetNumMotions(); - for (i = 0; i < numLibraryMotions; ++i) + const size_t numLibraryMotions = EMotionFX::GetMotionManager().GetNumMotions(); + for (size_t i = 0; i < numLibraryMotions; ++i) { // check if we have already added this motion, if not add it EMotionFX::Motion* motion = EMotionFX::GetMotionManager().GetMotion(i); @@ -476,45 +471,38 @@ namespace EMStudio } if (FindMotionEntryByID(motion->GetID()) == nullptr) { - mMotionEntries.push_back(new MotionTableEntry(motion)); + m_motionEntries.push_back(new MotionTableEntry(motion)); } } // iterate through all motions inside the motion window plugin - i = 0; - while (i < mMotionEntries.size()) + AZStd::erase_if(m_motionEntries, [](MotionTableEntry* entry) { - MotionTableEntry* entry = mMotionEntries[i]; // check if the motion still is in the motion library, if not also remove it from the motion window plugin - if (EMotionFX::GetMotionManager().FindMotionIndexByID(entry->mMotionID) == MCORE_INVALIDINDEX32) - { - delete mMotionEntries[i]; - mMotionEntries.erase(mMotionEntries.begin() + i); - } - else + if (EMotionFX::GetMotionManager().FindMotionIndexByID(entry->m_motionId) == InvalidIndex) { - i++; + delete entry; + return true; } - } + return false; + }); // update the motion list window - mMotionListWindow->ReInit(); + m_motionListWindow->ReInit(); } void MotionWindowPlugin::UpdateMotions() { - mMotionRetargetingWindow->UpdateMotions(); + m_motionRetargetingWindow->UpdateMotions(); } void MotionWindowPlugin::UpdateInterface() { AZStd::vector& motionInstances = GetSelectedMotionInstances(); - const size_t numMotionInstances = motionInstances.size(); - for (size_t i = 0; i < numMotionInstances; ++i) + for (EMotionFX::MotionInstance* motionInstance : motionInstances) { - EMotionFX::MotionInstance* motionInstance = motionInstances[i]; EMotionFX::Motion* motion = motionInstance->GetMotion(); motionInstance->InitFromPlayBackInfo(*motion->GetDefaultPlayBackInfo(), false); @@ -530,93 +518,80 @@ namespace EMStudio const CommandSystem::SelectionList& selection = GetCommandManager()->GetCurrentSelection(); const bool hasSelectedMotions = selection.GetNumSelectedMotions() > 0; - if (mMotionNameLabel) + if (m_motionNameLabel) { MotionTableEntry* entry = hasSelectedMotions ? FindMotionEntryByID(selection.GetMotion(0)->GetID()) : nullptr; - EMotionFX::Motion* motion = entry ? entry->mMotion : nullptr; - mMotionNameLabel->setText(motion ? motion->GetName() : nullptr); + EMotionFX::Motion* motion = entry ? entry->m_motion : nullptr; + m_motionNameLabel->setText(motion ? motion->GetName() : nullptr); } - const uint32 numMotions = EMotionFX::GetMotionManager().GetNumMotions(); - - if (mSaveAction) + if (m_saveAction) { // related to the selected motions - mSaveAction->setEnabled(hasSelectedMotions); + m_saveAction->setEnabled(hasSelectedMotions); } - if (mMotionListWindow) + if (m_motionListWindow) { - mMotionListWindow->UpdateInterface(); + m_motionListWindow->UpdateInterface(); } - if (mMotionExtractionWindow) + if (m_motionExtractionWindow) { - mMotionExtractionWindow->UpdateInterface(); + m_motionExtractionWindow->UpdateInterface(); } - if (mMotionRetargetingWindow) + if (m_motionRetargetingWindow) { - mMotionRetargetingWindow->UpdateInterface(); + m_motionRetargetingWindow->UpdateInterface(); } } - void MotionWindowPlugin::VisibilityChanged(bool visible) + void MotionWindowPlugin::VisibilityChanged([[maybe_unused]] bool visible) { - if (visible) - { - //mMotionRetargetingWindow->UpdateSelection(); - //mMotionExtractionWindow->UpdateExtractionNodeLabel(); - } } AZStd::vector& MotionWindowPlugin::GetSelectedMotionInstances() { const CommandSystem::SelectionList& selectionList = CommandSystem::GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); - const uint32 numSelectedMotions = selectionList.GetNumSelectedMotions(); + const size_t numSelectedActorInstances = selectionList.GetNumSelectedActorInstances(); + const size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); - mInternalMotionInstanceSelection.clear(); + s_internalMotionInstanceSelection.clear(); - for (uint32 i = 0; i < numSelectedActorInstances; ++i) + for (size_t i = 0; i < numSelectedActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); EMotionFX::MotionSystem* motionSystem = actorInstance->GetMotionSystem(); - const uint32 numMotionInstances = motionSystem->GetNumMotionInstances(); + const size_t numMotionInstances = motionSystem->GetNumMotionInstances(); - for (uint32 j = 0; j < numSelectedMotions; ++j) + for (size_t j = 0; j < numSelectedMotions; ++j) { EMotionFX::Motion* motion = selectionList.GetMotion(j); - for (uint32 k = 0; k < numMotionInstances; ++k) + for (size_t k = 0; k < numMotionInstances; ++k) { EMotionFX::MotionInstance* motionInstance = motionSystem->GetMotionInstance(k); if (motionInstance->GetMotion() == motion) { - mInternalMotionInstanceSelection.push_back(motionInstance); + s_internalMotionInstanceSelection.push_back(motionInstance); } } } } - return mInternalMotionInstanceSelection; + return s_internalMotionInstanceSelection; } MotionWindowPlugin::MotionTableEntry* MotionWindowPlugin::FindMotionEntryByID(uint32 motionID) { - const size_t numMotionEntries = mMotionEntries.size(); - for (size_t i = 0; i < numMotionEntries; ++i) + const auto foundEntry = AZStd::find_if(begin(m_motionEntries), end(m_motionEntries), [motionID](const MotionTableEntry* entry) { - MotionTableEntry* entry = mMotionEntries[i]; - if (entry->mMotionID == motionID) - { - return entry; - } - } - - return nullptr; + return entry->m_motionId == motionID; + }); + return foundEntry != end(m_motionEntries) ? *foundEntry : nullptr; } @@ -633,16 +608,14 @@ namespace EMStudio AZStd::string command, commandParameters; MCore::CommandGroup commandGroup("Play motions"); - const size_t numMotions = motions.size(); - for (size_t i = 0; i < numMotions; ++i) + for (EMotionFX::Motion* motion : motions) { - EMotionFX::Motion* motion = motions[i]; EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo(); // Don't blend in and out of the for previewing animations. We might only see a short bit of it for animations smaller than the blend in/out time. - defaultPlayBackInfo->mBlendInTime = 0.0f; - defaultPlayBackInfo->mBlendOutTime = 0.0f; - defaultPlayBackInfo->mFreezeAtLastFrame = (defaultPlayBackInfo->mNumLoops != EMFX_LOOPFOREVER); + defaultPlayBackInfo->m_blendInTime = 0.0f; + defaultPlayBackInfo->m_blendOutTime = 0.0f; + defaultPlayBackInfo->m_freezeAtLastFrame = (defaultPlayBackInfo->m_numLoops != EMFX_LOOPFOREVER); commandParameters = CommandSystem::CommandPlayMotion::PlayBackInfoToCommandParameters(defaultPlayBackInfo); @@ -663,17 +636,17 @@ namespace EMStudio const CommandSystem::SelectionList& selection = CommandSystem::GetCommandManager()->GetCurrentSelection(); // get the number of selected motions - const uint32 numMotions = selection.GetNumSelectedMotions(); + const size_t numMotions = selection.GetNumSelectedMotions(); if (numMotions == 0) { return; } // create our remove motion command group - MCore::CommandGroup commandGroup(AZStd::string::format("Stop %u motion instances", numMotions).c_str()); + MCore::CommandGroup commandGroup(AZStd::string::format("Stop %zu motion instances", numMotions).c_str()); AZStd::string command; - for (uint32 i = 0; i < numMotions; ++i) + for (size_t i = 0; i < numMotions; ++i) { MotionWindowPlugin::MotionTableEntry* entry = FindMotionEntryByID(selection.GetMotion(i)->GetID()); if (entry == nullptr) @@ -682,7 +655,7 @@ namespace EMStudio continue; } - command = AZStd::string::format("StopMotionInstances -filename \"%s\"", entry->mMotion->GetFileName()); + command = AZStd::string::format("StopMotionInstances -filename \"%s\"", entry->m_motion->GetFileName()); commandGroup.AddCommandString(command); } @@ -696,76 +669,21 @@ namespace EMStudio void MotionWindowPlugin::Render(RenderPlugin* renderPlugin, EMStudioPlugin::RenderInfo* renderInfo) { - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; // make sure the render objects are valid if (renderPlugin == nullptr || renderUtil == nullptr) { return; } - /* - if (mMotionRetargetingWindow->GetRenderMotionBindPose()) - { - const CommandSystem::SelectionList& selection = CommandSystem::GetCommandManager()->GetCurrentSelection(); - - // get the number of selected actor instances and iterate through them - const uint32 numActorInstances = selection.GetNumSelectedActorInstances(); - for (uint32 j = 0; j < numActorInstances; ++j) - { - EMotionFX::ActorInstance* actorInstance = selection.GetActorInstance(j); - EMotionFX::Actor* actor = actorInstance->GetActor(); - - // get the number of selected motions and iterate through them - const uint32 numMotions = selection.GetNumSelectedMotions(); - for (uint32 i = 0; i < numMotions; ++i) - { - EMotionFX::Motion* motion = selection.GetMotion(i); - if (motion->GetType() == EMotionFX::SkeletalMotion::TYPE_ID) - { - EMotionFX::SkeletalMotion* skeletalMotion = (EMotionFX::SkeletalMotion*)motion; - - EMotionFX::AnimGraphPosePool& posePool = EMotionFX::GetEMotionFX().GetThreadData(0)->GetPosePool(); - EMotionFX::AnimGraphPose* pose = posePool.RequestPose(m_actorInstance); - - skeletalMotion->CalcMotionBindPose(actor, pose->GetPose()); - - // for all nodes in the actor - const uint32 numNodes = actorInstance->GetNumEnabledNodes(); - for (uint32 n = 0; n < numNodes; ++n) - { - EMotionFX::Node* curNode = actor->GetSkeleton()->GetNode(actorInstance->GetEnabledNode(n)); - - // skip root nodes, you could also use curNode->IsRootNode() - // but we use the parent index here, as we will reuse it - uint32 parentIndex = curNode->GetParentIndex(); - if (parentIndex == MCORE_INVALIDINDEX32) - { - AZ::Vector3 startPos = mGlobalMatrices[curNode->GetNodeIndex()].GetTranslation(); - AZ::Vector3 endPos = startPos + AZ::Vector3(0.0f, 3.0f, 0.0f); - renderUtil->RenderLine(startPos, endPos, MCore::RGBAColor(0.0f, 1.0f, 1.0f)); - } - else - { - AZ::Vector3 startPos = mGlobalMatrices[curNode->GetNodeIndex()].GetTranslation(); - AZ::Vector3 endPos = mGlobalMatrices[parentIndex].GetTranslation(); - renderUtil->RenderLine(startPos, endPos, MCore::RGBAColor(0.0f, 1.0f, 1.0f)); - } - } - - posePool.FreePose(pose); - } - } - } - } - */ } // constructor MotionWindowPlugin::MotionTableEntry::MotionTableEntry(EMotionFX::Motion* motion) { - mMotionID = motion->GetID(); - mMotion = motion; + m_motionId = motion->GetID(); + m_motion = motion; } @@ -911,7 +829,7 @@ namespace EMStudio { MCORE_UNUSED(commandLine); CommandSystem::CommandImportMotion* importMotionCommand = static_cast(command); - return CallbackAddMotionByID(importMotionCommand->mOldMotionID); + return CallbackAddMotionByID(importMotionCommand->m_oldMotionId); } @@ -929,7 +847,7 @@ namespace EMStudio { MCORE_UNUSED(commandLine); CommandSystem::CommandRemoveMotion* removeMotionCommand = static_cast(command); - return CallbackRemoveMotion(removeMotionCommand->mOldMotionID); + return CallbackRemoveMotion(removeMotionCommand->m_oldMotionId); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.h index 0bd181e63b..7f4ebc3e78 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/MotionWindow/MotionWindowPlugin.h @@ -71,22 +71,22 @@ namespace EMStudio MotionTableEntry(EMotionFX::Motion* motion); - EMotionFX::Motion* mMotion; - uint32 mMotionID; + EMotionFX::Motion* m_motion; + uint32 m_motionId; }; MotionTableEntry* FindMotionEntryByID(uint32 motionID); - MCORE_INLINE size_t GetNumMotionEntries() { return mMotionEntries.size(); } - MCORE_INLINE MotionTableEntry* GetMotionEntry(size_t index) { return mMotionEntries[index]; } + MCORE_INLINE size_t GetNumMotionEntries() { return m_motionEntries.size(); } + MCORE_INLINE MotionTableEntry* GetMotionEntry(size_t index) { return m_motionEntries[index]; } bool AddMotion(uint32 motionID); bool RemoveMotionByIndex(size_t index); bool RemoveMotionById(uint32 motionID); static AZStd::vector& GetSelectedMotionInstances(); - MCORE_INLINE MotionRetargetingWindow* GetMotionRetargetingWindow() { return mMotionRetargetingWindow; } - MCORE_INLINE MotionExtractionWindow* GetMotionExtractionWindow() { return mMotionExtractionWindow; } - MCORE_INLINE MotionListWindow* GetMotionListWindow() { return mMotionListWindow; } + MCORE_INLINE MotionRetargetingWindow* GetMotionRetargetingWindow() { return m_motionRetargetingWindow; } + MCORE_INLINE MotionExtractionWindow* GetMotionExtractionWindow() { return m_motionExtractionWindow; } + MCORE_INLINE MotionListWindow* GetMotionListWindow() { return m_motionListWindow; } MCORE_INLINE const char* GetDefaultNodeSelectionLabelText() { return "Click to select node"; } int OnSaveDirtyMotions(); @@ -121,21 +121,21 @@ namespace EMStudio AZStd::vector m_callbacks; - AZStd::vector mMotionEntries; + AZStd::vector m_motionEntries; - MysticQt::DialogStack* mDialogStack; - MotionListWindow* mMotionListWindow; - MotionPropertiesWindow* mMotionPropertiesWindow; - MotionExtractionWindow* mMotionExtractionWindow; - MotionRetargetingWindow* mMotionRetargetingWindow; + MysticQt::DialogStack* m_dialogStack; + MotionListWindow* m_motionListWindow; + MotionPropertiesWindow* m_motionPropertiesWindow; + MotionExtractionWindow* m_motionExtractionWindow; + MotionRetargetingWindow* m_motionRetargetingWindow; - SaveDirtyMotionFilesCallback* mDirtyFilesCallback; + SaveDirtyMotionFilesCallback* m_dirtyFilesCallback; - QAction* mAddMotionsAction; - QAction* mSaveAction; + QAction* m_addMotionsAction; + QAction* m_saveAction; - QLabel* mMotionNameLabel; + QLabel* m_motionNameLabel; - static AZStd::vector mInternalMotionInstanceSelection; + static AZStd::vector s_internalMotionInstanceSelection; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp index 84c281a18f..67aee6a5af 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp @@ -32,8 +32,8 @@ namespace EMStudio : QDialog(parent) { // store the values - mActor = actor; - mNodeGroupName = nodeGroupName; + m_actor = actor; + m_nodeGroupName = nodeGroupName; // set the window title setWindowTitle("Rename Node Group"); @@ -48,23 +48,23 @@ namespace EMStudio layout->addWidget(new QLabel("Please enter the new node group name:")); // add the line edit - mLineEdit = new QLineEdit(); - connect(mLineEdit, &QLineEdit::textEdited, this, &NodeGroupManagementRenameWindow::TextEdited); - layout->addWidget(mLineEdit); + m_lineEdit = new QLineEdit(); + connect(m_lineEdit, &QLineEdit::textEdited, this, &NodeGroupManagementRenameWindow::TextEdited); + layout->addWidget(m_lineEdit); // set the current name and select all - mLineEdit->setText(nodeGroupName.c_str()); - mLineEdit->selectAll(); + m_lineEdit->setText(nodeGroupName.c_str()); + m_lineEdit->selectAll(); // create the button layout QHBoxLayout* buttonLayout = new QHBoxLayout(); - mOKButton = new QPushButton("OK"); + m_okButton = new QPushButton("OK"); QPushButton* cancelButton = new QPushButton("Cancel"); - buttonLayout->addWidget(mOKButton); + buttonLayout->addWidget(m_okButton); buttonLayout->addWidget(cancelButton); // connect the buttons - connect(mOKButton, &QPushButton::clicked, this, &NodeGroupManagementRenameWindow::Accepted); + connect(m_okButton, &QPushButton::clicked, this, &NodeGroupManagementRenameWindow::Accepted); connect(cancelButton, &QPushButton::clicked, this, &NodeGroupManagementRenameWindow::reject); // set the new layout @@ -78,44 +78,42 @@ namespace EMStudio const AZStd::string convertedNewName = text.toUtf8().data(); if (text.isEmpty()) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); } - else if (mNodeGroupName == convertedNewName) + else if (m_nodeGroupName == convertedNewName) { - //mErrorMsg->setVisible(false); - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } else { // find duplicate name, it can't be the same name because we already handle this case before - EMotionFX::NodeGroup* nodeGroup = mActor->FindNodeGroupByName(convertedNewName.c_str()); + EMotionFX::NodeGroup* nodeGroup = m_actor->FindNodeGroupByName(convertedNewName.c_str()); if (nodeGroup) { - mOKButton->setEnabled(false); - GetManager()->SetWidgetAsInvalidInput(mLineEdit); + m_okButton->setEnabled(false); + GetManager()->SetWidgetAsInvalidInput(m_lineEdit); return; } // no duplicate name found - mOKButton->setEnabled(true); - mLineEdit->setStyleSheet(""); + m_okButton->setEnabled(true); + m_lineEdit->setStyleSheet(""); } } void NodeGroupManagementRenameWindow::Accepted() { - const AZStd::string convertedNewName = mLineEdit->text().toUtf8().data(); + const AZStd::string convertedNewName = m_lineEdit->text().toUtf8().data(); // execute the command AZStd::string outResult; auto* command = aznew CommandSystem::CommandAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), - /*actorId=*/ mActor->GetID(), - /*name=*/ mNodeGroupName, + /*actorId=*/ m_actor->GetID(), + /*name=*/ m_nodeGroupName, /*newName=*/ convertedNewName ); if (GetCommandManager()->ExecuteCommand(command, outResult) == false) @@ -133,11 +131,11 @@ namespace EMStudio : QWidget(parent) { // init the button variables to nullptr - mAddButton = nullptr; - mRemoveButton = nullptr; - mClearButton = nullptr; - mNodeGroupsTable = nullptr; - mSelectedRow = MCORE_INVALIDINDEX32; + m_addButton = nullptr; + m_removeButton = nullptr; + m_clearButton = nullptr; + m_nodeGroupsTable = nullptr; + m_selectedRow = MCORE_INVALIDINDEX32; // set the node group widget SetNodeGroupWidget(nodeGroupWidget); @@ -157,20 +155,20 @@ namespace EMStudio void NodeGroupManagementWidget::Init() { // create the node groups table - mNodeGroupsTable = new QTableWidget(); + m_nodeGroupsTable = new QTableWidget(); // create the table widget - mNodeGroupsTable->setAlternatingRowColors(true); - mNodeGroupsTable->setCornerButtonEnabled(false); - mNodeGroupsTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mNodeGroupsTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_nodeGroupsTable->setAlternatingRowColors(true); + m_nodeGroupsTable->setCornerButtonEnabled(false); + m_nodeGroupsTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_nodeGroupsTable->setContextMenuPolicy(Qt::DefaultContextMenu); // set the table to row single selection - mNodeGroupsTable->setSelectionBehavior(QAbstractItemView::SelectRows); - mNodeGroupsTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_nodeGroupsTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_nodeGroupsTable->setSelectionMode(QAbstractItemView::SingleSelection); // set the column count - mNodeGroupsTable->setColumnCount(3); + m_nodeGroupsTable->setColumnCount(3); // set header items for the table QTableWidgetItem* enabledHeaderItem = new QTableWidgetItem(""); @@ -178,44 +176,44 @@ namespace EMStudio QTableWidgetItem* numNodesHeaderItem = new QTableWidgetItem("Num Nodes"); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); numNodesHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mNodeGroupsTable->setHorizontalHeaderItem(0, enabledHeaderItem); - mNodeGroupsTable->setHorizontalHeaderItem(1, nameHeaderItem); - mNodeGroupsTable->setHorizontalHeaderItem(2, numNodesHeaderItem); + m_nodeGroupsTable->setHorizontalHeaderItem(0, enabledHeaderItem); + m_nodeGroupsTable->setHorizontalHeaderItem(1, nameHeaderItem); + m_nodeGroupsTable->setHorizontalHeaderItem(2, numNodesHeaderItem); // set the first column fixed - QHeaderView* horizontalHeader = mNodeGroupsTable->horizontalHeader(); - mNodeGroupsTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); - mNodeGroupsTable->setColumnWidth(0, 19); + QHeaderView* horizontalHeader = m_nodeGroupsTable->horizontalHeader(); + m_nodeGroupsTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Fixed); + m_nodeGroupsTable->setColumnWidth(0, 19); // set the name column width - mNodeGroupsTable->setColumnWidth(1, 150); + m_nodeGroupsTable->setColumnWidth(1, 150); // set the vertical columns not visible - QHeaderView* verticalHeader = mNodeGroupsTable->verticalHeader(); + QHeaderView* verticalHeader = m_nodeGroupsTable->verticalHeader(); verticalHeader->setVisible(false); // set the last column to take the whole space horizontalHeader->setStretchLastSection(true); // disable editing - mNodeGroupsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_nodeGroupsTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // create buttons - mAddButton = new QPushButton(); - mRemoveButton = new QPushButton(); - mClearButton = new QPushButton(); + m_addButton = new QPushButton(); + m_removeButton = new QPushButton(); + m_clearButton = new QPushButton(); - EMStudioManager::MakeTransparentButton(mAddButton, "Images/Icons/Plus.svg", "Add a new node group"); - EMStudioManager::MakeTransparentButton(mRemoveButton, "Images/Icons/Minus.svg", "Remove selected node groups"); - EMStudioManager::MakeTransparentButton(mClearButton, "Images/Icons/Clear.svg", "Remove all node groups"); + EMStudioManager::MakeTransparentButton(m_addButton, "Images/Icons/Plus.svg", "Add a new node group"); + EMStudioManager::MakeTransparentButton(m_removeButton, "Images/Icons/Minus.svg", "Remove selected node groups"); + EMStudioManager::MakeTransparentButton(m_clearButton, "Images/Icons/Clear.svg", "Remove all node groups"); // add the buttons to the button layout QHBoxLayout* buttonLayout = new QHBoxLayout(); buttonLayout->setSpacing(0); buttonLayout->setAlignment(Qt::AlignLeft); - buttonLayout->addWidget(mAddButton); - buttonLayout->addWidget(mRemoveButton); - buttonLayout->addWidget(mClearButton); + buttonLayout->addWidget(m_addButton); + buttonLayout->addWidget(m_removeButton); + buttonLayout->addWidget(m_clearButton); // create the layouts QVBoxLayout* layout = new QVBoxLayout(); @@ -226,18 +224,16 @@ namespace EMStudio // add widgets to the main layout layout->addLayout(buttonLayout); - layout->addWidget(mNodeGroupsTable); + layout->addWidget(m_nodeGroupsTable); // set the main layout setLayout(layout); // connect controls to the slots - connect(mAddButton, &QPushButton::clicked, this, &NodeGroupManagementWidget::AddNodeGroup); - connect(mRemoveButton, &QPushButton::clicked, this, &NodeGroupManagementWidget::RemoveSelectedNodeGroup); - connect(mClearButton, &QPushButton::clicked, this, &NodeGroupManagementWidget::ClearNodeGroups); - connect(mNodeGroupsTable, &QTableWidget::itemSelectionChanged, this, &NodeGroupManagementWidget::UpdateNodeGroupWidget); - //connect( mNodeGroupsTable, SIGNAL(currentItemChanged(QTableWidgetItem*, QTableWidgetItem*)), this, SLOT(UpdateNodeGroupWidget(QTableWidgetItem*, QTableWidgetItem*)) ); - //connect( mNodeGroupsTable, SIGNAL(itemDoubleClicked(QTableWidgetItem*)), this, SLOT(NodeGroupeNameDoubleClicked(QTableWidgetItem*)) ); + connect(m_addButton, &QPushButton::clicked, this, &NodeGroupManagementWidget::AddNodeGroup); + connect(m_removeButton, &QPushButton::clicked, this, &NodeGroupManagementWidget::RemoveSelectedNodeGroup); + connect(m_clearButton, &QPushButton::clicked, this, &NodeGroupManagementWidget::ClearNodeGroups); + connect(m_nodeGroupsTable, &QTableWidget::itemSelectionChanged, this, &NodeGroupManagementWidget::UpdateNodeGroupWidget); } @@ -245,35 +241,35 @@ namespace EMStudio void NodeGroupManagementWidget::UpdateInterface() { // check if the current actor exists - if (mActor == nullptr) + if (m_actor == nullptr) { // remove all rows - mNodeGroupsTable->setRowCount(0); + m_nodeGroupsTable->setRowCount(0); // disable the controls - mAddButton->setDisabled(true); - mRemoveButton->setDisabled(true); - mClearButton->setDisabled(true); + m_addButton->setDisabled(true); + m_removeButton->setDisabled(true); + m_clearButton->setDisabled(true); // stop here return; } // enable/disable the controls - mAddButton->setDisabled(false); - const bool disableButtons = mActor->GetNumNodeGroups() == 0; - mRemoveButton->setDisabled(disableButtons); - mClearButton->setDisabled(disableButtons); + m_addButton->setDisabled(false); + const bool disableButtons = m_actor->GetNumNodeGroups() == 0; + m_removeButton->setDisabled(disableButtons); + m_clearButton->setDisabled(disableButtons); // set the row count - mNodeGroupsTable->setRowCount(mActor->GetNumNodeGroups()); + m_nodeGroupsTable->setRowCount(m_actor->GetNumNodeGroups()); // fill the table with the existing node groups - const uint32 numNodeGroups = mActor->GetNumNodeGroups(); + const uint32 numNodeGroups = m_actor->GetNumNodeGroups(); for (uint32 i = 0; i < numNodeGroups; ++i) { // get the nodegroup - EMotionFX::NodeGroup* nodeGroup = mActor->GetNodeGroup(i); + EMotionFX::NodeGroup* nodeGroup = m_actor->GetNodeGroup(i); // continue if node group does not exist if (nodeGroup == nullptr) @@ -295,18 +291,18 @@ namespace EMStudio QTableWidgetItem* tableItemNumNodes = new QTableWidgetItem(numGroupString.c_str()); // add items to the table - mNodeGroupsTable->setCellWidget(i, 0, checkbox); - mNodeGroupsTable->setItem(i, 1, tableItemGroupName); - mNodeGroupsTable->setItem(i, 2, tableItemNumNodes); + m_nodeGroupsTable->setCellWidget(i, 0, checkbox); + m_nodeGroupsTable->setItem(i, 1, tableItemGroupName); + m_nodeGroupsTable->setItem(i, 2, tableItemNumNodes); // set the row height - mNodeGroupsTable->setRowHeight(i, 21); + m_nodeGroupsTable->setRowHeight(i, 21); } // set the old selected row if any one - if (mSelectedRow != MCORE_INVALIDINDEX32) + if (m_selectedRow != MCORE_INVALIDINDEX32) { - mNodeGroupsTable->setCurrentCell(mSelectedRow, 0); + m_nodeGroupsTable->setCurrentCell(m_selectedRow, 0); } } @@ -315,7 +311,7 @@ namespace EMStudio void NodeGroupManagementWidget::SetActor(EMotionFX::Actor* actor) { // set the new actor - mActor = actor; + m_actor = actor; // update the interface UpdateInterface(); @@ -326,7 +322,7 @@ namespace EMStudio void NodeGroupManagementWidget::SetNodeGroupWidget(NodeGroupWidget* nodeGroupWidget) { // set the node group widget - mNodeGroupWidget = nodeGroupWidget; + m_nodeGroupWidget = nodeGroupWidget; } @@ -334,37 +330,37 @@ namespace EMStudio void NodeGroupManagementWidget::UpdateNodeGroupWidget() { // return if no node group widget is set - if (mNodeGroupWidget == nullptr) + if (m_nodeGroupWidget == nullptr) { return; } // set the node group widget to the actual selection - mNodeGroupWidget->SetActor(mActor); + m_nodeGroupWidget->SetActor(m_actor); // return if the actor is not valid - if (mActor == nullptr) + if (m_actor == nullptr) { return; } // get the current row - const int currentRow = mNodeGroupsTable->currentRow(); + const int currentRow = m_nodeGroupsTable->currentRow(); // check if the row is valid if (currentRow != -1) { // set the current row - mSelectedRow = currentRow; + m_selectedRow = currentRow; // set the node group - EMotionFX::NodeGroup* nodeGroup = mActor->FindNodeGroupByName(FromQtString(mNodeGroupsTable->item(mSelectedRow, 1)->text()).c_str()); - mNodeGroupWidget->SetNodeGroup(nodeGroup); + EMotionFX::NodeGroup* nodeGroup = m_actor->FindNodeGroupByName(FromQtString(m_nodeGroupsTable->item(m_selectedRow, 1)->text()).c_str()); + m_nodeGroupWidget->SetNodeGroup(nodeGroup); } else { - mNodeGroupWidget->SetNodeGroup(nullptr); - mSelectedRow = MCORE_INVALIDINDEX32; + m_nodeGroupWidget->SetNodeGroup(nullptr); + m_selectedRow = MCORE_INVALIDINDEX32; } } @@ -375,7 +371,7 @@ namespace EMStudio // find the node group index to add uint32 groupNumber = 0; AZStd::string groupName = AZStd::string::format("UnnamedNodeGroup%i", groupNumber); - while (SearchTableForString(mNodeGroupsTable, groupName.c_str(), true) >= 0) + while (SearchTableForString(m_nodeGroupsTable, groupName.c_str(), true) >= 0) { ++groupNumber; groupName = AZStd::string::format("UnnamedNodeGroup%i", groupNumber); @@ -383,20 +379,15 @@ namespace EMStudio // call command for adding a new node group AZStd::string outResult; - const AZStd::string command = AZStd::string::format("AddNodeGroup -actorID %i -name \"%s\"", mActor->GetID(), groupName.c_str()); + const AZStd::string command = AZStd::string::format("AddNodeGroup -actorID %i -name \"%s\"", m_actor->GetID(), groupName.c_str()); if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) { AZ_Error("EMotionFX", false, outResult.c_str()); } // select the new added row - const int insertPosition = SearchTableForString(mNodeGroupsTable, groupName.c_str()); - mNodeGroupsTable->selectRow(insertPosition); - - // find insert position - /*int insertPosition = SearchTableForString( mNodeGroupsTable, groupName.c_str() ); - if (insertPosition >= 0) - NodeGroupeNameDoubleClicked( mNodeGroupsTable->item(insertPosition, 0) );*/ + const int insertPosition = SearchTableForString(m_nodeGroupsTable, groupName.c_str()); + m_nodeGroupsTable->selectRow(insertPosition); } @@ -404,38 +395,38 @@ namespace EMStudio void NodeGroupManagementWidget::RemoveSelectedNodeGroup() { // set the node group of the node group widget to nullptr - if (mNodeGroupWidget) + if (m_nodeGroupWidget) { - mNodeGroupWidget->SetNodeGroup(nullptr); + m_nodeGroupWidget->SetNodeGroup(nullptr); } // return if there is no entry to delete - const int currentRow = mNodeGroupsTable->currentRow(); + const int currentRow = m_nodeGroupsTable->currentRow(); if (currentRow < 0) { return; } // get the nodegroup - QTableWidgetItem* item = mNodeGroupsTable->item(currentRow, 1); - EMotionFX::NodeGroup* nodeGroup = mActor->FindNodeGroupByName(FromQtString(item->text()).c_str()); + QTableWidgetItem* item = m_nodeGroupsTable->item(currentRow, 1); + EMotionFX::NodeGroup* nodeGroup = m_actor->FindNodeGroupByName(FromQtString(item->text()).c_str()); // call command for removing a nodegroup AZStd::string outResult; - const AZStd::string command = AZStd::string::format("RemoveNodeGroup -actorID %i -name \"%s\"", mActor->GetID(), nodeGroup->GetName()); + const AZStd::string command = AZStd::string::format("RemoveNodeGroup -actorID %i -name \"%s\"", m_actor->GetID(), nodeGroup->GetName()); if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) { AZ_Error("EMotionFX", false, outResult.c_str()); } // selected the next row - if (currentRow > (mNodeGroupsTable->rowCount() - 1)) + if (currentRow > (m_nodeGroupsTable->rowCount() - 1)) { - mNodeGroupsTable->selectRow(currentRow - 1); + m_nodeGroupsTable->selectRow(currentRow - 1); } else { - mNodeGroupsTable->selectRow(currentRow); + m_nodeGroupsTable->selectRow(currentRow); } } @@ -444,11 +435,11 @@ namespace EMStudio void NodeGroupManagementWidget::RenameSelectedNodeGroup() { // get the nodegroup - QTableWidgetItem* item = mNodeGroupsTable->item(mNodeGroupsTable->currentRow(), 1); - EMotionFX::NodeGroup* nodeGroup = mActor->FindNodeGroupByName(FromQtString(item->text()).c_str()); + QTableWidgetItem* item = m_nodeGroupsTable->item(m_nodeGroupsTable->currentRow(), 1); + EMotionFX::NodeGroup* nodeGroup = m_actor->FindNodeGroupByName(FromQtString(item->text()).c_str()); // show the rename window - NodeGroupManagementRenameWindow nodeGroupManagementRenameWindow(this, mActor, nodeGroup->GetName()); + NodeGroupManagementRenameWindow nodeGroupManagementRenameWindow(this, m_actor, nodeGroup->GetName()); nodeGroupManagementRenameWindow.exec(); } @@ -456,7 +447,7 @@ namespace EMStudio // function to clear the nodegroups void NodeGroupManagementWidget::ClearNodeGroups() { - CommandSystem::ClearNodeGroupsCommand(mActor); + CommandSystem::ClearNodeGroupsCommand(m_actor); } @@ -468,13 +459,13 @@ namespace EMStudio // find the checkbox row AZStd::string nodeGroupName; - const int rowCount = mNodeGroupsTable->rowCount(); + const int rowCount = m_nodeGroupsTable->rowCount(); for (int i = 0; i < rowCount; ++i) { - QCheckBox* rowChechbox = (QCheckBox*)mNodeGroupsTable->cellWidget(i, 0); + QCheckBox* rowChechbox = (QCheckBox*)m_nodeGroupsTable->cellWidget(i, 0); if (rowChechbox == senderCheckbox) { - nodeGroupName = mNodeGroupsTable->item(i, 1)->text().toUtf8().data(); + nodeGroupName = m_nodeGroupsTable->item(i, 1)->text().toUtf8().data(); break; } } @@ -483,7 +474,7 @@ namespace EMStudio AZStd::string outResult; auto* command = aznew CommandSystem::CommandAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), - /*actorId=*/ mActor->GetID(), + /*actorId=*/ m_actor->GetID(), /*name=*/ nodeGroupName, /*newName=*/ AZStd::nullopt, /*enabledOnDefault=*/ checked @@ -560,13 +551,13 @@ namespace EMStudio void NodeGroupManagementWidget::contextMenuEvent(QContextMenuEvent* event) { // if the actor is not valid, the node group management is disabled - if (mActor == nullptr) + if (m_actor == nullptr) { return; } // get the current selection - const QList selectedItems = mNodeGroupsTable->selectedItems(); + const QList selectedItems = m_nodeGroupsTable->selectedItems(); // get the number of selected items const uint32 numSelectedItems = selectedItems.count(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.h index a7a8616edc..37f92346e4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.h @@ -39,10 +39,10 @@ namespace EMStudio void Accepted(); private: - EMotionFX::Actor* mActor; - AZStd::string mNodeGroupName; - QLineEdit* mLineEdit; - QPushButton* mOKButton; + EMotionFX::Actor* m_actor; + AZStd::string m_nodeGroupName; + QLineEdit* m_lineEdit; + QPushButton* m_okButton; }; @@ -91,21 +91,21 @@ namespace EMStudio private: // pointer to the nodegroup widget - NodeGroupWidget* mNodeGroupWidget; + NodeGroupWidget* m_nodeGroupWidget; // searches for the given text in the table int SearchTableForString(QTableWidget* tableWidget, const QString& text, bool ignoreCurrentSelection = false); // the actor - EMotionFX::Actor* mActor; + EMotionFX::Actor* m_actor; // the listbox - QTableWidget* mNodeGroupsTable; - uint32 mSelectedRow; + QTableWidget* m_nodeGroupsTable; + uint32 m_selectedRow; // the buttons - QPushButton* mAddButton; - QPushButton* mRemoveButton; - QPushButton* mClearButton; + QPushButton* m_addButton; + QPushButton* m_removeButton; + QPushButton* m_clearButton; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp index 39ee1c4f5b..7ce09a55d7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp @@ -9,6 +9,8 @@ // inlude required headers #include "NodeGroupWidget.h" #include "../../../../EMStudioSDK/Source/EMStudioManager.h" +#include +#include #include #include @@ -31,10 +33,9 @@ namespace EMStudio NodeGroupWidget::NodeGroupWidget(QWidget* parent) : QWidget(parent) { - //mEnabledOnDefaultCheckbox = nullptr; - mNodeTable = nullptr; - mSelectNodesButton = nullptr; - mNodeGroup = nullptr; + m_nodeTable = nullptr; + m_selectNodesButton = nullptr; + m_nodeGroup = nullptr; // init the widget Init(); @@ -50,60 +51,48 @@ namespace EMStudio // the init function void NodeGroupWidget::Init() { - // create the disable checkbox - //mEnabledOnDefaultCheckbox = new QCheckBox( "Enabled On Default" ); - - // edit field for the group name - //mNodeGroupNameEdit = new QLineEdit(); - // create the node groups table - mNodeTable = new QTableWidget(0, 1, 0); + m_nodeTable = new QTableWidget(0, 1, 0); // create the table widget - mNodeTable->setCornerButtonEnabled(false); - mNodeTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); - mNodeTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_nodeTable->setCornerButtonEnabled(false); + m_nodeTable->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + m_nodeTable->setContextMenuPolicy(Qt::DefaultContextMenu); // set the table to row selection - mNodeTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_nodeTable->setSelectionBehavior(QAbstractItemView::SelectRows); // make the table items read only - mNodeTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_nodeTable->setEditTriggers(QAbstractItemView::NoEditTriggers); // set header items for the table QTableWidgetItem* nameHeaderItem = new QTableWidgetItem("Nodes"); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); + m_nodeTable->setHorizontalHeaderItem(0, nameHeaderItem); - QHeaderView* horizontalHeader = mNodeTable->horizontalHeader(); + QHeaderView* horizontalHeader = m_nodeTable->horizontalHeader(); horizontalHeader->setStretchLastSection(true); // create the node selection window - mNodeSelectionWindow = new NodeSelectionWindow(this, false); + m_nodeSelectionWindow = new NodeSelectionWindow(this, false); // create the selection buttons - mSelectNodesButton = new QPushButton(); - mAddNodesButton = new QPushButton(); - mRemoveNodesButton = new QPushButton(); + m_selectNodesButton = new QPushButton(); + m_addNodesButton = new QPushButton(); + m_removeNodesButton = new QPushButton(); - EMStudioManager::MakeTransparentButton(mSelectNodesButton, "Images/Icons/Plus.svg", "Select nodes and replace the current selection"); - EMStudioManager::MakeTransparentButton(mAddNodesButton, "Images/Icons/Plus.svg", "Select nodes and add them to the current selection"); - EMStudioManager::MakeTransparentButton(mRemoveNodesButton, "Images/Icons/Minus.svg", "Remove selected nodes from the list"); + EMStudioManager::MakeTransparentButton(m_selectNodesButton, "Images/Icons/Plus.svg", "Select nodes and replace the current selection"); + EMStudioManager::MakeTransparentButton(m_addNodesButton, "Images/Icons/Plus.svg", "Select nodes and add them to the current selection"); + EMStudioManager::MakeTransparentButton(m_removeNodesButton, "Images/Icons/Minus.svg", "Remove selected nodes from the list"); // create the buttons layout QHBoxLayout* buttonLayout = new QHBoxLayout(); buttonLayout->setSpacing(0); buttonLayout->setAlignment(Qt::AlignLeft); - buttonLayout->addWidget(mSelectNodesButton); - buttonLayout->addWidget(mAddNodesButton); - buttonLayout->addWidget(mRemoveNodesButton); - - // create layout for the edit field - /*QHBoxLayout* editLayout = new QHBoxLayout(); - editLayout->addWidget( new QLabel("Name:") ); - editLayout->addWidget( mNodeGroupNameEdit ); - editLayout->addWidget( mEnabledOnDefaultCheckbox );*/ + buttonLayout->addWidget(m_selectNodesButton); + buttonLayout->addWidget(m_addNodesButton); + buttonLayout->addWidget(m_removeNodesButton); // create the layouts QVBoxLayout* layout = new QVBoxLayout(); @@ -114,7 +103,7 @@ namespace EMStudio tableLayout->setMargin(0); tableLayout->addLayout(buttonLayout); - tableLayout->addWidget(mNodeTable); + tableLayout->addWidget(m_nodeTable); layout->addLayout(tableLayout); //layout->addLayout( editLayout ); @@ -123,15 +112,12 @@ namespace EMStudio setLayout(layout); // connect controls to the slots - connect(mSelectNodesButton, &QPushButton::clicked, this, &NodeGroupWidget::SelectNodesButtonPressed); - connect(mAddNodesButton, &QPushButton::clicked, this, &NodeGroupWidget::SelectNodesButtonPressed); - connect(mRemoveNodesButton, &QPushButton::clicked, this, &NodeGroupWidget::RemoveNodesButtonPressed); - connect(mNodeTable, &QTableWidget::itemSelectionChanged, this, &NodeGroupWidget::OnItemSelectionChanged); - //connect( mEnabledOnDefaultCheckbox, SIGNAL(clicked()), this, SLOT(EnabledOnDefaultChanged()) ); - //connect( mNodeGroupNameEdit, SIGNAL(editingFinished()), this, SLOT(NodeGroupNameEditingFinished()) ); - //connect( mNodeGroupNameEdit, SIGNAL(textChanged(QString)), this, SLOT(NodeGroupNameEditChanged(QString)) ); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnSelectionDone), this, &NodeGroupWidget::NodeSelectionFinished); - connect(mNodeSelectionWindow->GetNodeHierarchyWidget(), static_cast)>(&NodeHierarchyWidget::OnDoubleClicked), this, &NodeGroupWidget::NodeSelectionFinished); + connect(m_selectNodesButton, &QPushButton::clicked, this, &NodeGroupWidget::SelectNodesButtonPressed); + connect(m_addNodesButton, &QPushButton::clicked, this, &NodeGroupWidget::SelectNodesButtonPressed); + connect(m_removeNodesButton, &QPushButton::clicked, this, &NodeGroupWidget::RemoveNodesButtonPressed); + connect(m_nodeTable, &QTableWidget::itemSelectionChanged, this, &NodeGroupWidget::OnItemSelectionChanged); + connect(m_nodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnSelectionDone, this, &NodeGroupWidget::NodeSelectionFinished); + connect(m_nodeSelectionWindow->GetNodeHierarchyWidget(), &NodeHierarchyWidget::OnDoubleClicked, this, &NodeGroupWidget::NodeSelectionFinished); } @@ -139,48 +125,45 @@ namespace EMStudio void NodeGroupWidget::UpdateInterface() { // clear the table widget - mNodeTable->clear(); + m_nodeTable->clear(); // check if the node group is not valid - if (mNodeGroup == nullptr) + if (m_nodeGroup == nullptr) { // set the column count - mNodeTable->setColumnCount(0); + m_nodeTable->setColumnCount(0); // disable the widgets SetWidgetEnabled(false); - // clear the edit field - //mNodeGroupNameEdit->setText( "" ); - // stop here return; } // set the column count - mNodeTable->setColumnCount(1); + m_nodeTable->setColumnCount(1); // enable the widget SetWidgetEnabled(true); // set the remove nodes button enabled or not based on selection - mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); + m_removeNodesButton->setEnabled((m_nodeTable->rowCount() != 0) && (m_nodeTable->selectedItems().size() != 0)); // clear the table widget - mNodeTable->setRowCount(mNodeGroup->GetNumNodes()); + m_nodeTable->setRowCount(m_nodeGroup->GetNumNodes()); // set header items for the table - AZStd::string headerText = AZStd::string::format("%s Nodes (%i / %i)", ((mNodeGroup->GetIsEnabledOnDefault()) ? "Enabled" : "Disabled"), mNodeGroup->GetNumNodes(), mActor->GetNumNodes()); + AZStd::string headerText = AZStd::string::format("%s Nodes (%i / %zu)", ((m_nodeGroup->GetIsEnabledOnDefault()) ? "Enabled" : "Disabled"), m_nodeGroup->GetNumNodes(), m_actor->GetNumNodes()); QTableWidgetItem* nameHeaderItem = new QTableWidgetItem(headerText.c_str()); nameHeaderItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignCenter); - mNodeTable->setHorizontalHeaderItem(0, nameHeaderItem); + m_nodeTable->setHorizontalHeaderItem(0, nameHeaderItem); // fill the table with content - const uint16 numNodes = mNodeGroup->GetNumNodes(); + const uint16 numNodes = m_nodeGroup->GetNumNodes(); for (uint16 i = 0; i < numNodes; ++i) { // get the nodegroup - EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(mNodeGroup->GetNode(i)); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(m_nodeGroup->GetNode(i)); // continue if node does not exist if (node == nullptr) @@ -190,23 +173,23 @@ namespace EMStudio // create table items QTableWidgetItem* tableItemNodeName = new QTableWidgetItem(node->GetName()); - mNodeTable->setItem(i, 0, tableItemNodeName); + m_nodeTable->setItem(i, 0, tableItemNodeName); // set the row height - mNodeTable->setRowHeight(i, 21); + m_nodeTable->setRowHeight(i, 21); } // resize to contents and adjust header - QHeaderView* verticalHeader = mNodeTable->verticalHeader(); + QHeaderView* verticalHeader = m_nodeTable->verticalHeader(); verticalHeader->setVisible(false); - mNodeTable->resizeColumnsToContents(); - mNodeTable->horizontalHeader()->setStretchLastSection(true); + m_nodeTable->resizeColumnsToContents(); + m_nodeTable->horizontalHeader()->setStretchLastSection(true); // set table size - mNodeTable->setColumnWidth(0, 37); - mNodeTable->setColumnWidth(3, 0); - mNodeTable->setColumnHidden(3, true); - mNodeTable->sortItems(3); + m_nodeTable->setColumnWidth(0, 37); + m_nodeTable->setColumnWidth(3, 0); + m_nodeTable->setColumnHidden(3, true); + m_nodeTable->sortItems(3); } @@ -214,14 +197,14 @@ namespace EMStudio void NodeGroupWidget::SetNodeGroup(EMotionFX::NodeGroup* nodeGroup) { // check if the actor was set - if (mActor == nullptr) + if (m_actor == nullptr) { - mNodeGroup = nullptr; + m_nodeGroup = nullptr; return; } // set the node group - mNodeGroup = nodeGroup; + m_nodeGroup = nodeGroup; // update the interface UpdateInterface(); @@ -232,8 +215,8 @@ namespace EMStudio void NodeGroupWidget::SetActor(EMotionFX::Actor* actor) { // set the new actor - mActor = actor; - mNodeGroup = nullptr; + m_actor = actor; + m_nodeGroup = nullptr; // update the interface UpdateInterface(); @@ -244,20 +227,20 @@ namespace EMStudio void NodeGroupWidget::SelectNodesButtonPressed() { // check if node group is set - if (mNodeGroup == nullptr) + if (m_nodeGroup == nullptr) { return; } // set the action for the selected nodes QWidget* senderWidget = (QWidget*)sender(); - if (senderWidget == mAddNodesButton) + if (senderWidget == m_addNodesButton) { - mNodeAction = CommandSystem::CommandAdjustNodeGroup::NodeAction::Add; + m_nodeAction = CommandSystem::CommandAdjustNodeGroup::NodeAction::Add; } else { - mNodeAction = CommandSystem::CommandAdjustNodeGroup::NodeAction::Replace; + m_nodeAction = CommandSystem::CommandAdjustNodeGroup::NodeAction::Replace; } // get the selected actorinstance @@ -271,28 +254,28 @@ namespace EMStudio } // create selection list for the current nodes within the group - mNodeSelectionList.Clear(); - if (senderWidget == mSelectNodesButton) + m_nodeSelectionList.Clear(); + if (senderWidget == m_selectNodesButton) { - MCore::SmallArray& nodes = mNodeGroup->GetNodeArray(); + MCore::SmallArray& nodes = m_nodeGroup->GetNodeArray(); const uint16 numNodes = nodes.GetLength(); for (uint16 i = 0; i < numNodes; ++i) { - EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(nodes[i]); - mNodeSelectionList.AddNode(node); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(nodes[i]); + m_nodeSelectionList.AddNode(node); } } // show the node selection window - mNodeSelectionWindow->Update(actorInstance->GetID(), &mNodeSelectionList); - mNodeSelectionWindow->show(); + m_nodeSelectionWindow->Update(actorInstance->GetID(), &m_nodeSelectionList); + m_nodeSelectionWindow->show(); } // remove nodes void NodeGroupWidget::RemoveNodesButtonPressed() { - if (mNodeTable->selectedItems().empty()) + if (m_nodeTable->selectedItems().empty()) { return; } @@ -300,7 +283,7 @@ namespace EMStudio // generate node list string AZStd::vector nodeList; int lowestSelectedRow = AZStd::numeric_limits::max(); - for (const QTableWidgetItem* item : mNodeTable->selectedItems()) + for (const QTableWidgetItem* item : m_nodeTable->selectedItems()) { nodeList.emplace_back(FromQtString(item->text())); lowestSelectedRow = AZStd::min(lowestSelectedRow, item->row()); @@ -309,8 +292,8 @@ namespace EMStudio AZStd::string outResult; auto* command = aznew CommandSystem::CommandAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), - /*actorId=*/ mActor->GetID(), - /*name=*/ mNodeGroup->GetName(), + /*actorId=*/ m_actor->GetID(), + /*name=*/ m_nodeGroup->GetName(), /*newName=*/ AZStd::nullopt, /*enabledOnDefault=*/ AZStd::nullopt, /*nodeNames=*/ AZStd::move(nodeList), @@ -322,43 +305,43 @@ namespace EMStudio } // selected the next row - if (lowestSelectedRow > (mNodeTable->rowCount() - 1)) + if (lowestSelectedRow > (m_nodeTable->rowCount() - 1)) { - mNodeTable->selectRow(lowestSelectedRow - 1); + m_nodeTable->selectRow(lowestSelectedRow - 1); } else { - mNodeTable->selectRow(lowestSelectedRow); + m_nodeTable->selectRow(lowestSelectedRow); } } // add / select nodes - void NodeGroupWidget::NodeSelectionFinished(MCore::Array selectionList) + void NodeGroupWidget::NodeSelectionFinished(const AZStd::vector& selectionList) { // return if no nodes are selected - if (selectionList.GetLength() == 0) + if (selectionList.empty()) { return; } // generate node list string AZStd::vector nodeList; - const uint32 selectionListSize = selectionList.GetLength(); - for (uint32 i = 0; i < selectionListSize; ++i) + nodeList.reserve(selectionList.size()); + AZStd::transform(begin(selectionList), end(selectionList), AZStd::back_inserter(nodeList), [](const auto& item) { - nodeList.emplace_back(selectionList[i].GetNodeName()); - } + return item.GetNodeName(); + }); AZStd::string outResult; auto* command = aznew CommandSystem::CommandAdjustNodeGroup( GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), - /*actorId=*/ mActor->GetID(), - /*name=*/ mNodeGroup->GetName(), + /*actorId=*/ m_actor->GetID(), + /*name=*/ m_nodeGroup->GetName(), /*newName=*/ AZStd::nullopt, /*enabledOnDefault=*/ AZStd::nullopt, /*nodeNames=*/ AZStd::move(nodeList), - /*nodeAction=*/ mNodeAction + /*nodeAction=*/ m_nodeAction ); if (EMStudio::GetCommandManager()->ExecuteCommand(command, outResult) == false) { @@ -370,19 +353,17 @@ namespace EMStudio // handle item selection changes of the node table void NodeGroupWidget::OnItemSelectionChanged() { - mRemoveNodesButton->setEnabled((mNodeTable->rowCount() != 0) && (mNodeTable->selectedItems().size() != 0)); + m_removeNodesButton->setEnabled((m_nodeTable->rowCount() != 0) && (m_nodeTable->selectedItems().size() != 0)); } // enable/disable the dialog void NodeGroupWidget::SetWidgetEnabled(bool enabled) { - //mNodeGroupNameEdit->setDisabled( !enabled ); - //mEnabledOnDefaultCheckbox->setDisabled( !enabled ); - mNodeTable->setDisabled(!enabled); - mSelectNodesButton->setDisabled(!enabled); - mAddNodesButton->setDisabled(!enabled); - mRemoveNodesButton->setDisabled(!enabled); + m_nodeTable->setDisabled(!enabled); + m_selectNodesButton->setDisabled(!enabled); + m_addNodesButton->setDisabled(!enabled); + m_removeNodesButton->setDisabled(!enabled); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h index 2b4cad06de..c96b972085 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h @@ -45,7 +45,7 @@ namespace EMStudio public slots: void SelectNodesButtonPressed(); void RemoveNodesButtonPressed(); - void NodeSelectionFinished(MCore::Array selectionList); + void NodeSelectionFinished(const AZStd::vector& selectionList); void OnItemSelectionChanged(); private: @@ -53,18 +53,18 @@ namespace EMStudio void keyReleaseEvent(QKeyEvent* event) override; private: - EMotionFX::Actor* mActor; + EMotionFX::Actor* m_actor; - NodeSelectionWindow* mNodeSelectionWindow; - CommandSystem::SelectionList mNodeSelectionList; - EMotionFX::NodeGroup* mNodeGroup; - uint16 mNodeGroupIndex; - CommandSystem::CommandAdjustNodeGroup::NodeAction mNodeAction; + NodeSelectionWindow* m_nodeSelectionWindow; + CommandSystem::SelectionList m_nodeSelectionList; + EMotionFX::NodeGroup* m_nodeGroup; + uint16 m_nodeGroupIndex; + CommandSystem::CommandAdjustNodeGroup::NodeAction m_nodeAction; // widgets - QTableWidget* mNodeTable; - QPushButton* mSelectNodesButton; - QPushButton* mAddNodesButton; - QPushButton* mRemoveNodesButton; + QTableWidget* m_nodeTable; + QPushButton* m_selectNodesButton; + QPushButton* m_addNodesButton; + QPushButton* m_removeNodesButton; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp index 218035dc30..3fe5c589a7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp @@ -26,16 +26,16 @@ namespace EMStudio NodeGroupsPlugin::NodeGroupsPlugin() : EMStudio::DockWidgetPlugin() { - mDialogStack = nullptr; - mNodeGroupWidget = nullptr; - mNodeGroupManagementWidget = nullptr; - mSelectCallback = nullptr; - mUnselectCallback = nullptr; - mClearSelectionCallback = nullptr; - mAdjustNodeGroupCallback = nullptr; - mAddNodeGroupCallback = nullptr; - mRemoveNodeGroupCallback = nullptr; - mCurrentActor = nullptr; + m_dialogStack = nullptr; + m_nodeGroupWidget = nullptr; + m_nodeGroupManagementWidget = nullptr; + m_selectCallback = nullptr; + m_unselectCallback = nullptr; + m_clearSelectionCallback = nullptr; + m_adjustNodeGroupCallback = nullptr; + m_addNodeGroupCallback = nullptr; + m_removeNodeGroupCallback = nullptr; + m_currentActor = nullptr; } @@ -43,23 +43,23 @@ namespace EMStudio NodeGroupsPlugin::~NodeGroupsPlugin() { // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustNodeGroupCallback, false); - GetCommandManager()->RemoveCommandCallback(mAddNodeGroupCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveNodeGroupCallback, false); + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustNodeGroupCallback, false); + GetCommandManager()->RemoveCommandCallback(m_addNodeGroupCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeNodeGroupCallback, false); // remove the callback - delete mSelectCallback; - delete mUnselectCallback; - delete mClearSelectionCallback; - delete mAdjustNodeGroupCallback; - delete mAddNodeGroupCallback; - delete mRemoveNodeGroupCallback; + delete m_selectCallback; + delete m_unselectCallback; + delete m_clearSelectionCallback; + delete m_adjustNodeGroupCallback; + delete m_addNodeGroupCallback; + delete m_removeNodeGroupCallback; // clear dialogstack and delete afterwards - delete mDialogStack; + delete m_dialogStack; } @@ -75,40 +75,40 @@ namespace EMStudio bool NodeGroupsPlugin::Init() { // create the dialog stack - assert(mDialogStack == nullptr); - mDialogStack = new MysticQt::DialogStack(); - mDock->setMinimumWidth(300); - mDock->setMinimumHeight(100); - mDock->setWidget(mDialogStack); + assert(m_dialogStack == nullptr); + m_dialogStack = new MysticQt::DialogStack(); + m_dock->setMinimumWidth(300); + m_dock->setMinimumHeight(100); + m_dock->setWidget(m_dialogStack); // create the management and node group widgets - mNodeGroupWidget = new NodeGroupWidget(); - mNodeGroupManagementWidget = new NodeGroupManagementWidget(mNodeGroupWidget); + m_nodeGroupWidget = new NodeGroupWidget(); + m_nodeGroupManagementWidget = new NodeGroupManagementWidget(m_nodeGroupWidget); // add the widgets to the dialog stack - mDialogStack->Add(mNodeGroupManagementWidget, "Node Group Management", false, true, true, false); - mDialogStack->Add(mNodeGroupWidget, "Node Group", false, true, true); + m_dialogStack->Add(m_nodeGroupManagementWidget, "Node Group Management", false, true, true, false); + m_dialogStack->Add(m_nodeGroupWidget, "Node Group", false, true, true); // create and register the command callbacks only (only execute this code once for all plugins) - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); - mClearSelectionCallback = new CommandClearSelectionCallback(false); - mAdjustNodeGroupCallback = new CommandAdjustNodeGroupCallback(false); - mAddNodeGroupCallback = new CommandAddNodeGroupCallback(false); - mRemoveNodeGroupCallback = new CommandRemoveNodeGroupCallback(false); - - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); - GetCommandManager()->RegisterCommandCallback(CommandSystem::CommandAdjustNodeGroup::s_commandName.data(), mAdjustNodeGroupCallback); - GetCommandManager()->RegisterCommandCallback("AddNodeGroup", mAddNodeGroupCallback); - GetCommandManager()->RegisterCommandCallback("RemoveNodeGroup", mRemoveNodeGroupCallback); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); + m_clearSelectionCallback = new CommandClearSelectionCallback(false); + m_adjustNodeGroupCallback = new CommandAdjustNodeGroupCallback(false); + m_addNodeGroupCallback = new CommandAddNodeGroupCallback(false); + m_removeNodeGroupCallback = new CommandRemoveNodeGroupCallback(false); + + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); + GetCommandManager()->RegisterCommandCallback(CommandSystem::CommandAdjustNodeGroup::s_commandName.data(), m_adjustNodeGroupCallback); + GetCommandManager()->RegisterCommandCallback("AddNodeGroup", m_addNodeGroupCallback); + GetCommandManager()->RegisterCommandCallback("RemoveNodeGroup", m_removeNodeGroupCallback); // reinit the dialog ReInit(); // connect the window activation signal to refresh if reactivated - connect(mDock, &QDockWidget::visibilityChanged, this, &NodeGroupsPlugin::WindowReInit); + connect(m_dock, &QDockWidget::visibilityChanged, this, &NodeGroupsPlugin::WindowReInit); return true; } @@ -124,10 +124,10 @@ namespace EMStudio // show hint if no/multiple actor instances is/are selected if (actorInstance == nullptr) { - mCurrentActor = nullptr; - mNodeGroupWidget->SetActor(nullptr); - mNodeGroupWidget->SetNodeGroup(nullptr); - mNodeGroupManagementWidget->SetActor(nullptr); + m_currentActor = nullptr; + m_nodeGroupWidget->SetActor(nullptr); + m_nodeGroupWidget->SetNodeGroup(nullptr); + m_nodeGroupManagementWidget->SetActor(nullptr); return; } @@ -135,18 +135,18 @@ namespace EMStudio EMotionFX::Actor* actor = actorInstance->GetActor(); // only reinit the node groups window if actorinstance changed - if (mCurrentActor != actor) + if (m_currentActor != actor) { // set the new actor - mCurrentActor = actor; + m_currentActor = actor; // set the new actor on each widget - mNodeGroupWidget->SetActor(mCurrentActor); - mNodeGroupManagementWidget->SetActor(mCurrentActor); + m_nodeGroupWidget->SetActor(m_currentActor); + m_nodeGroupManagementWidget->SetActor(m_currentActor); } // set the dialog stack as main widget - mDock->setWidget(mDialogStack); + m_dock->setWidget(m_dialogStack); // update the interface UpdateInterface(); @@ -166,8 +166,8 @@ namespace EMStudio // update the interface void NodeGroupsPlugin::UpdateInterface() { - mNodeGroupManagementWidget->UpdateInterface(); - mNodeGroupWidget->UpdateInterface(); + m_nodeGroupManagementWidget->UpdateInterface(); + m_nodeGroupWidget->UpdateInterface(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.h index 7704708571..613d2e3494 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.h @@ -74,22 +74,22 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandAddNodeGroupCallback); MCORE_DEFINECOMMANDCALLBACK(CommandRemoveNodeGroupCallback); - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; - CommandClearSelectionCallback* mClearSelectionCallback; - CommandAdjustNodeGroupCallback* mAdjustNodeGroupCallback; - CommandAddNodeGroupCallback* mAddNodeGroupCallback; - CommandRemoveNodeGroupCallback* mRemoveNodeGroupCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; + CommandClearSelectionCallback* m_clearSelectionCallback; + CommandAdjustNodeGroupCallback* m_adjustNodeGroupCallback; + CommandAddNodeGroupCallback* m_addNodeGroupCallback; + CommandRemoveNodeGroupCallback* m_removeNodeGroupCallback; // current selected actor - EMotionFX::Actor* mCurrentActor; + EMotionFX::Actor* m_currentActor; // the dialog stack widgets - NodeGroupWidget* mNodeGroupWidget; - NodeGroupManagementWidget* mNodeGroupManagementWidget; + NodeGroupWidget* m_nodeGroupWidget; + NodeGroupManagementWidget* m_nodeGroupManagementWidget; // some qt stuff - MysticQt::DialogStack* mDialogStack; - QLabel* mInfoText; + MysticQt::DialogStack* m_dialogStack; + QLabel* m_infoText; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.cpp index 91b08b25de..6bd00a2b94 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.cpp @@ -40,7 +40,7 @@ namespace EMStudio } // global mesh information - const uint32 lodLevel = actorInstance->GetLODLevel(); + const size_t lodLevel = actorInstance->GetLODLevel(); uint32 numPolygons; actor->CalcMeshTotals(lodLevel, &numPolygons, &m_totalVertices, &m_totalIndices); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.h index 9c0155ee40..e1aa63b7dd 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/ActorInfo.h @@ -35,7 +35,7 @@ namespace EMStudio private: AZStd::string m_name; AZStd::string m_unitType; - int m_nodeCount; + AZ::u64 m_nodeCount; AZStd::vector m_nodeGroups; unsigned int m_totalVertices; unsigned int m_totalIndices; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.cpp index 88e6a64964..d4aec199d3 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.cpp @@ -20,7 +20,7 @@ namespace EMStudio { AZ_CLASS_ALLOCATOR_IMPL(MeshInfo, EMStudio::UIAllocator, 0) - MeshInfo::MeshInfo(EMotionFX::Actor* actor, [[maybe_unused]] EMotionFX::Node* node, unsigned int lodLevel, EMotionFX::Mesh* mesh) + MeshInfo::MeshInfo(EMotionFX::Actor* actor, [[maybe_unused]] EMotionFX::Node* node, size_t lodLevel, EMotionFX::Mesh* mesh) : m_lod(lodLevel) { // vertices, indices and polygons etc. @@ -33,7 +33,7 @@ namespace EMStudio if (m_orgVerticesCount) { - m_vertexDupeRatio = mesh->GetNumVertices() / (float)mesh->GetNumOrgVertices(); + m_vertexDupeRatio = (float)mesh->GetNumVertices() / (float)mesh->GetNumOrgVertices(); } else { @@ -44,15 +44,15 @@ namespace EMStudio mesh->CalcMaxNumInfluences(m_verticesByInfluences); // sub meshes - const uint32 numSubMeshes = mesh->GetNumSubMeshes(); - for (uint32 i = 0; i < numSubMeshes; ++i) + const size_t numSubMeshes = mesh->GetNumSubMeshes(); + for (size_t i = 0; i < numSubMeshes; ++i) { EMotionFX::SubMesh* subMesh = mesh->GetSubMesh(i); m_submeshes.emplace_back(actor, lodLevel, subMesh); } // vertex attribute layers - const uint32 numVertexAttributeLayers = mesh->GetNumVertexAttributeLayers(); + const size_t numVertexAttributeLayers = mesh->GetNumVertexAttributeLayers(); AZStd::string tmpString; for (uint32 i = 0; i < numVertexAttributeLayers; ++i) { @@ -89,7 +89,7 @@ namespace EMStudio tmpString = AZStd::string::format("Unknown data (TypeID=%d)", attributeLayerType); } - if (attributeLayer->GetNameString().size() > 0) + if (!attributeLayer->GetNameString().empty()) { tmpString += AZStd::string::format(" [%s]", attributeLayer->GetName()); } @@ -99,8 +99,8 @@ namespace EMStudio // shared vertex attribute layers - const uint32 numSharedVertexAttributeLayers = mesh->GetNumSharedVertexAttributeLayers(); - for (uint32 i = 0; i < numSharedVertexAttributeLayers; ++i) + const size_t numSharedVertexAttributeLayers = mesh->GetNumSharedVertexAttributeLayers(); + for (size_t i = 0; i < numSharedVertexAttributeLayers; ++i) { EMotionFX::VertexAttributeLayer* attributeLayer = mesh->GetSharedVertexAttributeLayer(i); @@ -114,7 +114,7 @@ namespace EMStudio tmpString = AZStd::string::format("Unknown data (TypeID=%d)", attributeLayerType); } - if (attributeLayer->GetNameString().size() > 0) + if (!attributeLayer->GetNameString().empty()) { tmpString += AZStd::string::format(" [%s]", attributeLayer->GetName()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.h index b8e9d0fc61..4e39e6dda1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/MeshInfo.h @@ -30,13 +30,13 @@ namespace EMStudio AZ_CLASS_ALLOCATOR_DECL MeshInfo() {} - MeshInfo(EMotionFX::Actor* actor, EMotionFX::Node* node, unsigned int lodLevel, EMotionFX::Mesh* mesh); + MeshInfo(EMotionFX::Actor* actor, EMotionFX::Node* node, size_t lodLevel, EMotionFX::Mesh* mesh); ~MeshInfo() = default; static void Reflect(AZ::ReflectContext* context); private: - unsigned int m_lod; + AZ::u64 m_lod; unsigned int m_verticesCount; unsigned int m_indicesCount; unsigned int m_polygonsCount; @@ -44,7 +44,7 @@ namespace EMStudio bool m_isQuadMesh; unsigned int m_orgVerticesCount; float m_vertexDupeRatio; - AZStd::vector m_verticesByInfluences; + AZStd::vector m_verticesByInfluences; AZStd::vector m_submeshes; AZStd::vector m_attributeLayers; AZStd::vector m_sharedAttributeLayers; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeInfo.cpp index f91468b6d2..3bbf9a0731 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeInfo.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeInfo.cpp @@ -23,7 +23,7 @@ namespace EMStudio NodeInfo::NodeInfo(EMotionFX::ActorInstance* actorInstance, EMotionFX::Node* node) { - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::TransformData* transformData = actorInstance->GetTransformData(); @@ -31,11 +31,11 @@ namespace EMStudio m_name = node->GetNameString(); // transform info - m_position = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex).mPosition; - m_rotation = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex).mRotation; + m_position = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex).m_position; + m_rotation = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex).m_rotation; #ifndef EMFX_SCALE_DISABLED - m_scale = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex).mScale; + m_scale = transformData->GetCurrentPose()->GetLocalSpaceTransform(nodeIndex).m_scale; #else m_scale = AZ::Vector3::CreateOne(); #endif @@ -53,31 +53,31 @@ namespace EMStudio if (actor->GetHasMirrorInfo()) { const EMotionFX::Actor::NodeMirrorInfo& nodeMirrorInfo = actor->GetNodeMirrorInfo(nodeIndex); - if (nodeMirrorInfo.mSourceNode != MCORE_INVALIDINDEX16 && nodeMirrorInfo.mSourceNode != nodeIndex) + if (nodeMirrorInfo.m_sourceNode != MCORE_INVALIDINDEX16 && nodeMirrorInfo.m_sourceNode != nodeIndex) { - m_mirrorNodeName = actor->GetSkeleton()->GetNode(nodeMirrorInfo.mSourceNode)->GetNameString(); + m_mirrorNodeName = actor->GetSkeleton()->GetNode(nodeMirrorInfo.m_sourceNode)->GetNameString(); } } // children - const uint32 numChildren = node->GetNumChildNodes(); - for (uint32 i = 0; i < numChildren; ++i) + const size_t numChildren = node->GetNumChildNodes(); + for (size_t i = 0; i < numChildren; ++i) { EMotionFX::Node* child = actor->GetSkeleton()->GetNode(node->GetChildIndex(i)); m_childNodeNames.emplace_back(child->GetNameString()); } // attributes - const uint32 numAttributes = node->GetNumAttributes(); - for (uint32 i = 0; i < numAttributes; ++i) + const size_t numAttributes = node->GetNumAttributes(); + for (size_t i = 0; i < numAttributes; ++i) { EMotionFX::NodeAttribute* nodeAttribute = node->GetAttribute(i); m_attributeTypes.emplace_back(nodeAttribute->GetTypeString()); } // meshes - const uint32 numLODLevels = actor->GetNumLODLevels(); - for (uint32 i = 0; i < numLODLevels; ++i) + const size_t numLODLevels = actor->GetNumLODLevels(); + for (size_t i = 0; i < numLODLevels; ++i) { EMotionFX::Mesh* mesh = actor->GetMesh(i, node->GetNodeIndex()); if (mesh) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.cpp index 0c1778aa23..6b7beb20de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.cpp @@ -28,8 +28,8 @@ namespace EMStudio { NodeWindowPlugin::NodeWindowPlugin() : EMStudio::DockWidgetPlugin() - , mDialogStack(nullptr) - , mHierarchyWidget(nullptr) + , m_dialogStack(nullptr) + , m_hierarchyWidget(nullptr) , m_propertyWidget(nullptr) { } @@ -79,35 +79,35 @@ namespace EMStudio GetCommandManager()->RegisterCommandCallback("ClearSelection", m_callbacks.back()); // create the dialog stack - AZ_Assert(!mDialogStack, "Expected an unitialized mDialogStack, was this function called more than once?"); - mDialogStack = new MysticQt::DialogStack(); + AZ_Assert(!m_dialogStack, "Expected an unitialized m_dialogStack, was this function called more than once?"); + m_dialogStack = new MysticQt::DialogStack(); // add the node hierarchy - mHierarchyWidget = new NodeHierarchyWidget(mDock, false); - mHierarchyWidget->setObjectName("EMFX.NodeWindowPlugin.NodeHierarchyWidget.HierarchyWidget"); - mHierarchyWidget->GetTreeWidget()->setMinimumWidth(100); - mDialogStack->Add(mHierarchyWidget, "Hierarchy", false, true); + m_hierarchyWidget = new NodeHierarchyWidget(m_dock, false); + m_hierarchyWidget->setObjectName("EMFX.NodeWindowPlugin.NodeHierarchyWidget.HierarchyWidget"); + m_hierarchyWidget->GetTreeWidget()->setMinimumWidth(100); + m_dialogStack->Add(m_hierarchyWidget, "Hierarchy", false, true); // add the node attributes widget - m_propertyWidget = aznew AzToolsFramework::ReflectedPropertyEditor(mDialogStack); + m_propertyWidget = aznew AzToolsFramework::ReflectedPropertyEditor(m_dialogStack); m_propertyWidget->setObjectName("EMFX.NodeWindowPlugin.ReflectedPropertyEditor.PropertyWidget"); m_propertyWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed); m_propertyWidget->SetAutoResizeLabels(true); - mDialogStack->Add(m_propertyWidget, "Node Attributes", false, true, true, false); + m_dialogStack->Add(m_propertyWidget, "Node Attributes", false, true, true, false); // prepare the dock window - mDock->setWidget(mDialogStack); - mDock->setMinimumWidth(100); - mDock->setMinimumHeight(100); + m_dock->setWidget(m_dialogStack); + m_dock->setMinimumWidth(100); + m_dock->setMinimumHeight(100); // add functionality to the controls - connect(mDock, &QDockWidget::visibilityChanged, this, &NodeWindowPlugin::VisibilityChanged); - connect(mHierarchyWidget->GetTreeWidget(), &QTreeWidget::itemSelectionChanged, this, &NodeWindowPlugin::OnNodeChanged); + connect(m_dock, &QDockWidget::visibilityChanged, this, &NodeWindowPlugin::VisibilityChanged); + connect(m_hierarchyWidget->GetTreeWidget(), &QTreeWidget::itemSelectionChanged, this, &NodeWindowPlugin::OnNodeChanged); - const AzQtComponents::FilteredSearchWidget* searchWidget = mHierarchyWidget->GetSearchWidget(); + const AzQtComponents::FilteredSearchWidget* searchWidget = m_hierarchyWidget->GetSearchWidget(); connect(searchWidget, &AzQtComponents::FilteredSearchWidget::TextFilterChanged, this, &NodeWindowPlugin::OnTextFilterChanged); - connect(mHierarchyWidget, &NodeHierarchyWidget::FilterStateChanged, this, &NodeWindowPlugin::UpdateVisibleNodeIndices); + connect(m_hierarchyWidget, &NodeHierarchyWidget::FilterStateChanged, this, &NodeWindowPlugin::UpdateVisibleNodeIndices); // reinit the dialog ReInit(); @@ -123,15 +123,15 @@ namespace EMStudio EMotionFX::ActorInstance* actorInstance = selection.GetSingleActorInstance(); // reset the node name filter - mHierarchyWidget->GetSearchWidget()->ClearTextFilter(); - mHierarchyWidget->GetTreeWidget()->clear(); + m_hierarchyWidget->GetSearchWidget()->ClearTextFilter(); + m_hierarchyWidget->GetTreeWidget()->clear(); m_propertyWidget->ClearInstances(); m_propertyWidget->InvalidateAll(); if (actorInstance) { - mHierarchyWidget->Update(actorInstance->GetID()); + m_hierarchyWidget->Update(actorInstance->GetID()); m_actorInfo.reset(aznew ActorInfo(actorInstance)); m_propertyWidget->AddInstance(m_actorInfo.get(), azrtti_typeid(m_actorInfo.get())); } @@ -158,14 +158,14 @@ namespace EMStudio selection.ClearNodeSelection(); m_selectedNodeIndices.clear(); - AZStd::vector& selectedItems = mHierarchyWidget->GetSelectedItems(); + AZStd::vector& selectedItems = m_hierarchyWidget->GetSelectedItems(); EMotionFX::ActorInstance* selectedInstance = nullptr; EMotionFX::Node* selectedNode = nullptr; for (const SelectionItem& selectedItem : selectedItems) { - const uint32 actorInstanceID = selectedItem.mActorInstanceID; + const uint32 actorInstanceID = selectedItem.m_actorInstanceId; const char* nodeName = selectedItem.GetNodeName(); EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); @@ -177,7 +177,7 @@ namespace EMStudio EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(nodeName); - if (node && mHierarchyWidget->CheckIfNodeVisible(actorInstance, node)) + if (node && m_hierarchyWidget->CheckIfNodeVisible(actorInstance, node)) { if (selectedInstance == nullptr) { @@ -278,26 +278,26 @@ namespace EMStudio return; } - AZStd::string filterString = mHierarchyWidget->GetSearchWidgetText(); + AZStd::string filterString = m_hierarchyWidget->GetSearchWidgetText(); AZStd::to_lower(filterString.begin(), filterString.end()); - const bool showNodes = mHierarchyWidget->GetDisplayNodes(); - const bool showBones = mHierarchyWidget->GetDisplayBones(); - const bool showMeshes = mHierarchyWidget->GetDisplayMeshes(); + const bool showNodes = m_hierarchyWidget->GetDisplayNodes(); + const bool showBones = m_hierarchyWidget->GetDisplayBones(); + const bool showMeshes = m_hierarchyWidget->GetDisplayMeshes(); // get access to the actor and the number of nodes EMotionFX::Actor* actor = actorInstance->GetActor(); - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); // reserve memory for the visible node indices m_visibleNodeIndices.reserve(numNodes); // extract the bones from the actor - MCore::Array boneList; + AZStd::vector boneList; actor->ExtractBoneList(actorInstance->GetLODLevel(), &boneList); // iterate through all nodes and check if the node is visible AZStd::string nodeName; - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); @@ -305,10 +305,10 @@ namespace EMStudio nodeName = node->GetNameString(); AZStd::to_lower(nodeName.begin(), nodeName.end()); - const uint32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); EMotionFX::Mesh* mesh = actor->GetMesh(actorInstance->GetLODLevel(), nodeIndex); const bool isMeshNode = (mesh); - const bool isBone = (boneList.Find(nodeIndex) != MCORE_INVALIDINDEX32); + const bool isBone = (AZStd::find(begin(boneList), end(boneList), nodeIndex) != end(boneList)); const bool isNode = (isMeshNode == false && isBone == false); if (((showMeshes && isMeshNode) || diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.h index 7b1655bd05..157486df10 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/NodeWindowPlugin.h @@ -76,14 +76,14 @@ namespace EMStudio AZStd::vector m_callbacks; - MysticQt::DialogStack* mDialogStack; - NodeHierarchyWidget* mHierarchyWidget; + MysticQt::DialogStack* m_dialogStack; + NodeHierarchyWidget* m_hierarchyWidget; AzToolsFramework::ReflectedPropertyEditor* m_propertyWidget; - AZStd::string mString; - AZStd::string mTempGroupName; - AZStd::unordered_set m_visibleNodeIndices; - AZStd::unordered_set m_selectedNodeIndices; + AZStd::string m_string; + AZStd::string m_tempGroupName; + AZStd::unordered_set m_visibleNodeIndices; + AZStd::unordered_set m_selectedNodeIndices; AZStd::unique_ptr m_actorInfo; AZStd::unique_ptr m_nodeInfo; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.cpp index 151254715e..d8a9926c33 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.cpp @@ -19,7 +19,7 @@ namespace EMStudio { AZ_CLASS_ALLOCATOR_IMPL(SubMeshInfo, EMStudio::UIAllocator, 0) - SubMeshInfo::SubMeshInfo(EMotionFX::Actor* actor, unsigned int lodLevel, EMotionFX::SubMesh* subMesh) + SubMeshInfo::SubMeshInfo(EMotionFX::Actor* actor, size_t lodLevel, EMotionFX::SubMesh* subMesh) { // In EMFX studio, we are not using the subMesh index - they all uses the default material. m_materialName = actor->GetMaterial(lodLevel, 0)->GetNameString(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.h index 3a6340d48c..bb5d5eda15 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeWindow/SubMeshInfo.h @@ -26,7 +26,7 @@ namespace EMStudio AZ_CLASS_ALLOCATOR_DECL SubMeshInfo() {} - SubMeshInfo(EMotionFX::Actor* actor, unsigned int lodLevel, EMotionFX::SubMesh* subMesh); + SubMeshInfo(EMotionFX::Actor* actor, size_t lodLevel, EMotionFX::SubMesh* subMesh); ~SubMeshInfo() = default; static void Reflect(AZ::ReflectContext* context); @@ -36,7 +36,7 @@ namespace EMStudio unsigned int m_verticesCount; unsigned int m_indicesCount; unsigned int m_polygonsCount; - unsigned int m_bonesCount; + size_t m_bonesCount; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.cpp index 04fbc9e412..c449f492b1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.cpp @@ -24,7 +24,7 @@ namespace EMStudio ActorPropertiesWindow::ActorPropertiesWindow(QWidget* parent, SceneManagerPlugin* plugin) : QWidget(parent) { - mPlugin = plugin; + m_plugin = plugin; } // init after the parent dock window has been created @@ -44,9 +44,9 @@ namespace EMStudio // actor name rowNr = 0; layout->addWidget(new QLabel("Actor name"), rowNr, 0); - mNameEdit = new QLineEdit(); - connect(mNameEdit, &QLineEdit::editingFinished, this, &ActorPropertiesWindow::NameEditChanged); - layout->addWidget(mNameEdit, rowNr, 1); + m_nameEdit = new QLineEdit(); + connect(m_nameEdit, &QLineEdit::editingFinished, this, &ActorPropertiesWindow::NameEditChanged); + layout->addWidget(m_nameEdit, rowNr, 1); // Motion extraction joint. rowNr++; @@ -94,14 +94,14 @@ namespace EMStudio // mirror setup rowNr++; - mMirrorSetupWindow = new MirrorSetupWindow(mPlugin->GetDockWidget(), mPlugin); - mMirrorSetupLink = new AzQtComponents::BrowseEdit(); - mMirrorSetupLink->setClearButtonEnabled(true); - mMirrorSetupLink->setLineEditReadOnly(true); - mMirrorSetupLink->setPlaceholderText("Click folder to setup"); + m_mirrorSetupWindow = new MirrorSetupWindow(m_plugin->GetDockWidget(), m_plugin); + m_mirrorSetupLink = new AzQtComponents::BrowseEdit(); + m_mirrorSetupLink->setClearButtonEnabled(true); + m_mirrorSetupLink->setLineEditReadOnly(true); + m_mirrorSetupLink->setPlaceholderText("Click folder to setup"); layout->addWidget(new QLabel("Mirror setup"), rowNr, 0); - layout->addWidget(mMirrorSetupLink, rowNr, 1); - connect(mMirrorSetupLink, &AzQtComponents::BrowseEdit::attachedButtonTriggered, this, &ActorPropertiesWindow::OnMirrorSetup); + layout->addWidget(m_mirrorSetupLink, rowNr, 1); + connect(m_mirrorSetupLink, &AzQtComponents::BrowseEdit::attachedButtonTriggered, this, &ActorPropertiesWindow::OnMirrorSetup); UpdateInterface(); } @@ -109,8 +109,8 @@ namespace EMStudio void ActorPropertiesWindow::UpdateInterface() { - mActor = nullptr; - mActorInstance = nullptr; + m_actor = nullptr; + m_actorInstance = nullptr; EMotionFX::ActorInstance* actorInstance = GetCommandManager()->GetCurrentSelection().GetSingleActorInstance(); EMotionFX::Actor* actor = GetCommandManager()->GetCurrentSelection().GetSingleActor(); @@ -118,29 +118,29 @@ namespace EMStudio // in case we have selected a single actor instance if (actorInstance) { - mActorInstance = actorInstance; - mActor = actorInstance->GetActor(); + m_actorInstance = actorInstance; + m_actor = actorInstance->GetActor(); } // in case we have selected a single actor else if (actor) { - mActor = actor; + m_actor = actor; - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* currentInstance = EMotionFX::GetActorManager().GetActorInstance(i); if (currentInstance->GetActor() == actor) { - mActorInstance = currentInstance; + m_actorInstance = currentInstance; break; } } } - mMirrorSetupWindow->Reinit(); + m_mirrorSetupWindow->Reinit(); - if (mActorInstance == nullptr || mActor == nullptr) + if (m_actorInstance == nullptr || m_actor == nullptr) { // reset data and disable interface elements m_motionExtractionJointBrowseEdit->setEnabled(false); @@ -155,37 +155,37 @@ namespace EMStudio m_excludeFromBoundsBrowseEdit->SetSelectedJoints({}); // actor name - mNameEdit->setEnabled(false); - mNameEdit->setText(""); + m_nameEdit->setEnabled(false); + m_nameEdit->setText(""); - mMirrorSetupLink->setEnabled(false); + m_mirrorSetupLink->setEnabled(false); return; } - mMirrorSetupLink->setEnabled(true); + m_mirrorSetupLink->setEnabled(true); // Motion extraction node - EMotionFX::Node* extractionNode = mActor->GetMotionExtractionNode(); + EMotionFX::Node* extractionNode = m_actor->GetMotionExtractionNode(); m_motionExtractionJointBrowseEdit->setEnabled(true); if (extractionNode) { - m_motionExtractionJointBrowseEdit->SetSelectedJoints({SelectionItem(mActorInstance->GetID(), extractionNode->GetName())}); + m_motionExtractionJointBrowseEdit->SetSelectedJoints({SelectionItem(m_actorInstance->GetID(), extractionNode->GetName())}); } else { m_motionExtractionJointBrowseEdit->SetSelectedJoints({}); } - EMotionFX::Node* bestMatchingNode = mActor->FindBestMotionExtractionNode(); - m_findBestMatchButton->setVisible(bestMatchingNode && mActor->GetMotionExtractionNode() != bestMatchingNode); + EMotionFX::Node* bestMatchingNode = m_actor->FindBestMotionExtractionNode(); + m_findBestMatchButton->setVisible(bestMatchingNode && m_actor->GetMotionExtractionNode() != bestMatchingNode); // Retarget root node - EMotionFX::Node* retargetRootNode = mActor->GetRetargetRootNode(); + EMotionFX::Node* retargetRootNode = m_actor->GetRetargetRootNode(); m_retargetRootJointBrowseEdit->setEnabled(true); if (retargetRootNode) { - m_retargetRootJointBrowseEdit->SetSelectedJoints({SelectionItem(mActorInstance->GetID(), retargetRootNode->GetName())}); + m_retargetRootJointBrowseEdit->SetSelectedJoints({SelectionItem(m_actorInstance->GetID(), retargetRootNode->GetName())}); } else { @@ -196,47 +196,23 @@ namespace EMStudio m_excludeFromBoundsBrowseEdit->setEnabled(true); AZStd::vector jointsExcludedFromBounds; - if (mActorInstance) + if (m_actorInstance) { - const uint32 numNodes = mActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = m_actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { - EMotionFX::Node* node = mActor->GetSkeleton()->GetNode(i); + EMotionFX::Node* node = m_actor->GetSkeleton()->GetNode(i); if (!node->GetIncludeInBoundsCalc()) { - jointsExcludedFromBounds.emplace_back(mActorInstance->GetID(), node->GetName()); + jointsExcludedFromBounds.emplace_back(m_actorInstance->GetID(), node->GetName()); } } } m_excludeFromBoundsBrowseEdit->SetSelectedJoints(jointsExcludedFromBounds); // actor name - mNameEdit->setEnabled(true); - mNameEdit->setText(mActor->GetName()); - } - - void ActorPropertiesWindow::GetNodeName(const MCore::Array& selection, AZStd::string* outNodeName, uint32* outActorID) - { - outNodeName->clear(); - *outActorID = MCORE_INVALIDINDEX32; - - if (selection.GetLength() != 1 || selection[0].GetNodeNameString().empty()) - { - AZ_Warning("EMotionFX", false, "Cannot adjust motion extraction node. No valid node selected."); - return; - } - - const uint32 actorInstanceID = selection[0].mActorInstanceID; - const char* nodeName = selection[0].GetNodeName(); - EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); - if (actorInstance == nullptr) - { - return; - } - - EMotionFX::Actor* actor = actorInstance->GetActor(); - *outActorID = actor->GetID(); - *outNodeName = nodeName; + m_nameEdit->setEnabled(true); + m_nameEdit->setText(m_actor->GetName()); } void ActorPropertiesWindow::GetNodeName(const AZStd::vector& joints, AZStd::string* outNodeName, uint32* outActorID) @@ -250,7 +226,7 @@ namespace EMStudio return; } - const uint32 actorInstanceID = joints[0].mActorInstanceID; + const uint32 actorInstanceID = joints[0].m_actorInstanceId; const char* nodeName = joints[0].GetNodeName(); EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(actorInstanceID); if (!actorInstance) @@ -323,13 +299,13 @@ namespace EMStudio void ActorPropertiesWindow::OnFindBestMatchingNode() { // check if the actor is invalid - if (mActor == nullptr) + if (m_actor == nullptr) { return; } // find the best motion extraction node - EMotionFX::Node* bestMatchingNode = mActor->FindBestMotionExtractionNode(); + EMotionFX::Node* bestMatchingNode = m_actor->FindBestMotionExtractionNode(); if (bestMatchingNode == nullptr) { return; @@ -339,7 +315,7 @@ namespace EMStudio MCore::CommandGroup commandGroup("Adjust motion extraction node"); // adjust the actor - const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -motionExtractionNodeName \"%s\"", mActor->GetID(), bestMatchingNode->GetName()); + const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -motionExtractionNodeName \"%s\"", m_actor->GetID(), bestMatchingNode->GetName()); commandGroup.AddCommandString(command); // execute the command group @@ -353,13 +329,13 @@ namespace EMStudio // actor name changed void ActorPropertiesWindow::NameEditChanged() { - if (mActor == nullptr) + if (m_actor == nullptr) { return; } // execute the command - const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -name \"%s\"", mActor->GetID(), mNameEdit->text().toUtf8().data()); + const AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -name \"%s\"", m_actor->GetID(), m_nameEdit->text().toUtf8().data()); AZStd::string result; if (!EMStudio::GetCommandManager()->ExecuteCommand(command, result)) @@ -377,13 +353,13 @@ namespace EMStudio return; } - AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodesExcludedFromBounds \"", mActor->GetID()); + AZStd::string command = AZStd::string::format("AdjustActor -actorID %i -nodesExcludedFromBounds \"", m_actor->GetID()); // prepare the nodes excluded from bounds string size_t addedItems = 0; for (const SelectionItem& selectedJoint : selectedJoints) { - EMotionFX::Node* node = mActor->GetSkeleton()->FindNodeByName(selectedJoint.GetNodeName()); + EMotionFX::Node* node = m_actor->GetSkeleton()->FindNodeByName(selectedJoint.GetNodeName()); if (node) { if (addedItems > 0) @@ -419,10 +395,10 @@ namespace EMStudio EMotionFX::Actor* actor = actorInstance->GetActor(); EMotionFX::Skeleton* skeleton = actor->GetSkeleton(); - const uint32 numJoints = mActor->GetNumNodes(); + const size_t numJoints = m_actor->GetNumNodes(); // Include all joints first. - for (uint32 i = 0; i < numJoints; ++i) + for (size_t i = 0; i < numJoints; ++i) { skeleton->GetNode(i)->SetIncludeInBoundsCalc(true); } @@ -441,9 +417,9 @@ namespace EMStudio // open the mirror setup void ActorPropertiesWindow::OnMirrorSetup() { - if (mMirrorSetupWindow) + if (m_mirrorSetupWindow) { - mMirrorSetupWindow->exec(); + m_mirrorSetupWindow->exec(); } } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.h index d969a12148..70af16ca17 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorPropertiesWindow.h @@ -45,7 +45,6 @@ namespace EMStudio void Init(); // helper functions - static void GetNodeName(const MCore::Array& selection, AZStd::string* outNodeName, uint32* outActorID); static void GetNodeName(const AZStd::vector& joints, AZStd::string* outNodeName, uint32* outActorID); public slots: @@ -70,14 +69,14 @@ namespace EMStudio ActorJointBrowseEdit* m_retargetRootJointBrowseEdit = nullptr; ActorJointBrowseEdit* m_excludeFromBoundsBrowseEdit = nullptr; - AzQtComponents::BrowseEdit* mMirrorSetupLink = nullptr; - MirrorSetupWindow* mMirrorSetupWindow = nullptr; + AzQtComponents::BrowseEdit* m_mirrorSetupLink = nullptr; + MirrorSetupWindow* m_mirrorSetupWindow = nullptr; // actor name - QLineEdit* mNameEdit = nullptr; + QLineEdit* m_nameEdit = nullptr; - SceneManagerPlugin* mPlugin = nullptr; - EMotionFX::Actor* mActor = nullptr; - EMotionFX::ActorInstance* mActorInstance = nullptr; + SceneManagerPlugin* m_plugin = nullptr; + EMotionFX::Actor* m_actor = nullptr; + EMotionFX::ActorInstance* m_actorInstance = nullptr; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.cpp index 309d6fb441..5012ee2578 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.cpp @@ -111,9 +111,9 @@ namespace EMStudio m_treeWidget->clear(); // iterate trough all actors and add them to the tree including their instances - const uint32 numActors = EMotionFX::GetActorManager().GetNumActors(); - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActors; ++i) + const size_t numActors = EMotionFX::GetActorManager().GetNumActors(); + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActors; ++i) { EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); @@ -153,7 +153,7 @@ namespace EMStudio // add as top level item m_treeWidget->addTopLevelItem(newItem); - for (uint32 k = 0; k < numActorInstances; ++k) + for (size_t k = 0; k < numActorInstances; ++k) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(k); if (actorInstance->GetActor() == actor && !actorInstance->GetIsOwnedByRuntime()) @@ -188,8 +188,8 @@ namespace EMStudio // disable signals m_treeWidget->blockSignals(true); - const uint32 numTopLevelItems = m_treeWidget->topLevelItemCount(); - for (uint32 i = 0; i < numTopLevelItems; ++i) + const int numTopLevelItems = m_treeWidget->topLevelItemCount(); + for (int i = 0; i < numTopLevelItems; ++i) { bool atLeastOneInstanceVisible = false; QTreeWidgetItem* item = m_treeWidget->topLevelItem(i); @@ -199,8 +199,8 @@ namespace EMStudio item->setSelected(actorSelected); - const uint32 numChildren = item->childCount(); - for (uint32 j = 0; j < numChildren; ++j) + const int numChildren = item->childCount(); + for (int j = 0; j < numChildren; ++j) { QTreeWidgetItem* child = item->child(j); EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().FindActorInstanceByID(GetIDFromTreeItem(child)); @@ -236,10 +236,8 @@ namespace EMStudio AZStd::vector toBeRemovedActors; const QList items = m_treeWidget->selectedItems(); - const uint32 numItems = items.length(); - for (uint32 i = 0; i < numItems; ++i) + for (const QTreeWidgetItem* item : items) { - QTreeWidgetItem* item = items[i]; if (!item) { continue; @@ -254,8 +252,8 @@ namespace EMStudio if (actor) { // remove actor instances - const uint32 numChildren = item->childCount(); - for (uint32 j = 0; j < numChildren; ++j) + const int numChildren = item->childCount(); + for (int j = 0; j < numChildren; ++j) { QTreeWidgetItem* child = item->child(j); @@ -326,11 +324,9 @@ namespace EMStudio // filter the list to keep the actor items only const QList items = m_treeWidget->selectedItems(); - const uint32 numItems = items.length(); - for (uint32 i = 0; i < numItems; ++i) + for (const QTreeWidgetItem* item : items) { // get the item and check if the item is valid - QTreeWidgetItem* item = items[i]; if (item == nullptr) { continue; @@ -384,8 +380,8 @@ namespace EMStudio if (!item->parent()) { - const uint32 numChildren = item->childCount(); - for (uint32 i = 0; i < numChildren; ++i) + const int numChildren = item->childCount(); + for (int i = 0; i < numChildren; ++i) { QTreeWidgetItem* child = item->child(i); @@ -422,8 +418,8 @@ namespace EMStudio } // get the selected items - const uint32 numTopItems = m_treeWidget->topLevelItemCount(); - for (uint32 i = 0; i < numTopItems; ++i) + const int numTopItems = m_treeWidget->topLevelItemCount(); + for (int i = 0; i < numTopItems; ++i) { // selection of the topLevelItems QTreeWidgetItem* topLevelItem = m_treeWidget->topLevelItem(i); @@ -439,8 +435,8 @@ namespace EMStudio } // loop trough the children and adjust selection there - uint32 numChilds = topLevelItem->childCount(); - for (uint32 j = 0; j < numChilds; ++j) + int numChilds = topLevelItem->childCount(); + for (int j = 0; j < numChilds; ++j) { QTreeWidgetItem* child = topLevelItem->child(j); if (child->isSelected()) @@ -486,20 +482,15 @@ namespace EMStudio void ActorsWindow::contextMenuEvent(QContextMenuEvent* event) { - const QList items = m_treeWidget->selectedItems(); - - // get number of selected items and top level items - const uint32 numSelected = items.size(); - const uint32 numTopItems = m_treeWidget->topLevelItemCount(); + const QList items = m_treeWidget->selectedItems(); // create the context menu QMenu menu(this); menu.setToolTipsVisible(true); bool actorSelected = false; - for (uint32 i = 0; i < numSelected; ++i) + for (const QTreeWidgetItem* item : items) { - QTreeWidgetItem* item = items[i]; if (item->parent() == nullptr) { actorSelected = true; @@ -518,7 +509,7 @@ namespace EMStudio } } - if (numSelected > 0) + if (!items.empty()) { if (instanceSelected) { @@ -546,7 +537,7 @@ namespace EMStudio connect(removeAction, &QAction::triggered, this, &ActorsWindow::OnRemoveButtonClicked); } - if (numTopItems > 0) + if (m_treeWidget->topLevelItemCount() > 0) { QAction* clearAction = menu.addAction("Remove all"); connect(clearAction, &QAction::triggered, this, &ActorsWindow::OnClearButtonClicked); @@ -596,24 +587,16 @@ namespace EMStudio // get number of selected items and top level items const QList items = m_treeWidget->selectedItems(); - const uint32 numSelected = items.size(); - const uint32 numTopItems = m_treeWidget->topLevelItemCount(); // check if at least one actor selected - bool actorSelected = false; - for (uint32 i = 0; i < numSelected; ++i) + const bool actorSelected = AZStd::any_of(items.begin(), items.end(), [](const QTreeWidgetItem* item) { - QTreeWidgetItem* item = items[i]; - if (item->parent() == nullptr) - { - actorSelected = true; - break; - } - } + return item->parent() == nullptr; + }); // set the enabled state of the buttons m_createInstanceAction->setEnabled(actorSelected); - m_saveAction->setEnabled(numSelected != 0); + m_saveAction->setEnabled(!items.empty()); } @@ -623,11 +606,9 @@ namespace EMStudio // create the instances of the selected actors const QList items = m_treeWidget->selectedItems(); - const uint32 numItems = items.length(); - for (uint32 i = 0; i < numItems; ++i) + for (const QTreeWidgetItem* item : items) { // check if parent or child item - QTreeWidgetItem* item = items[i]; if (item == nullptr || item->parent() == nullptr) { continue; @@ -652,7 +633,7 @@ namespace EMStudio } - uint32 ActorsWindow::GetIDFromTreeItem(QTreeWidgetItem* item) + uint32 ActorsWindow::GetIDFromTreeItem(const QTreeWidgetItem* item) { if (item == nullptr) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.h index 8608e59439..181120d515 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/ActorsWindow.h @@ -52,7 +52,7 @@ namespace EMStudio void keyReleaseEvent(QKeyEvent* event) override; void SetControlsEnabled(); - uint32 GetIDFromTreeItem(QTreeWidgetItem* item); + uint32 GetIDFromTreeItem(const QTreeWidgetItem* item); void SetVisibilityFlags(bool isVisible); private: diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.cpp index 6260e68284..d1fd241a2f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.cpp @@ -42,7 +42,7 @@ namespace EMStudio MirrorSetupWindow::MirrorSetupWindow(QWidget* parent, SceneManagerPlugin* plugin) : QDialog(parent) { - mPlugin = plugin; + m_plugin = plugin; // set the window title setWindowTitle("Mirror Setup"); @@ -53,10 +53,10 @@ namespace EMStudio // load some icons const QDir dataDir{ QString(MysticQt::GetDataDir().c_str()) }; - mBoneIcon = new QIcon(dataDir.filePath("Images/Icons/Bone.svg")); - mNodeIcon = new QIcon(dataDir.filePath("Images/Icons/Node.svg")); - mMeshIcon = new QIcon(dataDir.filePath("Images/Icons/Mesh.svg")); - mMappedIcon = new QIcon(dataDir.filePath("Images/Icons/Confirm.svg")); + m_boneIcon = new QIcon(dataDir.filePath("Images/Icons/Bone.svg")); + m_nodeIcon = new QIcon(dataDir.filePath("Images/Icons/Node.svg")); + m_meshIcon = new QIcon(dataDir.filePath("Images/Icons/Mesh.svg")); + m_mappedIcon = new QIcon(dataDir.filePath("Images/Icons/Confirm.svg")); // create the main layout QVBoxLayout* mainLayout = new QVBoxLayout(); @@ -72,36 +72,36 @@ namespace EMStudio toolBarLayout->setMargin(0); toolBarLayout->setSpacing(0); mainLayout->addLayout(toolBarLayout); - mButtonOpen = new QPushButton(); - EMStudioManager::MakeTransparentButton(mButtonOpen, "Images/Icons/Open.svg", "Load and apply a mapping template."); - connect(mButtonOpen, &QPushButton::clicked, this, &MirrorSetupWindow::OnLoadMapping); - mButtonSave = new QPushButton(); - EMStudioManager::MakeTransparentButton(mButtonSave, "Images/Menu/FileSave.svg", "Save the currently setup mapping as template."); - connect(mButtonSave, &QPushButton::clicked, this, &MirrorSetupWindow::OnSaveMapping); - mButtonClear = new QPushButton(); - EMStudioManager::MakeTransparentButton(mButtonClear, "Images/Icons/Clear.svg", "Clear the currently setup mapping entirely."); - connect(mButtonClear, &QPushButton::clicked, this, &MirrorSetupWindow::OnClearMapping); - - mButtonGuess = new QPushButton(); - EMStudioManager::MakeTransparentButton(mButtonGuess, "Images/Icons/Character.svg", "Perform name based mapping."); - connect(mButtonGuess, &QPushButton::clicked, this, &MirrorSetupWindow::OnBestGuess); - - toolBarLayout->addWidget(mButtonOpen, 0, Qt::AlignLeft); - toolBarLayout->addWidget(mButtonSave, 0, Qt::AlignLeft); - toolBarLayout->addWidget(mButtonClear, 0, Qt::AlignLeft); + m_buttonOpen = new QPushButton(); + EMStudioManager::MakeTransparentButton(m_buttonOpen, "Images/Icons/Open.svg", "Load and apply a mapping template."); + connect(m_buttonOpen, &QPushButton::clicked, this, &MirrorSetupWindow::OnLoadMapping); + m_buttonSave = new QPushButton(); + EMStudioManager::MakeTransparentButton(m_buttonSave, "Images/Menu/FileSave.svg", "Save the currently setup mapping as template."); + connect(m_buttonSave, &QPushButton::clicked, this, &MirrorSetupWindow::OnSaveMapping); + m_buttonClear = new QPushButton(); + EMStudioManager::MakeTransparentButton(m_buttonClear, "Images/Icons/Clear.svg", "Clear the currently setup mapping entirely."); + connect(m_buttonClear, &QPushButton::clicked, this, &MirrorSetupWindow::OnClearMapping); + + m_buttonGuess = new QPushButton(); + EMStudioManager::MakeTransparentButton(m_buttonGuess, "Images/Icons/Character.svg", "Perform name based mapping."); + connect(m_buttonGuess, &QPushButton::clicked, this, &MirrorSetupWindow::OnBestGuess); + + toolBarLayout->addWidget(m_buttonOpen, 0, Qt::AlignLeft); + toolBarLayout->addWidget(m_buttonSave, 0, Qt::AlignLeft); + toolBarLayout->addWidget(m_buttonClear, 0, Qt::AlignLeft); toolBarLayout->addSpacerItem(new QSpacerItem(100, 1, QSizePolicy::Expanding, QSizePolicy::Minimum)); QHBoxLayout* leftRightLayout = new QHBoxLayout(); leftRightLayout->addWidget(new QLabel("Left:"), 0, Qt::AlignRight); - mLeftEdit = new QLineEdit("Bip01 L"); - mLeftEdit->setMaximumWidth(75); - leftRightLayout->addWidget(mLeftEdit, 0, Qt::AlignRight); - mRightEdit = new QLineEdit("Bip01 R"); - mRightEdit->setMaximumWidth(75); + m_leftEdit = new QLineEdit("Bip01 L"); + m_leftEdit->setMaximumWidth(75); + leftRightLayout->addWidget(m_leftEdit, 0, Qt::AlignRight); + m_rightEdit = new QLineEdit("Bip01 R"); + m_rightEdit->setMaximumWidth(75); leftRightLayout->addWidget(new QLabel("Right:"), 0, Qt::AlignRight); - leftRightLayout->addWidget(mRightEdit, 0, Qt::AlignRight); - leftRightLayout->addWidget(mButtonGuess, 0, Qt::AlignRight); + leftRightLayout->addWidget(m_rightEdit, 0, Qt::AlignRight); + leftRightLayout->addWidget(m_buttonGuess, 0, Qt::AlignRight); leftRightLayout->setSpacing(6); leftRightLayout->setMargin(0); @@ -140,36 +140,35 @@ namespace EMStudio curSearchLayout->setSpacing(6); curSearchLayout->setMargin(0); - mCurrentList = new QTableWidget(); - mCurrentList->setAlternatingRowColors(true); - mCurrentList->setGridStyle(Qt::SolidLine); - mCurrentList->setSelectionBehavior(QAbstractItemView::SelectRows); - mCurrentList->setSelectionMode(QAbstractItemView::SingleSelection); - //mCurrentList->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - mCurrentList->setCornerButtonEnabled(false); - mCurrentList->setEditTriggers(QAbstractItemView::NoEditTriggers); - mCurrentList->setContextMenuPolicy(Qt::DefaultContextMenu); - mCurrentList->setColumnCount(3); - mCurrentList->setColumnWidth(0, 20); - mCurrentList->setColumnWidth(1, 20); - mCurrentList->setSortingEnabled(true); - QHeaderView* verticalHeader = mCurrentList->verticalHeader(); + m_currentList = new QTableWidget(); + m_currentList->setAlternatingRowColors(true); + m_currentList->setGridStyle(Qt::SolidLine); + m_currentList->setSelectionBehavior(QAbstractItemView::SelectRows); + m_currentList->setSelectionMode(QAbstractItemView::SingleSelection); + m_currentList->setCornerButtonEnabled(false); + m_currentList->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_currentList->setContextMenuPolicy(Qt::DefaultContextMenu); + m_currentList->setColumnCount(3); + m_currentList->setColumnWidth(0, 20); + m_currentList->setColumnWidth(1, 20); + m_currentList->setSortingEnabled(true); + QHeaderView* verticalHeader = m_currentList->verticalHeader(); verticalHeader->setVisible(false); QTableWidgetItem* headerItem = new QTableWidgetItem(""); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mCurrentList->setHorizontalHeaderItem(0, headerItem); + m_currentList->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem(""); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mCurrentList->setHorizontalHeaderItem(1, headerItem); + m_currentList->setHorizontalHeaderItem(1, headerItem); headerItem = new QTableWidgetItem("Name"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mCurrentList->setHorizontalHeaderItem(2, headerItem); - mCurrentList->horizontalHeader()->setStretchLastSection(true); - mCurrentList->horizontalHeader()->setSortIndicatorShown(false); - mCurrentList->horizontalHeader()->setSectionsClickable(false); - connect(mCurrentList, &QTableWidget::itemSelectionChanged, this, &MirrorSetupWindow::OnCurrentListSelectionChanged); - connect(mCurrentList, &QTableWidget::itemDoubleClicked, this, &MirrorSetupWindow::OnCurrentListDoubleClicked); - leftListLayout->addWidget(mCurrentList); + m_currentList->setHorizontalHeaderItem(2, headerItem); + m_currentList->horizontalHeader()->setStretchLastSection(true); + m_currentList->horizontalHeader()->setSortIndicatorShown(false); + m_currentList->horizontalHeader()->setSectionsClickable(false); + connect(m_currentList, &QTableWidget::itemSelectionChanged, this, &MirrorSetupWindow::OnCurrentListSelectionChanged); + connect(m_currentList, &QTableWidget::itemDoubleClicked, this, &MirrorSetupWindow::OnCurrentListDoubleClicked); + leftListLayout->addWidget(m_currentList); // add link button middle part QVBoxLayout* middleLayout = new QVBoxLayout(); @@ -204,35 +203,34 @@ namespace EMStudio sourceSearchLayout->setSpacing(6); sourceSearchLayout->setMargin(0); - mSourceList = new QTableWidget(); - mSourceList->setAlternatingRowColors(true); - mSourceList->setGridStyle(Qt::SolidLine); - mSourceList->setSelectionBehavior(QAbstractItemView::SelectRows); - mSourceList->setSelectionMode(QAbstractItemView::SingleSelection); - //mSourceList->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - mSourceList->setCornerButtonEnabled(false); - mSourceList->setEditTriggers(QAbstractItemView::NoEditTriggers); - mSourceList->setContextMenuPolicy(Qt::DefaultContextMenu); - mSourceList->setColumnCount(3); - mSourceList->setColumnWidth(0, 20); - mSourceList->setColumnWidth(1, 20); - mSourceList->setSortingEnabled(true); - verticalHeader = mSourceList->verticalHeader(); + m_sourceList = new QTableWidget(); + m_sourceList->setAlternatingRowColors(true); + m_sourceList->setGridStyle(Qt::SolidLine); + m_sourceList->setSelectionBehavior(QAbstractItemView::SelectRows); + m_sourceList->setSelectionMode(QAbstractItemView::SingleSelection); + m_sourceList->setCornerButtonEnabled(false); + m_sourceList->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_sourceList->setContextMenuPolicy(Qt::DefaultContextMenu); + m_sourceList->setColumnCount(3); + m_sourceList->setColumnWidth(0, 20); + m_sourceList->setColumnWidth(1, 20); + m_sourceList->setSortingEnabled(true); + verticalHeader = m_sourceList->verticalHeader(); verticalHeader->setVisible(false); headerItem = new QTableWidgetItem(""); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mSourceList->setHorizontalHeaderItem(0, headerItem); + m_sourceList->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem(""); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mSourceList->setHorizontalHeaderItem(1, headerItem); + m_sourceList->setHorizontalHeaderItem(1, headerItem); headerItem = new QTableWidgetItem("Name"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mSourceList->setHorizontalHeaderItem(2, headerItem); - mSourceList->horizontalHeader()->setStretchLastSection(true); - mSourceList->horizontalHeader()->setSortIndicatorShown(false); - mSourceList->horizontalHeader()->setSectionsClickable(false); - connect(mSourceList, &QTableWidget::itemSelectionChanged, this, &MirrorSetupWindow::OnSourceListSelectionChanged); - rightListLayout->addWidget(mSourceList); + m_sourceList->setHorizontalHeaderItem(2, headerItem); + m_sourceList->horizontalHeader()->setStretchLastSection(true); + m_sourceList->horizontalHeader()->setSortIndicatorShown(false); + m_sourceList->horizontalHeader()->setSectionsClickable(false); + connect(m_sourceList, &QTableWidget::itemSelectionChanged, this, &MirrorSetupWindow::OnSourceListSelectionChanged); + rightListLayout->addWidget(m_sourceList); // create the mapping table QVBoxLayout* lowerLayout = new QVBoxLayout(); @@ -244,53 +242,48 @@ namespace EMStudio mappingLayout->setMargin(0); lowerLayout->addLayout(mappingLayout); mappingLayout->addWidget(new QLabel("Mapping:"), 0, Qt::AlignLeft | Qt::AlignVCenter); - //mButtonGuess = new QPushButton(); - //EMStudioManager::MakeTransparentButton( mButtonGuess, "Images/Icons/Character.svg", "Best guess mapping" ); - //connect( mButtonGuess, SIGNAL(clicked()), this, SLOT(OnBestGuessGeometrical()) ); - //mappingLayout->addWidget( mButtonGuess, 0, Qt::AlignLeft ); spacerWidget = new QWidget(); spacerWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Minimum); mappingLayout->addWidget(spacerWidget); - mMappingTable = new QTableWidget(); - lowerLayout->addWidget(mMappingTable); - mMappingTable->setAlternatingRowColors(true); - mMappingTable->setGridStyle(Qt::SolidLine); - mMappingTable->setSelectionBehavior(QAbstractItemView::SelectRows); - mMappingTable->setSelectionMode(QAbstractItemView::SingleSelection); - //mMappingTable->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); - mMappingTable->setCornerButtonEnabled(false); - mMappingTable->setEditTriggers(QAbstractItemView::NoEditTriggers); - mMappingTable->setContextMenuPolicy(Qt::DefaultContextMenu); - mMappingTable->setContentsMargins(3, 1, 3, 1); - mMappingTable->setColumnCount(2); - mMappingTable->setColumnWidth(0, mMappingTable->width() / 2); - mMappingTable->setColumnWidth(1, mMappingTable->width() / 2); - verticalHeader = mMappingTable->verticalHeader(); + m_mappingTable = new QTableWidget(); + lowerLayout->addWidget(m_mappingTable); + m_mappingTable->setAlternatingRowColors(true); + m_mappingTable->setGridStyle(Qt::SolidLine); + m_mappingTable->setSelectionBehavior(QAbstractItemView::SelectRows); + m_mappingTable->setSelectionMode(QAbstractItemView::SingleSelection); + m_mappingTable->setCornerButtonEnabled(false); + m_mappingTable->setEditTriggers(QAbstractItemView::NoEditTriggers); + m_mappingTable->setContextMenuPolicy(Qt::DefaultContextMenu); + m_mappingTable->setContentsMargins(3, 1, 3, 1); + m_mappingTable->setColumnCount(2); + m_mappingTable->setColumnWidth(0, m_mappingTable->width() / 2); + m_mappingTable->setColumnWidth(1, m_mappingTable->width() / 2); + verticalHeader = m_mappingTable->verticalHeader(); verticalHeader->setVisible(false); // add the table headers headerItem = new QTableWidgetItem("Node"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMappingTable->setHorizontalHeaderItem(0, headerItem); + m_mappingTable->setHorizontalHeaderItem(0, headerItem); headerItem = new QTableWidgetItem("Mapped to"); headerItem->setTextAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mMappingTable->setHorizontalHeaderItem(1, headerItem); - mMappingTable->horizontalHeader()->setStretchLastSection(true); - mMappingTable->horizontalHeader()->setSortIndicatorShown(false); - mMappingTable->horizontalHeader()->setSectionsClickable(false); - connect(mMappingTable, &QTableWidget::itemDoubleClicked, this, &MirrorSetupWindow::OnMappingTableDoubleClicked); - connect(mMappingTable, &QTableWidget::itemSelectionChanged, this, &MirrorSetupWindow::OnMappingTableSelectionChanged); + m_mappingTable->setHorizontalHeaderItem(1, headerItem); + m_mappingTable->horizontalHeader()->setStretchLastSection(true); + m_mappingTable->horizontalHeader()->setSortIndicatorShown(false); + m_mappingTable->horizontalHeader()->setSectionsClickable(false); + connect(m_mappingTable, &QTableWidget::itemDoubleClicked, this, &MirrorSetupWindow::OnMappingTableDoubleClicked); + connect(m_mappingTable, &QTableWidget::itemSelectionChanged, this, &MirrorSetupWindow::OnMappingTableSelectionChanged); } // destructor MirrorSetupWindow::~MirrorSetupWindow() { - delete mBoneIcon; - delete mNodeIcon; - delete mMeshIcon; - delete mMappedIcon; + delete m_boneIcon; + delete m_nodeIcon; + delete m_meshIcon; + delete m_mappedIcon; } @@ -298,7 +291,7 @@ namespace EMStudio void MirrorSetupWindow::OnMappingTableDoubleClicked(QTableWidgetItem* item) { MCORE_UNUSED(item); - // TODO: open a node hierarchy widget, where we can select a node from the mSourceActor + // TODO: open a node hierarchy widget, where we can select a node from the m_sourceActor // the problem is that the node hierarchy widget works with actor instances, which we don't have and do not really want to create either // I think the node hierarchy widget shouldn't use actor instances only, but should support actors as well } @@ -322,26 +315,26 @@ namespace EMStudio // get the node name const uint32 rowIndex = item->row(); - const AZStd::string nodeName = mCurrentList->item(rowIndex, 2)->text().toUtf8().data(); + const AZStd::string nodeName = m_currentList->item(rowIndex, 2)->text().toUtf8().data(); // find its index in the current actor, and remove its mapping EMotionFX::Node* node = currentActor->GetSkeleton()->FindNodeByName(nodeName.c_str()); MCORE_ASSERT(node); // remove the mapping for this node - PerformMapping(node->GetNodeIndex(), MCORE_INVALIDINDEX32); + PerformMapping(node->GetNodeIndex(), InvalidIndex); } // current list selection changed void MirrorSetupWindow::OnCurrentListSelectionChanged() { - QList items = mCurrentList->selectedItems(); + QList items = m_currentList->selectedItems(); if (items.count() > 0) { //const uint32 currentListRow = items[0]->row(); - QTableWidgetItem* nameItem = mCurrentList->item(items[0]->row(), 2); - QList mappingTableItems = mMappingTable->findItems(nameItem->text(), Qt::MatchExactly); + QTableWidgetItem* nameItem = m_currentList->item(items[0]->row(), 2); + QList mappingTableItems = m_mappingTable->findItems(nameItem->text(), Qt::MatchExactly); for (int32 i = 0; i < mappingTableItems.count(); ++i) { @@ -352,8 +345,8 @@ namespace EMStudio const uint32 rowIndex = mappingTableItems[i]->row(); - mMappingTable->selectRow(rowIndex); - mMappingTable->setCurrentItem(mappingTableItems[i]); + m_mappingTable->selectRow(rowIndex); + m_mappingTable->setCurrentItem(mappingTableItems[i]); } } } @@ -362,12 +355,12 @@ namespace EMStudio // source list selection changed void MirrorSetupWindow::OnSourceListSelectionChanged() { - QList items = mSourceList->selectedItems(); + QList items = m_sourceList->selectedItems(); if (items.count() > 0) { //const uint32 currentListRow = items[0]->row(); - QTableWidgetItem* nameItem = mSourceList->item(items[0]->row(), 2); - QList mappingTableItems = mMappingTable->findItems(nameItem->text(), Qt::MatchExactly); + QTableWidgetItem* nameItem = m_sourceList->item(items[0]->row(), 2); + QList mappingTableItems = m_mappingTable->findItems(nameItem->text(), Qt::MatchExactly); for (int32 i = 0; i < mappingTableItems.count(); ++i) { @@ -378,8 +371,8 @@ namespace EMStudio const uint32 rowIndex = mappingTableItems[i]->row(); - mMappingTable->selectRow(rowIndex); - mMappingTable->setCurrentItem(mappingTableItems[i]); + m_mappingTable->selectRow(rowIndex); + m_mappingTable->setCurrentItem(mappingTableItems[i]); } } } @@ -389,30 +382,30 @@ namespace EMStudio void MirrorSetupWindow::OnMappingTableSelectionChanged() { // select both items in the list widgets as well - QList items = mMappingTable->selectedItems(); + QList items = m_mappingTable->selectedItems(); if (items.count() > 0) { const uint32 rowIndex = items[0]->row(); - QTableWidgetItem* item = mMappingTable->item(rowIndex, 0); + QTableWidgetItem* item = m_mappingTable->item(rowIndex, 0); if (item) { - QList listItems = mCurrentList->findItems(item->text(), Qt::MatchExactly); + QList listItems = m_currentList->findItems(item->text(), Qt::MatchExactly); if (listItems.count() > 0) { - mCurrentList->selectRow(listItems[0]->row()); - mCurrentList->setCurrentItem(listItems[0]); + m_currentList->selectRow(listItems[0]->row()); + m_currentList->setCurrentItem(listItems[0]); } } - item = mMappingTable->item(rowIndex, 1); + item = m_mappingTable->item(rowIndex, 1); if (item) { - QList listItems = mSourceList->findItems(item->text(), Qt::MatchExactly); + QList listItems = m_sourceList->findItems(item->text(), Qt::MatchExactly); if (listItems.count() > 0) { - mSourceList->selectRow(listItems[0]->row()); - mSourceList->setCurrentItem(listItems[0]); + m_sourceList->selectRow(listItems[0]->row()); + m_sourceList->setCurrentItem(listItems[0]); } } } @@ -432,21 +425,18 @@ namespace EMStudio // extract the list of bones if (currentActor) { - currentActor->ExtractBoneList(0, &mCurrentBoneList); + currentActor->ExtractBoneList(0, &m_currentBoneList); } // clear the node map if (reInitMap) { - mMap.clear(); + m_map.clear(); if (currentActor) { const size_t numNodes = aznumeric_caster(currentActor->GetNumNodes()); - mMap.resize(numNodes); - for (uint32 i = 0; i < numNodes; ++i) - { - mMap[i] = MCORE_INVALIDINDEX32; - } + m_map.resize(numNodes); + AZStd::fill(m_map.begin(), m_map.end(), InvalidIndex); } } @@ -484,17 +474,17 @@ namespace EMStudio { if (!actor) { - mCurrentList->setRowCount(0); + m_currentList->setRowCount(0); return; } // fill the left list widget QString currentName; - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); // count the number of rows - uint32 numRows = 0; - for (uint32 i = 0; i < numNodes; ++i) + int numRows = 0; + for (size_t i = 0; i < numNodes; ++i) { currentName = actor->GetSkeleton()->GetNode(i)->GetName(); if (currentName.contains(filterString, Qt::CaseInsensitive) || filterString.isEmpty()) @@ -502,46 +492,45 @@ namespace EMStudio numRows++; } } - mCurrentList->setRowCount(numRows); + m_currentList->setRowCount(numRows); // fill the rows - uint32 rowIndex = 0; - for (uint32 i = 0; i < numNodes; ++i) + int rowIndex = 0; + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); currentName = node->GetName(); if (currentName.contains(filterString, Qt::CaseInsensitive) || filterString.isEmpty()) { // mark if there is a mapping or not - const bool mapped = (mMap[node->GetNodeIndex()] != MCORE_INVALIDINDEX32); + const bool mapped = (m_map[node->GetNodeIndex()] != InvalidIndex); QTableWidgetItem* mappedItem = new QTableWidgetItem(); - mappedItem->setIcon(mapped ? *mMappedIcon : QIcon()); - mCurrentList->setItem(rowIndex, 0, mappedItem); + mappedItem->setIcon(mapped ? *m_mappedIcon : QIcon()); + m_currentList->setItem(rowIndex, 0, mappedItem); // pick the right icon for the type column QTableWidgetItem* typeItem = new QTableWidgetItem(); if (actor->GetMesh(0, node->GetNodeIndex())) { - typeItem->setIcon(*mMeshIcon); + typeItem->setIcon(*m_meshIcon); } - else - if (mCurrentBoneList.Contains(node->GetNodeIndex())) + else if (AZStd::find(begin(m_currentBoneList), end(m_currentBoneList), node->GetNodeIndex()) != end(m_currentBoneList)) { - typeItem->setIcon(*mBoneIcon); + typeItem->setIcon(*m_boneIcon); } else { - typeItem->setIcon(*mNodeIcon); + typeItem->setIcon(*m_nodeIcon); } - mCurrentList->setItem(rowIndex, 1, typeItem); + m_currentList->setItem(rowIndex, 1, typeItem); // set the name QTableWidgetItem* currentTableItem = new QTableWidgetItem(currentName); - mCurrentList->setItem(rowIndex, 2, currentTableItem); + m_currentList->setItem(rowIndex, 2, currentTableItem); // set the row height and add one index - mCurrentList->setRowHeight(rowIndex, 21); + m_currentList->setRowHeight(rowIndex, 21); ++rowIndex; } } @@ -553,17 +542,17 @@ namespace EMStudio { if (!actor) { - mSourceList->setRowCount(0); + m_sourceList->setRowCount(0); return; } // fill the left list widget QString name; - const uint32 numNodes = actor->GetNumNodes(); + const size_t numNodes = actor->GetNumNodes(); // count the number of rows - uint32 numRows = 0; - for (uint32 i = 0; i < numNodes; ++i) + int numRows = 0; + for (size_t i = 0; i < numNodes; ++i) { name = actor->GetSkeleton()->GetNode(i)->GetName(); if (name.contains(filterString, Qt::CaseInsensitive) || filterString.isEmpty()) @@ -571,46 +560,45 @@ namespace EMStudio numRows++; } } - mSourceList->setRowCount(numRows); + m_sourceList->setRowCount(numRows); // fill the rows - uint32 rowIndex = 0; - for (uint32 i = 0; i < numNodes; ++i) + int rowIndex = 0; + for (size_t i = 0; i < numNodes; ++i) { EMotionFX::Node* node = actor->GetSkeleton()->GetNode(i); name = node->GetName(); if (name.contains(filterString, Qt::CaseInsensitive) || filterString.isEmpty()) { // mark if there is a mapping or not - const bool mapped = AZStd::find(mMap.begin(), mMap.end(), i) != mMap.end(); + const bool mapped = AZStd::find(m_map.begin(), m_map.end(), i) != m_map.end(); QTableWidgetItem* mappedItem = new QTableWidgetItem(); - mappedItem->setIcon(mapped ? *mMappedIcon : QIcon()); - mSourceList->setItem(rowIndex, 0, mappedItem); + mappedItem->setIcon(mapped ? *m_mappedIcon : QIcon()); + m_sourceList->setItem(rowIndex, 0, mappedItem); // pick the right icon for the type column QTableWidgetItem* typeItem = new QTableWidgetItem(); if (actor->GetMesh(0, node->GetNodeIndex())) { - typeItem->setIcon(*mMeshIcon); + typeItem->setIcon(*m_meshIcon); } - else - if (AZStd::find(mSourceBoneList.begin(), mSourceBoneList.end(), node->GetNodeIndex()) != mSourceBoneList.end()) + else if (AZStd::find(m_sourceBoneList.begin(), m_sourceBoneList.end(), node->GetNodeIndex()) != m_sourceBoneList.end()) { - typeItem->setIcon(*mBoneIcon); + typeItem->setIcon(*m_boneIcon); } else { - typeItem->setIcon(*mNodeIcon); + typeItem->setIcon(*m_nodeIcon); } - mSourceList->setItem(rowIndex, 1, typeItem); + m_sourceList->setItem(rowIndex, 1, typeItem); // set the name QTableWidgetItem* currentTableItem = new QTableWidgetItem(name); - mSourceList->setItem(rowIndex, 2, currentTableItem); + m_sourceList->setItem(rowIndex, 2, currentTableItem); // set the row height and add one index - mSourceList->setRowHeight(rowIndex, 21); + m_sourceList->setRowHeight(rowIndex, 21); ++rowIndex; } } @@ -622,60 +610,58 @@ namespace EMStudio { if (!currentActor) { - mMappingTable->setRowCount(0); + m_mappingTable->setRowCount(0); return; } // fill the table QString currentName; QString sourceName; - const uint32 numNodes = currentActor->GetNumNodes(); - mMappingTable->setRowCount(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + const int numNodes = aznumeric_caster(currentActor->GetNumNodes()); + m_mappingTable->setRowCount(numNodes); + for (int i = 0; i < numNodes; ++i) { currentName = currentActor->GetSkeleton()->GetNode(i)->GetName(); QTableWidgetItem* currentTableItem = new QTableWidgetItem(currentName); - mMappingTable->setItem(i, 0, currentTableItem); - mMappingTable->setRowHeight(i, 21); + m_mappingTable->setItem(i, 0, currentTableItem); + m_mappingTable->setRowHeight(i, 21); - if (mMap[i] != MCORE_INVALIDINDEX32) + if (m_map[i] != InvalidIndex) { - sourceName = sourceActor->GetSkeleton()->GetNode(mMap[i])->GetName(); + sourceName = sourceActor->GetSkeleton()->GetNode(m_map[i])->GetName(); currentTableItem = new QTableWidgetItem(sourceName); - mMappingTable->setItem(i, 1, currentTableItem); + m_mappingTable->setItem(i, 1, currentTableItem); } else { - mMappingTable->setItem(i, 1, new QTableWidgetItem()); + m_mappingTable->setItem(i, 1, new QTableWidgetItem()); } } - //mMappingTable->resizeColumnsToContents(); - //mMappingTable->setColumnWidth(0, mMappingTable->columnWidth(0) + 25); } // pressing the link button void MirrorSetupWindow::OnLinkPressed() { - if (mCurrentList->currentRow() == -1 || mSourceList->currentRow() == -1) + if (m_currentList->currentRow() == -1 || m_sourceList->currentRow() == -1) { return; } // get the names - QTableWidgetItem* curItem = mCurrentList->currentItem(); - QTableWidgetItem* sourceItem = mSourceList->currentItem(); + QTableWidgetItem* curItem = m_currentList->currentItem(); + QTableWidgetItem* sourceItem = m_sourceList->currentItem(); if (!curItem || !sourceItem) { return; } - curItem = mCurrentList->item(curItem->row(), 2); - sourceItem = mSourceList->item(sourceItem->row(), 2); + curItem = m_currentList->item(curItem->row(), 2); + sourceItem = m_sourceList->item(sourceItem->row(), 2); const AZStd::string currentNodeName = curItem->text().toUtf8().data(); - const AZStd::string sourceNodeName = mSourceList->currentItem()->text().toUtf8().data(); + const AZStd::string sourceNodeName = m_sourceList->currentItem()->text().toUtf8().data(); if (sourceNodeName.empty() || currentNodeName.empty()) { return; @@ -694,57 +680,53 @@ namespace EMStudio // perform the mapping - void MirrorSetupWindow::PerformMapping(uint32 currentNodeIndex, uint32 sourceNodeIndex) + void MirrorSetupWindow::PerformMapping(size_t currentNodeIndex, size_t sourceNodeIndex) { EMotionFX::Actor* currentActor = GetSelectedActor(); // update the map - const uint32 oldSourceIndex = mMap[currentNodeIndex]; - mMap[currentNodeIndex] = sourceNodeIndex; + const size_t oldSourceIndex = m_map[currentNodeIndex]; + m_map[currentNodeIndex] = sourceNodeIndex; // update the current table const QString curName = currentActor->GetSkeleton()->GetNode(currentNodeIndex)->GetName(); - const QList currentListItems = mCurrentList->findItems(curName, Qt::MatchExactly); + const QList currentListItems = m_currentList->findItems(curName, Qt::MatchExactly); for (int32 i = 0; i < currentListItems.count(); ++i) { - const uint32 rowIndex = currentListItems[i]->row(); - //if (rowIndex != mCurrentList->currentRow()) - // continue; + const int rowIndex = currentListItems[i]->row(); - QTableWidgetItem* mappedItem = mCurrentList->item(rowIndex, 0); + QTableWidgetItem* mappedItem = m_currentList->item(rowIndex, 0); if (!mappedItem) { mappedItem = new QTableWidgetItem(); - mCurrentList->setItem(rowIndex, 0, mappedItem); + m_currentList->setItem(rowIndex, 0, mappedItem); } - if (sourceNodeIndex == MCORE_INVALIDINDEX32) + if (sourceNodeIndex == InvalidIndex) { mappedItem->setIcon(QIcon()); } else { - mappedItem->setIcon(*mMappedIcon); + mappedItem->setIcon(*m_mappedIcon); } } // update source table - if (sourceNodeIndex != MCORE_INVALIDINDEX32) + if (sourceNodeIndex != InvalidIndex) { - const bool stillUsed = AZStd::find(mMap.begin(), mMap.end(), sourceNodeIndex) != mMap.end(); + const bool stillUsed = AZStd::find(m_map.begin(), m_map.end(), sourceNodeIndex) != m_map.end(); const QString sourceName = currentActor->GetSkeleton()->GetNode(sourceNodeIndex)->GetName(); - const QList sourceListItems = mSourceList->findItems(sourceName, Qt::MatchExactly); + const QList sourceListItems = m_sourceList->findItems(sourceName, Qt::MatchExactly); for (int32 i = 0; i < sourceListItems.count(); ++i) { - const uint32 rowIndex = sourceListItems[i]->row(); - //if (rowIndex != mSourceList->currentRow()) - // continue; + const int rowIndex = sourceListItems[i]->row(); - QTableWidgetItem* mappedItem = mSourceList->item(rowIndex, 0); + QTableWidgetItem* mappedItem = m_sourceList->item(rowIndex, 0); if (!mappedItem) { mappedItem = new QTableWidgetItem(); - mSourceList->setItem(rowIndex, 0, mappedItem); + m_sourceList->setItem(rowIndex, 0, mappedItem); } if (stillUsed == false) @@ -753,28 +735,26 @@ namespace EMStudio } else { - mappedItem->setIcon(*mMappedIcon); + mappedItem->setIcon(*m_mappedIcon); } } } else // we're clearing it { - if (oldSourceIndex != MCORE_INVALIDINDEX32) + if (oldSourceIndex != InvalidIndex) { - const bool stillUsed = AZStd::find(mMap.begin(), mMap.end(), sourceNodeIndex) != mMap.end(); + const bool stillUsed = AZStd::find(m_map.begin(), m_map.end(), sourceNodeIndex) != m_map.end(); const QString sourceName = currentActor->GetSkeleton()->GetNode(oldSourceIndex)->GetName(); - const QList sourceListItems = mSourceList->findItems(sourceName, Qt::MatchExactly); + const QList sourceListItems = m_sourceList->findItems(sourceName, Qt::MatchExactly); for (int32 i = 0; i < sourceListItems.count(); ++i) { - const uint32 rowIndex = sourceListItems[i]->row(); - //if (rowIndex != mSourceList->currentRow()) - // continue; + const int rowIndex = sourceListItems[i]->row(); - QTableWidgetItem* mappedItem = mSourceList->item(rowIndex, 0); + QTableWidgetItem* mappedItem = m_sourceList->item(rowIndex, 0); if (!mappedItem) { mappedItem = new QTableWidgetItem(); - mSourceList->setItem(rowIndex, 0, mappedItem); + m_sourceList->setItem(rowIndex, 0, mappedItem); } if (stillUsed == false) @@ -783,21 +763,21 @@ namespace EMStudio } else { - mappedItem->setIcon(*mMappedIcon); + mappedItem->setIcon(*m_mappedIcon); } } } } // update the mapping table - QTableWidgetItem* item = mMappingTable->item(currentNodeIndex, 1); - if (!item && sourceNodeIndex != MCORE_INVALIDINDEX32) + QTableWidgetItem* item = m_mappingTable->item(aznumeric_caster(currentNodeIndex), 1); + if (!item && sourceNodeIndex != InvalidIndex) { item = new QTableWidgetItem(); - mMappingTable->setItem(currentNodeIndex, 1, item); + m_mappingTable->setItem(aznumeric_caster(currentNodeIndex), 1, item); } - if (sourceNodeIndex == MCORE_INVALIDINDEX32) + if (sourceNodeIndex == InvalidIndex) { if (item) { @@ -840,10 +820,10 @@ namespace EMStudio // remove the currently selected mapping void MirrorSetupWindow::RemoveCurrentSelectedMapping() { - QList items = mCurrentList->selectedItems(); + QList items = m_currentList->selectedItems(); if (items.count() > 0) { - QTableWidgetItem* item = mCurrentList->item(items[0]->row(), 0); + QTableWidgetItem* item = m_currentList->item(items[0]->row(), 0); if (item) { OnCurrentListDoubleClicked(item); @@ -893,15 +873,12 @@ namespace EMStudio } // now update our mapping data - const uint32 numNodes = currentActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) - { - mMap[i] = MCORE_INVALIDINDEX32; - } + const size_t numNodes = currentActor->GetNumNodes(); + AZStd::fill(m_map.begin(), AZStd::next(m_map.begin(), numNodes), InvalidIndex); // now apply the map we loaded to the data we have here - const uint32 numEntries = nodeMap->GetNumEntries(); - for (uint32 i = 0; i < numEntries; ++i) + const size_t numEntries = nodeMap->GetNumEntries(); + for (size_t i = 0; i < numEntries; ++i) { // find the current node EMotionFX::Node* currentNode = currentActor->GetSkeleton()->FindNodeByName(nodeMap->GetFirstName(i)); @@ -918,7 +895,7 @@ namespace EMStudio } // create the mapping - mMap[currentNode->GetNodeIndex()] = sourceNode->GetNodeIndex(); + m_map[currentNode->GetNodeIndex()] = sourceNode->GetNodeIndex(); } // apply the current map as command @@ -963,12 +940,12 @@ namespace EMStudio // create an emfx node map object EMotionFX::NodeMap* map = EMotionFX::NodeMap::Create(); - const uint32 numNodes = currentActor->GetNumNodes(); + const size_t numNodes = currentActor->GetNumNodes(); map->Reserve(numNodes); - for (uint32 i = 0; i < numNodes; ++i) + for (size_t i = 0; i < numNodes; ++i) { // skip unmapped entries - if (mMap[i] == MCORE_INVALIDINDEX32) + if (m_map[i] == InvalidIndex) { continue; } @@ -976,7 +953,7 @@ namespace EMStudio // add the entry to the map if it doesn't yet exist if (map->GetHasEntry(currentActor->GetSkeleton()->GetNode(i)->GetName()) == false) { - map->AddEntry(currentActor->GetSkeleton()->GetNode(i)->GetName(), currentActor->GetSkeleton()->GetNode(mMap[i])->GetName()); + map->AddEntry(currentActor->GetSkeleton()->GetNode(i)->GetName(), currentActor->GetSkeleton()->GetNode(m_map[i])->GetName()); } } @@ -1033,16 +1010,11 @@ namespace EMStudio return true; } - const uint32 numNodes = currentActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = currentActor->GetNumNodes(); + return AZStd::all_of(m_map.begin(), AZStd::next(m_map.begin(), numNodes), [](const size_t nodeIndex) { - if (mMap[i] != MCORE_INVALIDINDEX32) - { - return false; - } - } - - return true; + return nodeIndex != InvalidIndex; + }); } @@ -1058,10 +1030,10 @@ namespace EMStudio const bool canGuess = (currentActor); // enable or disable them - mButtonOpen->setEnabled(canOpen); - mButtonSave->setEnabled(canSave); - mButtonClear->setEnabled(canClear); - mButtonGuess->setEnabled(canGuess); + m_buttonOpen->setEnabled(canOpen); + m_buttonSave->setEnabled(canSave); + m_buttonClear->setEnabled(canClear); + m_buttonGuess->setEnabled(canGuess); } @@ -1075,34 +1047,27 @@ namespace EMStudio return; } - if (mLeftEdit->text().size() == 0 || mRightEdit->text().size() == 0) + if (m_leftEdit->text().size() == 0 || m_rightEdit->text().size() == 0) { QMessageBox::information(this, "Empty Left And Right Strings", "Please enter both a left and right sub-string.\nThis can be something like 'Left' and 'Right'.\nThis would map nodes like 'Left Arm' to 'Right Arm' nodes.", QMessageBox::Ok); return; } - // show a warning that we will overwrite the table entries - //if (QMessageBox::warning(this, "Overwrite Mapping?", "Are you sure you want to possibly overwrite items in the mapping?\nAll or some existing mapping information might be lost.", QMessageBox::Cancel|QMessageBox::Yes) != QMessageBox::Yes) - //return; - - // - // currentActor->MatchNodeMotionSources( FromQtString(mLeftEdit->text()), FromQtString(mRightEdit->text()) ); - // update the table and map uint32 numGuessed = 0; - const uint32 numNodes = currentActor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = currentActor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { // skip already setup mappings - if (mMap[i] != MCORE_INVALIDINDEX32) + if (m_map[i] != InvalidIndex) { continue; } - const uint16 matchIndex = currentActor->FindBestMatchForNode(currentActor->GetSkeleton()->GetNode(i)->GetName(), FromQtString(mLeftEdit->text()).c_str(), FromQtString(mRightEdit->text()).c_str()); + const uint16 matchIndex = currentActor->FindBestMatchForNode(currentActor->GetSkeleton()->GetNode(i)->GetName(), FromQtString(m_leftEdit->text()).c_str(), FromQtString(m_rightEdit->text()).c_str()); if (matchIndex != MCORE_INVALIDINDEX16) { - mMap[i] = matchIndex; + m_map[i] = matchIndex; numGuessed++; } } @@ -1110,28 +1075,6 @@ namespace EMStudio // update the actor UpdateActorMotionSources(); - /* - // try a geometrical mapping - EMotionFX::Pose pose; - pose.InitFromLocalBindSpaceTransforms( currentActor ); - - // for all nodes in the current actor - uint32 numGuessed = 0; - const uint32 numNodes = currentActor->GetNumNodes(); - for (uint32 i=0; iFindBestMirrorMatchForNode( static_cast(i), pose ); - if (matchIndex != MCORE_INVALIDINDEX16) - { - mMap[i] = matchIndex; - numGuessed++; - } - } - */ Reinit(false); // show some results @@ -1148,17 +1091,7 @@ namespace EMStudio { return; } - /* - const uint32 numNodes = currentActor->GetNumNodes(); - for (uint32 i=0; i( mMap[i] ); - } - */ // apply the current map as command ApplyCurrentMapAsCommand(); } @@ -1172,24 +1105,24 @@ namespace EMStudio return; } - const uint32 numNodes = actor->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = actor->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { if (actor->GetHasMirrorInfo()) { - uint16 motionSource = actor->GetNodeMirrorInfo(i).mSourceNode; + uint16 motionSource = actor->GetNodeMirrorInfo(i).m_sourceNode; if (motionSource != i) { - mMap[i] = motionSource; + m_map[i] = motionSource; } else { - mMap[i] = MCORE_INVALIDINDEX32; + m_map[i] = InvalidIndex; } } else { - mMap[i] = MCORE_INVALIDINDEX32; + m_map[i] = InvalidIndex; } } } @@ -1207,10 +1140,10 @@ namespace EMStudio // apply mirror changes AZStd::string commandString = AZStd::string::format("AdjustActor -actorID %d -mirrorSetup \"", currentActor->GetID()); - for (uint32 i = 0; i < currentActor->GetNumNodes(); ++i) + for (size_t i = 0; i < currentActor->GetNumNodes(); ++i) { - uint32 sourceNode = mMap[i]; - if (sourceNode != MCORE_INVALIDINDEX32 && sourceNode != i) + size_t sourceNode = m_map[i]; + if (sourceNode != InvalidIndex && sourceNode != i) { commandString += currentActor->GetSkeleton()->GetNode(i)->GetName(); commandString += ","; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.h index 47c321a1e7..6fc435025b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/MirrorSetupWindow.h @@ -12,7 +12,7 @@ #if !defined(Q_MOC_RUN) #include "../StandardPluginsConfig.h" #include -#include +#include #include #include #include @@ -63,30 +63,30 @@ namespace EMStudio private: - SceneManagerPlugin* mPlugin; - QTableWidget* mSourceList; - QTableWidget* mCurrentList; - QTableWidget* mMappingTable; - QPushButton* mButtonOpen; - QPushButton* mButtonSave; - QPushButton* mButtonClear; - QPushButton* mButtonGuess; - QLineEdit* mLeftEdit; - QLineEdit* mRightEdit; + SceneManagerPlugin* m_plugin; + QTableWidget* m_sourceList; + QTableWidget* m_currentList; + QTableWidget* m_mappingTable; + QPushButton* m_buttonOpen; + QPushButton* m_buttonSave; + QPushButton* m_buttonClear; + QPushButton* m_buttonGuess; + QLineEdit* m_leftEdit; + QLineEdit* m_rightEdit; AzQtComponents::FilteredSearchWidget* m_searchWidgetCurrent; AzQtComponents::FilteredSearchWidget* m_searchWidgetSource; - QIcon* mBoneIcon; - QIcon* mNodeIcon; - QIcon* mMeshIcon; - QIcon* mMappedIcon; - MCore::Array mCurrentBoneList; - AZStd::vector mSourceBoneList; - AZStd::vector mMap; + QIcon* m_boneIcon; + QIcon* m_nodeIcon; + QIcon* m_meshIcon; + QIcon* m_mappedIcon; + AZStd::vector m_currentBoneList; + AZStd::vector m_sourceBoneList; + AZStd::vector m_map; void FillCurrentListWidget(EMotionFX::Actor* actor, const QString& filterString); void FillSourceListWidget(EMotionFX::Actor* actor, const QString& filterString); void FillMappingTable(EMotionFX::Actor* currentActor, EMotionFX::Actor* sourceActor); - void PerformMapping(uint32 currentNodeIndex, uint32 sourceNodeIndex); + void PerformMapping(size_t currentNodeIndex, size_t sourceNodeIndex); void RemoveCurrentSelectedMapping(); void keyPressEvent(QKeyEvent* event); void keyReleaseEvent(QKeyEvent* event); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.cpp index 820cb78d51..3e498f6383 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.cpp @@ -25,8 +25,8 @@ namespace EMStudio { void SaveDirtyActorFilesCallback::GetDirtyFileNames(AZStd::vector* outFileNames, AZStd::vector* outObjects) { - const uint32 numLeaderActors = EMotionFX::GetActorManager().GetNumActors(); - for (uint32 i = 0; i < numLeaderActors; ++i) + const size_t numLeaderActors = EMotionFX::GetActorManager().GetNumActors(); + for (size_t i = 0; i < numLeaderActors; ++i) { EMotionFX::Actor* actor = EMotionFX::GetActorManager().GetActor(i); @@ -38,7 +38,7 @@ namespace EMStudio // add the link to the actual object ObjectPointer objPointer; - objPointer.mActor = actor; + objPointer.m_actor = actor; outObjects->push_back(objPointer); } } @@ -49,18 +49,16 @@ namespace EMStudio { MCORE_UNUSED(filenamesToSave); - const size_t numObjects = objects.size(); - for (size_t i = 0; i < numObjects; ++i) + for (const ObjectPointer& objPointer : objects) { // get the current object pointer and skip directly if the type check fails - ObjectPointer objPointer = objects[i]; - if (objPointer.mActor == nullptr) + if (objPointer.m_actor == nullptr) { continue; } - EMotionFX::Actor* actor = objPointer.mActor; - if (mPlugin->SaveDirtyActor(actor, commandGroup, false) == DirtyFileManager::CANCELED) + EMotionFX::Actor* actor = objPointer.m_actor; + if (m_plugin->SaveDirtyActor(actor, commandGroup, false) == DirtyFileManager::CANCELED) { return DirtyFileManager::CANCELED; } @@ -74,20 +72,20 @@ namespace EMStudio SceneManagerPlugin::SceneManagerPlugin() : EMStudio::DockWidgetPlugin() { - mImportActorCallback = nullptr; - mCreateActorInstanceCallback = nullptr; - mSelectCallback = nullptr; - mUnselectCallback = nullptr; - mClearSelectionCallback = nullptr; - mRemoveActorCallback = nullptr; - mRemoveActorInstanceCallback = nullptr; - mSaveActorAssetInfoCallback = nullptr; - mScaleActorDataCallback = nullptr; - mActorPropsWindow = nullptr; - mAdjustActorCallback = nullptr; - mActorSetCollisionMeshesCallback = nullptr; - mAdjustActorInstanceCallback = nullptr; - mDirtyFilesCallback = nullptr; + m_importActorCallback = nullptr; + m_createActorInstanceCallback = nullptr; + m_selectCallback = nullptr; + m_unselectCallback = nullptr; + m_clearSelectionCallback = nullptr; + m_removeActorCallback = nullptr; + m_removeActorInstanceCallback = nullptr; + m_saveActorAssetInfoCallback = nullptr; + m_scaleActorDataCallback = nullptr; + m_actorPropsWindow = nullptr; + m_adjustActorCallback = nullptr; + m_actorSetCollisionMeshesCallback = nullptr; + m_adjustActorInstanceCallback = nullptr; + m_dirtyFilesCallback = nullptr; } @@ -179,33 +177,33 @@ namespace EMStudio SceneManagerPlugin::~SceneManagerPlugin() { // unregister the command callbacks and get rid of the memory - GetCommandManager()->RemoveCommandCallback(mImportActorCallback, false); - GetCommandManager()->RemoveCommandCallback(mCreateActorInstanceCallback, false); - GetCommandManager()->RemoveCommandCallback(mSelectCallback, false); - GetCommandManager()->RemoveCommandCallback(mUnselectCallback, false); - GetCommandManager()->RemoveCommandCallback(mClearSelectionCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveActorCallback, false); - GetCommandManager()->RemoveCommandCallback(mRemoveActorInstanceCallback, false); - GetCommandManager()->RemoveCommandCallback(mSaveActorAssetInfoCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustActorCallback, false); - GetCommandManager()->RemoveCommandCallback(mActorSetCollisionMeshesCallback, false); - GetCommandManager()->RemoveCommandCallback(mAdjustActorInstanceCallback, false); - GetCommandManager()->RemoveCommandCallback(mScaleActorDataCallback, false); - delete mImportActorCallback; - delete mCreateActorInstanceCallback; - delete mSelectCallback; - delete mUnselectCallback; - delete mClearSelectionCallback; - delete mRemoveActorCallback; - delete mRemoveActorInstanceCallback; - delete mSaveActorAssetInfoCallback; - delete mAdjustActorCallback; - delete mActorSetCollisionMeshesCallback; - delete mAdjustActorInstanceCallback; - delete mScaleActorDataCallback; - - GetMainWindow()->GetDirtyFileManager()->RemoveCallback(mDirtyFilesCallback, false); - delete mDirtyFilesCallback; + GetCommandManager()->RemoveCommandCallback(m_importActorCallback, false); + GetCommandManager()->RemoveCommandCallback(m_createActorInstanceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_selectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_unselectCallback, false); + GetCommandManager()->RemoveCommandCallback(m_clearSelectionCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeActorCallback, false); + GetCommandManager()->RemoveCommandCallback(m_removeActorInstanceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_saveActorAssetInfoCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustActorCallback, false); + GetCommandManager()->RemoveCommandCallback(m_actorSetCollisionMeshesCallback, false); + GetCommandManager()->RemoveCommandCallback(m_adjustActorInstanceCallback, false); + GetCommandManager()->RemoveCommandCallback(m_scaleActorDataCallback, false); + delete m_importActorCallback; + delete m_createActorInstanceCallback; + delete m_selectCallback; + delete m_unselectCallback; + delete m_clearSelectionCallback; + delete m_removeActorCallback; + delete m_removeActorInstanceCallback; + delete m_saveActorAssetInfoCallback; + delete m_adjustActorCallback; + delete m_actorSetCollisionMeshesCallback; + delete m_adjustActorInstanceCallback; + delete m_scaleActorDataCallback; + + GetMainWindow()->GetDirtyFileManager()->RemoveCallback(m_dirtyFilesCallback, false); + delete m_dirtyFilesCallback; } @@ -223,57 +221,57 @@ namespace EMStudio MysticQt::DialogStack* dialogStack = new MysticQt::DialogStack(); // create and register the command callbacks only (only execute this code once for all plugins) - mImportActorCallback = new ImportActorCallback(false); - mCreateActorInstanceCallback = new CreateActorInstanceCallback(false); - mSelectCallback = new CommandSelectCallback(false); - mUnselectCallback = new CommandUnselectCallback(false); - mClearSelectionCallback = new CommandClearSelectionCallback(false); - mRemoveActorCallback = new RemoveActorCallback(false); - mRemoveActorInstanceCallback = new RemoveActorInstanceCallback(false); - mSaveActorAssetInfoCallback = new SaveActorAssetInfoCallback(false); - mAdjustActorCallback = new CommandAdjustActorCallback(false); - mActorSetCollisionMeshesCallback = new CommandActorSetCollisionMeshesCallback(false); - mAdjustActorInstanceCallback = new CommandAdjustActorInstanceCallback(false); - mScaleActorDataCallback = new CommandScaleActorDataCallback(false); - - GetCommandManager()->RegisterCommandCallback("ImportActor", mImportActorCallback); - GetCommandManager()->RegisterCommandCallback("CreateActorInstance", mCreateActorInstanceCallback); - GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); - GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); - GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); - GetCommandManager()->RegisterCommandCallback("RemoveActor", mRemoveActorCallback); - GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", mRemoveActorInstanceCallback); - GetCommandManager()->RegisterCommandCallback("SaveActorAssetInfo", mSaveActorAssetInfoCallback); - GetCommandManager()->RegisterCommandCallback("AdjustActor", mAdjustActorCallback); - GetCommandManager()->RegisterCommandCallback("ActorSetCollisionMeshes", mActorSetCollisionMeshesCallback); - GetCommandManager()->RegisterCommandCallback("AdjustActorInstance", mAdjustActorInstanceCallback); - GetCommandManager()->RegisterCommandCallback("ScaleActorData", mScaleActorDataCallback); + m_importActorCallback = new ImportActorCallback(false); + m_createActorInstanceCallback = new CreateActorInstanceCallback(false); + m_selectCallback = new CommandSelectCallback(false); + m_unselectCallback = new CommandUnselectCallback(false); + m_clearSelectionCallback = new CommandClearSelectionCallback(false); + m_removeActorCallback = new RemoveActorCallback(false); + m_removeActorInstanceCallback = new RemoveActorInstanceCallback(false); + m_saveActorAssetInfoCallback = new SaveActorAssetInfoCallback(false); + m_adjustActorCallback = new CommandAdjustActorCallback(false); + m_actorSetCollisionMeshesCallback = new CommandActorSetCollisionMeshesCallback(false); + m_adjustActorInstanceCallback = new CommandAdjustActorInstanceCallback(false); + m_scaleActorDataCallback = new CommandScaleActorDataCallback(false); + + GetCommandManager()->RegisterCommandCallback("ImportActor", m_importActorCallback); + GetCommandManager()->RegisterCommandCallback("CreateActorInstance", m_createActorInstanceCallback); + GetCommandManager()->RegisterCommandCallback("Select", m_selectCallback); + GetCommandManager()->RegisterCommandCallback("Unselect", m_unselectCallback); + GetCommandManager()->RegisterCommandCallback("ClearSelection", m_clearSelectionCallback); + GetCommandManager()->RegisterCommandCallback("RemoveActor", m_removeActorCallback); + GetCommandManager()->RegisterCommandCallback("RemoveActorInstance", m_removeActorInstanceCallback); + GetCommandManager()->RegisterCommandCallback("SaveActorAssetInfo", m_saveActorAssetInfoCallback); + GetCommandManager()->RegisterCommandCallback("AdjustActor", m_adjustActorCallback); + GetCommandManager()->RegisterCommandCallback("ActorSetCollisionMeshes", m_actorSetCollisionMeshesCallback); + GetCommandManager()->RegisterCommandCallback("AdjustActorInstance", m_adjustActorInstanceCallback); + GetCommandManager()->RegisterCommandCallback("ScaleActorData", m_scaleActorDataCallback); // create the actors window - mActorsWindow = new ActorsWindow(this); + m_actorsWindow = new ActorsWindow(this); // add in the dialog stack - dialogStack->Add(mActorsWindow, "Actors", false, true, true); + dialogStack->Add(m_actorsWindow, "Actors", false, true, true); // create the actor properties window - mActorPropsWindow = new ActorPropertiesWindow(mDock, this); - mActorPropsWindow->Init(); + m_actorPropsWindow = new ActorPropertiesWindow(m_dock, this); + m_actorPropsWindow->Init(); // add the actor properties window to the stack window - dialogStack->Add(mActorPropsWindow, "Actor Properties", false, false, true); + dialogStack->Add(m_actorPropsWindow, "Actor Properties", false, false, true); // set dialog stack as main widget of the dock - mDock->setWidget(dialogStack); + m_dock->setWidget(dialogStack); // connect - connect(mDock, &QDockWidget::visibilityChanged, this, &SceneManagerPlugin::WindowReInit); + connect(m_dock, &QDockWidget::visibilityChanged, this, &SceneManagerPlugin::WindowReInit); // reinit the dialog ReInit(); // initialize the dirty files callback - mDirtyFilesCallback = new SaveDirtyActorFilesCallback(this); - GetMainWindow()->GetDirtyFileManager()->AddCallback(mDirtyFilesCallback); + m_dirtyFilesCallback = new SaveDirtyActorFilesCallback(this); + GetMainWindow()->GetDirtyFileManager()->AddCallback(m_dirtyFilesCallback); return true; } @@ -283,7 +281,7 @@ namespace EMStudio void SceneManagerPlugin::ReInit() { // reinit the actors window - mActorsWindow->ReInit(); + m_actorsWindow->ReInit(); // update the interface UpdateInterface(); @@ -294,10 +292,10 @@ namespace EMStudio void SceneManagerPlugin::UpdateInterface() { // update interface of the actors window - mActorsWindow->UpdateInterface(); + m_actorsWindow->UpdateInterface(); // update interface of the actor properties window - mActorPropsWindow->UpdateInterface(); + m_actorPropsWindow->UpdateInterface(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.h index 5d0bbb50b1..b6d2a55306 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/SceneManager/SceneManagerPlugin.h @@ -37,7 +37,7 @@ namespace EMStudio public: SaveDirtyActorFilesCallback(SceneManagerPlugin* plugin) - : SaveDirtyFilesCallback() { mPlugin = plugin; } + : SaveDirtyFilesCallback() { m_plugin = plugin; } ~SaveDirtyActorFilesCallback() {} uint32 GetType() const override { return TYPE_ID; } @@ -54,7 +54,7 @@ namespace EMStudio int SaveDirtyFiles(const AZStd::vector& filenamesToSave, const AZStd::vector& objects, MCore::CommandGroup* commandGroup) override; private: - SceneManagerPlugin* mPlugin; + SceneManagerPlugin* m_plugin; }; class SceneManagerPlugin @@ -107,22 +107,22 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(CommandAdjustActorInstanceCallback); MCORE_DEFINECOMMANDCALLBACK(CommandScaleActorDataCallback); - ImportActorCallback* mImportActorCallback; - CreateActorInstanceCallback* mCreateActorInstanceCallback; - CommandSelectCallback* mSelectCallback; - CommandUnselectCallback* mUnselectCallback; - CommandClearSelectionCallback* mClearSelectionCallback; - RemoveActorCallback* mRemoveActorCallback; - RemoveActorInstanceCallback* mRemoveActorInstanceCallback; - SaveActorAssetInfoCallback* mSaveActorAssetInfoCallback; - CommandAdjustActorCallback* mAdjustActorCallback; - CommandActorSetCollisionMeshesCallback* mActorSetCollisionMeshesCallback; - CommandAdjustActorInstanceCallback* mAdjustActorInstanceCallback; - CommandScaleActorDataCallback* mScaleActorDataCallback; - - SaveDirtyActorFilesCallback* mDirtyFilesCallback; - - ActorsWindow* mActorsWindow; - ActorPropertiesWindow* mActorPropsWindow; + ImportActorCallback* m_importActorCallback; + CreateActorInstanceCallback* m_createActorInstanceCallback; + CommandSelectCallback* m_selectCallback; + CommandUnselectCallback* m_unselectCallback; + CommandClearSelectionCallback* m_clearSelectionCallback; + RemoveActorCallback* m_removeActorCallback; + RemoveActorInstanceCallback* m_removeActorInstanceCallback; + SaveActorAssetInfoCallback* m_saveActorAssetInfoCallback; + CommandAdjustActorCallback* m_adjustActorCallback; + CommandActorSetCollisionMeshesCallback* m_actorSetCollisionMeshesCallback; + CommandAdjustActorInstanceCallback* m_adjustActorInstanceCallback; + CommandScaleActorDataCallback* m_scaleActorDataCallback; + + SaveDirtyActorFilesCallback* m_dirtyFilesCallback; + + ActorsWindow* m_actorsWindow; + ActorPropertiesWindow* m_actorPropsWindow; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackControlsGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackControlsGroup.cpp index 88e398d1f1..9c4238f23d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackControlsGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackControlsGroup.cpp @@ -129,8 +129,8 @@ namespace EMStudio return false; } - const AZ::u32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (AZ::u32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = EMotionFX::GetActorManager().GetActorInstance(i); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackOptionsGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackOptionsGroup.cpp index c9d794d5d5..4a5cc3f3d5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackOptionsGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/PlaybackOptionsGroup.cpp @@ -81,7 +81,7 @@ namespace EMStudio { const CommandSystem::SelectionList& selection = CommandSystem::GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedMotions = selection.GetNumSelectedMotions(); + const size_t numSelectedMotions = selection.GetNumSelectedMotions(); const bool isEnabled = (numSelectedMotions == 1); m_loopForeverAction->setEnabled(isEnabled); @@ -98,8 +98,8 @@ namespace EMStudio MotionWindowPlugin* motionWindowPlugin = TimeViewToolBar::GetMotionWindowPlugin(); if (motionWindowPlugin) { - const uint32 numMotions = selection.GetNumSelectedMotions(); - for (uint32 i = 0; i < numMotions; ++i) + const size_t numMotions = selection.GetNumSelectedMotions(); + for (size_t i = 0; i < numMotions; ++i) { MotionWindowPlugin::MotionTableEntry* entry = motionWindowPlugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()); if (!entry) @@ -108,18 +108,18 @@ namespace EMStudio continue; } - EMotionFX::Motion* motion = entry->mMotion; + EMotionFX::Motion* motion = entry->m_motion; const EMotionFX::PlayBackInfo* defaultPlayBackInfo = motion->GetDefaultPlayBackInfo(); - m_loopForeverAction->setChecked(defaultPlayBackInfo->mNumLoops == EMFX_LOOPFOREVER); - m_mirrorAction->setChecked(defaultPlayBackInfo->mMirrorMotion); - m_inPlaceAction->setChecked(defaultPlayBackInfo->mInPlace); - m_retargetAction->setChecked(defaultPlayBackInfo->mRetarget); + m_loopForeverAction->setChecked(defaultPlayBackInfo->m_numLoops == EMFX_LOOPFOREVER); + m_mirrorAction->setChecked(defaultPlayBackInfo->m_mirrorMotion); + m_inPlaceAction->setChecked(defaultPlayBackInfo->m_inPlace); + m_retargetAction->setChecked(defaultPlayBackInfo->m_retarget); - const bool playBackward = (defaultPlayBackInfo->mPlayMode == EMotionFX::PLAYMODE_BACKWARD); + const bool playBackward = (defaultPlayBackInfo->m_playMode == EMotionFX::PLAYMODE_BACKWARD); m_backwardAction->setChecked(playBackward); - SetPlaySpeed(defaultPlayBackInfo->mPlaySpeed); + SetPlaySpeed(defaultPlayBackInfo->m_playSpeed); } } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.cpp index 3878f36885..defa8e4701 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.cpp @@ -23,20 +23,19 @@ namespace EMStudio { setObjectName("TimeInfoWidget"); - mPlugin = plugin; + m_plugin = plugin; // init font - mFont.setPixelSize(mShowOverwriteStartTime ? 22 : 18); - mOverwriteFont.setPixelSize(12); - //mFont.setBold( true ); + m_font.setPixelSize(m_showOverwriteStartTime ? 22 : 18); + m_overwriteFont.setPixelSize(12); - mOverwriteStartTime = 0; - mOverwriteEndTime = 0; - mOverwriteMode = false; + m_overwriteStartTime = 0; + m_overwriteEndTime = 0; + m_overwriteMode = false; // init brushes and pens - mPenText = QPen(QColor(200, 200, 200)); - mPenTextFocus = QPen(QColor(244, 156, 28)); + m_penText = QPen(QColor(200, 200, 200)); + m_penTextFocus = QPen(QColor(244, 156, 28)); setFocusPolicy(Qt::StrongFocus); } @@ -58,8 +57,8 @@ namespace EMStudio // set the overwrite time which will be displayed when the overwrite mode is active void TimeInfoWidget::SetOverwriteTime(double startTime, double endTime) { - mOverwriteStartTime = startTime; - mOverwriteEndTime = endTime; + m_overwriteStartTime = startTime; + m_overwriteEndTime = endTime; } @@ -75,91 +74,84 @@ namespace EMStudio QTextOption options; options.setAlignment(Qt::AlignCenter); - if (mPlugin->GetTrackDataWidget()->hasFocus()) + if (m_plugin->GetTrackDataWidget()->hasFocus()) { - painter.setPen(mPenTextFocus); + painter.setPen(m_penTextFocus); } else { - painter.setPen(mPenText); + painter.setPen(m_penText); } - painter.setFont(mFont); - - // use the time of the plugin in case we are not in overwrite mode, if we are use the overwrite time - //uint32 usedTime = mPlugin->mCurTimeX; - //if (mOverwriteMode) - // usedTime = mOverwriteTime; + painter.setFont(m_font); // calculate the time values for this pixel uint32 minutes; uint32 seconds; uint32 milSecs; uint32 frameNumber; - // mPlugin->CalcTime(mPlugin->mCurTimeX/mPlugin->mTimeScale, nullptr, &minutes, &seconds, &milSecs, &frameNumber, false); - mPlugin->DecomposeTime(mPlugin->mCurTime, &minutes, &seconds, &milSecs, &frameNumber); - mCurTimeString = AZStd::string::format("%.2d:%.2d:%.2d", minutes, seconds, milSecs); + m_plugin->DecomposeTime(m_plugin->m_curTime, &minutes, &seconds, &milSecs, &frameNumber); + m_curTimeString = AZStd::string::format("%.2d:%.2d:%.2d", minutes, seconds, milSecs); QRect upperTextRect = event->rect(); - if (mShowOverwriteStartTime) + if (m_showOverwriteStartTime) { upperTextRect.setTop(upperTextRect.top() + 1); upperTextRect.setHeight(upperTextRect.height() - 17); } else { - mPlugin->DecomposeTime(mOverwriteEndTime, &minutes, &seconds, &milSecs, &frameNumber); - mCurTimeString += AZStd::string::format(" / %.2d:%.2d:%.2d", minutes, seconds, milSecs); + m_plugin->DecomposeTime(m_overwriteEndTime, &minutes, &seconds, &milSecs, &frameNumber); + m_curTimeString += AZStd::string::format(" / %.2d:%.2d:%.2d", minutes, seconds, milSecs); } - painter.drawText(upperTextRect, mCurTimeString.c_str(), options); + painter.drawText(upperTextRect, m_curTimeString.c_str(), options); - if (!mShowOverwriteStartTime) + if (!m_showOverwriteStartTime) { return; } - if (mOverwriteStartTime < 0) + if (m_overwriteStartTime < 0) { - mOverwriteStartTime = 0; + m_overwriteStartTime = 0; } - if (mOverwriteEndTime < 0) + if (m_overwriteEndTime < 0) { - mOverwriteEndTime = 0; + m_overwriteEndTime = 0; } // calculate the time values for the overwrite time uint32 minutesStart, minutesEnd; uint32 secondsStart, secondsEnd; uint32 milSecsStart, milSecsEnd; - mPlugin->DecomposeTime(mOverwriteStartTime, &minutesStart, &secondsStart, &milSecsStart, &frameNumber); - mPlugin->DecomposeTime(mOverwriteEndTime, &minutesEnd, &secondsEnd, &milSecsEnd, &frameNumber); + m_plugin->DecomposeTime(m_overwriteStartTime, &minutesStart, &secondsStart, &milSecsStart, &frameNumber); + m_plugin->DecomposeTime(m_overwriteEndTime, &minutesEnd, &secondsEnd, &milSecsEnd, &frameNumber); // use the duration of the motion or recording if (minutesStart == minutesEnd && secondsStart == secondsEnd && milSecsStart == milSecsEnd) { - //mOverwriteTimeString = AZStd::string::format("%.2d:%.2d:%.2d", minutesStart, secondsStart, milSecsStart); uint32 dummyFrame; double duration; - mPlugin->GetDataTimes(&duration, nullptr, nullptr); - mPlugin->DecomposeTime(duration, &minutesEnd, &secondsEnd, &milSecsEnd, &dummyFrame); + m_plugin->GetDataTimes(&duration, nullptr, nullptr); + m_plugin->DecomposeTime(duration, &minutesEnd, &secondsEnd, &milSecsEnd, &dummyFrame); } - mOverwriteTimeString = AZStd::string::format("%.2d:%.2d:%.2d / %.2d:%.2d:%.2d", minutesStart, secondsStart, milSecsStart, minutesEnd, secondsEnd, milSecsEnd); + m_overwriteTimeString = AZStd::string::format("%.2d:%.2d:%.2d / %.2d:%.2d:%.2d", minutesStart, secondsStart, milSecsStart, minutesEnd, secondsEnd, milSecsEnd); QRect lowerTextRect = event->rect(); lowerTextRect.setTop(upperTextRect.height()); - painter.setFont(mOverwriteFont); - painter.drawText(lowerTextRect, mOverwriteTimeString.c_str(), options); + painter.setFont(m_overwriteFont); + painter.drawText(lowerTextRect, m_overwriteTimeString.c_str(), options); } // propagate key events to the plugin and let it handle by a shared function void TimeInfoWidget::keyPressEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyPressEvent(event); + m_plugin->OnKeyPressEvent(event); } } @@ -167,9 +159,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TimeInfoWidget::keyReleaseEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyReleaseEvent(event); + m_plugin->OnKeyReleaseEvent(event); } } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.h index 3c1146ed5b..bc9ac258eb 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeInfoWidget.h @@ -36,8 +36,8 @@ namespace EMStudio TimeInfoWidget(TimeViewPlugin* plugin, QWidget* parent = nullptr); ~TimeInfoWidget(); - bool GetIsOverwriteMode() { return mOverwriteMode; } - void SetIsOverwriteMode(bool active) { mOverwriteMode = active; } + bool GetIsOverwriteMode() { return m_overwriteMode; } + void SetIsOverwriteMode(bool active) { m_overwriteMode = active; } void SetOverwriteTime(double startTime, double endTime); protected: @@ -45,18 +45,18 @@ namespace EMStudio QSize sizeHint() const; private: - QFont mFont; - QFont mOverwriteFont; - QBrush mBrushBackground; - QPen mPenText; - QPen mPenTextFocus; - AZStd::string mCurTimeString; - AZStd::string mOverwriteTimeString; - TimeViewPlugin* mPlugin; - double mOverwriteStartTime; - double mOverwriteEndTime; - bool mOverwriteMode; - bool mShowOverwriteStartTime = false; + QFont m_font; + QFont m_overwriteFont; + QBrush m_brushBackground; + QPen m_penText; + QPen m_penTextFocus; + AZStd::string m_curTimeString; + AZStd::string m_overwriteTimeString; + TimeViewPlugin* m_plugin; + double m_overwriteStartTime; + double m_overwriteEndTime; + bool m_overwriteMode; + bool m_showOverwriteStartTime = false; void keyPressEvent(QKeyEvent* event); void keyReleaseEvent(QKeyEvent* event); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.cpp index 26c85cf377..550e95eeef 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.cpp @@ -6,6 +6,7 @@ * */ +#include #include "TimeTrack.h" #include "TimeViewPlugin.h" #include @@ -18,24 +19,22 @@ namespace EMStudio // the constructor TimeTrack::TimeTrack(TimeViewPlugin* plugin) { - mPlugin = plugin; - mHeight = 20; - mStartY = 0; - mEnabled = false; - mIsHighlighted = false; - mVisible = false; - mDeletable = true; + m_plugin = plugin; + m_height = 20; + m_startY = 0; + m_enabled = false; + m_isHighlighted = false; + m_visible = false; + m_deletable = true; // init font - mFont.setPixelSize(14); - //mFont.setBold( true ); + m_font.setPixelSize(14); // init brushes and pens - mBrushDataBG = QColor(60, 65, 70); - //mBrushDataBG = QColor(50, 50, 50); - mBrushDataDisabledBG = QColor(50, 50, 50);// use the same color //QBrush( QColor(33, 33, 33) ); - mBrushHeaderBG = QBrush(QColor(30, 30, 30)); - mPenText = QPen(QColor(255, 255, 255)); + m_brushDataBg = QColor(60, 65, 70); + m_brushDataDisabledBg = QColor(50, 50, 50);// use the same color //QBrush( QColor(33, 33, 33) ); + m_brushHeaderBg = QBrush(QColor(30, 30, 30)); + m_penText = QPen(QColor(255, 255, 255)); } @@ -51,14 +50,14 @@ namespace EMStudio { MCORE_UNUSED(width); - if (mVisible == false) + if (m_visible == false) { return; } - int32 animEndPixel = aznumeric_cast(mPlugin->TimeToPixel(animationLength)); - int32 clipStartPixel = aznumeric_cast(mPlugin->TimeToPixel(clipStartTime)); - int32 clipEndPixel = aznumeric_cast(mPlugin->TimeToPixel(clipEndTime)); + int32 animEndPixel = aznumeric_cast(m_plugin->TimeToPixel(animationLength)); + int32 clipStartPixel = aznumeric_cast(m_plugin->TimeToPixel(clipStartTime)); + int32 clipEndPixel = aznumeric_cast(m_plugin->TimeToPixel(clipEndTime)); // fill the background uint32 height = GetHeight(); @@ -67,17 +66,17 @@ namespace EMStudio QRect clipStartRect(0, startY, clipStartPixel, height); QRect clipEndRect(clipEndPixel, startY, animEndPixel - clipEndPixel, height); - QColor disabledBGColor = mBrushDataDisabledBG; - QColor bgColor = mBrushDataBG; + QColor disabledBGColor = m_brushDataDisabledBg; + QColor bgColor = m_brushDataBg; // make the colors a bit lighter so that we see some highlighting effect - if (mIsHighlighted) + if (m_isHighlighted) { disabledBGColor = disabledBGColor.lighter(120); bgColor = bgColor.lighter(120); } - if (mEnabled) + if (m_enabled) { painter.setPen(Qt::NoPen); painter.setBrush(disabledBGColor); @@ -104,10 +103,10 @@ namespace EMStudio // render all elements //uint32 numRenderedElements = 0; - const size_t numElems = mElements.size(); + const size_t numElems = m_elements.size(); for (size_t i = 0; i < numElems; ++i) { - TimeTrackElement* element = mElements[i]; + TimeTrackElement* element = m_elements[i]; // skip rendering the element in case it is not inside the visible area in the widget if (element->GetEndTime() < startTime || @@ -116,7 +115,7 @@ namespace EMStudio continue; } - bool enabled = mEnabled; + bool enabled = m_enabled; // make sure we render the motion event as disabled as soon as it is in the clipped area if (element->GetEndTime() < clipStartTime || @@ -136,7 +135,7 @@ namespace EMStudio // render the track header void TimeTrack::RenderHeader(QPainter& painter, uint32 width, int32 startY) { - if (mVisible == false) + if (m_visible == false) { return; } @@ -146,14 +145,14 @@ namespace EMStudio QRect rect(0, startY, width, height); painter.setPen(Qt::NoPen); - painter.setBrush(mBrushHeaderBG); + painter.setBrush(m_brushHeaderBg); painter.drawRect(rect); // render the name QTextOption options; options.setAlignment(Qt::AlignCenter); - painter.setPen(mPenText); - painter.drawText(rect, mName.c_str(), options); + painter.setPen(m_penText); + painter.drawText(rect, m_name.c_str(), options); } @@ -162,31 +161,28 @@ namespace EMStudio { if (delFromMem) { - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + for (TimeTrackElement* element : m_elements) { - delete mElements[i]; + delete element; } } - mElements.clear(); + m_elements.clear(); } // get the track element at a given pixel - TimeTrackElement* TimeTrack::GetElementAt(int32 x, int32 y) + TimeTrackElement* TimeTrack::GetElementAt(int32 x, int32 y) const { - if (mVisible == false) + if (m_visible == false) { return nullptr; } // for all elements - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + for (TimeTrackElement* element : m_elements) { // check if its inside - TimeTrackElement* element = mElements[i]; if (element->GetIsVisible() == false) { continue; @@ -203,66 +199,49 @@ namespace EMStudio // calculate the number of selected elements - uint32 TimeTrack::CalcNumSelectedElements() const + size_t TimeTrack::CalcNumSelectedElements() const { - if (mVisible == false) + if (m_visible == false) { return 0; } - uint32 result = 0; - - // for all elements - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + return AZStd::accumulate(begin(m_elements), end(m_elements), size_t{0}, [](size_t total, const TimeTrackElement* element) { - if (mElements[i]->GetIsSelected()) - { - result++; - } - } - - return result; + return total + element->GetIsSelected(); + }); } // find and return the first of the selected elements TimeTrackElement* TimeTrack::GetFirstSelectedElement() const { - if (mVisible == false) + if (m_visible == false) { return nullptr; } - // get the number of elements and iterate through them - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + const auto foundElement = AZStd::find_if(begin(m_elements), end(m_elements), [](const TimeTrackElement* element) { - // return the first selected element that we find - if (mElements[i]->GetIsSelected()) - { - return mElements[i]; - } - } - - // no selected element found - return nullptr; + return element->GetIsSelected(); + }); + return foundElement != end(m_elements) ? *foundElement : nullptr; } // select elements in a given range, unselect all other - void TimeTrack::RangeSelectElements(uint32 elementStartNr, uint32 elementEndNr) + void TimeTrack::RangeSelectElements(size_t elementStartNr, size_t elementEndNr) { // make sure the start number is actually the smaller one of the two values - const uint32 startNr = MCore::Min(elementStartNr, elementEndNr); - const uint32 endNr = MCore::Max(elementStartNr, elementEndNr); + const size_t startNr = AZStd::min(elementStartNr, elementEndNr); + const size_t endNr = AZStd::max(elementStartNr, elementEndNr); // get the number of elements and iterate through them - const size_t numElems = mElements.size(); + const size_t numElems = m_elements.size(); for (size_t i = 0; i < numElems; ++i) { const size_t elementNr = i; - TimeTrackElement* element = mElements[i]; + TimeTrackElement* element = m_elements[i]; // check if the current element is in range if (elementNr >= startNr && elementNr <= endNr) @@ -281,11 +260,9 @@ namespace EMStudio void TimeTrack::SelectElementsInRect(const QRect& rect, bool overwriteCurSelection, bool select, bool toggleMode) { // get the number of elements and iterate through them - const size_t numElems = mElements.size(); - for (size_t i = 0; i < numElems; ++i) + for (TimeTrackElement* element : m_elements) { // get the current element and the corresponding rect - TimeTrackElement* element = mElements[i]; QRect elementRect = element->CalcRect(); if (elementRect.intersects(rect)) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.h index 4e8731ecad..2d6023844c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrack.h @@ -37,80 +37,80 @@ namespace EMStudio TimeTrack(TimeViewPlugin* plugin); ~TimeTrack(); - void SetHeight(uint32 height) { mHeight = height; } - MCORE_INLINE uint32 GetHeight() const { return mHeight; } + void SetHeight(uint32 height) { m_height = height; } + MCORE_INLINE uint32 GetHeight() const { return m_height; } void RenderHeader(QPainter& painter, uint32 width, int32 startY); // @param startTime The time in seconds of the left border of the visible area in the widget. void RenderData(QPainter& painter, uint32 width, int32 startY, double startTime, double endTime, double animationLength, double clipStartTime, double clipEndTime); - MCORE_INLINE uint32 GetNumElements() const { return static_cast(mElements.size()); } - MCORE_INLINE TimeTrackElement* GetElement(uint32 index) const { return mElements[static_cast(index)]; } - void AddElement(TimeTrackElement* elem) { elem->SetTrack(this); mElements.push_back(elem); } + MCORE_INLINE size_t GetNumElements() const { return m_elements.size(); } + MCORE_INLINE TimeTrackElement* GetElement(size_t index) const { return m_elements[index]; } + void AddElement(TimeTrackElement* elem) { elem->SetTrack(this); m_elements.push_back(elem); } void RemoveElement(TimeTrackElement* elem, bool delFromMem = true) { - mElements.erase(AZStd::remove(mElements.begin(), mElements.end(), elem), mElements.end()); + m_elements.erase(AZStd::remove(m_elements.begin(), m_elements.end(), elem), m_elements.end()); if (delFromMem) { delete elem; } } - void RemoveElement(uint32 index, bool delFromMem = true) + void RemoveElement(size_t index, bool delFromMem = true) { if (delFromMem) { - delete mElements[index]; + delete m_elements[index]; } - mElements.erase(mElements.begin() + index); + m_elements.erase(m_elements.begin() + index); } void RemoveAllElements(bool delFromMem = true); void SetElementCount(size_t count) { - mElements.resize(count); + m_elements.resize(count); } - uint32 CalcNumSelectedElements() const; + size_t CalcNumSelectedElements() const; TimeTrackElement* GetFirstSelectedElement() const; - void RangeSelectElements(uint32 elementStartNr, uint32 elementEndNr); + void RangeSelectElements(size_t elementStartNr, size_t elementEndNr); void SelectElementsInRect(const QRect& rect, bool overwriteCurSelection, bool select, bool toggleMode); - MCORE_INLINE TimeViewPlugin* GetPlugin() { return mPlugin; } - MCORE_INLINE void SetStartY(uint32 y) { mStartY = y; } - MCORE_INLINE uint32 GetStartY() const { return mStartY; } - bool GetIsInside(uint32 y) { return (y >= mStartY) && (y <= (mStartY + mHeight)); } + MCORE_INLINE TimeViewPlugin* GetPlugin() { return m_plugin; } + MCORE_INLINE void SetStartY(uint32 y) { m_startY = y; } + MCORE_INLINE uint32 GetStartY() const { return m_startY; } + bool GetIsInside(uint32 y) const { return (y >= m_startY) && (y <= (m_startY + m_height)); } - void SetName(const char* name) { mName = name; } - const char* GetName() const { return mName.c_str(); } + void SetName(const char* name) { m_name = name; } + const char* GetName() const { return m_name.c_str(); } - bool GetIsEnabled() const { return mEnabled; } - void SetIsEnabled(bool enabled) { mEnabled = enabled; } + bool GetIsEnabled() const { return m_enabled; } + void SetIsEnabled(bool enabled) { m_enabled = enabled; } - bool GetIsDeletable() const { return mDeletable; } - void SetIsDeletable(bool isDeletable) { mDeletable = isDeletable; } + bool GetIsDeletable() const { return m_deletable; } + void SetIsDeletable(bool isDeletable) { m_deletable = isDeletable; } - bool GetIsVisible() const { return mVisible; } - void SetIsVisible(bool visible) { mVisible = visible; } + bool GetIsVisible() const { return m_visible; } + void SetIsVisible(bool visible) { m_visible = visible; } - MCORE_INLINE bool GetIsHighlighted() const { return mIsHighlighted; } - MCORE_INLINE void SetIsHighlighted(bool enabled) { mIsHighlighted = enabled; } + MCORE_INLINE bool GetIsHighlighted() const { return m_isHighlighted; } + MCORE_INLINE void SetIsHighlighted(bool enabled) { m_isHighlighted = enabled; } - TimeTrackElement* GetElementAt(int32 x, int32 y); + TimeTrackElement* GetElementAt(int32 x, int32 y) const; protected: - AZStd::string mName; - uint32 mHeight; - uint32 mStartY; - QFont mFont; - QBrush mBrushHeaderBG; - QColor mBrushDataBG; - QColor mBrushDataDisabledBG; - QPen mPenText; - TimeViewPlugin* mPlugin; - AZStd::vector mElements; - bool mEnabled; - bool mVisible; - bool mDeletable; - bool mIsHighlighted; + AZStd::string m_name; + uint32 m_height; + uint32 m_startY; + QFont m_font; + QBrush m_brushHeaderBg; + QColor m_brushDataBg; + QColor m_brushDataDisabledBg; + QPen m_penText; + TimeViewPlugin* m_plugin; + AZStd::vector m_elements; + bool m_enabled; + bool m_visible; + bool m_deletable; + bool m_isHighlighted; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.cpp index f0834ae0f9..5bb6d842fc 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.cpp @@ -21,27 +21,27 @@ namespace EMStudio { // statics - QColor TimeTrackElement::mTextColor = QColor(30, 30, 30); - QColor TimeTrackElement::mHighlightedTextColor = QColor(0, 0, 0); - QColor TimeTrackElement::mHighlightedColor = QColor(255, 128, 0); - int32 TimeTrackElement::mTickHalfWidth = 7; + QColor TimeTrackElement::s_textColor = QColor(30, 30, 30); + QColor TimeTrackElement::s_highlightedTextColor = QColor(0, 0, 0); + QColor TimeTrackElement::s_highlightedColor = QColor(255, 128, 0); + int32 TimeTrackElement::s_tickHalfWidth = 7; // constructor - TimeTrackElement::TimeTrackElement(const char* name, TimeTrack* timeTrack, uint32 elementNumber, QColor color) + TimeTrackElement::TimeTrackElement(const char* name, TimeTrack* timeTrack, size_t elementNumber, QColor color) { - mTrack = timeTrack; - mName = name; - mIsSelected = false; - mShowTimeHandles = false; - mIsHighlighted = false; - mStartTime = 0.0; - mEndTime = 0.0; - mColor = color; - mElementNumber = elementNumber; - mIsCut = false; + m_track = timeTrack; + m_name = name; + m_isSelected = false; + m_showTimeHandles = false; + m_isHighlighted = false; + m_startTime = 0.0; + m_endTime = 0.0; + m_color = color; + m_elementNumber = elementNumber; + m_isCut = false; // init font - mFont.setPixelSize(10); + m_font.setPixelSize(10); } @@ -54,13 +54,13 @@ namespace EMStudio // calculate the dimensions in pixels void TimeTrackElement::CalcDimensions(int32* outStartX, int32* outStartY, int32* outWidth, int32* outHeight) const { - TimeViewPlugin* plugin = mTrack->GetPlugin(); + TimeViewPlugin* plugin = m_track->GetPlugin(); - *outStartX = aznumeric_cast(plugin->TimeToPixel(mStartTime)); - int32 endX = aznumeric_cast(plugin->TimeToPixel(mEndTime)); - *outStartY = mTrack->GetStartY() + 1; + *outStartX = aznumeric_cast(plugin->TimeToPixel(m_startTime)); + int32 endX = aznumeric_cast(plugin->TimeToPixel(m_endTime)); + *outStartY = m_track->GetStartY() + 1; *outWidth = (endX - *outStartX); - *outHeight = mTrack->GetHeight() - 1; + *outHeight = m_track->GetHeight() - 1; } @@ -92,14 +92,14 @@ namespace EMStudio // create the rect QRect rect(startX, startY, width + 1, height); - QColor color = mColor; + QColor color = m_color; QColor borderColor(30, 30, 30); - QColor textColor = mTextColor; - if (mIsSelected) + QColor textColor = s_textColor; + if (m_isSelected) { - color = mHighlightedColor; - borderColor = mHighlightedColor; - textColor = mHighlightedTextColor; + color = s_highlightedColor; + borderColor = s_highlightedColor; + textColor = s_highlightedTextColor; } // in case the track is disabled @@ -111,14 +111,14 @@ namespace EMStudio } // make the colors a bit lighter so that we see some highlighting effect - if (mIsHighlighted) + if (m_isHighlighted) { borderColor = borderColor.lighter(130); color = color.lighter(130); } // in case the track is cutted - if (mIsCut) + if (m_isCut) { borderColor.setAlpha(90); color.setAlpha(90); @@ -149,32 +149,32 @@ namespace EMStudio options.setAlignment(Qt::AlignCenter); painter.setPen(textColor); - painter.setFont(mFont); + painter.setFont(m_font); painter.setRenderHint(QPainter::Antialiasing); - painter.drawText(rect, mName, options); + painter.drawText(rect, m_name, options); painter.setRenderHint(QPainter::Antialiasing, false); } else { height--; - mTickPoints[0] = QPoint(startX, startY); - mTickPoints[1] = QPoint(startX + mTickHalfWidth, startY + height / 2); - mTickPoints[2] = QPoint(startX + mTickHalfWidth, startY + height); - mTickPoints[3] = QPoint(startX - mTickHalfWidth, startY + height); - mTickPoints[4] = QPoint(startX - mTickHalfWidth, startY + height / 2); - mTickPoints[5] = QPoint(startX, startY); + m_tickPoints[0] = QPoint(startX, startY); + m_tickPoints[1] = QPoint(startX + s_tickHalfWidth, startY + height / 2); + m_tickPoints[2] = QPoint(startX + s_tickHalfWidth, startY + height); + m_tickPoints[3] = QPoint(startX - s_tickHalfWidth, startY + height); + m_tickPoints[4] = QPoint(startX - s_tickHalfWidth, startY + height / 2); + m_tickPoints[5] = QPoint(startX, startY); painter.setPen(Qt::NoPen); painter.setBrush(gradient); //painter.setBrush( color ); painter.setRenderHint(QPainter::Antialiasing); - painter.drawPolygon(mTickPoints, 5, Qt::WindingFill); + painter.drawPolygon(m_tickPoints, 5, Qt::WindingFill); painter.setRenderHint(QPainter::Antialiasing, false); painter.setBrush(Qt::NoBrush); painter.setPen(borderColor); painter.setRenderHint(QPainter::Antialiasing); - painter.drawPolyline(mTickPoints, 6); + painter.drawPolyline(m_tickPoints, 6); painter.setRenderHint(QPainter::Antialiasing, false); } } @@ -195,12 +195,12 @@ namespace EMStudio bool isTickElement = width < 1 ? true : false; if (isTickElement) { - startX -= mTickHalfWidth; - width += 2 * mTickHalfWidth; + startX -= s_tickHalfWidth; + width += 2 * s_tickHalfWidth; } // take scrolling into account - startX = aznumeric_cast(startX + mTrack->GetPlugin()->GetScrollX()); + startX = aznumeric_cast(startX + m_track->GetPlugin()->GetScrollX()); // check if we're inside the area of the element if (MCore::InRange(x, startX, startX + width) && MCore::InRange(y, startY, startY + height)) @@ -252,15 +252,15 @@ namespace EMStudio void TimeTrackElement::MoveRelative(double timeDelta) { // don't allow it to start before zero - if (mStartTime + timeDelta < 0.0) + if (m_startTime + timeDelta < 0.0) { - mStartTime -= mStartTime; - mEndTime -= mStartTime; + m_startTime -= m_startTime; + m_endTime -= m_startTime; } else { - mStartTime += timeDelta; - mEndTime += timeDelta; + m_startTime += timeDelta; + m_endTime += timeDelta; } } @@ -280,8 +280,8 @@ namespace EMStudio bool isTickElement = width < 1 ? true : false; if (isTickElement) { - startX -= mTickHalfWidth; - width += 2 * mTickHalfWidth; + startX -= s_tickHalfWidth; + width += 2 * s_tickHalfWidth; } int32 endX = startX + width; @@ -310,14 +310,14 @@ namespace EMStudio // resize the start point case RESIZEPOINT_START: { - double newStartTime = mStartTime + timeDelta; - mTrack->GetPlugin()->SnapTime(&newStartTime, this, snapThreshold); - mStartTime = newStartTime; + double newStartTime = m_startTime + timeDelta; + m_track->GetPlugin()->SnapTime(&newStartTime, this, snapThreshold); + m_startTime = newStartTime; - if (newStartTime > mEndTime) + if (newStartTime > m_endTime) { - mStartTime = mEndTime; - mEndTime = newStartTime; + m_startTime = m_endTime; + m_endTime = newStartTime; return RESIZEPOINT_END; } @@ -328,14 +328,14 @@ namespace EMStudio // resize the end point case RESIZEPOINT_END: { - double newEndTime = mEndTime + timeDelta; - mTrack->GetPlugin()->SnapTime(&newEndTime, this, snapThreshold); - mEndTime = newEndTime; + double newEndTime = m_endTime + timeDelta; + m_track->GetPlugin()->SnapTime(&newEndTime, this, snapThreshold); + m_endTime = newEndTime; - if (newEndTime < mStartTime) + if (newEndTime < m_startTime) { - mEndTime = mStartTime; - mStartTime = newEndTime; + m_endTime = m_startTime; + m_startTime = newEndTime; return RESIZEPOINT_START; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.h index a6d7116487..2bc4c5187b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeTrackElement.h @@ -35,28 +35,28 @@ namespace EMStudio RESIZEPOINT_END = 1 }; - TimeTrackElement(const char* name, TimeTrack* timeTrack, uint32 elementNumber = MCORE_INVALIDINDEX32, QColor color = QColor(0, 0, 0)); + TimeTrackElement(const char* name, TimeTrack* timeTrack, size_t elementNumber = InvalidIndex, QColor color = QColor(0, 0, 0)); virtual ~TimeTrackElement(); - MCORE_INLINE double GetStartTime() const { return mStartTime; } - MCORE_INLINE double GetEndTime() const { return mEndTime; } - MCORE_INLINE bool GetIsSelected() const { return mIsSelected; } - MCORE_INLINE TimeTrack* GetTrack() { return mTrack; } - MCORE_INLINE uint32 GetElementNumber() const { return mElementNumber; } - QColor GetColor() const { return mColor; } - - void SetIsSelected(bool selected) { mIsSelected = selected; } - void SetStartTime(double startTime) { mStartTime = startTime; } - void SetEndTime(double endTime) { mEndTime = endTime; } - void SetName(const char* name) { mName = name; } - void SetToolTip(const char* toolTip) { mToolTip = toolTip; } - void SetTrack(TimeTrack* track) { mTrack = track; } - void SetElementNumber(uint32 elementNumber) { mElementNumber = elementNumber; } - void SetColor(QColor color) { mColor = color; } - - const QString& GetName() const { return mName; } - const QString& GetToolTip() const { return mToolTip; } - const QFont& GetFont() const { return mFont; } + MCORE_INLINE double GetStartTime() const { return m_startTime; } + MCORE_INLINE double GetEndTime() const { return m_endTime; } + MCORE_INLINE bool GetIsSelected() const { return m_isSelected; } + MCORE_INLINE TimeTrack* GetTrack() { return m_track; } + MCORE_INLINE size_t GetElementNumber() const { return m_elementNumber; } + QColor GetColor() const { return m_color; } + + void SetIsSelected(bool selected) { m_isSelected = selected; } + void SetStartTime(double startTime) { m_startTime = startTime; } + void SetEndTime(double endTime) { m_endTime = endTime; } + void SetName(const char* name) { m_name = name; } + void SetToolTip(const char* toolTip) { m_toolTip = toolTip; } + void SetTrack(TimeTrack* track) { m_track = track; } + void SetElementNumber(size_t elementNumber) { m_elementNumber = elementNumber; } + void SetColor(QColor color) { m_color = color; } + + const QString& GetName() const { return m_name; } + const QString& GetToolTip() const { return m_toolTip; } + const QFont& GetFont() const { return m_font; } virtual void Render(QPainter& painter, bool isTrackEnabled); virtual bool SnapTime(double* inOutTime, double snapTreshold) const; @@ -68,42 +68,42 @@ namespace EMStudio void CalcDimensions(int32* outStartX, int32* outStartY, int32* outWidth, int32* outHeight) const; QRect CalcRect(); - bool GetShowTimeHandles() const { return mShowTimeHandles; } - void SetShowTimeHandles(bool show) { mShowTimeHandles = show; } - void SetShowToolTip(bool show) { mShowToolTip = show; } - bool GetShowToolTip() const { return mShowToolTip; } + bool GetShowTimeHandles() const { return m_showTimeHandles; } + void SetShowTimeHandles(bool show) { m_showTimeHandles = show; } + void SetShowToolTip(bool show) { m_showToolTip = show; } + bool GetShowToolTip() const { return m_showToolTip; } - bool GetIsVisible() const { return mVisible; } - void SetIsVisible(bool visible) { mVisible = visible; } + bool GetIsVisible() const { return m_visible; } + void SetIsVisible(bool visible) { m_visible = visible; } - bool GetIsCut() const { return mIsCut; } - void SetIsCut(bool cut) { mIsCut = cut; } + bool GetIsCut() const { return m_isCut; } + void SetIsCut(bool cut) { m_isCut = cut; } - MCORE_INLINE bool GetIsHighlighted() const { return mIsHighlighted; } - MCORE_INLINE void SetIsHighlighted(bool enabled) { mIsHighlighted = enabled; } + MCORE_INLINE bool GetIsHighlighted() const { return m_isHighlighted; } + MCORE_INLINE void SetIsHighlighted(bool enabled) { m_isHighlighted = enabled; } protected: - QFont mFont; - QBrush mBrush; - TimeTrack* mTrack; - double mStartTime; - double mEndTime; - QString mName; - QString mToolTip; - QColor mColor; - uint32 mElementNumber; - QPoint mTickPoints[6]; - - bool mVisible; - bool mIsCut; - bool mIsSelected; - bool mShowTimeHandles; - bool mShowToolTip; - bool mIsHighlighted; - - static QColor mHighlightedColor; - static QColor mTextColor; - static QColor mHighlightedTextColor; - static int32 mTickHalfWidth; + QFont m_font; + QBrush m_brush; + TimeTrack* m_track; + double m_startTime; + double m_endTime; + QString m_name; + QString m_toolTip; + QColor m_color; + size_t m_elementNumber; + QPoint m_tickPoints[6]; + + bool m_visible; + bool m_isCut; + bool m_isSelected; + bool m_showTimeHandles; + bool m_showToolTip; + bool m_isHighlighted; + + static QColor s_highlightedColor; + static QColor s_textColor; + static QColor s_highlightedTextColor; + static int32 s_tickHalfWidth; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp index 04628a6343..a87b7066b5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.cpp @@ -47,46 +47,46 @@ namespace EMStudio TimeViewPlugin::TimeViewPlugin() : EMStudio::DockWidgetPlugin() { - mPixelsPerSecond = 60; - mCurTime = 0; - mFPS = 32; - mTimeScale = 1.0; - mTargetTimeScale = 1.0; - mScrollX = 0.0; - mTargetScrollX = 0.0; - mMaxTime = 0.0; - mMaxHeight = 0.0; - mMinScale = 0.25; - mMaxScale = 100.0; - mCurMouseX = 0; - mCurMouseY = 0; - mTotalTime = FLT_MAX; - mZoomInCursor = nullptr; - mZoomOutCursor = nullptr; - mIsAnimating = false; - mDirty = true; - - mTrackDataHeaderWidget = nullptr; - mTrackDataWidget = nullptr; - mTrackHeaderWidget = nullptr; - mTimeInfoWidget = nullptr; - - mNodeHistoryItem = nullptr; - mEventHistoryItem = nullptr; - mActorInstanceData = nullptr; - mEventEmitterNode = nullptr; - - mMainWidget = nullptr; - mMotionWindowPlugin = nullptr; - mMotionEventsPlugin = nullptr; - mMotionListWindow = nullptr; + m_pixelsPerSecond = 60; + m_curTime = 0; + m_fps = 32; + m_timeScale = 1.0; + m_targetTimeScale = 1.0; + m_scrollX = 0.0; + m_targetScrollX = 0.0; + m_maxTime = 0.0; + m_maxHeight = 0.0; + m_minScale = 0.25; + m_maxScale = 100.0; + m_curMouseX = 0; + m_curMouseY = 0; + m_totalTime = FLT_MAX; + m_zoomInCursor = nullptr; + m_zoomOutCursor = nullptr; + m_isAnimating = false; + m_dirty = true; + + m_trackDataHeaderWidget = nullptr; + m_trackDataWidget = nullptr; + m_trackHeaderWidget = nullptr; + m_timeInfoWidget = nullptr; + + m_nodeHistoryItem = nullptr; + m_eventHistoryItem = nullptr; + m_actorInstanceData = nullptr; + m_eventEmitterNode = nullptr; + + m_mainWidget = nullptr; + m_motionWindowPlugin = nullptr; + m_motionEventsPlugin = nullptr; + m_motionListWindow = nullptr; m_motionSetPlugin = nullptr; - mMotion = nullptr; + m_motion = nullptr; - mBrushCurTimeHandle = QBrush(QColor(255, 180, 0)); - mPenCurTimeHandle = QPen(QColor(255, 180, 0)); - mPenTimeHandles = QPen(QColor(150, 150, 150), 1, Qt::DotLine); - mPenCurTimeHelper = QPen(QColor(100, 100, 100), 1, Qt::DotLine); + m_brushCurTimeHandle = QBrush(QColor(255, 180, 0)); + m_penCurTimeHandle = QPen(QColor(255, 180, 0)); + m_penTimeHandles = QPen(QColor(150, 150, 150), 1, Qt::DotLine); + m_penCurTimeHelper = QPen(QColor(100, 100, 100), 1, Qt::DotLine); } TimeViewPlugin::~TimeViewPlugin() @@ -103,14 +103,13 @@ namespace EMStudio RemoveAllTracks(); // get rid of the cursors - delete mZoomInCursor; - delete mZoomOutCursor; + delete m_zoomInCursor; + delete m_zoomOutCursor; // get rid of the motion infos - const uint32 numMotionInfos = mMotionInfos.GetLength(); - for (uint32 i = 0; i < numMotionInfos; ++i) + for (MotionInfo* motionInfo : m_motionInfos) { - delete mMotionInfos[i]; + delete motionInfo; } } @@ -163,12 +162,12 @@ namespace EMStudio { if (classID == MotionWindowPlugin::CLASS_ID) { - mMotionWindowPlugin = nullptr; + m_motionWindowPlugin = nullptr; } if (classID == MotionEventsPlugin::CLASS_ID) { - mMotionEventsPlugin = nullptr; + m_motionEventsPlugin = nullptr; } } @@ -197,37 +196,37 @@ namespace EMStudio GetCommandManager()->RegisterCommandCallback("PlayMotion", m_commandCallbacks.back()); // load the cursors - mZoomInCursor = new QCursor(QPixmap(QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Images/Rendering/ZoomInCursor.png")).scaled(32, 32)); - mZoomOutCursor = new QCursor(QPixmap(QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Images/Rendering/ZoomOutCursor.png")).scaled(32, 32)); + m_zoomInCursor = new QCursor(QPixmap(QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Images/Rendering/ZoomInCursor.png")).scaled(32, 32)); + m_zoomOutCursor = new QCursor(QPixmap(QDir{ QString(MysticQt::GetDataDir().c_str()) }.filePath("Images/Rendering/ZoomOutCursor.png")).scaled(32, 32)); // create main widget - mMainWidget = new QWidget(mDock); - mDock->setWidget(mMainWidget); + m_mainWidget = new QWidget(m_dock); + m_dock->setWidget(m_mainWidget); QGridLayout* mainLayout = new QGridLayout(); mainLayout->setMargin(0); mainLayout->setSpacing(0); - mMainWidget->setLayout(mainLayout); + m_mainWidget->setLayout(mainLayout); // create widgets in the header QHBoxLayout* topLayout = new QHBoxLayout(); // Top - mTimeViewToolBar = new TimeViewToolBar(this); + m_timeViewToolBar = new TimeViewToolBar(this); // Top-left - mTimeInfoWidget = new TimeInfoWidget(this); - mTimeInfoWidget->setFixedWidth(175); - topLayout->addWidget(mTimeInfoWidget); - topLayout->addWidget(mTimeViewToolBar); + m_timeInfoWidget = new TimeInfoWidget(this); + m_timeInfoWidget->setFixedWidth(175); + topLayout->addWidget(m_timeInfoWidget); + topLayout->addWidget(m_timeViewToolBar); mainLayout->addLayout(topLayout, 0, 0, 1, 2); // Top-right - mTrackDataHeaderWidget = new TrackDataHeaderWidget(this, mDock); - mTrackDataHeaderWidget->setFixedHeight(40); + m_trackDataHeaderWidget = new TrackDataHeaderWidget(this, m_dock); + m_trackDataHeaderWidget->setFixedHeight(40); // create widgets in the body. For the body we are going to put a scroll area // so we can get a vertical scroll bar when we have more tracks than what the // view can show - QScrollArea* bodyWidget = new QScrollArea(mMainWidget); + QScrollArea* bodyWidget = new QScrollArea(m_mainWidget); bodyWidget->setFrameShape(QFrame::NoFrame); bodyWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); bodyWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); @@ -243,39 +242,39 @@ namespace EMStudio mainLayout->addWidget(bodyWidget, 2, 0, 1, 2); // Bottom-left - mTrackHeaderWidget = new TrackHeaderWidget(this, mDock); - mTrackHeaderWidget->setFixedWidth(175); - bodyLayout->addWidget(mTrackHeaderWidget); + m_trackHeaderWidget = new TrackHeaderWidget(this, m_dock); + m_trackHeaderWidget->setFixedWidth(175); + bodyLayout->addWidget(m_trackHeaderWidget); // Left QHBoxLayout* addTrackAndTrackDataLayout = new QHBoxLayout; - addTrackAndTrackDataLayout->addWidget(mTrackHeaderWidget->GetAddTrackWidget()); - mTrackHeaderWidget->GetAddTrackWidget()->setFixedWidth(175); - addTrackAndTrackDataLayout->addWidget(mTrackDataHeaderWidget); + addTrackAndTrackDataLayout->addWidget(m_trackHeaderWidget->GetAddTrackWidget()); + m_trackHeaderWidget->GetAddTrackWidget()->setFixedWidth(175); + addTrackAndTrackDataLayout->addWidget(m_trackDataHeaderWidget); mainLayout->addLayout(addTrackAndTrackDataLayout, 1, 0, 1, 2); // bottom-right - mTrackDataWidget = new TrackDataWidget(this, mDock); - bodyLayout->addWidget(mTrackDataWidget); + m_trackDataWidget = new TrackDataWidget(this, m_dock); + bodyLayout->addWidget(m_trackDataWidget); - connect(mTrackDataWidget, &TrackDataWidget::SelectionChanged, this, &TimeViewPlugin::OnSelectionChanged); + connect(m_trackDataWidget, &TrackDataWidget::SelectionChanged, this, &TimeViewPlugin::OnSelectionChanged); - connect(mTrackDataWidget, &TrackDataWidget::ElementTrackChanged, this, &TimeViewPlugin::MotionEventTrackChanged); - connect(mTrackDataWidget, &TrackDataWidget::MotionEventChanged, this, &TimeViewPlugin::MotionEventChanged); + connect(m_trackDataWidget, &TrackDataWidget::ElementTrackChanged, this, &TimeViewPlugin::MotionEventTrackChanged); + connect(m_trackDataWidget, &TrackDataWidget::MotionEventChanged, this, &TimeViewPlugin::MotionEventChanged); connect(this, &TimeViewPlugin::DeleteKeyPressed, this, &TimeViewPlugin::RemoveSelectedMotionEvents); - connect(mDock, &QDockWidget::visibilityChanged, this, &TimeViewPlugin::VisibilityChanged); + connect(m_dock, &QDockWidget::visibilityChanged, this, &TimeViewPlugin::VisibilityChanged); connect(this, &TimeViewPlugin::ManualTimeChange, this, &TimeViewPlugin::OnManualTimeChange); - connect(mTimeViewToolBar, &TimeViewToolBar::RecorderStateChanged, this, &TimeViewPlugin::RecorderStateChanged); + connect(m_timeViewToolBar, &TimeViewToolBar::RecorderStateChanged, this, &TimeViewPlugin::RecorderStateChanged); SetCurrentTime(0.0f); SetScale(1.0f); SetRedrawFlag(); - mTimeViewToolBar->UpdateInterface(); + m_timeViewToolBar->UpdateInterface(); EMotionFX::AnimGraphEditorNotificationBus::Handler::BusConnect(); return true; @@ -285,7 +284,7 @@ namespace EMStudio // add a new track void TimeViewPlugin::AddTrack(TimeTrack* track) { - mTracks.Add(track); + m_tracks.emplace_back(track); SetRedrawFlag(); } @@ -294,49 +293,40 @@ namespace EMStudio void TimeViewPlugin::RemoveAllTracks() { // get the number of time tracks and iterate through them - const uint32 numTracks = mTracks.GetLength(); - for (uint32 i = 0; i < numTracks; ++i) + for (TimeTrack* track : m_tracks) { - delete mTracks[i]; + delete track; } - mTracks.Clear(); + m_tracks.clear(); SetRedrawFlag(); } TimeTrack* TimeViewPlugin::FindTrackByElement(TimeTrackElement* element) const { - // get the number of time tracks and iterate through them - const uint32 numTracks = mTracks.GetLength(); - for (uint32 i = 0; i < numTracks; ++i) + const auto foundTrack = AZStd::find_if(begin(m_tracks), end(m_tracks), [element](const TimeTrack* timeTrack) { - TimeTrack* timeTrack = mTracks[i]; - // get the number of time track elements and iterate through them - const uint32 numElements = timeTrack->GetNumElements(); - for (uint32 j = 0; j < numElements; ++j) + const size_t numElements = timeTrack->GetNumElements(); + for (size_t j = 0; j < numElements; ++j) { if (timeTrack->GetElement(j) == element) { - return timeTrack; + return true; } } - } - - return nullptr; + return false; + }); + return foundTrack != end(m_tracks) ? *foundTrack : nullptr; } - AZ::Outcome TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const + AZ::Outcome TimeViewPlugin::FindTrackIndex(const TimeTrack* track) const { - const AZ::u32 numTracks = mTracks.GetLength(); - for (AZ::u32 i = 0; i < numTracks; ++i) + const auto foundTrack = AZStd::find(begin(m_tracks), end(m_tracks), track); + if (foundTrack != end(m_tracks)) { - if (mTracks[i] == track) - { - return AZ::Success(i); - } + return AZ::Success(static_cast(AZStd::distance(begin(m_tracks), foundTrack))); } - return AZ::Failure(); } @@ -388,7 +378,7 @@ namespace EMStudio } if (outFrameNr) { - *outFrameNr = aznumeric_cast(timeValue / (double)mFPS); + *outFrameNr = aznumeric_cast(timeValue / (double)m_fps); } } @@ -398,10 +388,10 @@ namespace EMStudio { if (scaleXPixel) { - xPixel *= mTimeScale; + xPixel *= m_timeScale; } - const double pixelTime = ((xPixel + mScrollX) / mPixelsPerSecond); + const double pixelTime = ((xPixel + m_scrollX) / m_pixelsPerSecond); if (outPixelTime) { @@ -421,7 +411,7 @@ namespace EMStudio } if (outFrameNr) { - *outFrameNr = aznumeric_cast(pixelTime / (double)mFPS); + *outFrameNr = aznumeric_cast(pixelTime / (double)m_fps); } } @@ -433,11 +423,11 @@ namespace EMStudio return; } - if (mMotion) + if (m_motion) { - MotionInfo* motionInfo = FindMotionInfo(mMotion->GetID()); - motionInfo->mScale = mTargetTimeScale; - motionInfo->mScrollX = mTargetScrollX; + MotionInfo* motionInfo = FindMotionInfo(m_motion->GetID()); + motionInfo->m_scale = m_targetTimeScale; + motionInfo->m_scrollX = m_targetScrollX; } } @@ -446,20 +436,19 @@ namespace EMStudio void TimeViewPlugin::UpdateVisualData() { ValidatePluginLinks(); - mTrackDataHeaderWidget->update(); - mTrackDataWidget->update(); - mTimeInfoWidget->update(); - mDirty = false; + m_trackDataHeaderWidget->update(); + m_trackDataWidget->update(); + m_timeInfoWidget->update(); + m_dirty = false; } // calc the time value to a pixel value (excluding scroll) double TimeViewPlugin::TimeToPixel(double timeInSeconds, bool scale) const { - // return ((timeInSeconds * mPixelsPerSecond)/* / mTimeScale*/) - mScrollX; - double result = ((timeInSeconds * mPixelsPerSecond)) - mScrollX; + double result = ((timeInSeconds * m_pixelsPerSecond)) - m_scrollX; if (scale) { - return (result * mTimeScale); + return (result * m_timeScale); } else { @@ -472,11 +461,10 @@ namespace EMStudio TimeTrackElement* TimeViewPlugin::GetElementAt(int32 x, int32 y) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 i = 0; i < numTracks; ++i) + for (const TimeTrack* track : m_tracks) { // check if the absolute pixel is inside - TimeTrackElement* result = mTracks[i]->GetElementAt(aznumeric_cast(x + mScrollX), y); + TimeTrackElement* result = track->GetElementAt(aznumeric_cast(x + m_scrollX), y); if (result) { return result; @@ -491,17 +479,11 @@ namespace EMStudio TimeTrack* TimeViewPlugin::GetTrackAt(int32 y) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 i = 0; i < numTracks; ++i) + const auto foundTrack = AZStd::find_if(begin(m_tracks), end(m_tracks), [y](const TimeTrack* track) { - // check if the absolute pixel is inside - if (mTracks[i]->GetIsInside(y)) - { - return mTracks[i]; - } - } - - return nullptr; + return track->GetIsInside(y); + }); + return foundTrack != end(m_tracks) ? *foundTrack : nullptr; } @@ -509,14 +491,11 @@ namespace EMStudio void TimeViewPlugin::UnselectAllElements() { // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 t = 0; t < numTracks; ++t) + for (TimeTrack* track : m_tracks) { - TimeTrack* track = mTracks[t]; - // for all elements, deselect it - const uint32 numElems = track->GetNumElements(); - for (uint32 i = 0; i < numElems; ++i) + const size_t numElems = track->GetNumElements(); + for (size_t i = 0; i < numElems; ++i) { track->GetElement(i)->SetIsSelected(false); } @@ -530,7 +509,7 @@ namespace EMStudio // return the time of the current time marker, in seconds double TimeViewPlugin::GetCurrentTime() const { - return mCurTime; + return m_curTime; } @@ -538,39 +517,39 @@ namespace EMStudio { if (isScaledPixel) { - xPixel /= mTimeScale; + xPixel /= m_timeScale; } - return ((xPixel + mScrollX) / mPixelsPerSecond); + return ((xPixel + m_scrollX) / m_pixelsPerSecond); } void TimeViewPlugin::DeltaScrollX(double deltaX, bool animate) { - double newTime = (mTargetScrollX + (deltaX / mTimeScale)) / mPixelsPerSecond; - if (newTime < mMaxTime - (1 / mTimeScale)) + double newTime = (m_targetScrollX + (deltaX / m_timeScale)) / m_pixelsPerSecond; + if (newTime < m_maxTime - (1 / m_timeScale)) { - SetScrollX(mTargetScrollX + (deltaX / mTimeScale), animate); + SetScrollX(m_targetScrollX + (deltaX / m_timeScale), animate); } else { - SetScrollX((mMaxTime - ((1 / mTimeScale))) * mPixelsPerSecond, animate); + SetScrollX((m_maxTime - ((1 / m_timeScale))) * m_pixelsPerSecond, animate); } SetRedrawFlag(); } void TimeViewPlugin::SetScrollX(double scrollX, bool animate) { - mTargetScrollX = scrollX; + m_targetScrollX = scrollX; - if (mTargetScrollX < 0) + if (m_targetScrollX < 0) { - mTargetScrollX = 0; + m_targetScrollX = 0; } if (animate == false) { - mScrollX = mTargetScrollX; + m_scrollX = m_targetScrollX; } // inform the motion info about the changes @@ -583,11 +562,11 @@ namespace EMStudio void TimeViewPlugin::SetCurrentTime(double timeInSeconds) { const double oneMs = 1.0 / 1000.0; - if (!AZ::IsClose(mCurTime, timeInSeconds, oneMs)) + if (!AZ::IsClose(m_curTime, timeInSeconds, oneMs)) { - mDirty = true; + m_dirty = true; } - mCurTime = timeInSeconds; + m_curTime = timeInSeconds; } @@ -603,18 +582,16 @@ namespace EMStudio } // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 t = 0; t < numTracks; ++t) + for (TimeTrack* track : m_tracks) { - TimeTrack* track = mTracks[t]; if (track->GetIsVisible() == false || track->GetIsEnabled() == false) { continue; } // for all elements - const uint32 numElems = track->GetNumElements(); - for (uint32 i = 0; i < numElems; ++i) + const size_t numElems = track->GetNumElements(); + for (size_t i = 0; i < numElems; ++i) { // don't snap to itself TimeTrackElement* element = track->GetElement(i); @@ -646,20 +623,18 @@ namespace EMStudio void TimeViewPlugin::RenderElementTimeHandles(QPainter& painter, uint32 dataWindowHeight, const QPen& pen) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 t = 0; t < numTracks; ++t) + for (const TimeTrack* track : m_tracks) { - TimeTrack* track = mTracks[t]; if (track->GetIsVisible() == false) { continue; } // for all elements - const uint32 numElems = track->GetNumElements(); - for (uint32 i = 0; i < numElems; ++i) + const size_t numElems = track->GetNumElements(); + for (size_t i = 0; i < numElems; ++i) { - TimeTrackElement* elem = track->GetElement(i); + const TimeTrackElement* elem = track->GetElement(i); // if the element has to show its time handles, do it if (elem->GetShowTimeHandles()) @@ -682,14 +657,11 @@ namespace EMStudio void TimeViewPlugin::DisableAllToolTips() { // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 t = 0; t < numTracks; ++t) + for (const TimeTrack* track : m_tracks) { - TimeTrack* track = mTracks[t]; - - // for all elements - const uint32 numElems = track->GetNumElements(); - for (uint32 i = 0; i < numElems; ++i) + // for all elements + const size_t numElems = track->GetNumElements(); + for (size_t i = 0; i < numElems; ++i) { TimeTrackElement* elem = track->GetElement(i); elem->SetShowToolTip(false); @@ -703,18 +675,16 @@ namespace EMStudio bool TimeViewPlugin::FindResizePoint(int32 x, int32 y, TimeTrackElement** outElement, uint32* outID) { // for all tracks - const uint32 numTracks = mTracks.GetLength(); - for (uint32 t = 0; t < numTracks; ++t) + for (const TimeTrack* track : m_tracks) { - TimeTrack* track = mTracks[t]; - if (track->GetIsVisible() == false) + if (track->GetIsVisible() == false) { continue; } // for all elements - const uint32 numElems = track->GetNumElements(); - for (uint32 i = 0; i < numElems; ++i) + const size_t numElems = track->GetNumElements(); + for (size_t i = 0; i < numElems; ++i) { TimeTrackElement* elem = track->GetElement(i); @@ -749,95 +719,95 @@ namespace EMStudio // render the frame void TimeViewPlugin::ProcessFrame(float timePassedInSeconds) { - if (GetManager()->GetAvoidRendering() || mMainWidget->visibleRegion().isEmpty()) + if (GetManager()->GetAvoidRendering() || m_mainWidget->visibleRegion().isEmpty()) { return; } - mTotalTime += timePassedInSeconds; + m_totalTime += timePassedInSeconds; ValidatePluginLinks(); // animate the zoom - mScrollX += (mTargetScrollX - mScrollX) * 0.2; + m_scrollX += (m_targetScrollX - m_scrollX) * 0.2; - mIsAnimating = false; - if (mTargetTimeScale > mTimeScale) + m_isAnimating = false; + if (m_targetTimeScale > m_timeScale) { - if (MCore::Math::Abs(aznumeric_cast(mTargetScrollX - mScrollX)) <= 1) + if (MCore::Math::Abs(aznumeric_cast(m_targetScrollX - m_scrollX)) <= 1) { - mTimeScale += (mTargetTimeScale - mTimeScale) * 0.1; + m_timeScale += (m_targetTimeScale - m_timeScale) * 0.1; } } else { - mTimeScale += (mTargetTimeScale - mTimeScale) * 0.1; + m_timeScale += (m_targetTimeScale - m_timeScale) * 0.1; } - if (MCore::Math::Abs(aznumeric_cast(mTargetScrollX - mScrollX)) <= 1) + if (MCore::Math::Abs(aznumeric_cast(m_targetScrollX - m_scrollX)) <= 1) { - mScrollX = mTargetScrollX; + m_scrollX = m_targetScrollX; } else { - mIsAnimating = true; + m_isAnimating = true; } - if (MCore::Math::Abs(aznumeric_cast(mTargetTimeScale - mTimeScale)) <= 0.001) + if (MCore::Math::Abs(aznumeric_cast(m_targetTimeScale - m_timeScale)) <= 0.001) { - mTimeScale = mTargetTimeScale; + m_timeScale = m_targetTimeScale; } else { - mIsAnimating = true; + m_isAnimating = true; } // get the maximum time - GetDataTimes(&mMaxTime, nullptr, nullptr); + GetDataTimes(&m_maxTime, nullptr, nullptr); UpdateMaxHeight(); - mTrackDataWidget->UpdateRects(); + m_trackDataWidget->UpdateRects(); - if (MCore::Math::Abs(aznumeric_cast(mMaxHeight - mLastMaxHeight)) > 0.0001) + if (MCore::Math::Abs(aznumeric_cast(m_maxHeight - m_lastMaxHeight)) > 0.0001) { - mLastMaxHeight = mMaxHeight; + m_lastMaxHeight = m_maxHeight; } - if (mTrackDataWidget->mDragging == false && mTrackDataWidget->mResizing == false) + if (m_trackDataWidget->m_dragging == false && m_trackDataWidget->m_resizing == false) { - mTimeInfoWidget->SetOverwriteTime(PixelToTime(mCurMouseX), mMaxTime); + m_timeInfoWidget->SetOverwriteTime(PixelToTime(m_curMouseX), m_maxTime); } // update the hovering items - mEventEmitterNode = nullptr; - mActorInstanceData = mTrackDataWidget->FindActorInstanceData(); + m_eventEmitterNode = nullptr; + m_actorInstanceData = m_trackDataWidget->FindActorInstanceData(); if (EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon) { - mEventHistoryItem = mTrackDataWidget->FindEventHistoryItem(mActorInstanceData, aznumeric_cast(mCurMouseX), aznumeric_cast(mCurMouseY)); - mNodeHistoryItem = mTrackDataWidget->FindNodeHistoryItem(mActorInstanceData, aznumeric_cast(mCurMouseX), aznumeric_cast(mCurMouseY)); + m_eventHistoryItem = m_trackDataWidget->FindEventHistoryItem(m_actorInstanceData, aznumeric_cast(m_curMouseX), aznumeric_cast(m_curMouseY)); + m_nodeHistoryItem = m_trackDataWidget->FindNodeHistoryItem(m_actorInstanceData, aznumeric_cast(m_curMouseX), aznumeric_cast(m_curMouseY)); - if (mEventHistoryItem) + if (m_eventHistoryItem) { - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(mEventHistoryItem->mAnimGraphID); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_eventHistoryItem->m_animGraphId); if (animGraph) { - mEventEmitterNode = animGraph->RecursiveFindNodeById(mEventHistoryItem->mEmitterNodeId); + m_eventEmitterNode = animGraph->RecursiveFindNodeById(m_eventHistoryItem->m_emitterNodeId); } } } else { - mActorInstanceData = nullptr; - mNodeHistoryItem = nullptr; - mEventHistoryItem = nullptr; + m_actorInstanceData = nullptr; + m_nodeHistoryItem = nullptr; + m_eventHistoryItem = nullptr; } switch (m_mode) { case TimeViewMode::Motion: { - double newCurrentTime = mCurTime; + double newCurrentTime = m_curTime; - if (!mMotion) + if (!m_motion) { // Use the start time when either no motion is selected. newCurrentTime = 0.0f; @@ -846,17 +816,17 @@ namespace EMStudio { const AZStd::vector& motionInstances = MotionWindowPlugin::GetSelectedMotionInstances(); if (motionInstances.size() == 1 && - motionInstances[0]->GetMotion() == mMotion) + motionInstances[0]->GetMotion() == m_motion) { EMotionFX::MotionInstance* motionInstance = motionInstances[0]; - if (!AZ::IsClose(aznumeric_cast(mCurTime), motionInstance->GetCurrentTime(), MCore::Math::epsilon)) + if (!AZ::IsClose(aznumeric_cast(m_curTime), motionInstance->GetCurrentTime(), MCore::Math::epsilon)) { newCurrentTime = motionInstance->GetCurrentTime(); } } } - if (!mTrackDataWidget->mDragging && !mTrackDataWidget->mResizing) + if (!m_trackDataWidget->m_dragging && !m_trackDataWidget->m_resizing) { SetCurrentTime(newCurrentTime); } @@ -872,12 +842,12 @@ namespace EMStudio if (recorder.GetIsInPlayMode() && recorder.GetIsInAutoPlayMode()) { SetCurrentTime(recorder.GetCurrentPlayTime()); - MakeTimeVisible(mCurTime, 0.5, false); + MakeTimeVisible(m_curTime, 0.5, false); } if (recorder.GetIsRecording()) { - SetCurrentTime(mMaxTime); + SetCurrentTime(m_maxTime); MakeTimeVisible(recorder.GetRecordTime(), 0.95, false); } } @@ -896,15 +866,15 @@ namespace EMStudio } } - if (mIsAnimating) + if (m_isAnimating) { - mDirty = true; + m_dirty = true; } bool redraw = false; float fps = 15.0f; #ifndef MCORE_DEBUG - if (mIsAnimating) + if (m_isAnimating) { fps = 60.0f; } @@ -914,13 +884,13 @@ namespace EMStudio } #endif - if (mTotalTime >= 1.0f / fps) + if (m_totalTime >= 1.0f / fps) { redraw = true; - mTotalTime = 0.0f; + m_totalTime = 0.0f; } - if (redraw && mDirty) + if (redraw && m_dirty) { UpdateVisualData(); } @@ -929,34 +899,26 @@ namespace EMStudio void TimeViewPlugin::SetRedrawFlag() { - mDirty = true; + m_dirty = true; } void TimeViewPlugin::UpdateViewSettings() { - SetScale(mTimeScale); + SetScale(m_timeScale); } void TimeViewPlugin::SetScale(double scale, bool animate) { - // if (mMaxTime < centerTime) - /* double rangeStart = PixelToTime( 0.0 ); - double rangeEnd = PixelToTime( mTrackDataWidget->geometry().width() ); - if (rangeEnd > mMaxTime) - rangeEnd = mMaxTime; - - double centerTime = (rangeStart + rangeEnd) / 2.0; - */ double curTime = GetCurrentTime(); - mTargetTimeScale = scale; - mTargetTimeScale = MCore::Clamp(scale, mMinScale, mMaxScale); + m_targetTimeScale = scale; + m_targetTimeScale = MCore::Clamp(scale, m_minScale, m_maxScale); if (animate == false) { - mTimeScale = mTargetTimeScale; + m_timeScale = m_targetTimeScale; } UpdateCurrentMotionInfo(); @@ -966,44 +928,6 @@ namespace EMStudio // MakeTimeVisible( centerTime, 0.5 ); } - // set the maximum time value - /*void TimeViewPlugin::SetMaxTime(double maxTime) - { - mMaxTime = maxTime; - mMaxTimeInPixels = (maxTime * TIMEVIEW_PIXELSPERSECOND) / mTimeScale; - - double oldSliderMax = mHorizontalScroll->maximum(); - double oldNormalizedValue = (double)mHorizontalScroll->value() / oldSliderMax; - - mHorizontalScroll->setRange( 0, mMaxTimeInPixels ); - mHorizontalScroll->setValue( oldNormalizedValue * mMaxTimeInPixels ); - } - - - // set the time view scale and keep it in a reasonable range - void TimeViewPlugin::SetTimeScale(float scale) - { - mTimeScale = scale; - - const float minScale = 0.01f; - //const float maxScale = 100.0f; - - if (mTimeScale < minScale) - mTimeScale = minScale; - - if (mTimeScale > mMaxScale) - mTimeScale = mMaxScale; - - // adjust the maximum time - SetMaxTime(mMaxTime); - - // adjust the current play time - SetCurrentTime( GetCurrentTime() ); - - // inform the motion info about the changes - UpdateCurrentMotionInfo(); - }*/ - void TimeViewPlugin::OnKeyPressEvent(QKeyEvent* event) { @@ -1017,30 +941,30 @@ namespace EMStudio if (event->key() == Qt::Key_Down) { - mTrackDataWidget->scroll(0, 20); + m_trackDataWidget->scroll(0, 20); event->accept(); return; } if (event->key() == Qt::Key_Up) { - mTrackDataWidget->scroll(0, -20); + m_trackDataWidget->scroll(0, -20); event->accept(); return; } if (event->key() == Qt::Key_Plus) { - double zoomDelta = 0.1 * 3 * MCore::Clamp(mTargetTimeScale / 2.0, 1.0, 22.0); - SetScale(mTargetTimeScale + zoomDelta); + double zoomDelta = 0.1 * 3 * MCore::Clamp(m_targetTimeScale / 2.0, 1.0, 22.0); + SetScale(m_targetTimeScale + zoomDelta); event->accept(); return; } if (event->key() == Qt::Key_Minus) { - double zoomDelta = 0.1 * 3 * MCore::Clamp(mTargetTimeScale / 2.0, 1.0, 22.0); - SetScale(mTargetTimeScale - zoomDelta); + double zoomDelta = 0.1 * 3 * MCore::Clamp(m_targetTimeScale / 2.0, 1.0, 22.0); + SetScale(m_targetTimeScale - zoomDelta); event->accept(); return; } @@ -1049,10 +973,10 @@ namespace EMStudio { if (event->key() == Qt::Key_Left) { - mTargetScrollX -= (mPixelsPerSecond * 3) / mTimeScale; - if (mTargetScrollX < 0) + m_targetScrollX -= (m_pixelsPerSecond * 3) / m_timeScale; + if (m_targetScrollX < 0) { - mTargetScrollX = 0; + m_targetScrollX = 0; } event->accept(); return; @@ -1060,10 +984,10 @@ namespace EMStudio if (event->key() == Qt::Key_Right) { - const double newTime = (mScrollX + ((mPixelsPerSecond * 3) / mTimeScale)) / mPixelsPerSecond; - if (newTime < mMaxTime) + const double newTime = (m_scrollX + ((m_pixelsPerSecond * 3) / m_timeScale)) / m_pixelsPerSecond; + if (newTime < m_maxTime) { - mTargetScrollX += ((mPixelsPerSecond * 3) / mTimeScale); + m_targetScrollX += ((m_pixelsPerSecond * 3) / m_timeScale); } event->accept(); @@ -1094,10 +1018,10 @@ namespace EMStudio if (event->key() == Qt::Key_PageUp) { - mTargetScrollX -= mTrackDataWidget->geometry().width() / mTimeScale; - if (mTargetScrollX < 0) + m_targetScrollX -= m_trackDataWidget->geometry().width() / m_timeScale; + if (m_targetScrollX < 0) { - mTargetScrollX = 0; + m_targetScrollX = 0; } event->accept(); return; @@ -1105,10 +1029,10 @@ namespace EMStudio if (event->key() == Qt::Key_PageDown) { - const double newTime = (mScrollX + (mTrackDataWidget->geometry().width() / mTimeScale)) / mPixelsPerSecond; - if (newTime < mMaxTime) + const double newTime = (m_scrollX + (m_trackDataWidget->geometry().width() / m_timeScale)) / m_pixelsPerSecond; + if (newTime < m_maxTime) { - mTargetScrollX += mTrackDataWidget->geometry().width() / mTimeScale; + m_targetScrollX += m_trackDataWidget->geometry().width() / m_timeScale; } event->accept(); @@ -1135,9 +1059,9 @@ namespace EMStudio void TimeViewPlugin::ValidatePluginLinks() { - mMotionWindowPlugin = nullptr; - mMotionListWindow = nullptr; - mMotionEventsPlugin = nullptr; + m_motionWindowPlugin = nullptr; + m_motionListWindow = nullptr; + m_motionEventsPlugin = nullptr; m_motionSetPlugin = nullptr; EMStudio::PluginManager* pluginManager = EMStudio::GetPluginManager(); @@ -1145,9 +1069,9 @@ namespace EMStudio EMStudioPlugin* motionBasePlugin = pluginManager->FindActivePlugin(MotionWindowPlugin::CLASS_ID); if (motionBasePlugin) { - mMotionWindowPlugin = static_cast(motionBasePlugin); - mMotionListWindow = mMotionWindowPlugin->GetMotionListWindow(); - connect(mMotionListWindow, &MotionListWindow::MotionSelectionChanged, this, &TimeViewPlugin::MotionSelectionChanged, Qt::UniqueConnection); // UniqueConnection as we could connect multiple times. + m_motionWindowPlugin = static_cast(motionBasePlugin); + m_motionListWindow = m_motionWindowPlugin->GetMotionListWindow(); + connect(m_motionListWindow, &MotionListWindow::MotionSelectionChanged, this, &TimeViewPlugin::MotionSelectionChanged, Qt::UniqueConnection); // UniqueConnection as we could connect multiple times. } EMStudioPlugin* motionSetBasePlugin = pluginManager->FindActivePlugin(MotionSetsWindowPlugin::CLASS_ID); @@ -1160,8 +1084,8 @@ namespace EMStudio EMStudioPlugin* motionEventsBasePlugin = pluginManager->FindActivePlugin(MotionEventsPlugin::CLASS_ID); if (motionEventsBasePlugin) { - mMotionEventsPlugin = static_cast(motionEventsBasePlugin); - mMotionEventsPlugin->ValidatePluginLinks(); + m_motionEventsPlugin = static_cast(motionEventsBasePlugin); + m_motionEventsPlugin->ValidatePluginLinks(); } } @@ -1169,7 +1093,7 @@ namespace EMStudio void TimeViewPlugin::MotionSelectionChanged() { ValidatePluginLinks(); - if ((mMotionListWindow && mMotionListWindow->isVisible()) || + if ((m_motionListWindow && m_motionListWindow->isVisible()) || (m_motionSetPlugin && m_motionSetPlugin->GetMotionSetWindow() && m_motionSetPlugin->GetMotionSetWindow()->isVisible())) { SetMode(TimeViewMode::Motion); @@ -1179,18 +1103,18 @@ namespace EMStudio void TimeViewPlugin::UpdateSelection() { - mSelectedEvents.Clear(false); - if (!mMotion) + m_selectedEvents.clear(); + if (!m_motion) { return; } // get the motion event table - const EMotionFX::MotionEventTable* eventTable = mMotion->GetEventTable(); + const EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable(); // get the number of tracks in the time view and iterate through them - const uint32 numTracks = GetNumTracks(); - for (uint32 trackIndex = 0; trackIndex < numTracks; ++trackIndex) + const size_t numTracks = GetNumTracks(); + for (size_t trackIndex = 0; trackIndex < numTracks; ++trackIndex) { // get the current time view track const TimeTrack* track = GetTrack(trackIndex); @@ -1206,8 +1130,8 @@ namespace EMStudio } // get the number of elements in the track and iterate through them - const uint32 numTrackElements = track->GetNumElements(); - for (uint32 elementIndex = 0; elementIndex < numTrackElements; ++elementIndex) + const size_t numTrackElements = track->GetNumElements(); + for (size_t elementIndex = 0; elementIndex < numTrackElements; ++elementIndex) { TimeTrackElement* element = track->GetElement(elementIndex); if (element->GetIsVisible() == false) @@ -1218,10 +1142,10 @@ namespace EMStudio if (element->GetIsSelected()) { EventSelectionItem selectionItem; - selectionItem.mMotion = mMotion; - selectionItem.mTrackNr = trackNr.GetValue(); - selectionItem.mEventNr = element->GetElementNumber(); - mSelectedEvents.Add(selectionItem); + selectionItem.m_motion = m_motion; + selectionItem.m_trackNr = trackNr.GetValue(); + selectionItem.m_eventNr = element->GetElementNumber(); + m_selectedEvents.emplace_back(selectionItem); } } } @@ -1230,10 +1154,10 @@ namespace EMStudio void TimeViewPlugin::ReInit() { - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex) { // set the motion first back to nullptr - mMotion = nullptr; + m_motion = nullptr; } // update the selection and save it @@ -1246,16 +1170,16 @@ namespace EMStudio (EMotionFX::GetRecorder().GetIsRecording() || EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon || EMotionFX::GetRecorder().GetIsInPlayMode())) { SetScrollX(0); - mTrackHeaderWidget->ReInit(); + m_trackHeaderWidget->ReInit(); return; } - if (mMotion) + if (m_motion) { size_t trackIndex; AZStd::string text; - const EMotionFX::MotionEventTable* eventTable = mMotion->GetEventTable(); + const EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable(); RemoveAllTracks(); @@ -1289,7 +1213,7 @@ namespace EMStudio TimeTrackElement* element = nullptr; if (eventIndex < timeTrack->GetNumElements()) { - element = timeTrack->GetElement(static_cast(eventIndex)); + element = timeTrack->GetElement(eventIndex); } else { @@ -1297,16 +1221,14 @@ namespace EMStudio timeTrack->AddElement(element); } - // Select the element if in mSelectedEvents. - const AZ::u32 numSelectedEvents = mSelectedEvents.GetLength(); - for (AZ::u32 selectedEventIndex = 0; selectedEventIndex < numSelectedEvents; ++selectedEventIndex) + // Select the element if in m_selectedEvents. + for (const EventSelectionItem& selectionItem : m_selectedEvents) { - const EventSelectionItem& selectionItem = mSelectedEvents[selectedEventIndex]; - if (mMotion != selectionItem.mMotion) + if (m_motion != selectionItem.m_motion) { continue; } - if (selectionItem.mTrackNr == static_cast(trackIndex) && selectionItem.mEventNr == static_cast(eventIndex)) + if (selectionItem.m_trackNr == trackIndex && selectionItem.m_eventNr == eventIndex) { element->SetIsSelected(true); break; @@ -1334,7 +1256,7 @@ namespace EMStudio element->SetIsVisible(true); element->SetName(text.c_str()); element->SetColor(qColor); - element->SetElementNumber(static_cast(eventIndex)); + element->SetElementNumber(eventIndex); element->SetStartTime(motionEvent.GetStartTime()); element->SetEndTime(motionEvent.GetEndTime()); @@ -1398,16 +1320,16 @@ namespace EMStudio timeTrack->SetElementCount(numMotionEvents); } } - else // mMotion == nullptr + else // m_motion == nullptr { - const uint32 numEventTracks = GetNumTracks(); - for (uint32 trackIndex = 0; trackIndex < numEventTracks; ++trackIndex) + const size_t numEventTracks = GetNumTracks(); + for (size_t trackIndex = 0; trackIndex < numEventTracks; ++trackIndex) { TimeTrack* timeTrack = GetTrack(trackIndex); timeTrack->SetIsVisible(false); - const uint32 numMotionEvents = timeTrack->GetNumElements(); - for (uint32 j = 0; j < numMotionEvents; ++j) + const size_t numMotionEvents = timeTrack->GetNumElements(); + for (size_t j = 0; j < numMotionEvents; ++j) { TimeTrackElement* element = timeTrack->GetElement(j); element->SetIsVisible(false); @@ -1416,27 +1338,26 @@ namespace EMStudio } // update the time view plugin - mTrackHeaderWidget->ReInit(); + m_trackHeaderWidget->ReInit(); - if (mMotion) + if (m_motion) { - //animationLength = mMotion->GetMaxTime(); - MotionInfo* motionInfo = FindMotionInfo(mMotion->GetID()); + MotionInfo* motionInfo = FindMotionInfo(m_motion->GetID()); // if we already selected before, set the remembered settings - if (motionInfo->mInitialized) + if (motionInfo->m_initialized) { - const int32 tempScroll = aznumeric_cast(motionInfo->mScrollX); - SetScale(motionInfo->mScale); + const int32 tempScroll = aznumeric_cast(motionInfo->m_scrollX); + SetScale(motionInfo->m_scale); SetScrollX(tempScroll); } else { // selected the animation the first time - motionInfo->mInitialized = true; - mTargetTimeScale = CalcFitScale(mMinScale, mMaxScale) * 0.8; - motionInfo->mScale = mTargetTimeScale; - motionInfo->mScrollX = 0.0; + motionInfo->m_initialized = true; + m_targetTimeScale = CalcFitScale(m_minScale, m_maxScale) * 0.8; + motionInfo->m_scale = m_targetTimeScale; + motionInfo->m_scrollX = 0.0; } } @@ -1447,53 +1368,47 @@ namespace EMStudio // find the motion info for the given motion id TimeViewPlugin::MotionInfo* TimeViewPlugin::FindMotionInfo(uint32 motionID) { - const uint32 numMotionInfos = mMotionInfos.GetLength(); - for (uint32 i = 0; i < numMotionInfos; ++i) + const auto foundMotionInfo = AZStd::find_if(begin(m_motionInfos), end(m_motionInfos), [motionID](const MotionInfo* motionInfo) { - MotionInfo* motionInfo = mMotionInfos[i]; - - if (motionInfo->mMotionID == motionID) - { - return motionInfo; - } + return motionInfo->m_motionId == motionID; + }); + if (foundMotionInfo != end(m_motionInfos)) + { + return *foundMotionInfo; } // we haven't found a motion info for the given id yet, so create a new one MotionInfo* motionInfo = new MotionInfo(); - motionInfo->mMotionID = motionID; - motionInfo->mInitialized = false; - mMotionInfos.Add(motionInfo); + motionInfo->m_motionId = motionID; + motionInfo->m_initialized = false; + m_motionInfos.emplace_back(motionInfo); return motionInfo; } - void TimeViewPlugin::Select(const MCore::Array& selection) + void TimeViewPlugin::Select(const AZStd::vector& selection) { - uint32 i; - - mSelectedEvents = selection; + m_selectedEvents = selection; // get the number of tracks in the time view and iterate through them - const uint32 numTracks = GetNumTracks(); - for (i = 0; i < numTracks; ++i) + const size_t numTracks = GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { TimeTrack* track = GetTrack(i); // get the number of elements in the track and iterate through them - const uint32 numTrackElements = track->GetNumElements(); - for (uint32 j = 0; j < numTrackElements; ++j) + const size_t numTrackElements = track->GetNumElements(); + for (size_t j = 0; j < numTrackElements; ++j) { TimeTrackElement* element = track->GetElement(j); element->SetIsSelected(false); } } - const uint32 numSelectedEvents = selection.GetLength(); - for (i = 0; i < numSelectedEvents; ++i) + for (const EventSelectionItem& selectionItem : selection) { - const EventSelectionItem* selectionItem = &selection[i]; - TimeTrack* track = GetTrack(static_cast(selectionItem->mTrackNr)); - TimeTrackElement* element = track->GetElement(selectionItem->mEventNr); + TimeTrack* track = GetTrack(selectionItem.m_trackNr); + TimeTrackElement* element = track->GetElement(selectionItem.m_eventNr); element->SetIsSelected(true); } @@ -1509,23 +1424,23 @@ namespace EMStudio return nullptr; } - if (mEventNr >= eventTrack->GetNumEvents()) + if (m_eventNr >= eventTrack->GetNumEvents()) { return nullptr; } - return &(eventTrack->GetEvent(mEventNr)); + return &(eventTrack->GetEvent(m_eventNr)); } EMotionFX::MotionEventTrack* EventSelectionItem::GetEventTrack() { - if (mTrackNr >= mMotion->GetEventTable()->GetNumTracks()) + if (m_trackNr >= m_motion->GetEventTable()->GetNumTracks()) { return nullptr; } - EMotionFX::MotionEventTrack* eventTrack = mMotion->GetEventTable()->GetTrack(mTrackNr); + EMotionFX::MotionEventTrack* eventTrack = m_motion->GetEventTable()->GetTrack(m_trackNr); return eventTrack; } @@ -1533,7 +1448,7 @@ namespace EMStudio void TimeViewPlugin::AddMotionEvent(int32 x, int32 y) { - if (mMotion == nullptr) + if (m_motion == nullptr) { return; } @@ -1583,8 +1498,8 @@ namespace EMStudio } // get the motion event number by getting the time track element number - uint32 motionEventNr = element->GetElementNumber(); - if (motionEventNr == MCORE_INVALIDINDEX32) + size_t motionEventNr = element->GetElementNumber(); + if (motionEventNr == InvalidIndex) { return; } @@ -1597,7 +1512,7 @@ namespace EMStudio } // get the corresponding motion event track - EMotionFX::MotionEventTable* eventTable = mMotion->GetEventTable(); + EMotionFX::MotionEventTable* eventTable = m_motion->GetEventTable(); EMotionFX::MotionEventTrack* eventTrack = eventTable->FindTrackByName(timeTrack->GetName()); if (eventTrack == nullptr) { @@ -1612,7 +1527,7 @@ namespace EMStudio // adjust the motion event AZStd::string outResult, command; - command = AZStd::string::format("AdjustMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %i -startTime %f -endTime %f", mMotion->GetID(), eventTrack->GetName(), motionEventNr, startTime, endTime); + command = AZStd::string::format("AdjustMotionEvent -motionID %i -eventTrackName \"%s\" -eventNr %zu -startTime %f -endTime %f", m_motion->GetID(), eventTrack->GetName(), motionEventNr, startTime, endTime); if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) { MCore::LogError(outResult.c_str()); @@ -1626,28 +1541,28 @@ namespace EMStudio AZStd::string result; MCore::CommandGroup commandGroup("Remove motion events"); - if (mTrackDataWidget) + if (m_trackDataWidget) { - mTrackDataWidget->ClearState(); + m_trackDataWidget->ClearState(); } - if (mMotion == nullptr) + if (m_motion == nullptr) { return; } - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex) { return; } // get the motion event table - // MotionEventTable& eventTable = mMotion->GetEventTable(); - MCore::Array eventNumbers; + // MotionEventTable& eventTable = m_motion->GetEventTable(); + AZStd::vector eventNumbers; // get the number of tracks in the time view and iterate through them - const uint32 numTracks = GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { // get the current time view track TimeTrack* track = GetTrack(i); @@ -1656,17 +1571,17 @@ namespace EMStudio continue; } - eventNumbers.Clear(false); + eventNumbers.clear(); // get the number of elements in the track and iterate through them - const uint32 numTrackElements = track->GetNumElements(); - for (uint32 j = 0; j < numTrackElements; ++j) + const size_t numTrackElements = track->GetNumElements(); + for (size_t j = 0; j < numTrackElements; ++j) { TimeTrackElement* element = track->GetElement(j); if (element->GetIsSelected() && element->GetIsVisible()) { - eventNumbers.Add(j); + eventNumbers.emplace_back(j); } } @@ -1690,23 +1605,22 @@ namespace EMStudio AZStd::string result; MCore::CommandGroup commandGroup("Remove motion events"); - if (mMotion == nullptr) + if (m_motion == nullptr) { return; } - if (EMotionFX::GetMotionManager().FindMotionIndex(mMotion) == MCORE_INVALIDINDEX32) + if (EMotionFX::GetMotionManager().FindMotionIndex(m_motion) == InvalidIndex) { return; } // get the motion event table - // MotionEventTable& eventTable = mMotion->GetEventTable(); - MCore::Array eventNumbers; + AZStd::vector eventNumbers; // get the number of tracks in the time view and iterate through them - const uint32 numTracks = GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { // get the current time view track TimeTrack* track = GetTrack(i); @@ -1715,16 +1629,16 @@ namespace EMStudio continue; } - eventNumbers.Clear(false); + eventNumbers.clear(); // get the number of elements in the track and iterate through them - const uint32 numTrackElements = track->GetNumElements(); - for (uint32 j = 0; j < numTrackElements; ++j) + const size_t numTrackElements = track->GetNumElements(); + for (size_t j = 0; j < numTrackElements; ++j) { TimeTrackElement* element = track->GetElement(j); if (element->GetIsVisible()) { - eventNumbers.Add(j); + eventNumbers.emplace_back(j); } } @@ -1769,11 +1683,11 @@ namespace EMStudio if (outClipStart) { - *outClipStart = playbackInfo->mClipStartTime; + *outClipStart = playbackInfo->m_clipStartTime; } if (outClipEnd) { - *outClipEnd = playbackInfo->mClipEndTime; + *outClipEnd = playbackInfo->m_clipEndTime; } if (outMaxTime) { @@ -1807,8 +1721,8 @@ namespace EMStudio // zoom to fit void TimeViewPlugin::ZoomToFit() { - mTargetScrollX = 0.0; - mTargetTimeScale = CalcFitScale(mMinScale, mMaxScale); + m_targetScrollX = 0.0; + m_targetTimeScale = CalcFitScale(m_minScale, m_maxScale); } @@ -1823,8 +1737,8 @@ namespace EMStudio double scale = 1.0; if (maxTime > 0.0) { - double width = mTrackDataWidget->geometry().width(); - scale = (width / mPixelsPerSecond) / maxTime; + double width = m_trackDataWidget->geometry().width(); + scale = (width / m_pixelsPerSecond) / maxTime; } if (scale < minScale) @@ -1845,7 +1759,7 @@ namespace EMStudio bool TimeViewPlugin::GetIsTimeVisible(double timeValue) const { const double pixel = TimeToPixel(timeValue); - return (pixel >= 0.0 && pixel < mTrackDataWidget->geometry().width()); + return (pixel >= 0.0 && pixel < m_trackDataWidget->geometry().width()); } @@ -1857,17 +1771,17 @@ namespace EMStudio const double pixel = TimeToPixel(timeValue, false); // if we need to scroll to the right - double width = mTrackDataWidget->geometry().width() / mTimeScale; - mTargetScrollX += (pixel - width) + width * (1.0 - offsetFactor); + double width = m_trackDataWidget->geometry().width() / m_timeScale; + m_targetScrollX += (pixel - width) + width * (1.0 - offsetFactor); - if (mTargetScrollX < 0) + if (m_targetScrollX < 0) { - mTargetScrollX = 0; + m_targetScrollX = 0; } if (animate == false) { - mScrollX = mTargetScrollX; + m_scrollX = m_targetScrollX; } } @@ -1875,7 +1789,7 @@ namespace EMStudio // update the maximum height void TimeViewPlugin::UpdateMaxHeight() { - mMaxHeight = 0.0; + m_maxHeight = 0.0; // find the selected actor instance EMotionFX::Recorder& recorder = EMotionFX::GetRecorder(); @@ -1885,10 +1799,10 @@ namespace EMStudio if (actorInstance) { // find the actor instance data for this actor instance - const uint32 actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance); - if (actorInstanceDataIndex != MCORE_INVALIDINDEX32) + const size_t actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance); + if (actorInstanceDataIndex != InvalidIndex) { - RecorderGroup* recorderGroup = mTimeViewToolBar->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_timeViewToolBar->GetRecorderGroup(); const bool displayNodeActivity = recorderGroup->GetDisplayNodeActivity(); const bool displayEvents = recorderGroup->GetDisplayMotionEvents(); const bool displayRelativeGraph = recorderGroup->GetDisplayRelativeGraph(); @@ -1897,7 +1811,7 @@ namespace EMStudio const EMotionFX::Recorder::ActorInstanceData& actorInstanceData = recorder.GetActorInstanceData(actorInstanceDataIndex); if (displayNodeActivity) { - mMaxHeight += ((recorder.CalcMaxNodeHistoryTrackIndex(actorInstanceData) + 1) * (mTrackDataWidget->mNodeHistoryItemHeight + 3)); + m_maxHeight += ((recorder.CalcMaxNodeHistoryTrackIndex(actorInstanceData) + 1) * (m_trackDataWidget->m_nodeHistoryItemHeight + 3)); isTop = false; } @@ -1905,18 +1819,18 @@ namespace EMStudio { if (isTop == false) { - mMaxHeight += 10 + 10; + m_maxHeight += 10 + 10; } isTop = false; - mMaxHeight += mTrackDataWidget->mEventHistoryTotalHeight; + m_maxHeight += m_trackDataWidget->m_eventHistoryTotalHeight; } if (displayRelativeGraph) { if (isTop == false) { - mMaxHeight += 10; + m_maxHeight += 10; } isTop = false; @@ -1926,19 +1840,17 @@ namespace EMStudio } else { - if (mMotion) + if (m_motion) { - const uint32 numTracks = mTracks.GetLength(); - for (uint32 i = 0; i < numTracks; ++i) + for (const TimeTrack* track : m_tracks) { - TimeTrack* track = mTracks[i]; - if (track->GetIsVisible() == false) + if (track->GetIsVisible() == false) { continue; } - mMaxHeight += track->GetHeight(); - mMaxHeight += 1; + m_maxHeight += track->GetHeight(); + m_maxHeight += 1; } } } @@ -1949,39 +1861,37 @@ namespace EMStudio void TimeViewPlugin::OnZoomAll() { ZoomToFit(); - //if (mTargetTimeScale < 1.0) - //mTargetTimeScale = 1.0; } // goto time zero void TimeViewPlugin::OnGotoTimeZero() { - mTargetScrollX = 0; + m_targetScrollX = 0; } // reset timeline void TimeViewPlugin::OnResetTimeline() { - mTargetScrollX = 0; - mTargetTimeScale = 1.0; + m_targetScrollX = 0; + m_targetTimeScale = 1.0; } // center on current time void TimeViewPlugin::OnCenterOnCurTime() { - MakeTimeVisible(mCurTime, 0.5); + MakeTimeVisible(m_curTime, 0.5); } // center on current time void TimeViewPlugin::OnShowNodeHistoryNodeInGraph() { - if (mNodeHistoryItem && mActorInstanceData) + if (m_nodeHistoryItem && m_actorInstanceData) { - emit DoubleClickedRecorderNodeHistoryItem(mActorInstanceData, mNodeHistoryItem); + emit DoubleClickedRecorderNodeHistoryItem(m_actorInstanceData, m_nodeHistoryItem); } } @@ -1989,9 +1899,9 @@ namespace EMStudio // center on current time void TimeViewPlugin::OnClickNodeHistoryNode() { - if (mNodeHistoryItem && mActorInstanceData) + if (m_nodeHistoryItem && m_actorInstanceData) { - emit ClickedRecorderNodeHistoryItem(mActorInstanceData, mNodeHistoryItem); + emit ClickedRecorderNodeHistoryItem(m_actorInstanceData, m_nodeHistoryItem); } } @@ -1999,17 +1909,17 @@ namespace EMStudio // zooming on rect void TimeViewPlugin::ZoomRect(const QRect& rect) { - mTargetScrollX = mScrollX + (rect.left() / mTimeScale); - mTargetTimeScale = mTrackDataWidget->geometry().width() / (double)(rect.width() / mTimeScale); + m_targetScrollX = m_scrollX + (rect.left() / m_timeScale); + m_targetTimeScale = m_trackDataWidget->geometry().width() / (double)(rect.width() / m_timeScale); - if (mTargetTimeScale < 1.0) + if (m_targetTimeScale < 1.0) { - mTargetTimeScale = 1.0; + m_targetTimeScale = 1.0; } - if (mTargetTimeScale > mMaxScale) + if (m_targetTimeScale > m_maxScale) { - mTargetTimeScale = mMaxScale; + m_targetTimeScale = m_maxScale; } } @@ -2109,7 +2019,7 @@ namespace EMStudio // calculate the content heights uint32 TimeViewPlugin::CalcContentHeight() const { - RecorderGroup* recorderGroup = mTimeViewToolBar->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_timeViewToolBar->GetRecorderGroup(); const bool displayNodeActivity = recorderGroup->GetDisplayNodeActivity(); const bool displayEvents = recorderGroup->GetDisplayMotionEvents(); const bool displayRelativeGraph = recorderGroup->GetDisplayRelativeGraph(); @@ -2117,12 +2027,12 @@ namespace EMStudio uint32 result = 0; if (displayNodeActivity) { - result += mTrackDataWidget->mNodeHistoryRect.bottom(); + result += m_trackDataWidget->m_nodeHistoryRect.bottom(); } if (displayEvents) { - result += mTrackDataWidget->mEventHistoryTotalHeight; + result += m_trackDataWidget->m_eventHistoryTotalHeight; } if (displayRelativeGraph) @@ -2159,15 +2069,15 @@ namespace EMStudio case TimeViewMode::Motion: { EMotionFX::Motion* motion = GetCommandManager()->GetCurrentSelection().GetSingleMotion(); - if ((mMotion != motion) || modeChanged) + if ((m_motion != motion) || modeChanged) { - mMotion = motion; + m_motion = motion; ReInit(); } - if (mTrackHeaderWidget) + if (m_trackHeaderWidget) { - mTrackHeaderWidget->GetAddTrackWidget()->setEnabled(motion != nullptr); + m_trackHeaderWidget->GetAddTrackWidget()->setEnabled(motion != nullptr); } break; @@ -2175,13 +2085,13 @@ namespace EMStudio default: { - mMotion = nullptr; + m_motion = nullptr; ReInit(); OnZoomAll(); SetCurrentTime(0.0f); } } - mTimeViewToolBar->UpdateInterface(); + m_timeViewToolBar->UpdateInterface(); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.h index db3a7dec8a..1eed525c41 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewPlugin.h @@ -36,14 +36,12 @@ namespace EMStudio struct EventSelectionItem { - MCORE_MEMORYOBJECTCATEGORY(EventSelectionItem, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS); - EMotionFX::MotionEvent* GetMotionEvent(); EMotionFX::MotionEventTrack* GetEventTrack(); - uint32 mEventNr;// the motion event index in its track - size_t mTrackNr;// the corresponding track in which the event is in - EMotionFX::Motion* mMotion;// the parent motion of the event track + size_t m_eventNr;// the motion event index in its track + size_t m_trackNr;// the corresponding track in which the event is in + EMotionFX::Motion* m_motion;// the parent motion of the event track }; class TimeViewPlugin @@ -90,7 +88,7 @@ namespace EMStudio void SetMode(TimeViewMode mode); TimeViewMode GetMode() const { return m_mode; } - double GetScrollX() const { return mScrollX; } + double GetScrollX() const { return m_scrollX; } void DeltaScrollX(double deltaX, bool animate = true); @@ -110,16 +108,16 @@ namespace EMStudio double CalcFitScale(double minScale = 1.0, double maxScale = 100.0) const; void MakeTimeVisible(double timeValue, double offsetFactor = 0.95, bool animate = true); bool GetIsTimeVisible(double timeValue) const; - float GetTimeScale() const { return aznumeric_cast(mTimeScale); } + float GetTimeScale() const { return aznumeric_cast(m_timeScale); } void RenderElementTimeHandles(QPainter& painter, uint32 dataWindowHeight, const QPen& pen); void DisableAllToolTips(); void AddTrack(TimeTrack* track); void RemoveAllTracks(); - TimeTrack* GetTrack(uint32 index) { return mTracks[index]; } - uint32 GetNumTracks() const { return mTracks.GetLength(); } - AZ::Outcome FindTrackIndex(const TimeTrack* track) const; + TimeTrack* GetTrack(size_t index) { return m_tracks[index]; } + size_t GetNumTracks() const { return m_tracks.size(); } + AZ::Outcome FindTrackIndex(const TimeTrack* track) const; TimeTrack* FindTrackByElement(TimeTrackElement* element) const; void UnselectAllElements(); @@ -134,15 +132,15 @@ namespace EMStudio bool FindResizePoint(int32 x, int32 y, TimeTrackElement** outElement, uint32* outID); - QCursor* GetZoomInCursor() const { return mZoomInCursor; } - QCursor* GetZoomOutCursor() const { return mZoomOutCursor; } + QCursor* GetZoomInCursor() const { return m_zoomInCursor; } + QCursor* GetZoomOutCursor() const { return m_zoomOutCursor; } // some getters - TrackDataHeaderWidget* GetTrackDataHeaderWidget() { return mTrackDataHeaderWidget; } - TrackDataWidget* GetTrackDataWidget() { return mTrackDataWidget; } - TrackHeaderWidget* GetTrackHeaderWidget() { return mTrackHeaderWidget; } - TimeInfoWidget* GetTimeInfoWidget() { return mTimeInfoWidget; } - TimeViewToolBar* GetTimeViewToolBar() { return mTimeViewToolBar; } + TrackDataHeaderWidget* GetTrackDataHeaderWidget() { return m_trackDataHeaderWidget; } + TrackDataWidget* GetTrackDataWidget() { return m_trackDataWidget; } + TrackHeaderWidget* GetTrackHeaderWidget() { return m_trackHeaderWidget; } + TimeInfoWidget* GetTimeInfoWidget() { return m_timeInfoWidget; } + TimeViewToolBar* GetTimeViewToolBar() { return m_timeViewToolBar; } void OnKeyPressEvent(QKeyEvent* event); void OnKeyReleaseEvent(QKeyEvent* event); @@ -153,12 +151,12 @@ namespace EMStudio void ZoomRect(const QRect& rect); - uint32 GetNumSelectedEvents() { return mSelectedEvents.GetLength(); } - EventSelectionItem GetSelectedEvent(uint32 index) const { return mSelectedEvents[index]; } + size_t GetNumSelectedEvents() { return m_selectedEvents.size(); } + EventSelectionItem GetSelectedEvent(size_t index) const { return m_selectedEvents[index]; } - void Select(const MCore::Array& selection); + void Select(const AZStd::vector& selection); - MCORE_INLINE EMotionFX::Motion* GetMotion() const { return mMotion; } + MCORE_INLINE EMotionFX::Motion* GetMotion() const { return m_motion; } void SetRedrawFlag(); uint32 CalcContentHeight() const; @@ -182,7 +180,7 @@ namespace EMStudio void OnCenterOnCurTime(); void OnShowNodeHistoryNodeInGraph(); void OnClickNodeHistoryNode(); - void MotionEventTrackChanged(uint32 eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName) { UnselectAllElements(); CommandSystem::CommandHelperMotionEventTrackChanged(eventNr, startTime, endTime, oldTrackName, newTrackName); } + void MotionEventTrackChanged(size_t eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName) { UnselectAllElements(); CommandSystem::CommandHelperMotionEventTrackChanged(eventNr, startTime, endTime, oldTrackName, newTrackName); } void OnManualTimeChange(float timeValue); signals: @@ -207,66 +205,66 @@ namespace EMStudio MCORE_DEFINECOMMANDCALLBACK(UpdateInterfaceCallback); AZStd::vector m_commandCallbacks; - TrackDataHeaderWidget* mTrackDataHeaderWidget; - TrackDataWidget* mTrackDataWidget; - TrackHeaderWidget* mTrackHeaderWidget; - TimeInfoWidget* mTimeInfoWidget; - TimeViewToolBar* mTimeViewToolBar; - QWidget* mMainWidget; + TrackDataHeaderWidget* m_trackDataHeaderWidget; + TrackDataWidget* m_trackDataWidget; + TrackHeaderWidget* m_trackHeaderWidget; + TimeInfoWidget* m_timeInfoWidget; + TimeViewToolBar* m_timeViewToolBar; + QWidget* m_mainWidget; TimeViewMode m_mode = TimeViewMode::None; - EMotionFX::Motion* mMotion; - MotionWindowPlugin* mMotionWindowPlugin; - MotionEventsPlugin* mMotionEventsPlugin; - MotionListWindow* mMotionListWindow; + EMotionFX::Motion* m_motion; + MotionWindowPlugin* m_motionWindowPlugin; + MotionEventsPlugin* m_motionEventsPlugin; + MotionListWindow* m_motionListWindow; MotionSetsWindowPlugin* m_motionSetPlugin; - MCore::Array mSelectedEvents; + AZStd::vector m_selectedEvents; - EMotionFX::Recorder::ActorInstanceData* mActorInstanceData; - EMotionFX::Recorder::NodeHistoryItem* mNodeHistoryItem; - EMotionFX::Recorder::EventHistoryItem* mEventHistoryItem; - EMotionFX::AnimGraphNode* mEventEmitterNode; + EMotionFX::Recorder::ActorInstanceData* m_actorInstanceData; + EMotionFX::Recorder::NodeHistoryItem* m_nodeHistoryItem; + EMotionFX::Recorder::EventHistoryItem* m_eventHistoryItem; + EMotionFX::AnimGraphNode* m_eventEmitterNode; struct MotionInfo { - uint32 mMotionID; - bool mInitialized; - double mScale; - double mScrollX; + uint32 m_motionId; + bool m_initialized; + double m_scale; + double m_scrollX; }; MotionInfo* FindMotionInfo(uint32 motionID); void UpdateCurrentMotionInfo(); - MCore::Array mMotionInfos; - MCore::Array mTracks; - - double mPixelsPerSecond; // pixels per second - double mScrollX; // horizontal scroll offset - double mCurTime; // current time - double mFPS; // the frame rate, used to snap time values to and to calculate frame numbers - double mCurMouseX; - double mCurMouseY; - double mMaxTime; // the end time of the full time bar - double mMaxHeight; - double mLastMaxHeight; - double mTimeScale; // the time zoom scale factor - double mMaxScale; - double mMinScale; - float mTotalTime; - - double mTargetTimeScale; - double mTargetScrollX; - - bool mIsAnimating; - bool mDirty; - - QCursor* mZoomInCursor; - QCursor* mZoomOutCursor; - - QPen mPenCurTimeHandle; - QPen mPenTimeHandles; - QPen mPenCurTimeHelper; - QBrush mBrushCurTimeHandle; + AZStd::vector m_motionInfos; + AZStd::vector m_tracks; + + double m_pixelsPerSecond; // pixels per second + double m_scrollX; // horizontal scroll offset + double m_curTime; // current time + double m_fps; // the frame rate, used to snap time values to and to calculate frame numbers + double m_curMouseX; + double m_curMouseY; + double m_maxTime; // the end time of the full time bar + double m_maxHeight; + double m_lastMaxHeight; + double m_timeScale; // the time zoom scale factor + double m_maxScale; + double m_minScale; + float m_totalTime; + + double m_targetTimeScale; + double m_targetScrollX; + + bool m_isAnimating; + bool m_dirty; + + QCursor* m_zoomInCursor; + QCursor* m_zoomOutCursor; + + QPen m_penCurTimeHandle; + QPen m_penTimeHandles; + QPen m_penCurTimeHelper; + QBrush m_brushCurTimeHandle; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.cpp index 8a503ef1f7..d95b606b3f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.cpp @@ -32,7 +32,7 @@ namespace EMStudio { setObjectName("TimeViewToolBar"); - mPlugin = plugin; + m_plugin = plugin; m_recorderGroup = new RecorderGroup(plugin, this); m_playbackControls = new PlaybackControlsGroup(this); @@ -75,7 +75,7 @@ namespace EMStudio void TimeViewToolBar::OnPlayForwardButton() { - switch (mPlugin->GetMode()) + switch (m_plugin->GetMode()) { case TimeViewMode::Motion: { @@ -100,12 +100,12 @@ namespace EMStudio } const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numSelectedMotions = selectionList.GetNumSelectedMotions(); + const size_t numSelectedMotions = selectionList.GetNumSelectedMotions(); AZStd::vector motionsToPlay; motionsToPlay.reserve(numSelectedMotions); - for (uint32 i = 0; i < numSelectedMotions; ++i) + for (size_t i = 0; i < numSelectedMotions; ++i) { EMotionFX::Motion* motion = selectionList.GetMotion(i); @@ -179,11 +179,11 @@ namespace EMStudio const float newTime = MCore::Min(EMotionFX::GetRecorder().GetCurrentPlayTime() + (1.0f / 60.0f), EMotionFX::GetRecorder().GetRecordTime()); EMotionFX::GetRecorder().SetCurrentPlayTime(newTime); - if (mPlugin) + if (m_plugin) { - mPlugin->SetCurrentTime(newTime); - mPlugin->GetTimeInfoWidget()->update(); - mPlugin->SetRedrawFlag(); + m_plugin->SetCurrentTime(newTime); + m_plugin->GetTimeInfoWidget()->update(); + m_plugin->SetRedrawFlag(); } } @@ -195,11 +195,11 @@ namespace EMStudio const float newTime = MCore::Max(EMotionFX::GetRecorder().GetCurrentPlayTime() - (1.0f / 60.0f), 0.0f); EMotionFX::GetRecorder().SetCurrentPlayTime(newTime); - if (mPlugin) + if (m_plugin) { - mPlugin->SetCurrentTime(newTime); - mPlugin->GetTimeInfoWidget()->update(); - mPlugin->SetRedrawFlag(); + m_plugin->SetCurrentTime(newTime); + m_plugin->GetTimeInfoWidget()->update(); + m_plugin->SetRedrawFlag(); } emit RecorderStateChanged(); @@ -212,21 +212,19 @@ namespace EMStudio case RecorderGroup::Default: { const AZStd::vector& motionInstances = MotionWindowPlugin::GetSelectedMotionInstances(); - const size_t numMotionInstances = motionInstances.size(); - for (size_t i = 0; i < numMotionInstances; ++i) + for (EMotionFX::MotionInstance* motionInstance : motionInstances) { - EMotionFX::MotionInstance* motionInstance = motionInstances[i]; - motionInstance->SetCurrentTime(motionInstance->GetDuration()); + motionInstance->SetCurrentTime(motionInstance->GetDuration()); } break; } case RecorderGroup::PlaybackRecording: { EMotionFX::GetRecorder().SetCurrentPlayTime(EMotionFX::GetRecorder().GetRecordTime()); - if (mPlugin) + if (m_plugin) { - mPlugin->SetCurrentTime(EMotionFX::GetRecorder().GetCurrentPlayTime()); - mPlugin->SetRedrawFlag(); + m_plugin->SetCurrentTime(EMotionFX::GetRecorder().GetCurrentPlayTime()); + m_plugin->SetRedrawFlag(); } break; } @@ -244,21 +242,19 @@ namespace EMStudio case RecorderGroup::Default: { const AZStd::vector& motionInstances = MotionWindowPlugin::GetSelectedMotionInstances(); - const size_t numMotionInstances = motionInstances.size(); - for (size_t i = 0; i < numMotionInstances; ++i) + for (EMotionFX::MotionInstance* motionInstance : motionInstances) { - EMotionFX::MotionInstance* motionInstance = motionInstances[i]; - motionInstance->Rewind(); + motionInstance->Rewind(); } break; } case RecorderGroup::PlaybackRecording: { EMotionFX::GetRecorder().SetCurrentPlayTime(0.0f); - if (mPlugin) + if (m_plugin) { - mPlugin->SetCurrentTime(EMotionFX::GetRecorder().GetCurrentPlayTime()); - mPlugin->SetRedrawFlag(); + m_plugin->SetCurrentTime(EMotionFX::GetRecorder().GetCurrentPlayTime()); + m_plugin->SetRedrawFlag(); } break; } @@ -276,8 +272,8 @@ namespace EMStudio // Check if at least one actor instance has an anim graph playing. bool activateAnimGraph = true; const CommandSystem::SelectionList& selectionList = GetCommandManager()->GetCurrentSelection(); - const uint32 numActorInstances = selectionList.GetNumSelectedActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = selectionList.GetNumSelectedActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance = selectionList.GetActorInstance(i); if (!actorInstance->GetIsOwnedByRuntime() && actorInstance->GetAnimGraphInstance()) @@ -298,28 +294,28 @@ namespace EMStudio } EMotionFX::Recorder::RecordSettings settings; - settings.mFPS = 1000000; - settings.mRecordTransforms = true; - settings.mRecordAnimGraphStates = true; - settings.mRecordNodeHistory = true; - settings.mRecordScale = true; - settings.mInitialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb - settings.mHistoryStatesOnly = m_recorderGroup->GetRecordStatesOnly(); - settings.mRecordEvents = m_recorderGroup->GetRecordEvents(); + settings.m_fps = 1000000; + settings.m_recordTransforms = true; + settings.m_recordAnimGraphStates = true; + settings.m_recordNodeHistory = true; + settings.m_recordScale = true; + settings.m_initialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb + settings.m_historyStatesOnly = m_recorderGroup->GetRecordStatesOnly(); + settings.m_recordEvents = m_recorderGroup->GetRecordEvents(); if (m_recorderGroup->GetRecordMotionsOnly()) { - settings.mNodeHistoryTypes.insert(azrtti_typeid()); + settings.m_nodeHistoryTypes.insert(azrtti_typeid()); } EMotionFX::GetRecorder().StartRecording(settings); // reinit the time view plugin - if (mPlugin) + if (m_plugin) { - mPlugin->ReInit(); - mPlugin->SetScale(1.0); - mPlugin->SetScrollX(0); + m_plugin->ReInit(); + m_plugin->SetScale(1.0); + m_plugin->SetScrollX(0); } } else @@ -330,13 +326,13 @@ namespace EMStudio EMotionFX::GetRecorder().SetCurrentPlayTime(0.0f); // reinit the time view plugin - if (mPlugin) + if (m_plugin) { - mPlugin->ReInit(); - mPlugin->OnZoomAll(); - mPlugin->SetCurrentTime(0.0f); - mPlugin->GetTrackDataWidget()->setFocus(); - mPlugin->GetTrackDataHeaderWidget()->setFocus(); + m_plugin->ReInit(); + m_plugin->OnZoomAll(); + m_plugin->SetCurrentTime(0.0f); + m_plugin->GetTrackDataWidget()->setFocus(); + m_plugin->GetTrackDataHeaderWidget()->setFocus(); } } @@ -351,12 +347,12 @@ namespace EMStudio UpdateInterface(); // reinit the time view plugin - if (mPlugin) + if (m_plugin) { - mPlugin->ReInit(); - mPlugin->SetScale(1.0); - mPlugin->SetScrollX(0); - mPlugin->SetCurrentTime(0.0f); + m_plugin->ReInit(); + m_plugin->SetScale(1.0); + m_plugin->SetScrollX(0); + m_plugin->SetCurrentTime(0.0f); } emit RecorderStateChanged(); @@ -370,8 +366,8 @@ namespace EMStudio MCore::CommandGroup commandGroup("Adjust default motion instances"); // get the number of selected motions and iterate through them - const uint32 numMotions = selection.GetNumSelectedMotions(); - for (uint32 i = 0; i < numMotions; ++i) + const size_t numMotions = selection.GetNumSelectedMotions(); + for (size_t i = 0; i < numMotions; ++i) { MotionWindowPlugin* plugin = GetMotionWindowPlugin(); MotionWindowPlugin::MotionTableEntry* entry = plugin ? plugin->FindMotionEntryByID(selection.GetMotion(i)->GetID()) : nullptr; @@ -381,11 +377,11 @@ namespace EMStudio continue; } - EMotionFX::Motion* motion = entry->mMotion; + EMotionFX::Motion* motion = entry->m_motion; EMotionFX::PlayBackInfo* playbackInfo = motion->GetDefaultPlayBackInfo(); AZStd::string commandParameters; - if (MCore::Compare::CheckIfIsClose(playbackInfo->mPlaySpeed, m_playbackOptions->GetPlaySpeed(), 0.001f) == false) + if (MCore::Compare::CheckIfIsClose(playbackInfo->m_playSpeed, m_playbackOptions->GetPlaySpeed(), 0.001f) == false) { commandParameters += AZStd::string::format("-playSpeed %f ", m_playbackOptions->GetPlaySpeed()); } @@ -401,25 +397,25 @@ namespace EMStudio } const bool mirrorMotion = m_playbackOptions->GetMirrorMotion(); - if (playbackInfo->mMirrorMotion != mirrorMotion) + if (playbackInfo->m_mirrorMotion != mirrorMotion) { commandParameters += AZStd::string::format("-mirrorMotion %s ", AZStd::to_string(mirrorMotion).c_str()); } const EMotionFX::EPlayMode playMode = m_playbackOptions->GetPlayMode(); - if (playbackInfo->mPlayMode != playMode) + if (playbackInfo->m_playMode != playMode) { commandParameters += AZStd::string::format("-playMode %i ", static_cast(playMode)); } const bool inPlace = m_playbackOptions->GetInPlace(); - if (playbackInfo->mInPlace != inPlace) + if (playbackInfo->m_inPlace != inPlace) { commandParameters += AZStd::string::format("-inPlace %s ", AZStd::to_string(inPlace).c_str()); } const bool retarget = m_playbackOptions->GetRetarget(); - if (playbackInfo->mRetarget != retarget) + if (playbackInfo->m_retarget != retarget) { commandParameters += AZStd::string::format("-retarget %s ", AZStd::to_string(retarget).c_str()); } @@ -441,7 +437,7 @@ namespace EMStudio void TimeViewToolBar::UpdateInterface() { - const TimeViewMode mode = mPlugin->GetMode(); + const TimeViewMode mode = m_plugin->GetMode(); const bool playbackOptionsVisible = m_playbackOptions->UpdateInterface(mode, /*showRightSeparator=*/false); const bool playbackControlsVisible = m_playbackControls->UpdateInterface(mode, /*showRightSeparator=*/playbackOptionsVisible); @@ -450,15 +446,15 @@ namespace EMStudio void TimeViewToolBar::OnDetailedNodes() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); if (!m_recorderGroup->GetDetailedNodes()) { - mPlugin->mTrackDataWidget->mNodeHistoryItemHeight = 20; + m_plugin->m_trackDataWidget->m_nodeHistoryItemHeight = 20; } else { - mPlugin->mTrackDataWidget->mNodeHistoryItemHeight = 35; + m_plugin->m_trackDataWidget->m_nodeHistoryItemHeight = 35; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.h index 0e2abbc594..eda6337832 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TimeViewToolBar.h @@ -63,7 +63,7 @@ namespace EMStudio RecorderGroup::RecordingMode GetCurrentRecordingMode() const; private: - TimeViewPlugin* mPlugin = nullptr; + TimeViewPlugin* m_plugin = nullptr; RecorderGroup* m_recorderGroup; PlaybackControlsGroup* m_playbackControls; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.cpp index a70a12dbeb..0d1f55c172 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.cpp @@ -49,46 +49,46 @@ namespace EMStudio TrackDataHeaderWidget::TrackDataHeaderWidget(TimeViewPlugin* plugin, QWidget* parent) : QOpenGLWidget(parent) , QOpenGLFunctions() - , mPlugin(plugin) - , mLastMouseX(0) - , mLastMouseY(0) - , mMouseLeftClicked(false) - , mMouseRightClicked(false) - , mMouseMidClicked(false) - , mIsScrolling(false) - , mAllowContextMenu(true) + , m_plugin(plugin) + , m_lastMouseX(0) + , m_lastMouseY(0) + , m_mouseLeftClicked(false) + , m_mouseRightClicked(false) + , m_mouseMidClicked(false) + , m_isScrolling(false) + , m_allowContextMenu(true) { setObjectName("TrackDataHeaderWidget"); // init brushes and pens - mBrushBackgroundOutOfRange = QBrush(QColor(35, 35, 35), Qt::SolidPattern); + m_brushBackgroundOutOfRange = QBrush(QColor(35, 35, 35), Qt::SolidPattern); - mHeaderGradientActive = QLinearGradient(0, 0, 0, 35); - mHeaderGradientActive.setColorAt(1.0f, QColor(100, 105, 110)); - mHeaderGradientActive.setColorAt(0.5f, QColor(30, 35, 40)); - mHeaderGradientActive.setColorAt(0.0f, QColor(20, 20, 20)); + m_headerGradientActive = QLinearGradient(0, 0, 0, 35); + m_headerGradientActive.setColorAt(1.0f, QColor(100, 105, 110)); + m_headerGradientActive.setColorAt(0.5f, QColor(30, 35, 40)); + m_headerGradientActive.setColorAt(0.0f, QColor(20, 20, 20)); - mHeaderGradientActiveFocus = QLinearGradient(0, 0, 0, 35); - mHeaderGradientActiveFocus.setColorAt(1.0f, QColor(100, 105, 130)); - mHeaderGradientActiveFocus.setColorAt(0.5f, QColor(30, 35, 40)); - mHeaderGradientActiveFocus.setColorAt(0.0f, QColor(20, 20, 20)); + m_headerGradientActiveFocus = QLinearGradient(0, 0, 0, 35); + m_headerGradientActiveFocus.setColorAt(1.0f, QColor(100, 105, 130)); + m_headerGradientActiveFocus.setColorAt(0.5f, QColor(30, 35, 40)); + m_headerGradientActiveFocus.setColorAt(0.0f, QColor(20, 20, 20)); - mHeaderGradientInactive = QLinearGradient(0, 0, 0, 35); - mHeaderGradientInactive.setColorAt(1.0f, QColor(30, 30, 30)); - mHeaderGradientInactive.setColorAt(0.0f, QColor(20, 20, 20)); + m_headerGradientInactive = QLinearGradient(0, 0, 0, 35); + m_headerGradientInactive.setColorAt(1.0f, QColor(30, 30, 30)); + m_headerGradientInactive.setColorAt(0.0f, QColor(20, 20, 20)); - mHeaderGradientInactiveFocus = QLinearGradient(0, 0, 0, 35); - mHeaderGradientInactiveFocus.setColorAt(1.0f, QColor(30, 30, 30)); - mHeaderGradientInactiveFocus.setColorAt(0.0f, QColor(20, 20, 20)); + m_headerGradientInactiveFocus = QLinearGradient(0, 0, 0, 35); + m_headerGradientInactiveFocus.setColorAt(1.0f, QColor(30, 30, 30)); + m_headerGradientInactiveFocus.setColorAt(0.0f, QColor(20, 20, 20)); - mPenMainTimeStepLinesActive = QPen(QColor(110, 110, 110)); + m_penMainTimeStepLinesActive = QPen(QColor(110, 110, 110)); - mTimeLineFont.setPixelSize(12); - mDataFont.setPixelSize(13); + m_timeLineFont.setPixelSize(12); + m_dataFont.setPixelSize(13); // load the time handle top image QDir imageName{ QString(MysticQt::GetMysticQt()->GetDataDir().c_str()) }; - mTimeHandleTop = QPixmap(imageName.filePath("Images/Icons/TimeHandleTop.png")); + m_timeHandleTop = QPixmap(imageName.filePath("Images/Icons/TimeHandleTop.png")); setMouseTracking(true); setAcceptDrops(true); @@ -117,9 +117,9 @@ namespace EMStudio { MCORE_UNUSED(w); MCORE_UNUSED(h); - if (mPlugin) + if (m_plugin) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); } } @@ -135,16 +135,16 @@ namespace EMStudio // draw a background rect painter.setPen(Qt::NoPen); - painter.setBrush(mBrushBackgroundOutOfRange); + painter.setBrush(m_brushBackgroundOutOfRange); painter.drawRect(rect); - painter.setFont(mDataFont); + painter.setFont(m_dataFont); // draw the timeline painter.setRenderHint(QPainter::Antialiasing, false); DrawTimeLine(painter, rect); const uint32 height = geometry().height(); - mPlugin->RenderElementTimeHandles(painter, height, mPlugin->mPenTimeHandles); + m_plugin->RenderElementTimeHandles(painter, height, m_plugin->m_penTimeHandles); DrawTimeMarker(painter, rect); } @@ -154,10 +154,10 @@ namespace EMStudio { // draw the current time marker float startHeight = 0.0f; - const float curTimeX = aznumeric_cast(mPlugin->TimeToPixel(mPlugin->mCurTime)); - painter.drawPixmap(aznumeric_cast(curTimeX - (mTimeHandleTop.width() / 2) - 1), 0, mTimeHandleTop); + const float curTimeX = aznumeric_cast(m_plugin->TimeToPixel(m_plugin->m_curTime)); + painter.drawPixmap(aznumeric_cast(curTimeX - (m_timeHandleTop.width() / 2) - 1), 0, m_timeHandleTop); - painter.setPen(mPlugin->mPenCurTimeHandle); + painter.setPen(m_plugin->m_penCurTimeHandle); painter.drawLine(QPointF(curTimeX, startHeight), QPointF(curTimeX, rect.bottom())); } @@ -169,52 +169,52 @@ namespace EMStudio } // if double clicked in the timeline - mPlugin->MakeTimeVisible(mPlugin->PixelToTime(event->x()), 0.5); + m_plugin->MakeTimeVisible(m_plugin->PixelToTime(event->x()), 0.5); } // when the mouse is moving, while a button is pressed void TrackDataHeaderWidget::mouseMoveEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); - const int32 deltaRelX = event->x() - mLastMouseX; - mLastMouseX = event->x(); - mPlugin->mCurMouseX = event->x(); - mPlugin->mCurMouseY = event->y(); + const int32 deltaRelX = event->x() - m_lastMouseX; + m_lastMouseX = event->x(); + m_plugin->m_curMouseX = event->x(); + m_plugin->m_curMouseY = event->y(); - const int32 deltaRelY = event->y() - mLastMouseY; - mLastMouseY = event->y(); + const int32 deltaRelY = event->y() - m_lastMouseY; + m_lastMouseY = event->y(); const bool altPressed = event->modifiers() & Qt::AltModifier; - const bool isZooming = mMouseLeftClicked == false && mMouseRightClicked && altPressed; - const bool isPanning = mMouseLeftClicked == false && isZooming == false && (mMouseMidClicked || mMouseRightClicked); + const bool isZooming = m_mouseLeftClicked == false && m_mouseRightClicked && altPressed; + const bool isPanning = m_mouseLeftClicked == false && isZooming == false && (m_mouseMidClicked || m_mouseRightClicked); if (deltaRelY != 0) { - mAllowContextMenu = false; + m_allowContextMenu = false; } - if (mMouseRightClicked) + if (m_mouseRightClicked) { - mIsScrolling = true; + m_isScrolling = true; } // if the mouse left button is pressed - if (mMouseLeftClicked) + if (m_mouseLeftClicked) { // update the current time marker int newX = event->x(); newX = AZ::GetClamp(newX, 0, geometry().width() - 1); - mPlugin->mCurTime = mPlugin->PixelToTime(newX); + m_plugin->m_curTime = m_plugin->PixelToTime(newX); EMotionFX::Recorder& recorder = EMotionFX::GetRecorder(); if (recorder.GetRecordTime() > AZ::Constants::FloatEpsilon) { if (recorder.GetIsInPlayMode()) { - recorder.SetCurrentPlayTime(aznumeric_cast(mPlugin->GetCurrentTime())); + recorder.SetCurrentPlayTime(aznumeric_cast(m_plugin->GetCurrentTime())); recorder.SetAutoPlay(false); - emit mPlugin->ManualTimeChange(aznumeric_cast(mPlugin->GetCurrentTime())); + emit m_plugin->ManualTimeChange(aznumeric_cast(m_plugin->GetCurrentTime())); } } else @@ -223,33 +223,33 @@ namespace EMStudio if (motionInstances.size() == 1) { EMotionFX::MotionInstance* motionInstance = motionInstances[0]; - motionInstance->SetCurrentTime(aznumeric_cast(mPlugin->GetCurrentTime()), false); + motionInstance->SetCurrentTime(aznumeric_cast(m_plugin->GetCurrentTime()), false); motionInstance->SetPause(true); - emit mPlugin->ManualTimeChange(aznumeric_cast(mPlugin->GetCurrentTime())); + emit m_plugin->ManualTimeChange(aznumeric_cast(m_plugin->GetCurrentTime())); } } - mIsScrolling = true; + m_isScrolling = true; } else if (isPanning) { if (EMotionFX::GetRecorder().GetIsRecording() == false) { - mPlugin->DeltaScrollX(-deltaRelX, false); + m_plugin->DeltaScrollX(-deltaRelX, false); } } else if (isZooming) { if (deltaRelY < 0) { - setCursor(*(mPlugin->GetZoomOutCursor())); + setCursor(*(m_plugin->GetZoomOutCursor())); } else { - setCursor(*(mPlugin->GetZoomInCursor())); + setCursor(*(m_plugin->GetZoomInCursor())); } - DoMouseYMoveZoom(deltaRelY, mPlugin); + DoMouseYMoveZoom(deltaRelY, m_plugin); } else // no left mouse button is pressed { @@ -275,43 +275,43 @@ namespace EMStudio void TrackDataHeaderWidget::UpdateMouseOverCursor() { // disable all tooltips - mPlugin->DisableAllToolTips(); + m_plugin->DisableAllToolTips(); } // when the mouse is pressed void TrackDataHeaderWidget::mousePressEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); const bool ctrlPressed = event->modifiers() & Qt::ControlModifier; const bool shiftPressed = event->modifiers() & Qt::ShiftModifier; const bool altPressed = event->modifiers() & Qt::AltModifier; // store the last clicked position - mAllowContextMenu = true; + m_allowContextMenu = true; if (event->button() == Qt::RightButton) { - mMouseRightClicked = true; + m_mouseRightClicked = true; } if (event->button() == Qt::MidButton) { - mMouseMidClicked = true; + m_mouseMidClicked = true; } if (event->button() == Qt::LeftButton) { - mMouseLeftClicked = true; + m_mouseLeftClicked = true; EMotionFX::Recorder& recorder = EMotionFX::GetRecorder(); - if (!mPlugin->mNodeHistoryItem && !altPressed) + if (!m_plugin->m_nodeHistoryItem && !altPressed) { // update the current time marker int newX = event->x(); newX = AZ::GetClamp(newX, 0, geometry().width() - 1); - mPlugin->mCurTime = mPlugin->PixelToTime(newX); + m_plugin->m_curTime = m_plugin->PixelToTime(newX); if (recorder.GetRecordTime() > AZ::Constants::FloatEpsilon) { @@ -320,10 +320,10 @@ namespace EMStudio recorder.StartPlayBack(); } - recorder.SetCurrentPlayTime(aznumeric_cast(mPlugin->GetCurrentTime())); + recorder.SetCurrentPlayTime(aznumeric_cast(m_plugin->GetCurrentTime())); recorder.SetAutoPlay(false); - emit mPlugin->ManualTimeChangeStart(aznumeric_cast(mPlugin->GetCurrentTime())); - emit mPlugin->ManualTimeChange(aznumeric_cast(mPlugin->GetCurrentTime())); + emit m_plugin->ManualTimeChangeStart(aznumeric_cast(m_plugin->GetCurrentTime())); + emit m_plugin->ManualTimeChange(aznumeric_cast(m_plugin->GetCurrentTime())); } else { @@ -331,19 +331,19 @@ namespace EMStudio if (motionInstances.size() == 1) { EMotionFX::MotionInstance* motionInstance = motionInstances[0]; - motionInstance->SetCurrentTime(aznumeric_cast(mPlugin->GetCurrentTime()), false); + motionInstance->SetCurrentTime(aznumeric_cast(m_plugin->GetCurrentTime()), false); motionInstance->SetPause(true); - mPlugin->GetTimeViewToolBar()->UpdateInterface(); - emit mPlugin->ManualTimeChangeStart(aznumeric_cast(mPlugin->GetCurrentTime())); - emit mPlugin->ManualTimeChange(aznumeric_cast(mPlugin->GetCurrentTime())); + m_plugin->GetTimeViewToolBar()->UpdateInterface(); + emit m_plugin->ManualTimeChangeStart(aznumeric_cast(m_plugin->GetCurrentTime())); + emit m_plugin->ManualTimeChange(aznumeric_cast(m_plugin->GetCurrentTime())); } } } } //const bool altPressed = event->modifiers() & Qt::AltModifier; - const bool isZooming = mMouseLeftClicked == false && mMouseRightClicked && altPressed; - const bool isPanning = mMouseLeftClicked == false && isZooming == false && (mMouseMidClicked || mMouseRightClicked); + const bool isZooming = m_mouseLeftClicked == false && m_mouseRightClicked && altPressed; + const bool isPanning = m_mouseLeftClicked == false && isZooming == false && (m_mouseMidClicked || m_mouseRightClicked); if (isPanning) { @@ -352,7 +352,7 @@ namespace EMStudio if (isZooming) { - setCursor(*(mPlugin->GetZoomInCursor())); + setCursor(*(m_plugin->GetZoomInCursor())); } } @@ -360,33 +360,33 @@ namespace EMStudio // when releasing the mouse button void TrackDataHeaderWidget::mouseReleaseEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); setCursor(Qt::ArrowCursor); // disable overwrite mode in any case when the mouse gets released so that we display the current time from the plugin again - if (mPlugin->GetTimeInfoWidget()) + if (m_plugin->GetTimeInfoWidget()) { - mPlugin->GetTimeInfoWidget()->SetIsOverwriteMode(false); + m_plugin->GetTimeInfoWidget()->SetIsOverwriteMode(false); } const bool ctrlPressed = event->modifiers() & Qt::ControlModifier; if (event->button() == Qt::RightButton) { - mMouseRightClicked = false; - mIsScrolling = false; + m_mouseRightClicked = false; + m_isScrolling = false; } if (event->button() == Qt::MidButton) { - mMouseMidClicked = false; + m_mouseMidClicked = false; } if (event->button() == Qt::LeftButton) { - mMouseLeftClicked = false; - mIsScrolling = false; + m_mouseLeftClicked = false; + m_isScrolling = false; return; } @@ -397,7 +397,7 @@ namespace EMStudio // drag & drop support void TrackDataHeaderWidget::dragEnterEvent(QDragEnterEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); // this is needed to actually reach the drop event function event->acceptProposedAction(); @@ -444,16 +444,16 @@ namespace EMStudio // handle mouse wheel event void TrackDataHeaderWidget::wheelEvent(QWheelEvent* event) { - DoWheelEvent(event, mPlugin); + DoWheelEvent(event, m_plugin); } void TrackDataHeaderWidget::dragMoveEvent(QDragMoveEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); QPoint mousePos = event->pos(); - double dropTime = mPlugin->PixelToTime(mousePos.x()); - mPlugin->SetCurrentTime(dropTime); + double dropTime = m_plugin->PixelToTime(mousePos.x()); + m_plugin->SetCurrentTime(dropTime); const AZStd::vector& motionInstances = MotionWindowPlugin::GetSelectedMotionInstances(); if (motionInstances.size() == 1) @@ -470,9 +470,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TrackDataHeaderWidget::keyPressEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyPressEvent(event); + m_plugin->OnKeyPressEvent(event); } } @@ -480,9 +480,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TrackDataHeaderWidget::keyReleaseEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyReleaseEvent(event); + m_plugin->OnKeyReleaseEvent(event); } } @@ -493,12 +493,11 @@ namespace EMStudio double animationLength = 0.0; double clipStart = 0.0; double clipEnd = 0.0; - mPlugin->GetDataTimes(&animationLength, &clipStart, &clipEnd); + m_plugin->GetDataTimes(&animationLength, &clipStart, &clipEnd); // calculate the pixel offsets - double animEndPixel = mPlugin->TimeToPixel(animationLength); - double clipStartPixel = mPlugin->TimeToPixel(clipStart); - //double clipEndPixel = mPlugin->TimeToPixel(clipEnd); + double animEndPixel = m_plugin->TimeToPixel(animationLength); + double clipStartPixel = m_plugin->TimeToPixel(clipStart); // fill with the background color QRect motionRect = rect; @@ -511,16 +510,16 @@ namespace EMStudio painter.setPen(Qt::NoPen); if (hasFocus() == false) { - painter.setBrush(mHeaderGradientActive); + painter.setBrush(m_headerGradientActive); painter.drawRect(motionRect); - painter.setBrush(mHeaderGradientInactive); + painter.setBrush(m_headerGradientInactive); painter.drawRect(outOfRangeRect); } else { - painter.setBrush(mHeaderGradientActiveFocus); + painter.setBrush(m_headerGradientActiveFocus); painter.drawRect(motionRect); - painter.setBrush(mHeaderGradientInactiveFocus); + painter.setBrush(m_headerGradientInactiveFocus); painter.drawRect(outOfRangeRect); } @@ -529,7 +528,7 @@ namespace EMStudio if (recorder.GetRecordTime() > MCore::Math::epsilon) { QRectF recorderRect = rect; - recorderRect.setRight(mPlugin->TimeToPixel(recorder.GetRecordTime())); + recorderRect.setRight(m_plugin->TimeToPixel(recorder.GetRecordTime())); recorderRect.setTop(height() - 3); recorderRect.setBottom(height()); @@ -542,7 +541,7 @@ namespace EMStudio if (animationLength > MCore::Math::epsilon) { QRectF rangeRect = rect; - rangeRect.setRight(mPlugin->TimeToPixel(animationLength)); + rangeRect.setRight(m_plugin->TimeToPixel(animationLength)); rangeRect.setTop(height() - 3); rangeRect.setBottom(height()); @@ -554,21 +553,16 @@ namespace EMStudio QTextOption options; options.setAlignment(Qt::AlignCenter); - painter.setFont(mTimeLineFont); + painter.setFont(m_timeLineFont); const uint32 width = rect.width(); //const uint32 height = rect.height(); float yOffset = 19.0f; - //const double pixelsPerSecond = mPlugin->mPixelsPerSecond; - - double timeOffset = mPlugin->PixelToTime(0.0) * 1000.0; + double timeOffset = m_plugin->PixelToTime(0.0) * 1000.0; timeOffset = (timeOffset - ((int32)timeOffset % 5000)) / 1000.0; - //if (rand() % 10 == 0) - //MCore::LogInfo("%f", mPlugin->mTimeScale); - uint32 minutes, seconds, milSecs, frameNumber; double pixelTime; @@ -578,35 +572,34 @@ namespace EMStudio //uint32 index = 0; while (curX <= width) { - curX = mPlugin->TimeToPixel(curTime, false); - mPlugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); + curX = m_plugin->TimeToPixel(curTime, false); + m_plugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); seconds += minutes * 60; - curX *= mPlugin->mTimeScale; + curX *= m_plugin->m_timeScale; curTime += 5.0; - painter.setPen(mPenMainTimeStepLinesActive); + painter.setPen(m_penMainTimeStepLinesActive); painter.drawLine(QPointF(curX, yOffset - 3.0f), QPointF(curX, yOffset + 10.0f)); - mTimeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory + m_timeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory - //painter.setPen( mPenText ); painter.setPen(QColor(175, 175, 175)); - painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), mTimeString.c_str(), options); + painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), m_timeString.c_str(), options); } // draw the seconds curTime = timeOffset; - if (mPlugin->mTimeScale >= 0.25) + if (m_plugin->m_timeScale >= 0.25) { uint32 index = 0; curX = 0.0; while (curX <= width) { - curX = mPlugin->TimeToPixel(curTime, false); - mPlugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); + curX = m_plugin->TimeToPixel(curTime, false); + m_plugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); seconds += minutes * 60; - curX *= mPlugin->mTimeScale; + curX *= m_plugin->m_timeScale; curTime += 1.0; if (index % 5 == 0) @@ -618,8 +611,8 @@ namespace EMStudio if (curX > -100 && curX < width + 100) { - painter.setPen(mPenMainTimeStepLinesActive); - if (mPlugin->mTimeScale < 0.9) + painter.setPen(m_penMainTimeStepLinesActive); + if (m_plugin->m_timeScale < 0.9) { painter.drawLine(QPointF(curX, yOffset - 1.0f), QPointF(curX, yOffset + 5.0f)); } @@ -628,11 +621,11 @@ namespace EMStudio painter.drawLine(QPointF(curX, yOffset - 3.0f), QPointF(curX, yOffset + 10.0f)); } - if (mPlugin->mTimeScale >= 0.48) + if (m_plugin->m_timeScale >= 0.48) { - mTimeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory + m_timeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory - float alpha = aznumeric_cast((mPlugin->mTimeScale - 0.48f) / 1.0f); + float alpha = aznumeric_cast((m_plugin->m_timeScale - 0.48f) / 1.0f); alpha *= 2; if (alpha > 1.0f) { @@ -640,7 +633,7 @@ namespace EMStudio } painter.setPen(QColor(200, 200, 200, aznumeric_cast(alpha * 255))); - painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), mTimeString.c_str(), options); + painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), m_timeString.c_str(), options); } } } @@ -648,16 +641,16 @@ namespace EMStudio // 500 ms curTime = timeOffset; - if (mPlugin->mTimeScale >= 0.1) + if (m_plugin->m_timeScale >= 0.1) { uint32 index = 0; curX = 0; while (curX <= width) { - curX = mPlugin->TimeToPixel(curTime, false); - mPlugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); + curX = m_plugin->TimeToPixel(curTime, false); + m_plugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); seconds += minutes * 60; - curX *= mPlugin->mTimeScale; + curX *= m_plugin->m_timeScale; curTime += 0.5; if (index % 2 == 0) @@ -669,10 +662,10 @@ namespace EMStudio if (curX > -100 && curX < width + 100) { - painter.setPen(mPenMainTimeStepLinesActive); - if (mPlugin->mTimeScale < 1.5) + painter.setPen(m_penMainTimeStepLinesActive); + if (m_plugin->m_timeScale < 1.5) { - if (mPlugin->mTimeScale < 1.0) + if (m_plugin->m_timeScale < 1.0) { painter.drawLine(QPointF(curX, yOffset - 1.0f), QPointF(curX, yOffset + 1.0f)); } @@ -686,19 +679,18 @@ namespace EMStudio painter.drawLine(QPointF(curX, yOffset - 3.0f), QPointF(curX, yOffset + 10.0f)); } - if (mPlugin->mTimeScale >= 2.0f) + if (m_plugin->m_timeScale >= 2.0f) { - mTimeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory + m_timeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory - float alpha = aznumeric_cast((mPlugin->mTimeScale - 2.0f) / 2.0f); + float alpha = aznumeric_cast((m_plugin->m_timeScale - 2.0f) / 2.0f); if (alpha > 1.0f) { alpha = 1.0; } - //painter.setPen( mPenText ); painter.setPen(QColor(175, 175, 175, aznumeric_cast(alpha * 255))); - painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), mTimeString.c_str(), options); + painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), m_timeString.c_str(), options); } } } @@ -706,7 +698,7 @@ namespace EMStudio // 100 ms curTime = timeOffset; - if (mPlugin->mTimeScale >= 0.95f) + if (m_plugin->m_timeScale >= 0.95f) { uint32 index = 0; curX = 0; @@ -717,10 +709,10 @@ namespace EMStudio index = 1; } - curX = mPlugin->TimeToPixel(curTime, false); - mPlugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); + curX = m_plugin->TimeToPixel(curTime, false); + m_plugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); seconds += minutes * 60; - curX *= mPlugin->mTimeScale; + curX *= m_plugin->m_timeScale; curTime += 0.1; if (index == 0 || index == 5 || index == 10) @@ -733,40 +725,40 @@ namespace EMStudio if (curX > -100 && curX < width + 100) { - painter.setPen(mPenMainTimeStepLinesActive); + painter.setPen(m_penMainTimeStepLinesActive); painter.drawLine(QPointF(curX, yOffset), QPointF(curX, yOffset + 3.0f)); - if (mPlugin->mTimeScale >= 11.0f) + if (m_plugin->m_timeScale >= 11.0f) { - float alpha = aznumeric_cast((mPlugin->mTimeScale - 11.0f) / 4.0f); + float alpha = aznumeric_cast((m_plugin->m_timeScale - 11.0f) / 4.0f); if (alpha > 1.0f) { alpha = 1.0; } - mTimeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory + m_timeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory painter.setPen(QColor(110, 110, 110, aznumeric_cast(alpha * 255))); - painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), mTimeString.c_str(), options); + painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), m_timeString.c_str(), options); } } } } - timeOffset = mPlugin->PixelToTime(0.0) * 1000.0; + timeOffset = m_plugin->PixelToTime(0.0) * 1000.0; timeOffset = (timeOffset - ((int32)timeOffset % 1000)) / 1000.0; // 50 ms curTime = timeOffset; - if (mPlugin->mTimeScale >= 1.9) + if (m_plugin->m_timeScale >= 1.9) { uint32 index = 0; curX = 0; while (curX <= width) { - curX = mPlugin->TimeToPixel(curTime, false); - mPlugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); + curX = m_plugin->TimeToPixel(curTime, false); + m_plugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); seconds += minutes * 60; - curX *= mPlugin->mTimeScale; + curX *= m_plugin->m_timeScale; curTime += 0.05; if (index % 2 == 0) @@ -779,21 +771,20 @@ namespace EMStudio if (curX > -100 && curX < width + 100) { - painter.setPen(mPenMainTimeStepLinesActive); + painter.setPen(m_penMainTimeStepLinesActive); painter.drawLine(QPointF(curX, yOffset), QPointF(curX, yOffset + 1.0f)); - if (mPlugin->mTimeScale >= 25.0f) + if (m_plugin->m_timeScale >= 25.0f) { - float alpha = aznumeric_cast((mPlugin->mTimeScale - 25.0f) / 6.0f); + float alpha = aznumeric_cast((m_plugin->m_timeScale - 25.0f) / 6.0f); if (alpha > 1.0f) { alpha = 1.0; } - mTimeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory - //painter.setPen( mPenText ); + m_timeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory painter.setPen(QColor(80, 80, 80, aznumeric_cast(alpha * 255))); - painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), mTimeString.c_str(), options); + painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), m_timeString.c_str(), options); } } } @@ -802,15 +793,15 @@ namespace EMStudio // 10 ms curTime = timeOffset; - if (mPlugin->mTimeScale >= 7.9) + if (m_plugin->m_timeScale >= 7.9) { uint32 index = 0; curX = 0; while (curX <= width) { - curX = mPlugin->TimeToPixel(curTime, false); - mPlugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); - curX *= mPlugin->mTimeScale; + curX = m_plugin->TimeToPixel(curTime, false); + m_plugin->CalcTime(curX, &pixelTime, &minutes, &seconds, &milSecs, &frameNumber, false); + curX *= m_plugin->m_timeScale; curTime += 0.01; if (index % 5 == 0) @@ -824,21 +815,20 @@ namespace EMStudio if (curX > -100 && curX < width + 100) { //MCore::LogInfo("%f", curX); - painter.setPen(mPenMainTimeStepLinesActive); + painter.setPen(m_penMainTimeStepLinesActive); painter.drawLine(QPointF(curX, yOffset), QPointF(curX, yOffset + 1.0f)); - if (mPlugin->mTimeScale >= 65.0) + if (m_plugin->m_timeScale >= 65.0) { - float alpha = aznumeric_cast((mPlugin->mTimeScale - 65.0f) / 5.0f); + float alpha = aznumeric_cast((m_plugin->m_timeScale - 65.0f) / 5.0f); if (alpha > 1.0f) { alpha = 1.0; } - mTimeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory - //painter.setPen( mPenText ); + m_timeString = AZStd::string::format("%.2d:%.2d", seconds, milSecs); // will only do an allocation once, reuses the memory painter.setPen(QColor(60, 60, 60, aznumeric_cast(alpha * 255))); - painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), mTimeString.c_str(), options); + painter.drawText(QRect(aznumeric_cast(curX - 25), aznumeric_cast(yOffset - 23), 52, 20), m_timeString.c_str(), options); } } } @@ -855,10 +845,10 @@ namespace EMStudio // Timeline actions //--------------------- QAction* action = menu.addAction("Zoom To Fit All"); - connect(action, &QAction::triggered, mPlugin, &TimeViewPlugin::OnZoomAll); + connect(action, &QAction::triggered, m_plugin, &TimeViewPlugin::OnZoomAll); action = menu.addAction("Reset Timeline"); - connect(action, &QAction::triggered, mPlugin, &TimeViewPlugin::OnResetTimeline); + connect(action, &QAction::triggered, m_plugin, &TimeViewPlugin::OnResetTimeline); // show the menu at the given position menu.exec(event->globalPos()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.h index 6b932dca57..16d6171e4b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataHeaderWidget.h @@ -10,7 +10,7 @@ #if !defined(Q_MOC_RUN) #include -#include +#include #include "../StandardPluginsConfig.h" #include #include @@ -57,26 +57,26 @@ namespace EMStudio void keyReleaseEvent(QKeyEvent* event) override; private: - QBrush mBrushBackgroundOutOfRange; - TimeViewPlugin* mPlugin; - bool mMouseLeftClicked; - bool mMouseMidClicked; - bool mMouseRightClicked; - bool mIsScrolling; - int32 mLastMouseX; - int32 mLastMouseY; - bool mAllowContextMenu; + QBrush m_brushBackgroundOutOfRange; + TimeViewPlugin* m_plugin; + bool m_mouseLeftClicked; + bool m_mouseMidClicked; + bool m_mouseRightClicked; + bool m_isScrolling; + int32 m_lastMouseX; + int32 m_lastMouseY; + bool m_allowContextMenu; - QPixmap mTimeHandleTop; + QPixmap m_timeHandleTop; - QFont mTimeLineFont; - QFont mDataFont; - AZStd::string mTimeString; - QLinearGradient mHeaderGradientActive; - QLinearGradient mHeaderGradientInactive; - QLinearGradient mHeaderGradientActiveFocus; - QLinearGradient mHeaderGradientInactiveFocus; - QPen mPenMainTimeStepLinesActive; + QFont m_timeLineFont; + QFont m_dataFont; + AZStd::string m_timeString; + QLinearGradient m_headerGradientActive; + QLinearGradient m_headerGradientInactive; + QLinearGradient m_headerGradientActiveFocus; + QLinearGradient m_headerGradientInactiveFocus; + QPen m_penMainTimeStepLinesActive; void UpdateMouseOverCursor(); void DrawTimeLine(QPainter& painter, const QRect& rect); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.cpp index b1bad30b28..6c2ab60010 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.cpp @@ -55,37 +55,37 @@ namespace EMStudio TrackDataWidget::TrackDataWidget(TimeViewPlugin* plugin, QWidget* parent) : QOpenGLWidget(parent) , QOpenGLFunctions() - , mBrushBackground(QColor(40, 45, 50), Qt::SolidPattern) - , mBrushBackgroundClipped(QColor(40, 40, 40), Qt::SolidPattern) - , mBrushBackgroundOutOfRange(QColor(35, 35, 35), Qt::SolidPattern) - , mPlugin(plugin) - , mMouseLeftClicked(false) - , mMouseMidClicked(false) - , mMouseRightClicked(false) - , mDragging(false) - , mResizing(false) - , mRectZooming(false) - , mIsScrolling(false) - , mLastLeftClickedX(0) - , mLastMouseMoveX(0) - , mLastMouseX(0) - , mLastMouseY(0) - , mNodeHistoryItemHeight(20) - , mEventHistoryTotalHeight(0) - , mAllowContextMenu(true) - , mDraggingElement(nullptr) - , mDragElementTrack(nullptr) - , mResizeElement(nullptr) - , mGraphStartHeight(0) - , mEventsStartHeight(0) - , mNodeRectsStartHeight(0) - , mSelectStart(0, 0) - , mSelectEnd(0, 0) - , mRectSelecting(false) + , m_brushBackground(QColor(40, 45, 50), Qt::SolidPattern) + , m_brushBackgroundClipped(QColor(40, 40, 40), Qt::SolidPattern) + , m_brushBackgroundOutOfRange(QColor(35, 35, 35), Qt::SolidPattern) + , m_plugin(plugin) + , m_mouseLeftClicked(false) + , m_mouseMidClicked(false) + , m_mouseRightClicked(false) + , m_dragging(false) + , m_resizing(false) + , m_rectZooming(false) + , m_isScrolling(false) + , m_lastLeftClickedX(0) + , m_lastMouseMoveX(0) + , m_lastMouseX(0) + , m_lastMouseY(0) + , m_nodeHistoryItemHeight(20) + , m_eventHistoryTotalHeight(0) + , m_allowContextMenu(true) + , m_draggingElement(nullptr) + , m_dragElementTrack(nullptr) + , m_resizeElement(nullptr) + , m_graphStartHeight(0) + , m_eventsStartHeight(0) + , m_nodeRectsStartHeight(0) + , m_selectStart(0, 0) + , m_selectEnd(0, 0) + , m_rectSelecting(false) { setObjectName("TrackDataWidget"); - mDataFont.setPixelSize(13); + m_dataFont.setPixelSize(13); setMouseTracking(true); setAcceptDrops(true); @@ -114,9 +114,9 @@ namespace EMStudio { MCORE_UNUSED(w); MCORE_UNUSED(h); - if (mPlugin) + if (m_plugin) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); } } @@ -124,10 +124,10 @@ namespace EMStudio // calculate the selection rect void TrackDataWidget::CalcSelectRect(QRect& outRect) { - const int32 startX = MCore::Min(mSelectStart.x(), mSelectEnd.x()); - const int32 startY = MCore::Min(mSelectStart.y(), mSelectEnd.y()); - const int32 width = abs(mSelectEnd.x() - mSelectStart.x()); - const int32 height = abs(mSelectEnd.y() - mSelectStart.y()); + const int32 startX = MCore::Min(m_selectStart.x(), m_selectEnd.x()); + const int32 startY = MCore::Min(m_selectStart.y(), m_selectEnd.y()); + const int32 width = abs(m_selectEnd.x() - m_selectStart.x()); + const int32 height = abs(m_selectEnd.y() - m_selectStart.y()); outRect = QRect(startX, startY, width, height); } @@ -145,12 +145,12 @@ namespace EMStudio // draw a background rect painter.setPen(Qt::NoPen); - painter.setBrush(mBrushBackgroundOutOfRange); + painter.setBrush(m_brushBackgroundOutOfRange); painter.drawRect(rect); - painter.setFont(mDataFont); + painter.setFont(m_dataFont); // if there is a recording show that, otherwise show motion tracks - switch (mPlugin->GetMode()) + switch (m_plugin->GetMode()) { case TimeViewMode::AnimGraph: { @@ -170,18 +170,18 @@ namespace EMStudio painter.setRenderHint(QPainter::Antialiasing, false); - mPlugin->RenderElementTimeHandles(painter, geometry().height(), mPlugin->mPenTimeHandles); + m_plugin->RenderElementTimeHandles(painter, geometry().height(), m_plugin->m_penTimeHandles); DrawTimeMarker(painter, rect); // render selection rect - if (mRectSelecting) + if (m_rectSelecting) { painter.resetTransform(); QRect selectRect; CalcSelectRect(selectRect); - if (mRectZooming) + if (m_rectZooming) { painter.setBrush(QColor(0, 100, 200, 75)); painter.setPen(QColor(0, 100, 255)); @@ -189,7 +189,7 @@ namespace EMStudio } else { - if (EMotionFX::GetRecorder().GetRecordTime() < MCore::Math::epsilon && mPlugin->mMotion) + if (EMotionFX::GetRecorder().GetRecordTime() < MCore::Math::epsilon && m_plugin->m_motion) { painter.setBrush(QColor(200, 120, 0, 75)); painter.setPen(QColor(255, 128, 0)); @@ -199,11 +199,11 @@ namespace EMStudio } } - void TrackDataWidget::RemoveTrack(AZ::u32 trackIndex) + void TrackDataWidget::RemoveTrack(size_t trackIndex) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); CommandSystem::CommandRemoveEventTrack(trackIndex); - mPlugin->UnselectAllElements(); + m_plugin->UnselectAllElements(); ClearState(); } @@ -212,8 +212,8 @@ namespace EMStudio { // draw the current time marker float startHeight = 0.0f; - const float curTimeX = aznumeric_cast(mPlugin->TimeToPixel(mPlugin->mCurTime)); - painter.setPen(mPlugin->mPenCurTimeHandle); + const float curTimeX = aznumeric_cast(m_plugin->TimeToPixel(m_plugin->m_curTime)); + painter.setPen(m_plugin->m_penCurTimeHandle); painter.drawLine(QPointF(curTimeX, startHeight), QPointF(curTimeX, rect.bottom())); } @@ -229,7 +229,7 @@ namespace EMStudio QRect motionRect = rect; const float animationLength = recorder.GetRecordTime(); - const double animEndPixel = mPlugin->TimeToPixel(animationLength); + const double animEndPixel = m_plugin->TimeToPixel(animationLength); backgroundRect.setLeft(aznumeric_cast(animEndPixel)); motionRect.setRight(aznumeric_cast(animEndPixel)); motionRect.setTop(0); @@ -237,9 +237,9 @@ namespace EMStudio // render the rects painter.setPen(Qt::NoPen); - painter.setBrush(mBrushBackground); + painter.setBrush(m_brushBackground); painter.drawRect(motionRect); - painter.setBrush(mBrushBackgroundOutOfRange); + painter.setBrush(m_brushBackgroundOutOfRange); painter.drawRect(backgroundRect); // find the selected actor instance @@ -250,8 +250,8 @@ namespace EMStudio } // find the actor instance data for this actor instance - const uint32 actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance); - if (actorInstanceDataIndex == MCORE_INVALIDINDEX32) // it doesn't exist, so we didn't record anything for this actor instance + const size_t actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance); + if (actorInstanceDataIndex == InvalidIndex) // it doesn't exist, so we didn't record anything for this actor instance { return; } @@ -259,7 +259,7 @@ namespace EMStudio // get the actor instance data for the first selected actor instance, and render the node history for that const EMotionFX::Recorder::ActorInstanceData* actorInstanceData = &recorder.GetActorInstanceData(actorInstanceDataIndex); - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); const bool displayNodeActivity = recorderGroup->GetDisplayNodeActivity(); const bool displayEvents = recorderGroup->GetDisplayMotionEvents(); const bool displayRelativeGraph = recorderGroup->GetDisplayRelativeGraph(); @@ -270,31 +270,31 @@ namespace EMStudio if (displayNodeActivity) { - mNodeRectsStartHeight = startOffset; + m_nodeRectsStartHeight = startOffset; PaintRecorderNodeHistory(painter, rect, actorInstanceData); isTop = false; - startOffset = mNodeHistoryRect.bottom(); - requiredHeight = mNodeHistoryRect.bottom(); + startOffset = m_nodeHistoryRect.bottom(); + requiredHeight = m_nodeHistoryRect.bottom(); } if (displayEvents) { if (isTop == false) { - mEventsStartHeight = startOffset; - mEventsStartHeight += PaintSeparator(painter, mEventsStartHeight, animationLength); - mEventsStartHeight += 10; - startOffset = mEventsStartHeight; + m_eventsStartHeight = startOffset; + m_eventsStartHeight += PaintSeparator(painter, m_eventsStartHeight, animationLength); + m_eventsStartHeight += 10; + startOffset = m_eventsStartHeight; requiredHeight += 11; } else { startOffset += 3; - mEventsStartHeight = startOffset; + m_eventsStartHeight = startOffset; requiredHeight += 3; } - startOffset += mEventHistoryTotalHeight; + startOffset += m_eventHistoryTotalHeight; isTop = false; PaintRecorderEventHistory(painter, rect, actorInstanceData); @@ -304,15 +304,15 @@ namespace EMStudio { if (isTop == false) { - mGraphStartHeight = startOffset + 10; - mGraphStartHeight += PaintSeparator(painter, mGraphStartHeight, animationLength); - startOffset = mGraphStartHeight; + m_graphStartHeight = startOffset + 10; + m_graphStartHeight += PaintSeparator(painter, m_graphStartHeight, animationLength); + startOffset = m_graphStartHeight; requiredHeight += 11; } else { startOffset += 3; - mGraphStartHeight = startOffset; + m_graphStartHeight = startOffset; requiredHeight += 3; } @@ -341,17 +341,17 @@ namespace EMStudio painter.setRenderHint(QPainter::Antialiasing, true); // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; int32 windowWidth = geometry().width(); - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); const bool useNodeColors = recorderGroup->GetUseNodeTypeColors(); const bool limitGraphHeight = recorderGroup->GetLimitGraphHeight(); - const bool showNodeNames = mPlugin->mTrackHeaderWidget->mNodeNamesCheckBox->isChecked(); - const bool showMotionFiles = mPlugin->mTrackHeaderWidget->mMotionFilesCheckBox->isChecked(); - const bool interpolate = recorder.GetRecordSettings().mInterpolate; + const bool showNodeNames = m_plugin->m_trackHeaderWidget->m_nodeNamesCheckBox->isChecked(); + const bool showMotionFiles = m_plugin->m_trackHeaderWidget->m_motionFilesCheckBox->isChecked(); + const bool interpolate = recorder.GetRecordSettings().m_interpolate; - float graphHeight = aznumeric_cast(geometry().height() - mGraphStartHeight); + float graphHeight = aznumeric_cast(geometry().height() - m_graphStartHeight); float graphBottom; if (limitGraphHeight == false) { @@ -364,30 +364,27 @@ namespace EMStudio graphHeight = 200; } - graphBottom = mGraphStartHeight + graphHeight; + graphBottom = m_graphStartHeight + graphHeight; } - const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mGraphContentsComboBox->currentIndex(); + const uint32 graphContentsCode = m_plugin->m_trackHeaderWidget->m_graphContentsComboBox->currentIndex(); - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; + double startTimePixel = m_plugin->TimeToPixel(curItem->m_startTime); + double endTimePixel = m_plugin->TimeToPixel(curItem->m_endTime); - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); - double endTimePixel = mPlugin->TimeToPixel(curItem->mEndTime); - - const QRect itemRect(QPoint(aznumeric_cast(startTimePixel), mGraphStartHeight), QPoint(aznumeric_cast(endTimePixel), geometry().height())); + const QRect itemRect(QPoint(aznumeric_cast(startTimePixel), m_graphStartHeight), QPoint(aznumeric_cast(endTimePixel), geometry().height())); if (rect.intersects(itemRect) == false) { continue; } - const AZ::Color colorCode = (useNodeColors) ? curItem->mTypeColor : curItem->mColor; + const AZ::Color colorCode = (useNodeColors) ? curItem->m_typeColor : curItem->m_color; QColor color; color.setRgbF(colorCode.GetR(), colorCode.GetG(), colorCode.GetB(), colorCode.GetA()); - if (mPlugin->mNodeHistoryItem != curItem || mIsScrolling || mPlugin->mIsAnimating) + if (m_plugin->m_nodeHistoryItem != curItem || m_isScrolling || m_plugin->m_isAnimating) { painter.setPen(color); color.setAlpha(64); @@ -405,20 +402,20 @@ namespace EMStudio int32 widthInPixels = aznumeric_cast(endTimePixel - startTimePixel); if (widthInPixels > 0) { - EMotionFX::KeyTrackLinearDynamic* keyTrack = &curItem->mGlobalWeights; // init on global weights + EMotionFX::KeyTrackLinearDynamic* keyTrack = &curItem->m_globalWeights; // init on global weights if (graphContentsCode == 1) { - keyTrack = &curItem->mLocalWeights; + keyTrack = &curItem->m_localWeights; } else if (graphContentsCode == 2) { - keyTrack = &curItem->mPlayTimes; + keyTrack = &curItem->m_playTimes; } - float lastWeight = keyTrack->GetValueAtTime(0.0f, &curItem->mCachedKey, nullptr, interpolate); - const float keyTimeStep = (curItem->mEndTime - curItem->mStartTime) / (float)widthInPixels; + float lastWeight = keyTrack->GetValueAtTime(0.0f, &curItem->m_cachedKey, nullptr, interpolate); + const float keyTimeStep = (curItem->m_endTime - curItem->m_startTime) / (float)widthInPixels; const int32 pixelStepSize = 1;//(widthInPixels / 300.0f) + 1; @@ -438,12 +435,12 @@ namespace EMStudio firstPixel = false; } - const float weight = keyTrack->GetValueAtTime(w * keyTimeStep, &curItem->mCachedKey, nullptr, interpolate); + const float weight = keyTrack->GetValueAtTime(w * keyTimeStep, &curItem->m_cachedKey, nullptr, interpolate); const float height = graphBottom - weight * graphHeight; path.lineTo(QPointF(startTimePixel + w + 1, height)); } - const float weight = keyTrack->GetValueAtTime(curItem->mEndTime, &curItem->mCachedKey, nullptr, interpolate); + const float weight = keyTrack->GetValueAtTime(curItem->m_endTime, &curItem->m_cachedKey, nullptr, interpolate); const float height = graphBottom - weight * graphHeight; path.lineTo(QPointF(startTimePixel + widthInPixels - 1, height)); path.lineTo(QPointF(startTimePixel + widthInPixels, graphBottom + 1)); @@ -452,14 +449,13 @@ namespace EMStudio } // calculate the remapped track list, based on sorted global weight, with the most influencing track on top - recorder.ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(mPlugin->mCurTime), true, (EMotionFX::Recorder::EValueType)graphContentsCode, &mActiveItems, &mTrackRemap); + recorder.ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(m_plugin->m_curTime), true, (EMotionFX::Recorder::EValueType)graphContentsCode, &m_activeItems, &m_trackRemap); // display the values and names - uint32 offset = 0; - const uint32 numActiveItems = mActiveItems.GetLength(); - for (uint32 i = 0; i < numActiveItems; ++i) + int offset = 0; + for (const EMotionFX::Recorder::ExtractedNodeHistoryItem& activeItem : m_activeItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = mActiveItems[i].mNodeHistoryItem; + EMotionFX::Recorder::NodeHistoryItem* curItem = activeItem.m_nodeHistoryItem; if (curItem == nullptr) { continue; @@ -467,39 +463,39 @@ namespace EMStudio offset += 15; - mTempString.clear(); + m_tempString.clear(); if (showNodeNames) { - mTempString += curItem->mName.c_str(); + m_tempString += curItem->m_name.c_str(); } - if (showMotionFiles && curItem->mMotionFileName.size() > 0) + if (showMotionFiles && !curItem->m_motionFileName.empty()) { - if (!mTempString.empty()) + if (!m_tempString.empty()) { - mTempString += " - "; + m_tempString += " - "; } - mTempString += curItem->mMotionFileName.c_str(); + m_tempString += curItem->m_motionFileName.c_str(); } - if (!mTempString.empty()) + if (!m_tempString.empty()) { - mTempString += AZStd::string::format(" = %.4f", mActiveItems[i].mValue); + m_tempString += AZStd::string::format(" = %.4f", activeItem.m_value); } else { - mTempString = AZStd::string::format("%.4f", mActiveItems[i].mValue); + m_tempString = AZStd::string::format("%.4f", activeItem.m_value); } - const AZ::Color colorCode = (useNodeColors) ? mActiveItems[i].mNodeHistoryItem->mTypeColor : mActiveItems[i].mNodeHistoryItem->mColor; + const AZ::Color colorCode = (useNodeColors) ? activeItem.m_nodeHistoryItem->m_typeColor : activeItem.m_nodeHistoryItem->m_color; QColor color; color.setRgbF(colorCode.GetR(), colorCode.GetG(), colorCode.GetB(), colorCode.GetA()); painter.setPen(color); painter.setBrush(Qt::NoBrush); - painter.setFont(mDataFont); - painter.drawText(3, offset + mGraphStartHeight, mTempString.c_str()); + painter.setFont(m_dataFont); + painter.drawText(3, offset + m_graphStartHeight, m_tempString.c_str()); } } @@ -516,10 +512,10 @@ namespace EMStudio } // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_eventHistoryItems; QRect clipRect = rect; - clipRect.setRight(aznumeric_cast(mPlugin->TimeToPixel(animationLength))); + clipRect.setRight(aznumeric_cast(m_plugin->TimeToPixel(animationLength))); painter.setClipRect(clipRect); painter.setClipping(true); @@ -528,13 +524,10 @@ namespace EMStudio const float tickHeight = 16; QPointF tickPoints[6]; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (const EMotionFX::Recorder::EventHistoryItem* curItem : historyItems) { - EMotionFX::Recorder::EventHistoryItem* curItem = historyItems[i]; - - float height = aznumeric_cast((curItem->mTrackIndex * 20) + mEventsStartHeight); - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); + float height = aznumeric_cast((curItem->m_trackIndex * 20) + m_eventsStartHeight); + double startTimePixel = m_plugin->TimeToPixel(curItem->m_startTime); const QRect itemRect(QPoint(aznumeric_cast(startTimePixel - tickHalfWidth), aznumeric_cast(height)), QSize(aznumeric_cast(tickHalfWidth * 2), aznumeric_cast(tickHeight))); if (rect.intersects(itemRect) == false) @@ -544,17 +537,17 @@ namespace EMStudio // try to locate the node based on its unique ID QColor borderColor(30, 30, 30); - const AZ::Color& colorCode = curItem->mColor; + const AZ::Color& colorCode = curItem->m_color; QColor color; color.setRgbF(colorCode.GetR(), colorCode.GetG(), colorCode.GetB(), colorCode.GetA()); - if (mIsScrolling == false && mPlugin->mIsAnimating == false) + if (m_isScrolling == false && m_plugin->m_isAnimating == false) { - if (mPlugin->mNodeHistoryItem && mPlugin->mNodeHistoryItem->mNodeId == curItem->mEmitterNodeId) + if (m_plugin->m_nodeHistoryItem && m_plugin->m_nodeHistoryItem->m_nodeId == curItem->m_emitterNodeId) { - if (curItem->mStartTime >= mPlugin->mNodeHistoryItem->mStartTime && curItem->mStartTime <= mPlugin->mNodeHistoryItem->mEndTime) + if (curItem->m_startTime >= m_plugin->m_nodeHistoryItem->m_startTime && curItem->m_startTime <= m_plugin->m_nodeHistoryItem->m_endTime) { - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); if (recorderGroup->GetDisplayNodeActivity()) { borderColor = QColor(255, 128, 0); @@ -563,7 +556,7 @@ namespace EMStudio } } - if (mPlugin->mEventHistoryItem == curItem) + if (m_plugin->m_eventHistoryItem == curItem) { borderColor = QColor(255, 128, 0); color = borderColor; @@ -614,67 +607,64 @@ namespace EMStudio } // skip the complete rendering of the node history data when its bounds are not inside view - if (!rect.intersects(mNodeHistoryRect)) + if (!rect.intersects(m_nodeHistoryRect)) { return; } // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; int32 windowWidth = geometry().width(); // calculate the remapped track list, based on sorted global weight, with the most influencing track on top - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); const bool sorted = recorderGroup->GetSortNodeActivity(); const bool useNodeColors = recorderGroup->GetUseNodeTypeColors(); - const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); - recorder.ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(mPlugin->mCurTime), sorted, (EMotionFX::Recorder::EValueType)graphContentsCode, &mActiveItems, &mTrackRemap); + const int graphContentsCode = m_plugin->m_trackHeaderWidget->m_nodeContentsComboBox->currentIndex(); + recorder.ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(m_plugin->m_curTime), sorted, (EMotionFX::Recorder::EValueType)graphContentsCode, &m_activeItems, &m_trackRemap); - const bool showNodeNames = mPlugin->mTrackHeaderWidget->mNodeNamesCheckBox->isChecked(); - const bool showMotionFiles = mPlugin->mTrackHeaderWidget->mMotionFilesCheckBox->isChecked(); - const bool interpolate = recorder.GetRecordSettings().mInterpolate; + const bool showNodeNames = m_plugin->m_trackHeaderWidget->m_nodeNamesCheckBox->isChecked(); + const bool showMotionFiles = m_plugin->m_trackHeaderWidget->m_motionFilesCheckBox->isChecked(); + const bool interpolate = recorder.GetRecordSettings().m_interpolate; - const uint32 nodeContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); + const int nodeContentsCode = m_plugin->m_trackHeaderWidget->m_nodeContentsComboBox->currentIndex(); // for all history items QRectF itemRect; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; - // draw the background rect - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); - double endTimePixel = mPlugin->TimeToPixel(curItem->mEndTime); + double startTimePixel = m_plugin->TimeToPixel(curItem->m_startTime); + double endTimePixel = m_plugin->TimeToPixel(curItem->m_endTime); - const uint32 trackIndex = mTrackRemap[ curItem->mTrackIndex ]; + const size_t trackIndex = m_trackRemap[ curItem->m_trackIndex ]; itemRect.setLeft(startTimePixel); itemRect.setRight(endTimePixel - 1); - itemRect.setTop((mNodeRectsStartHeight + (trackIndex * (mNodeHistoryItemHeight + 3)) + 3) /* - mPlugin->mScrollY*/); - itemRect.setBottom(itemRect.top() + mNodeHistoryItemHeight); + itemRect.setTop((m_nodeRectsStartHeight + (aznumeric_cast(trackIndex) * (m_nodeHistoryItemHeight + 3)) + 3)); + itemRect.setBottom(itemRect.top() + m_nodeHistoryItemHeight); if (!rect.intersects(itemRect.toRect())) { continue; } - const AZ::Color colorCode = (useNodeColors) ? curItem->mTypeColor : curItem->mColor; + const AZ::Color colorCode = (useNodeColors) ? curItem->m_typeColor : curItem->m_color; QColor color; color.setRgbF(colorCode.GetR(), colorCode.GetG(), colorCode.GetB(), colorCode.GetA()); bool matchesEvent = false; - if (mIsScrolling == false && mPlugin->mIsAnimating == false) + if (m_isScrolling == false && m_plugin->m_isAnimating == false) { - if (mPlugin->mNodeHistoryItem == curItem) + if (m_plugin->m_nodeHistoryItem == curItem) { color = QColor(255, 128, 0); } - if (mPlugin->mEventEmitterNode && mPlugin->mEventEmitterNode->GetId() == curItem->mNodeId && mPlugin->mEventHistoryItem) + if (m_plugin->m_eventEmitterNode && m_plugin->m_eventEmitterNode->GetId() == curItem->m_nodeId && m_plugin->m_eventHistoryItem) { - if (mPlugin->mEventHistoryItem->mStartTime >= curItem->mStartTime && mPlugin->mEventHistoryItem->mStartTime <= curItem->mEndTime) + if (m_plugin->m_eventHistoryItem->m_startTime >= curItem->m_startTime && m_plugin->m_eventHistoryItem->m_startTime <= curItem->m_endTime) { color = QColor(255, 128, 0); matchesEvent = true; @@ -698,24 +688,24 @@ namespace EMStudio int32 widthInPixels = aznumeric_cast(endTimePixel - startTimePixel); if (widthInPixels > 0) { - EMotionFX::KeyTrackLinearDynamic* keyTrack = &curItem->mGlobalWeights; // init on global weights + const EMotionFX::KeyTrackLinearDynamic* keyTrack = &curItem->m_globalWeights; // init on global weights if (nodeContentsCode == 1) { - keyTrack = &curItem->mLocalWeights; + keyTrack = &curItem->m_localWeights; } else if (nodeContentsCode == 2) { - keyTrack = &curItem->mPlayTimes; + keyTrack = &curItem->m_playTimes; } - float lastWeight = keyTrack->GetValueAtTime(0.0f, &curItem->mCachedKey, nullptr, interpolate); - const float keyTimeStep = (curItem->mEndTime - curItem->mStartTime) / (float)widthInPixels; + float lastWeight = keyTrack->GetValueAtTime(0.0f, &curItem->m_cachedKey, nullptr, interpolate); + const float keyTimeStep = (curItem->m_endTime - curItem->m_startTime) / (float)widthInPixels; const int32 pixelStepSize = 1;//(widthInPixels / 300.0f) + 1; path.moveTo(QPointF(startTimePixel - 1, itemRect.bottom() + 1)); - path.lineTo(QPointF(startTimePixel + 1, itemRect.bottom() - 1 - lastWeight * mNodeHistoryItemHeight)); + path.lineTo(QPointF(startTimePixel + 1, itemRect.bottom() - 1 - lastWeight * m_nodeHistoryItemHeight)); bool firstPixel = true; for (int32 w = 1; w < widthInPixels - 1; w += pixelStepSize) { @@ -730,13 +720,13 @@ namespace EMStudio firstPixel = false; } - const float weight = keyTrack->GetValueAtTime(w * keyTimeStep, &curItem->mCachedKey, nullptr, interpolate); - const float height = aznumeric_cast(itemRect.bottom() - weight * mNodeHistoryItemHeight); + const float weight = keyTrack->GetValueAtTime(w * keyTimeStep, &curItem->m_cachedKey, nullptr, interpolate); + const float height = aznumeric_cast(itemRect.bottom() - weight * m_nodeHistoryItemHeight); path.lineTo(QPointF(startTimePixel + w + 1, height)); } - const float weight = keyTrack->GetValueAtTime(curItem->mEndTime, &curItem->mCachedKey, nullptr, interpolate); - const float height = aznumeric_cast(itemRect.bottom() - weight * mNodeHistoryItemHeight); + const float weight = keyTrack->GetValueAtTime(curItem->m_endTime, &curItem->m_cachedKey, nullptr, interpolate); + const float height = aznumeric_cast(itemRect.bottom() - weight * m_nodeHistoryItemHeight); path.lineTo(QPointF(startTimePixel + widthInPixels - 1, height)); path.lineTo(QPointF(startTimePixel + widthInPixels, itemRect.bottom() + 1)); painter.drawPath(path); @@ -747,9 +737,9 @@ namespace EMStudio // draw the text if (matchesEvent != true) { - if (mIsScrolling == false && mPlugin->mIsAnimating == false) + if (m_isScrolling == false && m_plugin->m_isAnimating == false) { - if (mPlugin->mNodeHistoryItem != curItem) + if (m_plugin->m_nodeHistoryItem != curItem) { painter.setPen(QColor(255, 255, 255, 175)); } @@ -768,25 +758,25 @@ namespace EMStudio painter.setPen(Qt::black); } - mTempString.clear(); + m_tempString.clear(); if (showNodeNames) { - mTempString += curItem->mName.c_str(); + m_tempString += curItem->m_name.c_str(); } - if (showMotionFiles && curItem->mMotionFileName.size() > 0) + if (showMotionFiles && !curItem->m_motionFileName.empty()) { - if (!mTempString.empty()) + if (!m_tempString.empty()) { - mTempString += " - "; + m_tempString += " - "; } - mTempString += curItem->mMotionFileName.c_str(); + m_tempString += curItem->m_motionFileName.c_str(); } - if (!mTempString.empty()) + if (!m_tempString.empty()) { - painter.drawText(aznumeric_cast(itemRect.left() + 3), aznumeric_cast(itemRect.bottom() - 2), mTempString.c_str()); + painter.drawText(aznumeric_cast(itemRect.left() + 3), aznumeric_cast(itemRect.bottom() - 2), m_tempString.c_str()); } painter.setClipping(false); @@ -803,17 +793,17 @@ namespace EMStudio // get the track over which the cursor is positioned QPoint localCursorPos = mapFromGlobal(QCursor::pos()); - TimeTrack* mouseCursorTrack = mPlugin->GetTrackAt(localCursorPos.y()); + TimeTrack* mouseCursorTrack = m_plugin->GetTrackAt(localCursorPos.y()); if (localCursorPos.x() < 0 || localCursorPos.x() > width()) { mouseCursorTrack = nullptr; } // handle highlighting - const uint32 numTracks = mPlugin->GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = m_plugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { - TimeTrack* track = mPlugin->GetTrack(i); + TimeTrack* track = m_plugin->GetTrack(i); // set the highlighting flag for the track if (track == mouseCursorTrack) @@ -822,11 +812,11 @@ namespace EMStudio track->SetIsHighlighted(true); // get the element over which the cursor is positioned - TimeTrackElement* mouseCursorElement = mPlugin->GetElementAt(localCursorPos.x(), localCursorPos.y()); + TimeTrackElement* mouseCursorElement = m_plugin->GetElementAt(localCursorPos.x(), localCursorPos.y()); // get the number of elements, iterate through them and disable the highlight flag - const uint32 numElements = track->GetNumElements(); - for (uint32 e = 0; e < numElements; ++e) + const size_t numElements = track->GetNumElements(); + for (size_t e = 0; e < numElements; ++e) { TimeTrackElement* element = track->GetElement(e); @@ -845,8 +835,8 @@ namespace EMStudio track->SetIsHighlighted(false); // get the number of elements, iterate through them and disable the highlight flag - const uint32 numElements = track->GetNumElements(); - for (uint32 e = 0; e < numElements; ++e) + const size_t numElements = track->GetNumElements(); + for (size_t e = 0; e < numElements; ++e) { TimeTrackElement* element = track->GetElement(e); element->SetIsHighlighted(false); @@ -854,7 +844,7 @@ namespace EMStudio } } - EMotionFX::Motion* motion = mPlugin->GetMotion(); + EMotionFX::Motion* motion = m_plugin->GetMotion(); if (motion) { // get the motion length @@ -862,8 +852,8 @@ namespace EMStudio // get the playback info and read out the clip start/end times EMotionFX::PlayBackInfo* playbackInfo = motion->GetDefaultPlayBackInfo(); - clipStart = playbackInfo->mClipStartTime; - clipEnd = playbackInfo->mClipEndTime; + clipStart = playbackInfo->m_clipStartTime; + clipEnd = playbackInfo->m_clipEndTime; // HACK: fix this later clipStart = 0.0; @@ -871,9 +861,9 @@ namespace EMStudio } // calculate the pixel index of where the animation ends and where it gets clipped - const double animEndPixel = mPlugin->TimeToPixel(animationLength); - const double clipStartPixel = mPlugin->TimeToPixel(clipStart); - const double clipEndPixel = mPlugin->TimeToPixel(clipEnd); + const double animEndPixel = m_plugin->TimeToPixel(animationLength); + const double clipStartPixel = m_plugin->TimeToPixel(clipStart); + const double clipEndPixel = m_plugin->TimeToPixel(clipEnd); // enable anti aliassing //painter.setRenderHint(QPainter::Antialiasing); @@ -898,13 +888,13 @@ namespace EMStudio // render the rects painter.setPen(Qt::NoPen); - painter.setBrush(mBrushBackgroundClipped); + painter.setBrush(m_brushBackgroundClipped); painter.drawRect(clipStartRect); - painter.setBrush(mBrushBackground); + painter.setBrush(m_brushBackground); painter.drawRect(motionRect); - painter.setBrush(mBrushBackgroundClipped); + painter.setBrush(m_brushBackgroundClipped); painter.drawRect(clipEndRect); - painter.setBrush(mBrushBackgroundOutOfRange); + painter.setBrush(m_brushBackgroundOutOfRange); painter.drawRect(outOfRangeRect); // render the tracks @@ -919,39 +909,35 @@ namespace EMStudio // calculate the start and end time range of the visible area double visibleStartTime, visibleEndTime; - visibleStartTime = mPlugin->PixelToTime(0); //mPlugin->CalcTime( 0, &visibleStartTime, nullptr, nullptr, nullptr, nullptr ); - visibleEndTime = mPlugin->PixelToTime(width); //mPlugin->CalcTime( width, &visibleEndTime, nullptr, nullptr, nullptr, nullptr ); + visibleStartTime = m_plugin->PixelToTime(0); + visibleEndTime = m_plugin->PixelToTime(width); // for all tracks - const uint32 numTracks = mPlugin->mTracks.GetLength(); - for (uint32 i = 0; i < numTracks; ++i) + for (TimeTrack* track : m_plugin->m_tracks) { - TimeTrack* track = mPlugin->mTracks[i]; track->SetStartY(yOffset); // path for making the cut elements a bit transparent - if (mCutMode) + if (m_cutMode) { // disable cut mode for all elements on default - const uint32 numElements = track->GetNumElements(); - for (uint32 e = 0; e < numElements; ++e) + const size_t numElements = track->GetNumElements(); + for (size_t e = 0; e < numElements; ++e) { track->GetElement(e)->SetIsCut(false); } // get the number of copy elements and check if ours is in - const size_t numCopyElements = mCopyElements.size(); - for (size_t c = 0; c < numCopyElements; ++c) + for (const CopyElement& copyElement : m_copyElements) { // get the copy element and make sure we're in the right track - const CopyElement& copyElement = mCopyElements[c]; if (copyElement.m_trackName != track->GetName()) { continue; } // set the cut mode of the elements - for (uint32 e = 0; e < numElements; ++e) + for (size_t e = 0; e < numElements; ++e) { TimeTrackElement* element = track->GetElement(e); if (MCore::Compare::CheckIfIsClose(aznumeric_cast(element->GetStartTime()), copyElement.m_startTime, MCore::Math::epsilon) && @@ -972,27 +958,27 @@ namespace EMStudio } // render the element time handles - mPlugin->RenderElementTimeHandles(painter, height, mPlugin->mPenTimeHandles); + m_plugin->RenderElementTimeHandles(painter, height, m_plugin->m_penTimeHandles); } // show the time of the currently dragging element in the time info view void TrackDataWidget::ShowElementTimeInfo(TimeTrackElement* element) { - if (mPlugin->GetTimeInfoWidget() == nullptr) + if (m_plugin->GetTimeInfoWidget() == nullptr) { return; } // enable overwrite mode so that the time info widget will show the custom time rather than the current time of the plugin - mPlugin->GetTimeInfoWidget()->SetIsOverwriteMode(true); + m_plugin->GetTimeInfoWidget()->SetIsOverwriteMode(true); // calculate the dimensions int32 startX, startY, width, height; element->CalcDimensions(&startX, &startY, &width, &height); // show the times of the element - mPlugin->GetTimeInfoWidget()->SetOverwriteTime(mPlugin->PixelToTime(startX), mPlugin->PixelToTime(startX + width)); + m_plugin->GetTimeInfoWidget()->SetOverwriteTime(m_plugin->PixelToTime(startX), m_plugin->PixelToTime(startX + width)); } @@ -1004,21 +990,21 @@ namespace EMStudio } // if we clicked inside the node history area - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); if (GetIsInsideNodeHistory(event->y()) && recorderGroup->GetDisplayNodeActivity()) { EMotionFX::Recorder::ActorInstanceData* actorInstanceData = FindActorInstanceData(); EMotionFX::Recorder::NodeHistoryItem* historyItem = FindNodeHistoryItem(actorInstanceData, event->x(), event->y()); if (historyItem) { - emit mPlugin->DoubleClickedRecorderNodeHistoryItem(actorInstanceData, historyItem); + emit m_plugin->DoubleClickedRecorderNodeHistoryItem(actorInstanceData, historyItem); } } } void TrackDataWidget::SetPausedTime(float timeValue, bool emitTimeChangeStart) { - mPlugin->mCurTime = timeValue; + m_plugin->m_curTime = timeValue; const AZStd::vector& motionInstances = MotionWindowPlugin::GetSelectedMotionInstances(); if (motionInstances.size() == 1) { @@ -1028,137 +1014,137 @@ namespace EMStudio } if (emitTimeChangeStart) { - emit mPlugin->ManualTimeChangeStart(timeValue); + emit m_plugin->ManualTimeChangeStart(timeValue); } - emit mPlugin->ManualTimeChange(timeValue); + emit m_plugin->ManualTimeChange(timeValue); } // when the mouse is moving, while a button is pressed void TrackDataWidget::mouseMoveEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); QPoint mousePos = event->pos(); - const int32 deltaRelX = event->x() - mLastMouseX; - mLastMouseX = event->x(); - mPlugin->mCurMouseX = event->x(); - mPlugin->mCurMouseY = event->y(); + const int32 deltaRelX = event->x() - m_lastMouseX; + m_lastMouseX = event->x(); + m_plugin->m_curMouseX = event->x(); + m_plugin->m_curMouseY = event->y(); - const int32 deltaRelY = event->y() - mLastMouseY; - mLastMouseY = event->y(); + const int32 deltaRelY = event->y() - m_lastMouseY; + m_lastMouseY = event->y(); const bool altPressed = event->modifiers() & Qt::AltModifier; - const bool isZooming = mMouseLeftClicked == false && mMouseRightClicked && altPressed; - const bool isPanning = mMouseLeftClicked == false && isZooming == false && (mMouseMidClicked || mMouseRightClicked); + const bool isZooming = m_mouseLeftClicked == false && m_mouseRightClicked && altPressed; + const bool isPanning = m_mouseLeftClicked == false && isZooming == false && (m_mouseMidClicked || m_mouseRightClicked); if (deltaRelY != 0) { - mAllowContextMenu = false; + m_allowContextMenu = false; } // get the track over which the cursor is positioned - TimeTrack* mouseCursorTrack = mPlugin->GetTrackAt(event->y()); + TimeTrack* mouseCursorTrack = m_plugin->GetTrackAt(event->y()); - if (mMouseRightClicked) + if (m_mouseRightClicked) { - mIsScrolling = true; + m_isScrolling = true; } // if the mouse left button is pressed - if (mMouseLeftClicked) + if (m_mouseLeftClicked) { if (altPressed) { - mRectZooming = true; + m_rectZooming = true; } else { - mRectZooming = false; + m_rectZooming = false; } // rect selection: update mouse position - if (mRectSelecting) + if (m_rectSelecting) { - mSelectEnd = mousePos; + m_selectEnd = mousePos; } - if (mDraggingElement == nullptr && mResizeElement == nullptr && mRectSelecting == false) + if (m_draggingElement == nullptr && m_resizeElement == nullptr && m_rectSelecting == false) { // update the current time marker int newX = event->x(); newX = MCore::Clamp(newX, 0, geometry().width() - 1); - mPlugin->mCurTime = mPlugin->PixelToTime(newX); + m_plugin->m_curTime = m_plugin->PixelToTime(newX); EMotionFX::Recorder& recorder = EMotionFX::GetRecorder(); if (recorder.GetRecordTime() > MCore::Math::epsilon) { if (recorder.GetIsInPlayMode()) { - recorder.SetCurrentPlayTime(aznumeric_cast(mPlugin->GetCurrentTime())); + recorder.SetCurrentPlayTime(aznumeric_cast(m_plugin->GetCurrentTime())); recorder.SetAutoPlay(false); - emit mPlugin->ManualTimeChange(aznumeric_cast(mPlugin->GetCurrentTime())); + emit m_plugin->ManualTimeChange(aznumeric_cast(m_plugin->GetCurrentTime())); } } else { - SetPausedTime(aznumeric_cast(mPlugin->mCurTime)); + SetPausedTime(aznumeric_cast(m_plugin->m_curTime)); } - mIsScrolling = true; + m_isScrolling = true; } TimeTrack* dragElementTrack = nullptr; - if (mDraggingElement) + if (m_draggingElement) { - dragElementTrack = mDraggingElement->GetTrack(); + dragElementTrack = m_draggingElement->GetTrack(); } // calculate the delta movement - const int32 deltaX = event->x() - mLastLeftClickedX; + const int32 deltaX = event->x() - m_lastLeftClickedX; const int32 movement = abs(deltaX); const bool elementTrackChanged = (mouseCursorTrack && dragElementTrack && mouseCursorTrack != dragElementTrack); - if ((movement > 1 && !mDragging) || elementTrackChanged) + if ((movement > 1 && !m_dragging) || elementTrackChanged) { - mDragging = true; + m_dragging = true; } // handle resizing - if (mResizing) + if (m_resizing) { - if (mPlugin->FindTrackByElement(mResizeElement) == nullptr) + if (m_plugin->FindTrackByElement(m_resizeElement) == nullptr) { - mResizeElement = nullptr; + m_resizeElement = nullptr; } - if (mResizeElement) + if (m_resizeElement) { - TimeTrack* resizeElementTrack = mResizeElement->GetTrack(); + TimeTrack* resizeElementTrack = m_resizeElement->GetTrack(); // only allow resizing on enabled time tracks if (resizeElementTrack->GetIsEnabled()) { - mResizeElement->SetShowTimeHandles(true); - mResizeElement->SetShowToolTip(false); + m_resizeElement->SetShowTimeHandles(true); + m_resizeElement->SetShowToolTip(false); - double resizeTime = (deltaRelX / mPlugin->mTimeScale) / mPlugin->mPixelsPerSecond; - mResizeID = mResizeElement->HandleResize(mResizeID, resizeTime, 0.02 / mPlugin->mTimeScale); + double resizeTime = (deltaRelX / m_plugin->m_timeScale) / m_plugin->m_pixelsPerSecond; + m_resizeId = m_resizeElement->HandleResize(m_resizeId, resizeTime, 0.02 / m_plugin->m_timeScale); // show the time of the currently resizing element in the time info view - ShowElementTimeInfo(mResizeElement); + ShowElementTimeInfo(m_resizeElement); // Move the current time marker along with the event resizing position. float timeValue = 0.0f; - switch (mResizeID) + switch (m_resizeId) { case TimeTrackElement::RESIZEPOINT_START: { - timeValue = aznumeric_cast(mResizeElement->GetStartTime()); + timeValue = aznumeric_cast(m_resizeElement->GetStartTime()); break; } case TimeTrackElement::RESIZEPOINT_END: { - timeValue = aznumeric_cast(mResizeElement->GetEndTime()); + timeValue = aznumeric_cast(m_resizeElement->GetEndTime()); break; } default: @@ -1176,7 +1162,7 @@ namespace EMStudio } // if we are not dragging or no element is being dragged, there is nothing to do - if (mDragging == false || mDraggingElement == nullptr) + if (m_dragging == false || m_draggingElement == nullptr) { return; } @@ -1185,79 +1171,79 @@ namespace EMStudio if (elementTrackChanged) { // if yes we need to remove the dragging element from the old time track - dragElementTrack->RemoveElement(mDraggingElement, false); + dragElementTrack->RemoveElement(m_draggingElement, false); // and add it to the new time track where the cursor now is over - mouseCursorTrack->AddElement(mDraggingElement); - mDraggingElement->SetTrack(mouseCursorTrack); + mouseCursorTrack->AddElement(m_draggingElement); + m_draggingElement->SetTrack(mouseCursorTrack); } // show the time of the currently dragging element in the time info view - ShowElementTimeInfo(mDraggingElement); + ShowElementTimeInfo(m_draggingElement); // adjust the cursor setCursor(Qt::ClosedHandCursor); - mDraggingElement->SetShowToolTip(false); + m_draggingElement->SetShowToolTip(false); // show the time handles - mDraggingElement->SetShowTimeHandles(true); + m_draggingElement->SetShowTimeHandles(true); - const double snapThreshold = 0.02 / mPlugin->mTimeScale; + const double snapThreshold = 0.02 / m_plugin->m_timeScale; // calculate how many pixels we moved with the mouse - const int32 deltaMovement = event->x() - mLastMouseMoveX; - mLastMouseMoveX = event->x(); + const int32 deltaMovement = event->x() - m_lastMouseMoveX; + m_lastMouseMoveX = event->x(); // snap the moved amount to a given time value - double snappedTime = mDraggingElement->GetStartTime() + ((deltaMovement / mPlugin->mPixelsPerSecond) / mPlugin->mTimeScale); + double snappedTime = m_draggingElement->GetStartTime() + ((deltaMovement / m_plugin->m_pixelsPerSecond) / m_plugin->m_timeScale); bool startSnapped = false; if (abs(deltaMovement) < 2 && abs(deltaMovement) > 0) // only snap when moving the mouse very slowly { - startSnapped = mPlugin->SnapTime(&snappedTime, mDraggingElement, snapThreshold); + startSnapped = m_plugin->SnapTime(&snappedTime, m_draggingElement, snapThreshold); } // in case the start time didn't snap to anything if (startSnapped == false) { // try to snap the end time - double snappedEndTime = mDraggingElement->GetEndTime() + ((deltaMovement / mPlugin->mPixelsPerSecond) / mPlugin->mTimeScale); - /*bool endSnapped = */ mPlugin->SnapTime(&snappedEndTime, mDraggingElement, snapThreshold); + double snappedEndTime = m_draggingElement->GetEndTime() + ((deltaMovement / m_plugin->m_pixelsPerSecond) / m_plugin->m_timeScale); + /*bool endSnapped = */ m_plugin->SnapTime(&snappedEndTime, m_draggingElement, snapThreshold); // apply the delta movement - const double deltaTime = snappedEndTime - mDraggingElement->GetEndTime(); - mDraggingElement->MoveRelative(deltaTime); + const double deltaTime = snappedEndTime - m_draggingElement->GetEndTime(); + m_draggingElement->MoveRelative(deltaTime); } else { // apply the snapped delta movement - const double deltaTime = snappedTime - mDraggingElement->GetStartTime(); - mDraggingElement->MoveRelative(deltaTime); + const double deltaTime = snappedTime - m_draggingElement->GetStartTime(); + m_draggingElement->MoveRelative(deltaTime); } - dragElementTrack = mDraggingElement->GetTrack(); - const float timeValue = aznumeric_cast(mDraggingElement->GetStartTime()); + dragElementTrack = m_draggingElement->GetTrack(); + const float timeValue = aznumeric_cast(m_draggingElement->GetStartTime()); SetPausedTime(timeValue); } else if (isPanning) { if (EMotionFX::GetRecorder().GetIsRecording() == false) { - mPlugin->DeltaScrollX(-deltaRelX, false); + m_plugin->DeltaScrollX(-deltaRelX, false); } } else if (isZooming) { if (deltaRelY < 0) { - setCursor(*(mPlugin->GetZoomOutCursor())); + setCursor(*(m_plugin->GetZoomOutCursor())); } else { - setCursor(*(mPlugin->GetZoomInCursor())); + setCursor(*(m_plugin->GetZoomInCursor())); } - DoMouseYMoveZoom(deltaRelY, mPlugin); + DoMouseYMoveZoom(deltaRelY, m_plugin); } else // no left mouse button is pressed { @@ -1285,10 +1271,10 @@ namespace EMStudio void TrackDataWidget::UpdateMouseOverCursor(int32 x, int32 y) { // disable all tooltips - mPlugin->DisableAllToolTips(); + m_plugin->DisableAllToolTips(); // get the time track and return directly if we are not over a valid track with the cursor - TimeTrack* timeTrack = mPlugin->GetTrackAt(y); + TimeTrack* timeTrack = m_plugin->GetTrackAt(y); if (timeTrack == nullptr) { setCursor(Qt::ArrowCursor); @@ -1296,7 +1282,7 @@ namespace EMStudio } // get the element over which the cursor is positioned - TimeTrackElement* element = mPlugin->GetElementAt(x, y); + TimeTrackElement* element = m_plugin->GetElementAt(x, y); // in case the cursor is over an element, show tool tips if (element) @@ -1305,7 +1291,7 @@ namespace EMStudio } else { - mPlugin->DisableAllToolTips(); + m_plugin->DisableAllToolTips(); } // do not allow any editing in case the track is not enabled @@ -1316,10 +1302,10 @@ namespace EMStudio } // check if we are hovering over a resize point - if (mPlugin->FindResizePoint(x, y, &mResizeElement, &mResizeID)) + if (m_plugin->FindResizePoint(x, y, &m_resizeElement, &m_resizeId)) { setCursor(Qt::SizeHorCursor); - mResizeElement->SetShowToolTip(true); + m_resizeElement->SetShowToolTip(true); } else // if we're not above a resize point { @@ -1338,7 +1324,7 @@ namespace EMStudio // when the mouse is pressed void TrackDataWidget::mousePressEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); QPoint mousePos = event->pos(); @@ -1347,35 +1333,35 @@ namespace EMStudio const bool altPressed = event->modifiers() & Qt::AltModifier; // store the last clicked position - mLastMouseMoveX = event->x(); - mAllowContextMenu = true; - mRectSelecting = false; + m_lastMouseMoveX = event->x(); + m_allowContextMenu = true; + m_rectSelecting = false; if (event->button() == Qt::RightButton) { - mMouseRightClicked = true; + m_mouseRightClicked = true; } if (event->button() == Qt::MidButton) { - mMouseMidClicked = true; + m_mouseMidClicked = true; } if (event->button() == Qt::LeftButton) { - mMouseLeftClicked = true; + m_mouseLeftClicked = true; EMotionFX::Recorder& recorder = EMotionFX::GetRecorder(); - if ((mPlugin->mNodeHistoryItem == nullptr) && altPressed == false && (recorder.GetRecordTime() >= MCore::Math::epsilon)) + if ((m_plugin->m_nodeHistoryItem == nullptr) && altPressed == false && (recorder.GetRecordTime() >= MCore::Math::epsilon)) { // update the current time marker int newX = event->x(); newX = MCore::Clamp(newX, 0, geometry().width() - 1); - mPlugin->mCurTime = mPlugin->PixelToTime(newX); + m_plugin->m_curTime = m_plugin->PixelToTime(newX); if (recorder.GetRecordTime() < MCore::Math::epsilon) { - SetPausedTime(aznumeric_cast(mPlugin->GetCurrentTime()), /*emitTimeChangeStart=*/true); + SetPausedTime(aznumeric_cast(m_plugin->GetCurrentTime()), /*emitTimeChangeStart=*/true); } else { @@ -1384,34 +1370,34 @@ namespace EMStudio recorder.StartPlayBack(); } - recorder.SetCurrentPlayTime(aznumeric_cast(mPlugin->GetCurrentTime())); + recorder.SetCurrentPlayTime(aznumeric_cast(m_plugin->GetCurrentTime())); recorder.SetAutoPlay(false); - emit mPlugin->ManualTimeChangeStart(aznumeric_cast(mPlugin->GetCurrentTime())); - emit mPlugin->ManualTimeChange(aznumeric_cast(mPlugin->GetCurrentTime())); + emit m_plugin->ManualTimeChangeStart(aznumeric_cast(m_plugin->GetCurrentTime())); + emit m_plugin->ManualTimeChange(aznumeric_cast(m_plugin->GetCurrentTime())); } } else // not inside timeline { // if we clicked inside the node history area - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); if (GetIsInsideNodeHistory(event->y()) && recorderGroup->GetDisplayNodeActivity()) { EMotionFX::Recorder::ActorInstanceData* actorInstanceData = FindActorInstanceData(); EMotionFX::Recorder::NodeHistoryItem* historyItem = FindNodeHistoryItem(actorInstanceData, event->x(), event->y()); if (historyItem && altPressed == false) { - emit mPlugin->ClickedRecorderNodeHistoryItem(actorInstanceData, historyItem); + emit m_plugin->ClickedRecorderNodeHistoryItem(actorInstanceData, historyItem); } } { // unselect all elements if (ctrlPressed == false && shiftPressed == false) { - mPlugin->UnselectAllElements(); + m_plugin->UnselectAllElements(); } // find the element we're clicking in - TimeTrackElement* element = mPlugin->GetElementAt(event->x(), event->y()); + TimeTrackElement* element = m_plugin->GetElementAt(event->x(), event->y()); if (element) { // show the time of the currently dragging element in the time info view @@ -1421,26 +1407,26 @@ namespace EMStudio if (timeTrack->GetIsEnabled()) { - mDraggingElement = element; - mDragElementTrack = timeTrack; - mDraggingElement->SetShowTimeHandles(true); + m_draggingElement = element; + m_dragElementTrack = timeTrack; + m_draggingElement->SetShowTimeHandles(true); setCursor(Qt::ClosedHandCursor); } else { - mDraggingElement = nullptr; - mDragElementTrack = nullptr; + m_draggingElement = nullptr; + m_dragElementTrack = nullptr; } // shift select if (shiftPressed) { // get the element number of the clicked element - const uint32 clickedElementNr = element->GetElementNumber(); + const size_t clickedElementNr = element->GetElementNumber(); // get the element number of the first previously selected element TimeTrackElement* firstSelectedElement = timeTrack->GetFirstSelectedElement(); - const uint32 firstSelectedNr = firstSelectedElement ? firstSelectedElement->GetElementNumber() : 0; + const size_t firstSelectedNr = firstSelectedElement ? firstSelectedElement->GetElementNumber() : 0; // range select timeTrack->RangeSelectElements(firstSelectedNr, clickedElementNr); @@ -1457,35 +1443,28 @@ namespace EMStudio } else // no element clicked { - mDraggingElement = nullptr; - mDragElementTrack = nullptr; + m_draggingElement = nullptr; + m_dragElementTrack = nullptr; // rect selection - mRectSelecting = true; - mSelectStart = mousePos; - mSelectEnd = mSelectStart; + m_rectSelecting = true; + m_selectStart = mousePos; + m_selectEnd = m_selectStart; setCursor(Qt::ArrowCursor); } // if we're going to resize - if (mResizeElement && mResizeID != MCORE_INVALIDINDEX32) - { - mResizing = true; - } - else - { - mResizing = false; - } + m_resizing = m_resizeElement && m_resizeId != InvalidIndex32; // store the last clicked position - mMouseLeftClicked = true; - mLastLeftClickedX = event->x(); + m_mouseLeftClicked = true; + m_lastLeftClickedX = event->x(); } } } - const bool isZooming = mMouseLeftClicked == false && mMouseRightClicked && altPressed; - const bool isPanning = mMouseLeftClicked == false && isZooming == false && (mMouseMidClicked || mMouseRightClicked); + const bool isZooming = m_mouseLeftClicked == false && m_mouseRightClicked && altPressed; + const bool isPanning = m_mouseLeftClicked == false && isZooming == false && (m_mouseMidClicked || m_mouseRightClicked); if (isPanning) { @@ -1494,7 +1473,7 @@ namespace EMStudio if (isZooming) { - setCursor(*(mPlugin->GetZoomInCursor())); + setCursor(*(m_plugin->GetZoomInCursor())); } } @@ -1502,58 +1481,58 @@ namespace EMStudio // when releasing the mouse button void TrackDataWidget::mouseReleaseEvent(QMouseEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); setCursor(Qt::ArrowCursor); // disable overwrite mode in any case when the mouse gets released so that we display the current time from the plugin again - if (mPlugin->GetTimeInfoWidget()) + if (m_plugin->GetTimeInfoWidget()) { - mPlugin->GetTimeInfoWidget()->SetIsOverwriteMode(false); + m_plugin->GetTimeInfoWidget()->SetIsOverwriteMode(false); } - mLastMouseMoveX = event->x(); + m_lastMouseMoveX = event->x(); const bool ctrlPressed = event->modifiers() & Qt::ControlModifier; //const bool shiftPressed = event->modifiers() & Qt::ShiftModifier; if (event->button() == Qt::RightButton) { - mMouseRightClicked = false; - mIsScrolling = false; + m_mouseRightClicked = false; + m_isScrolling = false; } if (event->button() == Qt::MidButton) { - mMouseMidClicked = false; + m_mouseMidClicked = false; } if (event->button() == Qt::LeftButton) { - TimeTrack* mouseCursorTrack = mPlugin->GetTrackAt(event->y()); - const bool elementTrackChanged = (mouseCursorTrack && mDragElementTrack && mouseCursorTrack != mDragElementTrack); + TimeTrack* mouseCursorTrack = m_plugin->GetTrackAt(event->y()); + const bool elementTrackChanged = (mouseCursorTrack && m_dragElementTrack && mouseCursorTrack != m_dragElementTrack); - if (mDragging && mMouseLeftClicked && mDraggingElement && !mIsScrolling && !mResizing) + if (m_dragging && m_mouseLeftClicked && m_draggingElement && !m_isScrolling && !m_resizing) { - SetPausedTime(aznumeric_cast(mDraggingElement->GetStartTime())); + SetPausedTime(aznumeric_cast(m_draggingElement->GetStartTime())); } - if ((mResizing || mDragging) && elementTrackChanged == false && mDraggingElement) + if ((m_resizing || m_dragging) && elementTrackChanged == false && m_draggingElement) { - emit MotionEventChanged(mDraggingElement, mDraggingElement->GetStartTime(), mDraggingElement->GetEndTime()); + emit MotionEventChanged(m_draggingElement, m_draggingElement->GetStartTime(), m_draggingElement->GetEndTime()); } - mMouseLeftClicked = false; - mDragging = false; - mResizing = false; - mIsScrolling = false; + m_mouseLeftClicked = false; + m_dragging = false; + m_resizing = false; + m_isScrolling = false; // rect selection - if (mRectSelecting) + if (m_rectSelecting) { - if (mRectZooming) + if (m_rectZooming) { - mRectZooming = false; + m_rectZooming = false; // calc the selection rect QRect selectRect; @@ -1562,7 +1541,7 @@ namespace EMStudio // zoom in on the rect if (selectRect.isEmpty() == false) { - mPlugin->ZoomRect(selectRect); + m_plugin->ZoomRect(selectRect); } } else @@ -1574,8 +1553,6 @@ namespace EMStudio // select things inside it if (selectRect.isEmpty() == false) { - //selectRect = mActiveGraph->GetTransform().inverted().mapRect( selectRect ); - // rect select the elements const bool overwriteSelection = (ctrlPressed == false); SelectElementsInRect(selectRect, overwriteSelection, true, ctrlPressed); @@ -1584,37 +1561,37 @@ namespace EMStudio } // check if we moved an element to another track - if (elementTrackChanged && mDraggingElement) + if (elementTrackChanged && m_draggingElement) { // lastly fire a signal so that the data can change along with - emit ElementTrackChanged(mDraggingElement->GetElementNumber(), aznumeric_cast(mDraggingElement->GetStartTime()), aznumeric_cast(mDraggingElement->GetEndTime()), mDragElementTrack->GetName(), mouseCursorTrack->GetName()); + emit ElementTrackChanged(m_draggingElement->GetElementNumber(), aznumeric_cast(m_draggingElement->GetStartTime()), aznumeric_cast(m_draggingElement->GetEndTime()), m_dragElementTrack->GetName(), mouseCursorTrack->GetName()); } - mDragElementTrack = nullptr; + m_dragElementTrack = nullptr; - if (mDraggingElement) + if (m_draggingElement) { - mDraggingElement->SetShowTimeHandles(false); - mDraggingElement = nullptr; + m_draggingElement->SetShowTimeHandles(false); + m_draggingElement = nullptr; } // disable rect selection mode again - mRectSelecting = false; + m_rectSelecting = false; return; } // disable rect selection mode again - mRectSelecting = false; + m_rectSelecting = false; UpdateMouseOverCursor(event->x(), event->y()); } void TrackDataWidget::ClearState() { - mDragElementTrack = nullptr; - mDraggingElement = nullptr; - mDragging = false; - mResizing = false; - mResizeElement = nullptr; + m_dragElementTrack = nullptr; + m_draggingElement = nullptr; + m_dragging = false; + m_resizing = false; + m_resizeElement = nullptr; } // the mouse wheel is adjusted @@ -1658,15 +1635,15 @@ namespace EMStudio // handle mouse wheel event void TrackDataWidget::wheelEvent(QWheelEvent* event) { - DoWheelEvent(event, mPlugin); + DoWheelEvent(event, m_plugin); } // drag & drop support void TrackDataWidget::dragEnterEvent(QDragEnterEvent* event) { - mPlugin->SetRedrawFlag(); - mOldCurrentTime = mPlugin->GetCurrentTime(); + m_plugin->SetRedrawFlag(); + m_oldCurrentTime = m_plugin->GetCurrentTime(); // this is needed to actually reach the drop event function event->acceptProposedAction(); @@ -1675,11 +1652,11 @@ namespace EMStudio void TrackDataWidget::dragMoveEvent(QDragMoveEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); QPoint mousePos = event->pos(); - double dropTime = mPlugin->PixelToTime(mousePos.x()); - mPlugin->SetCurrentTime(dropTime); + double dropTime = m_plugin->PixelToTime(mousePos.x()); + m_plugin->SetCurrentTime(dropTime); SetPausedTime(aznumeric_cast(dropTime)); } @@ -1687,26 +1664,26 @@ namespace EMStudio void TrackDataWidget::dropEvent(QDropEvent* event) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); // accept the drop event->acceptProposedAction(); // emit drop event emit MotionEventPresetsDropped(event->pos()); - mPlugin->SetCurrentTime(mOldCurrentTime); + m_plugin->SetCurrentTime(m_oldCurrentTime); } // the context menu event void TrackDataWidget::contextMenuEvent(QContextMenuEvent* event) { - if (mIsScrolling || mDragging || mResizing || !mAllowContextMenu) + if (m_isScrolling || m_dragging || m_resizing || !m_allowContextMenu) { return; } - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); if (EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon) { @@ -1714,34 +1691,34 @@ namespace EMStudio return; } - if (mPlugin->mMotion == nullptr) + if (m_plugin->m_motion == nullptr) { return; } QPoint point = event->pos(); - mContextMenuX = point.x(); - mContextMenuY = point.y(); + m_contextMenuX = point.x(); + m_contextMenuY = point.y(); - TimeTrack* timeTrack = mPlugin->GetTrackAt(mContextMenuY); + TimeTrack* timeTrack = m_plugin->GetTrackAt(m_contextMenuY); - uint32 numElements = 0; - uint32 numSelectedElements = 0; + size_t numElements = 0; + size_t numSelectedElements = 0; // calculate the number of selected and total events - const uint32 numTracks = mPlugin->GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = m_plugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { // get the current time view track - TimeTrack* track = mPlugin->GetTrack(i); + TimeTrack* track = m_plugin->GetTrack(i); if (track->GetIsVisible() == false) { continue; } // get the number of elements in the track and iterate through them - const uint32 numTrackElements = track->GetNumElements(); - for (uint32 j = 0; j < numTrackElements; ++j) + const size_t numTrackElements = track->GetNumElements(); + for (size_t j = 0; j < numTrackElements; ++j) { TimeTrackElement* element = track->GetElement(j); numElements++; @@ -1756,7 +1733,7 @@ namespace EMStudio if (timeTrack) { numElements = timeTrack->GetNumElements(); - for (uint32 i = 0; i < numElements; ++i) + for (size_t i = 0; i < numElements; ++i) { TimeTrackElement* element = timeTrack->GetElement(i); @@ -1772,7 +1749,7 @@ namespace EMStudio if (timeTrack) { - TimeTrackElement* element = mPlugin->GetElementAt(mContextMenuX, mContextMenuY); + TimeTrackElement* element = m_plugin->GetElementAt(m_contextMenuX, m_contextMenuY); if (element == nullptr) { QAction* action = menu.addAction("Add motion event"); @@ -1861,9 +1838,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TrackDataWidget::keyPressEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyPressEvent(event); + m_plugin->OnKeyPressEvent(event); } } @@ -1871,31 +1848,31 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TrackDataWidget::keyReleaseEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyReleaseEvent(event); + m_plugin->OnKeyReleaseEvent(event); } } void TrackDataWidget::AddMotionEvent(int32 x, int32 y) { - mPlugin->AddMotionEvent(x, y); + m_plugin->AddMotionEvent(x, y); } void TrackDataWidget::RemoveMotionEvent(int32 x, int32 y) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); // get the time track on which we dropped the preset - TimeTrack* timeTrack = mPlugin->GetTrackAt(y); + TimeTrack* timeTrack = m_plugin->GetTrackAt(y); if (timeTrack == nullptr) { return; } // get the time track on which we dropped the preset - TimeTrackElement* element = mPlugin->GetElementAt(x, y); + TimeTrackElement* element = m_plugin->GetElementAt(x, y); if (element == nullptr) { return; @@ -1908,33 +1885,33 @@ namespace EMStudio // remove selected motion events in track void TrackDataWidget::RemoveSelectedMotionEventsInTrack() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); // get the track where we are at the moment - TimeTrack* timeTrack = mPlugin->GetTrackAt(mLastMouseY); + TimeTrack* timeTrack = m_plugin->GetTrackAt(m_lastMouseY); if (timeTrack == nullptr) { return; } - MCore::Array eventNumbers; + AZStd::vector eventNumbers; // calculate the number of selected events - const uint32 numEvents = timeTrack->GetNumElements(); - for (uint32 i = 0; i < numEvents; ++i) + const size_t numEvents = timeTrack->GetNumElements(); + for (size_t i = 0; i < numEvents; ++i) { TimeTrackElement* element = timeTrack->GetElement(i); // increase the counter in case the element is selected if (element->GetIsSelected()) { - eventNumbers.Add(i); + eventNumbers.emplace_back(i); } } // remove the motion events CommandSystem::CommandHelperRemoveMotionEvents(timeTrack->GetName(), eventNumbers); - mPlugin->UnselectAllElements(); + m_plugin->UnselectAllElements(); ClearState(); } @@ -1942,39 +1919,39 @@ namespace EMStudio // remove all motion events in track void TrackDataWidget::RemoveAllMotionEventsInTrack() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); - TimeTrack* timeTrack = mPlugin->GetTrackAt(mLastMouseY); + TimeTrack* timeTrack = m_plugin->GetTrackAt(m_lastMouseY); if (timeTrack == nullptr) { return; } - MCore::Array eventNumbers; + AZStd::vector eventNumbers; // construct an array with the event numbers - const uint32 numEvents = timeTrack->GetNumElements(); - for (uint32 i = 0; i < numEvents; ++i) + const size_t numEvents = timeTrack->GetNumElements(); + for (size_t i = 0; i < numEvents; ++i) { - eventNumbers.Add(i); + eventNumbers.emplace_back(i); } // remove the motion events CommandSystem::CommandHelperRemoveMotionEvents(timeTrack->GetName(), eventNumbers); - mPlugin->UnselectAllElements(); + m_plugin->UnselectAllElements(); ClearState(); } void TrackDataWidget::OnRemoveEventTrack() { - const TimeTrack* timeTrack = mPlugin->GetTrackAt(mLastMouseY); + const TimeTrack* timeTrack = m_plugin->GetTrackAt(m_lastMouseY); if (!timeTrack) { return; } - const AZ::Outcome trackIndexOutcome = mPlugin->FindTrackIndex(timeTrack); + const AZ::Outcome trackIndexOutcome = m_plugin->FindTrackIndex(timeTrack); if (trackIndexOutcome.IsSuccess()) { RemoveTrack(trackIndexOutcome.GetValue()); @@ -1984,10 +1961,10 @@ namespace EMStudio void TrackDataWidget::FillCopyElements(bool selectedItemsOnly) { // clear the array before feeding it - mCopyElements.clear(); + m_copyElements.clear(); // get the time track name - const TimeTrack* timeTrack = mPlugin->GetTrackAt(mContextMenuY); + const TimeTrack* timeTrack = m_plugin->GetTrackAt(m_contextMenuY); if (timeTrack == nullptr) { return; @@ -1995,7 +1972,7 @@ namespace EMStudio const AZStd::string trackName = timeTrack->GetName(); // check if the motion is valid and return failure in case it is not - const EMotionFX::Motion* motion = mPlugin->GetMotion(); + const EMotionFX::Motion* motion = m_plugin->GetMotion(); if (motion == nullptr) { return; @@ -2010,9 +1987,9 @@ namespace EMStudio } // iterate through the elements - const uint32 numElements = timeTrack->GetNumElements(); + const size_t numElements = timeTrack->GetNumElements(); MCORE_ASSERT(numElements == eventTrack->GetNumEvents()); - for (uint32 i = 0; i < numElements; ++i) + for (size_t i = 0; i < numElements; ++i) { // get the element and skip all unselected ones const TimeTrackElement* element = timeTrack->GetElement(i); @@ -2025,7 +2002,7 @@ namespace EMStudio const EMotionFX::MotionEvent& motionEvent = eventTrack->GetEvent(i); // create the copy paste element and add it to the array - mCopyElements.emplace_back( + m_copyElements.emplace_back( motion->GetID(), eventTrack->GetNameString(), motionEvent.GetEventDatas(), @@ -2039,44 +2016,44 @@ namespace EMStudio // cut all events from a track void TrackDataWidget::OnCutTrack() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); FillCopyElements(false); - mCutMode = true; + m_cutMode = true; } // copy all events from a track void TrackDataWidget::OnCopyTrack() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); FillCopyElements(false); - mCutMode = false; + m_cutMode = false; } // cut motion event void TrackDataWidget::OnCutElement() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); FillCopyElements(true); - mCutMode = true; + m_cutMode = true; } // copy motion event void TrackDataWidget::OnCopyElement() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); FillCopyElements(true); - mCutMode = false; + m_cutMode = false; } @@ -2101,10 +2078,10 @@ namespace EMStudio // paste motion events void TrackDataWidget::DoPaste(bool useLocation) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); // get the time track name where we are pasting - TimeTrack* timeTrack = mPlugin->GetTrackAt(mContextMenuY); + TimeTrack* timeTrack = m_plugin->GetTrackAt(m_contextMenuY); if (timeTrack == nullptr) { return; @@ -2112,23 +2089,23 @@ namespace EMStudio AZStd::string trackName = timeTrack->GetName(); // get the number of elements to copy - const size_t numElements = mCopyElements.size(); + const size_t numElements = m_copyElements.size(); // create the command group MCore::CommandGroup commandGroup("Paste motion events"); // find the min and maximum time values of the events to paste - auto [minEvent, maxEvent] = AZStd::minmax_element(begin(mCopyElements), end(mCopyElements), [](const CopyElement& left, const CopyElement& right) + auto [minEvent, maxEvent] = AZStd::minmax_element(begin(m_copyElements), end(m_copyElements), [](const CopyElement& left, const CopyElement& right) { return left.m_startTime < right.m_startTime; }); - if (mCutMode) + if (m_cutMode) { // iterate through the copy elements from back to front and delete the selected ones for (int32 i = static_cast(numElements) - 1; i >= 0; i--) { - const CopyElement& copyElement = mCopyElements[i]; + const CopyElement& copyElement = m_copyElements[i]; // get the motion to which the original element belongs to EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(copyElement.m_motionID); @@ -2146,7 +2123,7 @@ namespace EMStudio } // get the number of events and iterate through them - size_t eventNr = MCORE_INVALIDINDEX32; + size_t eventNr = InvalidIndex; const size_t numEvents = eventTrack->GetNumEvents(); for (eventNr = 0; eventNr < numEvents; ++eventNr) { @@ -2160,20 +2137,18 @@ namespace EMStudio } // remove event - if (eventNr != MCORE_INVALIDINDEX32) + if (eventNr != InvalidIndex) { - CommandSystem::CommandHelperRemoveMotionEvent(copyElement.m_motionID, copyElement.m_trackName.c_str(), static_cast(eventNr), &commandGroup); + CommandSystem::CommandHelperRemoveMotionEvent(copyElement.m_motionID, copyElement.m_trackName.c_str(), eventNr, &commandGroup); } } } - const float offset = useLocation ? aznumeric_cast(mPlugin->PixelToTime(mContextMenuX, true)) - minEvent->m_startTime : 0.0f; + const float offset = useLocation ? aznumeric_cast(m_plugin->PixelToTime(m_contextMenuX, true)) - minEvent->m_startTime : 0.0f; // iterate through the elements to copy and add the new motion events - for (uint32 i = 0; i < numElements; ++i) + for (const CopyElement& copyElement : m_copyElements) { - const CopyElement& copyElement = mCopyElements[i]; - float startTime = copyElement.m_startTime + offset; float endTime = copyElement.m_endTime + offset; @@ -2194,16 +2169,16 @@ namespace EMStudio MCore::LogError(outResult.c_str()); } - if (mCutMode) + if (m_cutMode) { - mCopyElements.clear(); + m_copyElements.clear(); } } void TrackDataWidget::OnCreatePresetEvent() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); EMStudioPlugin* plugin = EMStudio::GetPluginManager()->FindActivePlugin(MotionEventsPlugin::CLASS_ID); if (plugin == nullptr) { @@ -2212,13 +2187,13 @@ namespace EMStudio MotionEventsPlugin* eventsPlugin = static_cast(plugin); - QPoint mousePos(mContextMenuX, mContextMenuY); + QPoint mousePos(m_contextMenuX, m_contextMenuY); eventsPlugin->OnEventPresetDropped(mousePos); } void TrackDataWidget::OnAddTrack() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); CommandSystem::CommandAddEventTrack(); } @@ -2226,11 +2201,11 @@ namespace EMStudio void TrackDataWidget::SelectElementsInRect(const QRect& rect, bool overwriteCurSelection, bool select, bool toggleMode) { // get the number of tracks and iterate through them - const uint32 numTracks = mPlugin->GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = m_plugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { // get the current time track - TimeTrack* track = mPlugin->GetTrack(i); + TimeTrack* track = m_plugin->GetTrack(i); if (track->GetIsVisible() == false) { continue; @@ -2285,7 +2260,7 @@ namespace EMStudio else { // get the hovered element and track - TimeTrackElement* element = mPlugin->GetElementAt(localPos.x(), localPos.y()); + TimeTrackElement* element = m_plugin->GetElementAt(localPos.x(), localPos.y()); if (element == nullptr) { return QOpenGLWidget::event(event); @@ -2314,20 +2289,20 @@ namespace EMStudio const EMotionFX::Recorder::ActorInstanceData* actorInstanceData = FindActorInstanceData(); // if we recorded node history - mNodeHistoryRect = QRect(); - if (actorInstanceData && actorInstanceData->mNodeHistoryItems.GetLength() > 0) + m_nodeHistoryRect = QRect(); + if (actorInstanceData && !actorInstanceData->m_nodeHistoryItems.empty()) { - const uint32 height = (recorder.CalcMaxNodeHistoryTrackIndex(*actorInstanceData) + 1) * (mNodeHistoryItemHeight + 3) + mNodeRectsStartHeight; - mNodeHistoryRect.setTop(mNodeRectsStartHeight); - mNodeHistoryRect.setBottom(height); - mNodeHistoryRect.setLeft(0); - mNodeHistoryRect.setRight(geometry().width()); + const int height = aznumeric_caster((recorder.CalcMaxNodeHistoryTrackIndex(*actorInstanceData) + 1) * (m_nodeHistoryItemHeight + 3) + m_nodeRectsStartHeight); + m_nodeHistoryRect.setTop(m_nodeRectsStartHeight); + m_nodeHistoryRect.setBottom(height); + m_nodeHistoryRect.setLeft(0); + m_nodeHistoryRect.setRight(geometry().width()); } - mEventHistoryTotalHeight = 0; - if (actorInstanceData && actorInstanceData->mEventHistoryItems.GetLength() > 0) + m_eventHistoryTotalHeight = 0; + if (actorInstanceData && !actorInstanceData->m_eventHistoryItems.empty()) { - mEventHistoryTotalHeight = (recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20; + m_eventHistoryTotalHeight = aznumeric_caster((recorder.CalcMaxEventHistoryTrackIndex(*actorInstanceData) + 1) * 20); } } @@ -2345,25 +2320,22 @@ namespace EMStudio return nullptr; } - // make sure the mTrackRemap array is up to date - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + // make sure the m_trackRemap array is up to date + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); const bool sorted = recorderGroup->GetSortNodeActivity(); - const uint32 graphContentsCode = mPlugin->mTrackHeaderWidget->mNodeContentsComboBox->currentIndex(); - EMotionFX::GetRecorder().ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(mPlugin->mCurTime), sorted, (EMotionFX::Recorder::EValueType)graphContentsCode, &mActiveItems, &mTrackRemap); + const int graphContentsCode = m_plugin->m_trackHeaderWidget->m_nodeContentsComboBox->currentIndex(); + EMotionFX::GetRecorder().ExtractNodeHistoryItems(*actorInstanceData, aznumeric_cast(m_plugin->m_curTime), sorted, (EMotionFX::Recorder::EValueType)graphContentsCode, &m_activeItems, &m_trackRemap); // get the history items shortcut - const MCore::Array& historyItems = actorInstanceData->mNodeHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_nodeHistoryItems; QRect rect; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (EMotionFX::Recorder::NodeHistoryItem* curItem : historyItems) { - EMotionFX::Recorder::NodeHistoryItem* curItem = historyItems[i]; - // draw the background rect - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); - double endTimePixel = mPlugin->TimeToPixel(curItem->mEndTime); + double startTimePixel = m_plugin->TimeToPixel(curItem->m_startTime); + double endTimePixel = m_plugin->TimeToPixel(curItem->m_endTime); if (startTimePixel > x || endTimePixel < x) { @@ -2372,8 +2344,8 @@ namespace EMStudio rect.setLeft(aznumeric_cast(startTimePixel)); rect.setRight(aznumeric_cast(endTimePixel)); - rect.setTop((mNodeRectsStartHeight + (mTrackRemap[curItem->mTrackIndex] * (mNodeHistoryItemHeight + 3)) + 3)); - rect.setBottom(rect.top() + mNodeHistoryItemHeight); + rect.setTop((m_nodeRectsStartHeight + (aznumeric_cast(m_trackRemap[curItem->m_trackIndex]) * (m_nodeHistoryItemHeight + 3)) + 3)); + rect.setBottom(rect.top() + m_nodeHistoryItemHeight); if (rect.contains(x, y)) { @@ -2398,8 +2370,8 @@ namespace EMStudio } // find the actor instance data for this actor instance - const uint32 actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance); - if (actorInstanceDataIndex == MCORE_INVALIDINDEX32) // it doesn't exist, so we didn't record anything for this actor instance + const size_t actorInstanceDataIndex = recorder.FindActorInstanceDataIndex(actorInstance); + if (actorInstanceDataIndex == InvalidIndex) // it doesn't exist, so we didn't record anything for this actor instance { return nullptr; } @@ -2413,8 +2385,8 @@ namespace EMStudio void TrackDataWidget::DoRecorderContextMenuEvent(QContextMenuEvent* event) { QPoint point = event->pos(); - mContextMenuX = point.x(); - mContextMenuY = point.y(); + m_contextMenuX = point.x(); + m_contextMenuY = point.y(); // create the context menu QMenu menu(this); @@ -2423,10 +2395,10 @@ namespace EMStudio // Timeline actions //--------------------- QAction* action = menu.addAction("Zoom To Fit All"); - connect(action, &QAction::triggered, mPlugin, &TimeViewPlugin::OnZoomAll); + connect(action, &QAction::triggered, m_plugin, &TimeViewPlugin::OnZoomAll); action = menu.addAction("Reset Timeline"); - connect(action, &QAction::triggered, mPlugin, &TimeViewPlugin::OnResetTimeline); + connect(action, &QAction::triggered, m_plugin, &TimeViewPlugin::OnResetTimeline); //--------------------- // Right-clicked on a motion item @@ -2437,7 +2409,7 @@ namespace EMStudio menu.addSeparator(); action = menu.addAction("Show Node In Graph"); - connect(action, &QAction::triggered, mPlugin, &TimeViewPlugin::OnShowNodeHistoryNodeInGraph); + connect(action, &QAction::triggered, m_plugin, &TimeViewPlugin::OnShowNodeHistoryNodeInGraph); } // show the menu at the given position @@ -2451,34 +2423,34 @@ namespace EMStudio // node name outString += AZStd::string::format("

Node Name: 

"); - outString += AZStd::string::format("

%s

", item->mName.c_str()); + outString += AZStd::string::format("

%s

", item->m_name.c_str()); // build the node path string - EMotionFX::ActorInstance* actorInstance = FindActorInstanceData()->mActorInstance; + EMotionFX::ActorInstance* actorInstance = FindActorInstanceData()->m_actorInstance; EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); if (animGraphInstance) { EMotionFX::AnimGraph* animGraph = animGraphInstance->GetAnimGraph(); - EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(item->mNodeId); + EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(item->m_nodeId); if (node) { - MCore::Array nodePath; + AZStd::vector nodePath; EMotionFX::AnimGraphNode* curNode = node->GetParentNode(); while (curNode) { - nodePath.Insert(0, curNode); + nodePath.emplace(nodePath.begin(), curNode); curNode = curNode->GetParentNode(); } AZStd::string nodePathString; nodePathString.reserve(256); - for (uint32 i = 0; i < nodePath.GetLength(); ++i) + for (const EMotionFX::AnimGraphNode* parentNode : nodePath) { - nodePathString += nodePath[i]->GetName(); - if (i != nodePath.GetLength() - 1) + if (!nodePathString.empty()) { nodePathString += " > "; } + nodePathString += parentNode->GetName(); } outString += AZStd::string::format("

Node Path: 

"); @@ -2493,22 +2465,22 @@ namespace EMStudio if (node->GetNumChildNodes() > 0) { outString += AZStd::string::format("

Child Nodes: 

"); - outString += AZStd::string::format("

%d

", node->GetNumChildNodes()); + outString += AZStd::string::format("

%zu

", node->GetNumChildNodes()); outString += AZStd::string::format("

Recursive Children: 

"); - outString += AZStd::string::format("

%d

", node->RecursiveCalcNumNodes()); + outString += AZStd::string::format("

%zu

", node->RecursiveCalcNumNodes()); } } } // motion name - if (item->mMotionID != MCORE_INVALIDINDEX32 && item->mMotionFileName.size() > 0) + if (item->m_motionId != InvalidIndex32 && !item->m_motionFileName.empty()) { outString += AZStd::string::format("

Motion FileName: 

"); - outString += AZStd::string::format("

%s

", item->mMotionFileName.c_str()); + outString += AZStd::string::format("

%s

", item->m_motionFileName.c_str()); // show motion info - EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(item->mMotionID); + EMotionFX::Motion* motion = EMotionFX::GetMotionManager().FindMotionByID(item->m_motionId); if (motion) { AZStd::string path; @@ -2551,18 +2523,14 @@ namespace EMStudio return nullptr; } - const MCore::Array& historyItems = actorInstanceData->mEventHistoryItems; + const AZStd::vector& historyItems = actorInstanceData->m_eventHistoryItems; const float tickHalfWidth = 7; const float tickHeight = 16; - const uint32 numItems = historyItems.GetLength(); - for (uint32 i = 0; i < numItems; ++i) + for (EMotionFX::Recorder::EventHistoryItem* curItem : historyItems) { - EMotionFX::Recorder::EventHistoryItem* curItem = historyItems[i]; - - float height = aznumeric_cast((curItem->mTrackIndex * 20) + mEventsStartHeight); - double startTimePixel = mPlugin->TimeToPixel(curItem->mStartTime); - //double endTimePixel = mPlugin->TimeToPixel( curItem->mEndTime ); + float height = aznumeric_caster((curItem->m_trackIndex * 20) + m_eventsStartHeight); + double startTimePixel = m_plugin->TimeToPixel(curItem->m_startTime); const QRect rect(QPoint(aznumeric_cast(startTimePixel - tickHalfWidth), aznumeric_cast(height)), QSize(aznumeric_cast(tickHalfWidth * 2), aznumeric_cast(tickHeight))); if (rect.contains(QPoint(x, y))) @@ -2580,7 +2548,7 @@ namespace EMStudio { outString = ""; - const EMotionFX::MotionEvent* motionEvent = item->mEventInfo.mEvent; + const EMotionFX::MotionEvent* motionEvent = item->m_eventInfo.m_event; for (const EMotionFX::EventDataPtr& eventData : motionEvent->GetEventDatas()) { if (eventData) @@ -2604,25 +2572,25 @@ namespace EMStudio outString += AZStd::string::format(""); outString += AZStd::string::format(""); - outString += AZStd::string::format("", item->mEventInfo.mTimeValue); + outString += AZStd::string::format("", item->m_eventInfo.m_timeValue); outString += AZStd::string::format(""); - outString += AZStd::string::format("", item->mStartTime); + outString += AZStd::string::format("", item->m_startTime); outString += AZStd::string::format(""); - outString += AZStd::string::format("", (item->mIsTickEvent == false) ? "Yes" : "No"); + outString += AZStd::string::format("", (item->m_isTickEvent == false) ? "Yes" : "No"); - if (item->mIsTickEvent == false) + if (item->m_isTickEvent == false) { const static AZStd::string eventStartText = "Event Start"; const static AZStd::string eventActiveText = "Event Active"; const static AZStd::string eventEndText = "Event End"; const AZStd::string* outputEventStateText = &eventStartText; - if (item->mEventInfo.m_eventState == EMotionFX::EventInfo::EventState::ACTIVE) + if (item->m_eventInfo.m_eventState == EMotionFX::EventInfo::EventState::ACTIVE) { outputEventStateText = &eventActiveText; } - else if (item->mEventInfo.m_eventState == EMotionFX::EventInfo::EventState::END) + else if (item->m_eventInfo.m_eventState == EMotionFX::EventInfo::EventState::END) { outputEventStateText = &eventEndText; } @@ -2631,40 +2599,39 @@ namespace EMStudio } outString += AZStd::string::format(""); - outString += AZStd::string::format("", item->mEventInfo.mGlobalWeight); + outString += AZStd::string::format("", item->m_eventInfo.m_globalWeight); outString += AZStd::string::format(""); - outString += AZStd::string::format("", item->mEventInfo.mLocalWeight); + outString += AZStd::string::format("", item->m_eventInfo.m_localWeight); // build the node path string - EMotionFX::ActorInstance* actorInstance = FindActorInstanceData()->mActorInstance; + EMotionFX::ActorInstance* actorInstance = FindActorInstanceData()->m_actorInstance; EMotionFX::AnimGraphInstance* animGraphInstance = actorInstance->GetAnimGraphInstance(); if (animGraphInstance) { - EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(item->mAnimGraphID);//animGraphInstance->GetAnimGraph(); - EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(item->mEmitterNodeId); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(item->m_animGraphId);//animGraphInstance->GetAnimGraph(); + EMotionFX::AnimGraphNode* node = animGraph->RecursiveFindNodeById(item->m_emitterNodeId); if (node) { outString += AZStd::string::format(""); outString += AZStd::string::format("", node->GetName()); - MCore::Array nodePath; + AZStd::vector nodePath; EMotionFX::AnimGraphNode* curNode = node->GetParentNode(); while (curNode) { - nodePath.Insert(0, curNode); + nodePath.emplace(0, curNode); curNode = curNode->GetParentNode(); } AZStd::string nodePathString; - nodePathString.reserve(256); - for (uint32 i = 0; i < nodePath.GetLength(); ++i) + for (const EMotionFX::AnimGraphNode* parentNode : nodePath) { - nodePathString += nodePath[i]->GetName(); - if (i != nodePath.GetLength() - 1) + if (!nodePathString.empty()) { nodePathString += " > "; } + nodePathString += parentNode->GetName(); } outString += AZStd::string::format(""); @@ -2679,10 +2646,10 @@ namespace EMStudio if (node->GetNumChildNodes() > 0) { outString += AZStd::string::format(""); - outString += AZStd::string::format("", node->GetNumChildNodes()); + outString += AZStd::string::format("", node->GetNumChildNodes()); outString += AZStd::string::format(""); - outString += AZStd::string::format("", node->RecursiveCalcNumNodes()); + outString += AZStd::string::format("", node->RecursiveCalcNumNodes()); } // show the motion info @@ -2727,7 +2694,7 @@ namespace EMStudio { painter.setPen(QColor(60, 70, 80)); painter.setBrush(Qt::NoBrush); - painter.drawLine(QPoint(0, heightOffset), QPoint(aznumeric_cast(mPlugin->TimeToPixel(animationLength)), heightOffset)); + painter.drawLine(QPoint(0, heightOffset), QPoint(aznumeric_cast(m_plugin->TimeToPixel(animationLength)), heightOffset)); return 1; } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.h index 75968d1995..d0cbf8f032 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackDataWidget.h @@ -10,7 +10,7 @@ #if !defined(Q_MOC_RUN) #include -#include +#include #include "../StandardPluginsConfig.h" #include #include @@ -50,7 +50,7 @@ namespace EMStudio void resizeGL(int w, int h) override; void paintGL() override; - void RemoveTrack(AZ::u32 trackIndex); + void RemoveTrack(size_t trackIndex); protected: //void paintEvent(QPaintEvent* event); @@ -70,11 +70,11 @@ namespace EMStudio void MotionEventChanged(TimeTrackElement* element, double startTime, double endTime); void TrackAdded(TimeTrack* track); void SelectionChanged(); - void ElementTrackChanged(uint32 eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName); + void ElementTrackChanged(size_t eventNr, float startTime, float endTime, const char* oldTrackName, const char* newTrackName); private slots: - void OnRemoveElement() { RemoveMotionEvent(mContextMenuX, mContextMenuY); } - void OnAddElement() { AddMotionEvent(mContextMenuX, mContextMenuY); } + void OnRemoveElement() { RemoveMotionEvent(m_contextMenuX, m_contextMenuY); } + void OnAddElement() { AddMotionEvent(m_contextMenuX, m_contextMenuY); } void OnAddTrack(); void OnCreatePresetEvent(); void RemoveSelectedMotionEventsInTrack(); @@ -106,38 +106,38 @@ namespace EMStudio void PaintRelativeGraph(QPainter& painter, const QRect& rect, const EMotionFX::Recorder::ActorInstanceData* actorInstanceData); uint32 PaintSeparator(QPainter& painter, int32 heightOffset, float animationLength); - QBrush mBrushBackground; - QBrush mBrushBackgroundClipped; - QBrush mBrushBackgroundOutOfRange; - TimeViewPlugin* mPlugin; - bool mMouseLeftClicked; - bool mMouseMidClicked; - bool mMouseRightClicked; - bool mDragging; - bool mResizing; - bool mRectZooming; - bool mIsScrolling; - int32 mLastLeftClickedX; - int32 mLastMouseMoveX; - int32 mLastMouseX; - int32 mLastMouseY; - uint32 mNodeHistoryItemHeight; - uint32 mEventHistoryTotalHeight; - bool mAllowContextMenu; - - TimeTrackElement* mDraggingElement; - TimeTrack* mDragElementTrack; - TimeTrackElement* mResizeElement; - uint32 mResizeID; - int32 mContextMenuX; - int32 mContextMenuY; - uint32 mGraphStartHeight; - uint32 mEventsStartHeight; - uint32 mNodeRectsStartHeight; - double mOldCurrentTime; - - MCore::Array mActiveItems; - MCore::Array mTrackRemap; + QBrush m_brushBackground; + QBrush m_brushBackgroundClipped; + QBrush m_brushBackgroundOutOfRange; + TimeViewPlugin* m_plugin; + bool m_mouseLeftClicked; + bool m_mouseMidClicked; + bool m_mouseRightClicked; + bool m_dragging; + bool m_resizing; + bool m_rectZooming; + bool m_isScrolling; + int32 m_lastLeftClickedX; + int32 m_lastMouseMoveX; + int32 m_lastMouseX; + int32 m_lastMouseY; + uint32 m_nodeHistoryItemHeight; + uint32 m_eventHistoryTotalHeight; + bool m_allowContextMenu; + + TimeTrackElement* m_draggingElement; + TimeTrack* m_dragElementTrack; + TimeTrackElement* m_resizeElement; + uint32 m_resizeId; + int32 m_contextMenuX; + int32 m_contextMenuY; + uint32 m_graphStartHeight; + uint32 m_eventsStartHeight; + uint32 m_nodeRectsStartHeight; + double m_oldCurrentTime; + + AZStd::vector m_activeItems; + AZStd::vector m_trackRemap; // copy and paste struct CopyElement @@ -158,21 +158,21 @@ namespace EMStudio } }; - bool GetIsReadyForPaste() const { return mCopyElements.empty() == false; } + bool GetIsReadyForPaste() const { return m_copyElements.empty() == false; } void FillCopyElements(bool selectedItemsOnly); - AZStd::vector mCopyElements; - bool mCutMode; + AZStd::vector m_copyElements; + bool m_cutMode; - QFont mDataFont; - AZStd::string mTempString; + QFont m_dataFont; + AZStd::string m_tempString; // rect selection - QPoint mSelectStart; - QPoint mSelectEnd; - bool mRectSelecting; + QPoint m_selectStart; + QPoint m_selectEnd; + bool m_rectSelecting; - QRect mNodeHistoryRect; + QRect m_nodeHistoryRect; void CalcSelectRect(QRect& outRect); void SelectElementsInRect(const QRect& rect, bool overwriteCurSelection, bool select, bool toggleMode); @@ -181,7 +181,7 @@ namespace EMStudio void UpdateMouseOverCursor(int32 x, int32 y); void DrawTimeMarker(QPainter& painter, const QRect& rect); - bool GetIsInsideNodeHistory(int32 y) const { return mNodeHistoryRect.contains(1, y); } + bool GetIsInsideNodeHistory(int32 y) const { return m_nodeHistoryRect.contains(1, y); } void DoRecorderContextMenuEvent(QContextMenuEvent* event); void UpdateRects(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.cpp index 963d188aa6..bbdaf6e4a7 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.cpp @@ -33,18 +33,18 @@ namespace EMStudio TrackHeaderWidget::TrackHeaderWidget(TimeViewPlugin* plugin, QWidget* parent) : QWidget(parent) { - mPlugin = plugin; - mTrackLayout = nullptr; - mTrackWidget = nullptr; - mStackWidget = nullptr; - mNodeNamesCheckBox = nullptr; - mMotionFilesCheckBox = nullptr; + m_plugin = plugin; + m_trackLayout = nullptr; + m_trackWidget = nullptr; + m_stackWidget = nullptr; + m_nodeNamesCheckBox = nullptr; + m_motionFilesCheckBox = nullptr; // create the main layout - mMainLayout = new QVBoxLayout(); - mMainLayout->setMargin(2); - mMainLayout->setSpacing(0); - mMainLayout->setAlignment(Qt::AlignTop); + m_mainLayout = new QVBoxLayout(); + m_mainLayout->setMargin(2); + m_mainLayout->setSpacing(0); + m_mainLayout->setAlignment(Qt::AlignTop); //////////////////////////////// // Create the add event button @@ -65,12 +65,12 @@ namespace EMStudio mainAddWidget->setFixedSize(175, 40); mainAddWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - mMainLayout->addWidget(mainAddWidget); - mAddTrackWidget = mainAddWidget; + m_mainLayout->addWidget(mainAddWidget); + m_addTrackWidget = mainAddWidget; //////////////////////////////// // recorder settings - mStackWidget = new MysticQt::DialogStack(); + m_stackWidget = new MysticQt::DialogStack(); //----------- @@ -80,51 +80,51 @@ namespace EMStudio contentsLayout->setMargin(0); contentsWidget->setLayout(contentsLayout); - mNodeNamesCheckBox = new QCheckBox("Show Node Names"); - mNodeNamesCheckBox->setChecked(true); - mNodeNamesCheckBox->setCheckable(true); - AzQtComponents::CheckBox::applyToggleSwitchStyle(mNodeNamesCheckBox); - connect(mNodeNamesCheckBox, &QCheckBox::stateChanged, this, &TrackHeaderWidget::OnCheckBox); - contentsLayout->addWidget(mNodeNamesCheckBox); + m_nodeNamesCheckBox = new QCheckBox("Show Node Names"); + m_nodeNamesCheckBox->setChecked(true); + m_nodeNamesCheckBox->setCheckable(true); + AzQtComponents::CheckBox::applyToggleSwitchStyle(m_nodeNamesCheckBox); + connect(m_nodeNamesCheckBox, &QCheckBox::stateChanged, this, &TrackHeaderWidget::OnCheckBox); + contentsLayout->addWidget(m_nodeNamesCheckBox); - mMotionFilesCheckBox = new QCheckBox("Show Motion Files"); - mMotionFilesCheckBox->setChecked(false); - mMotionFilesCheckBox->setCheckable(true); - AzQtComponents::CheckBox::applyToggleSwitchStyle(mMotionFilesCheckBox); - connect(mMotionFilesCheckBox, &QCheckBox::stateChanged, this, &TrackHeaderWidget::OnCheckBox); - contentsLayout->addWidget(mMotionFilesCheckBox); + m_motionFilesCheckBox = new QCheckBox("Show Motion Files"); + m_motionFilesCheckBox->setChecked(false); + m_motionFilesCheckBox->setCheckable(true); + AzQtComponents::CheckBox::applyToggleSwitchStyle(m_motionFilesCheckBox); + connect(m_motionFilesCheckBox, &QCheckBox::stateChanged, this, &TrackHeaderWidget::OnCheckBox); + contentsLayout->addWidget(m_motionFilesCheckBox); QHBoxLayout* comboLayout = new QHBoxLayout(); comboLayout->addWidget(new QLabel("Nodes:")); - mNodeContentsComboBox = new QComboBox(); - mNodeContentsComboBox->setEditable(false); - mNodeContentsComboBox->addItem("Global Weights"); - mNodeContentsComboBox->addItem("Local Weights"); - mNodeContentsComboBox->addItem("Local Time"); - mNodeContentsComboBox->setCurrentIndex(0); - connect(mNodeContentsComboBox, static_cast(&QComboBox::currentIndexChanged), this, &TrackHeaderWidget::OnComboBoxIndexChanged); - comboLayout->addWidget(mNodeContentsComboBox); + m_nodeContentsComboBox = new QComboBox(); + m_nodeContentsComboBox->setEditable(false); + m_nodeContentsComboBox->addItem("Global Weights"); + m_nodeContentsComboBox->addItem("Local Weights"); + m_nodeContentsComboBox->addItem("Local Time"); + m_nodeContentsComboBox->setCurrentIndex(0); + connect(m_nodeContentsComboBox, static_cast(&QComboBox::currentIndexChanged), this, &TrackHeaderWidget::OnComboBoxIndexChanged); + comboLayout->addWidget(m_nodeContentsComboBox); contentsLayout->addLayout(comboLayout); comboLayout = new QHBoxLayout(); comboLayout->addWidget(new QLabel("Graph:")); - mGraphContentsComboBox = new QComboBox(); - mGraphContentsComboBox->setEditable(false); - mGraphContentsComboBox->addItem("Global Weights"); - mGraphContentsComboBox->addItem("Local Weights"); - mGraphContentsComboBox->addItem("Local Time"); - mGraphContentsComboBox->setCurrentIndex(0); - connect(mGraphContentsComboBox, static_cast(&QComboBox::currentIndexChanged), this, &TrackHeaderWidget::OnComboBoxIndexChanged); - comboLayout->addWidget(mGraphContentsComboBox); + m_graphContentsComboBox = new QComboBox(); + m_graphContentsComboBox->setEditable(false); + m_graphContentsComboBox->addItem("Global Weights"); + m_graphContentsComboBox->addItem("Local Weights"); + m_graphContentsComboBox->addItem("Local Time"); + m_graphContentsComboBox->setCurrentIndex(0); + connect(m_graphContentsComboBox, static_cast(&QComboBox::currentIndexChanged), this, &TrackHeaderWidget::OnComboBoxIndexChanged); + comboLayout->addWidget(m_graphContentsComboBox); contentsLayout->addLayout(comboLayout); - mStackWidget->Add(contentsWidget, "Contents", false, false, true); + m_stackWidget->Add(contentsWidget, "Contents", false, false, true); //----------- - mMainLayout->addWidget(mStackWidget); + m_mainLayout->addWidget(m_stackWidget); setFocusPolicy(Qt::StrongFocus); - setLayout(mMainLayout); + setLayout(m_mainLayout); ReInit(); } @@ -138,119 +138,119 @@ namespace EMStudio void TrackHeaderWidget::ReInit() { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); - if (mTrackWidget) + if (m_trackWidget) { - mTrackWidget->hide(); - mMainLayout->removeWidget(mTrackWidget); - mTrackWidget->deleteLater(); // TODO: this causes flickering, but normal deletion will make it crash + m_trackWidget->hide(); + m_mainLayout->removeWidget(m_trackWidget); + m_trackWidget->deleteLater(); // TODO: this causes flickering, but normal deletion will make it crash } - mTrackWidget = nullptr; + m_trackWidget = nullptr; // If we are in anim graph mode and have a recording, don't init for the motions. - if ((mPlugin->GetMode() != TimeViewMode::Motion) && - (EMotionFX::GetRecorder().GetIsRecording() || EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon || EMotionFX::GetRecorder().GetIsInPlayMode() || !mPlugin->mMotion)) + if ((m_plugin->GetMode() != TimeViewMode::Motion) && + (EMotionFX::GetRecorder().GetIsRecording() || EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon || EMotionFX::GetRecorder().GetIsInPlayMode() || !m_plugin->m_motion)) { - mAddTrackWidget->setVisible(false); + m_addTrackWidget->setVisible(false); setVisible(false); - if ((mPlugin->GetMode() != TimeViewMode::Motion) && + if ((m_plugin->GetMode() != TimeViewMode::Motion) && (EMotionFX::GetRecorder().GetIsRecording() || EMotionFX::GetRecorder().GetRecordTime() > MCore::Math::epsilon)) { - mStackWidget->setVisible(true); + m_stackWidget->setVisible(true); } else { - mStackWidget->setVisible(false); + m_stackWidget->setVisible(false); } return; } - mAddTrackWidget->setVisible(true); + m_addTrackWidget->setVisible(true); setVisible(true); - mStackWidget->setVisible(false); + m_stackWidget->setVisible(false); - const uint32 numTracks = mPlugin->mTracks.GetLength(); - if (numTracks == 0) + if (m_plugin->m_tracks.empty()) { return; } - mTrackWidget = new QWidget(); - mTrackLayout = new QVBoxLayout(); - mTrackLayout->setMargin(0); - mTrackLayout->setSpacing(1); + m_trackWidget = new QWidget(); + m_trackLayout = new QVBoxLayout(); + m_trackLayout->setMargin(0); + m_trackLayout->setSpacing(1); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = m_plugin->m_tracks.size(); + for (size_t i = 0; i < numTracks; ++i) { - TimeTrack* track = mPlugin->mTracks[i]; + TimeTrack* track = m_plugin->m_tracks[i]; if (track->GetIsVisible() == false) { continue; } - HeaderTrackWidget* widget = new HeaderTrackWidget(mTrackWidget, mPlugin, this, track, i); + HeaderTrackWidget* widget = new HeaderTrackWidget(m_trackWidget, m_plugin, this, track, i); connect(widget, &HeaderTrackWidget::TrackNameChanged, this, &TrackHeaderWidget::OnTrackNameChanged); connect(widget, &HeaderTrackWidget::EnabledStateChanged, this, &TrackHeaderWidget::OnTrackEnabledStateChanged); - mTrackLayout->addWidget(widget); + m_trackLayout->addWidget(widget); } - mTrackWidget->setLayout(mTrackLayout); - mMainLayout->addWidget(mTrackWidget); + m_trackWidget->setLayout(m_trackLayout); + m_mainLayout->addWidget(m_trackWidget); } - HeaderTrackWidget::HeaderTrackWidget(QWidget* parent, TimeViewPlugin* parentPlugin, TrackHeaderWidget* trackHeaderWidget, TimeTrack* timeTrack, uint32 trackIndex) + HeaderTrackWidget::HeaderTrackWidget(QWidget* parent, TimeViewPlugin* parentPlugin, TrackHeaderWidget* trackHeaderWidget, TimeTrack* timeTrack, size_t trackIndex) : QWidget(parent) { - mPlugin = parentPlugin; + m_plugin = parentPlugin; QHBoxLayout* mainLayout = new QHBoxLayout(); mainLayout->setMargin(0); mainLayout->setSpacing(0); - mHeaderTrackWidget = trackHeaderWidget; - mEnabledCheckbox = new QCheckBox(); - mNameLabel = new QLabel(timeTrack->GetName()); - mNameEdit = new QLineEdit(timeTrack->GetName()); - mTrack = timeTrack; - mTrackIndex = trackIndex; + m_headerTrackWidget = trackHeaderWidget; + m_enabledCheckbox = new QCheckBox(); + m_nameLabel = new QLabel(timeTrack->GetName()); + m_nameEdit = new QLineEdit(timeTrack->GetName()); + m_track = timeTrack; + m_trackIndex = trackIndex; - mNameEdit->setVisible(false); - mNameEdit->setFrame(false); + m_nameEdit->setVisible(false); + m_nameEdit->setFrame(false); - mEnabledCheckbox->setFixedWidth(36); - AzQtComponents::CheckBox::applyToggleSwitchStyle(mEnabledCheckbox); + m_enabledCheckbox->setFixedWidth(36); + AzQtComponents::CheckBox::applyToggleSwitchStyle(m_enabledCheckbox); if (timeTrack->GetIsEnabled()) { - mEnabledCheckbox->setCheckState(Qt::Checked); + m_enabledCheckbox->setCheckState(Qt::Checked); } else { - mNameEdit->setStyleSheet("background-color: rgb(70, 70, 70);"); - mEnabledCheckbox->setCheckState(Qt::Unchecked); + m_nameEdit->setStyleSheet("background-color: rgb(70, 70, 70);"); + m_enabledCheckbox->setCheckState(Qt::Unchecked); } if (timeTrack->GetIsDeletable() == false) { - mNameEdit->setReadOnly(true); - mEnabledCheckbox->setEnabled(false); + m_nameEdit->setReadOnly(true); + m_enabledCheckbox->setEnabled(false); } else { - mNameLabel->installEventFilter(this); + m_nameLabel->installEventFilter(this); } - connect(mNameEdit, &QLineEdit::editingFinished, this, &HeaderTrackWidget::NameChanged); - connect(mNameEdit, &QLineEdit::textEdited, this, &HeaderTrackWidget::NameEdited); - connect(mEnabledCheckbox, &QCheckBox::stateChanged, this, &HeaderTrackWidget::EnabledCheckBoxChanged); + connect(m_nameEdit, &QLineEdit::editingFinished, this, &HeaderTrackWidget::NameChanged); + connect(m_nameEdit, &QLineEdit::textEdited, this, &HeaderTrackWidget::NameEdited); + connect(m_enabledCheckbox, &QCheckBox::stateChanged, this, &HeaderTrackWidget::EnabledCheckBoxChanged); setContextMenuPolicy(Qt::CustomContextMenu); connect(this, &QWidget::customContextMenuRequested, this, [this](const QPoint& pos) @@ -258,20 +258,18 @@ namespace EMStudio QMenu m; auto action = m.addAction(tr("Remove track"), this, [=] { - mPlugin->GetTrackDataWidget()->RemoveTrack(mTrackIndex); + m_plugin->GetTrackDataWidget()->RemoveTrack(m_trackIndex); }); - action->setEnabled(mTrack->GetIsDeletable()); + action->setEnabled(m_track->GetIsDeletable()); m.exec(mapToGlobal(pos)); }); mainLayout->insertSpacing(0, 4); - mainLayout->addWidget(mNameLabel); - mainLayout->addWidget(mNameEdit); - mainLayout->addWidget(mEnabledCheckbox); + mainLayout->addWidget(m_nameLabel); + mainLayout->addWidget(m_nameEdit); + mainLayout->addWidget(m_enabledCheckbox); mainLayout->insertSpacing(5, 2); - //mainLayout->setAlignment(mEnabledCheckbox, Qt::AlignLeft); - setLayout(mainLayout); setMinimumHeight(20); @@ -280,12 +278,12 @@ namespace EMStudio bool HeaderTrackWidget::eventFilter(QObject* object, QEvent* event) { - if (object == mNameLabel && event->type() == QEvent::MouseButtonDblClick) + if (object == m_nameLabel && event->type() == QEvent::MouseButtonDblClick) { - mNameLabel->setVisible(false); - mNameEdit->setVisible(true); - mNameEdit->selectAll(); - mNameEdit->setFocus(); + m_nameLabel->setVisible(false); + m_nameEdit->setVisible(true); + m_nameEdit->selectAll(); + m_nameEdit->setFocus(); } return QWidget::eventFilter(object, event); } @@ -293,28 +291,28 @@ namespace EMStudio void HeaderTrackWidget::NameChanged() { MCORE_ASSERT(sender()->inherits("QLineEdit")); - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); QLineEdit* widget = qobject_cast(sender()); - mNameLabel->setVisible(true); - mNameEdit->setVisible(false); + m_nameLabel->setVisible(true); + m_nameEdit->setVisible(false); if (ValidateName()) { - mNameLabel->setText(widget->text()); - emit TrackNameChanged(widget->text(), mTrackIndex); + m_nameLabel->setText(widget->text()); + emit TrackNameChanged(widget->text(), m_trackIndex); } } bool HeaderTrackWidget::ValidateName() { - AZStd::string name = mNameEdit->text().toUtf8().data(); + AZStd::string name = m_nameEdit->text().toUtf8().data(); bool nameUnique = true; - const uint32 numTracks = mPlugin->GetNumTracks(); - for (uint32 i = 0; i < numTracks; ++i) + const size_t numTracks = m_plugin->GetNumTracks(); + for (size_t i = 0; i < numTracks; ++i) { - TimeTrack* track = mPlugin->GetTrack(i); + TimeTrack* track = m_plugin->GetTrack(i); - if (mTrack != track) + if (m_track != track) { if (name == track->GetName()) { @@ -331,21 +329,21 @@ namespace EMStudio void HeaderTrackWidget::NameEdited(const QString& text) { MCORE_UNUSED(text); - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); if (ValidateName() == false) { - GetManager()->SetWidgetAsInvalidInput(mNameEdit); + GetManager()->SetWidgetAsInvalidInput(m_nameEdit); } else { - mNameEdit->setStyleSheet(""); + m_nameEdit->setStyleSheet(""); } } void HeaderTrackWidget::EnabledCheckBoxChanged(int state) { - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); bool enabled = false; if (state == Qt::Checked) @@ -353,16 +351,16 @@ namespace EMStudio enabled = true; } - emit EnabledStateChanged(enabled, mTrackIndex); + emit EnabledStateChanged(enabled, m_trackIndex); } // propagate key events to the plugin and let it handle by a shared function void HeaderTrackWidget::keyPressEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyPressEvent(event); + m_plugin->OnKeyPressEvent(event); } } @@ -370,9 +368,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void HeaderTrackWidget::keyReleaseEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyReleaseEvent(event); + m_plugin->OnKeyReleaseEvent(event); } } @@ -380,9 +378,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TrackHeaderWidget::keyPressEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyPressEvent(event); + m_plugin->OnKeyPressEvent(event); } } @@ -390,9 +388,9 @@ namespace EMStudio // propagate key events to the plugin and let it handle by a shared function void TrackHeaderWidget::keyReleaseEvent(QKeyEvent* event) { - if (mPlugin) + if (m_plugin) { - mPlugin->OnKeyReleaseEvent(event); + m_plugin->OnKeyReleaseEvent(event); } } @@ -401,16 +399,16 @@ namespace EMStudio void TrackHeaderWidget::OnDetailedNodesCheckBox(int state) { MCORE_UNUSED(state); - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); - RecorderGroup* recorderGroup = mPlugin->GetTimeViewToolBar()->GetRecorderGroup(); + RecorderGroup* recorderGroup = m_plugin->GetTimeViewToolBar()->GetRecorderGroup(); if (!recorderGroup->GetDetailedNodes()) { - mPlugin->mTrackDataWidget->mNodeHistoryItemHeight = 20; + m_plugin->m_trackDataWidget->m_nodeHistoryItemHeight = 20; } else { - mPlugin->mTrackDataWidget->mNodeHistoryItemHeight = 35; + m_plugin->m_trackDataWidget->m_nodeHistoryItemHeight = 35; } } @@ -419,7 +417,7 @@ namespace EMStudio void TrackHeaderWidget::OnCheckBox(int state) { MCORE_UNUSED(state); - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); } @@ -427,6 +425,6 @@ namespace EMStudio void TrackHeaderWidget::OnComboBoxIndexChanged(int state) { MCORE_UNUSED(state); - mPlugin->SetRedrawFlag(); + m_plugin->SetRedrawFlag(); } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.h index ced87059a4..b794f248f6 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/TimeView/TrackHeaderWidget.h @@ -46,24 +46,24 @@ namespace EMStudio MCORE_MEMORYOBJECTCATEGORY(HeaderTrackWidget, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_STANDARDPLUGINS); public: - HeaderTrackWidget(QWidget* parent, TimeViewPlugin* parentPlugin, TrackHeaderWidget* trackHeaderWidget, TimeTrack* timeTrack, uint32 trackIndex); + HeaderTrackWidget(QWidget* parent, TimeViewPlugin* parentPlugin, TrackHeaderWidget* trackHeaderWidget, TimeTrack* timeTrack, size_t trackIndex); - QCheckBox* mEnabledCheckbox; - QLabel* mNameLabel; - QLineEdit* mNameEdit; - QPushButton* mRemoveButton; - TimeTrack* mTrack; - uint32 mTrackIndex; - TrackHeaderWidget* mHeaderTrackWidget; - TimeViewPlugin* mPlugin; + QCheckBox* m_enabledCheckbox; + QLabel* m_nameLabel; + QLineEdit* m_nameEdit; + QPushButton* m_removeButton; + TimeTrack* m_track; + size_t m_trackIndex; + TrackHeaderWidget* m_headerTrackWidget; + TimeViewPlugin* m_plugin; bool ValidateName(); bool eventFilter(QObject* object, QEvent* event) override; signals: - void TrackNameChanged(const QString& text, int trackNr); - void EnabledStateChanged(bool checked, int trackNr); + void TrackNameChanged(const QString& text, size_t trackNr); + void EnabledStateChanged(bool checked, size_t trackNr); public slots: void NameChanged(); @@ -93,28 +93,28 @@ namespace EMStudio void ReInit(); void UpdateDataContents(); - QWidget* GetAddTrackWidget() { return mAddTrackWidget; } + QWidget* GetAddTrackWidget() { return m_addTrackWidget; } public slots: void OnAddTrackButtonClicked() { CommandSystem::CommandAddEventTrack(); } - void OnTrackNameChanged(const QString& text, int trackNr) { CommandSystem::CommandRenameEventTrack(trackNr, FromQtString(text).c_str()); } - void OnTrackEnabledStateChanged(bool enabled, int trackNr) { CommandSystem::CommandEnableEventTrack(trackNr, enabled); } + void OnTrackNameChanged(const QString& text, size_t trackNr) { CommandSystem::CommandRenameEventTrack(trackNr, FromQtString(text).c_str()); } + void OnTrackEnabledStateChanged(bool enabled, size_t trackNr) { CommandSystem::CommandEnableEventTrack(trackNr, enabled); } void OnDetailedNodesCheckBox(int state); void OnCheckBox(int state); void OnComboBoxIndexChanged(int state); private: - TimeViewPlugin* mPlugin; - QVBoxLayout* mMainLayout; - QWidget* mTrackWidget; - QVBoxLayout* mTrackLayout; - QWidget* mAddTrackWidget; - QPushButton* mAddTrackButton; - MysticQt::DialogStack* mStackWidget; - QComboBox* mGraphContentsComboBox; - QComboBox* mNodeContentsComboBox; - QCheckBox* mNodeNamesCheckBox; - QCheckBox* mMotionFilesCheckBox; + TimeViewPlugin* m_plugin; + QVBoxLayout* m_mainLayout; + QWidget* m_trackWidget; + QVBoxLayout* m_trackLayout; + QWidget* m_addTrackWidget; + QPushButton* m_addTrackButton; + MysticQt::DialogStack* m_stackWidget; + QComboBox* m_graphContentsComboBox; + QComboBox* m_nodeContentsComboBox; + QCheckBox* m_nodeNamesCheckBox; + QCheckBox* m_motionFilesCheckBox; void keyPressEvent(QKeyEvent* event); void keyReleaseEvent(QKeyEvent* event); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/standardplugins_files.cmake b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/standardplugins_files.cmake index ae5a633c7f..65af4d50ee 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/standardplugins_files.cmake +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/standardplugins_files.cmake @@ -133,8 +133,6 @@ set(FILES Source/AnimGraph/ParameterEditor/Vector4ParameterEditor.h Source/CommandBar/CommandBarPlugin.cpp Source/CommandBar/CommandBarPlugin.h - Source/CommandBrowser/CommandBrowserPlugin.cpp - Source/CommandBrowser/CommandBrowserPlugin.h Source/LogWindow/LogWindowCallback.cpp Source/LogWindow/LogWindowCallback.h Source/LogWindow/LogWindowPlugin.cpp diff --git a/Gems/EMotionFX/Code/Editor/Platform/Windows/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter_Windows.cpp b/Gems/EMotionFX/Code/Editor/Platform/Windows/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter_Windows.cpp index 05bb9a5773..01ad023bd1 100644 --- a/Gems/EMotionFX/Code/Editor/Platform/Windows/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter_Windows.cpp +++ b/Gems/EMotionFX/Code/Editor/Platform/Windows/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindowEventFilter_Windows.cpp @@ -22,7 +22,7 @@ namespace EMStudio { // The reason why there are multiple of such messages is because it emits messages for all related hardware nodes. // But we do not know the name of the hardware to look for here either, so we can't filter that. - emit m_MainWindow->HardwareChangeDetected(); + emit m_mainWindow->HardwareChangeDetected(); } } diff --git a/Gems/EMotionFX/Code/Include/Integration/AnimGraphComponentBus.h b/Gems/EMotionFX/Code/Include/Integration/AnimGraphComponentBus.h index ac5c74fe7c..3ee0069efd 100644 --- a/Gems/EMotionFX/Code/Include/Integration/AnimGraphComponentBus.h +++ b/Gems/EMotionFX/Code/Include/Integration/AnimGraphComponentBus.h @@ -44,47 +44,47 @@ namespace EMotionFX /// Retrieving the index and using it to set parameter values is more performant than setting by name. /// \param parameterName - name of parameter for which to retrieve the index. /// \return parameter index - virtual AZ::u32 FindParameterIndex(const char* parameterName) = 0; + virtual size_t FindParameterIndex(const char* parameterName) = 0; /// Retrieve parameter name for a given parameter index. /// \param parameterName - index of parameter for which to retrieve the name. /// \return parameter name - virtual const char* FindParameterName(AZ::u32 parameterIndex) = 0; + virtual const char* FindParameterName(size_t parameterIndex) = 0; /// Updates a anim graph property given a float value. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterFloat(AZ::u32 parameterIndex, float value) = 0; + virtual void SetParameterFloat(size_t parameterIndex, float value) = 0; /// Updates a anim graph property given a boolean value. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterBool(AZ::u32 parameterIndex, bool value) = 0; + virtual void SetParameterBool(size_t parameterIndex, bool value) = 0; /// Updates a anim graph property given a string value. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterString(AZ::u32 parameterIndex, const char* value) = 0; + virtual void SetParameterString(size_t parameterIndex, const char* value) = 0; /// Updates a anim graph property given a Vector2 value. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterVector2(AZ::u32 parameterIndex, const AZ::Vector2& value) = 0; + virtual void SetParameterVector2(size_t parameterIndex, const AZ::Vector2& value) = 0; /// Updates a anim graph property given a Vector3 value. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterVector3(AZ::u32 parameterIndex, const AZ::Vector3& value) = 0; + virtual void SetParameterVector3(size_t parameterIndex, const AZ::Vector3& value) = 0; /// Updates a anim graph property given euler rotation values. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterRotationEuler(AZ::u32 parameterIndex, const AZ::Vector3& value) = 0; + virtual void SetParameterRotationEuler(size_t parameterIndex, const AZ::Vector3& value) = 0; /// Updates a anim graph property given a quaternion value. /// \param parameterIndex - index of parameter to set /// \param value - value to set - virtual void SetParameterRotation(AZ::u32 parameterIndex, const AZ::Quaternion& value) = 0; + virtual void SetParameterRotation(size_t parameterIndex, const AZ::Quaternion& value) = 0; /// Updates a anim graph property given a float value. @@ -127,31 +127,31 @@ namespace EMotionFX /// Retrieves a anim graph property as a float value. /// \param parameterIndex - index of parameter to set - virtual float GetParameterFloat(AZ::u32 parameterIndex) = 0; + virtual float GetParameterFloat(size_t parameterIndex) = 0; /// Retrieves a anim graph property as a boolean value. /// \param parameterIndex - index of parameter to set - virtual bool GetParameterBool(AZ::u32 parameterIndex) = 0; + virtual bool GetParameterBool(size_t parameterIndex) = 0; /// Retrieves a anim graph property given a string value. /// \param parameterIndex - index of parameter to set - virtual AZStd::string GetParameterString(AZ::u32 parameterIndex) = 0; + virtual AZStd::string GetParameterString(size_t parameterIndex) = 0; /// Retrieves a anim graph property as a Vector2 value. /// \param parameterIndex - index of parameter to set - virtual AZ::Vector2 GetParameterVector2(AZ::u32 parameterIndex) = 0; + virtual AZ::Vector2 GetParameterVector2(size_t parameterIndex) = 0; /// Retrieves a anim graph property as a Vector3 value. /// \param parameterIndex - index of parameter to set - virtual AZ::Vector3 GetParameterVector3(AZ::u32 parameterIndex) = 0; + virtual AZ::Vector3 GetParameterVector3(size_t parameterIndex) = 0; /// Retrieves a anim graph property given as euler rotation values. /// \param parameterIndex - index of parameter to set - virtual AZ::Vector3 GetParameterRotationEuler(AZ::u32 parameterIndex) = 0; + virtual AZ::Vector3 GetParameterRotationEuler(size_t parameterIndex) = 0; /// Retrieves a anim graph property as a quaternion value. /// \param parameterIndex - index of parameter to set - virtual AZ::Quaternion GetParameterRotation(AZ::u32 parameterIndex) = 0; + virtual AZ::Quaternion GetParameterRotation(size_t parameterIndex) = 0; /// Retrieves a anim graph property as a float value. /// \param parameterName - name of parameter to get @@ -241,42 +241,42 @@ namespace EMotionFX /// \param parameterIndex - index of changed parameter /// \param beforeValue - value before the change /// \param afterValue - value after the change - virtual void OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] AZ::u32 parameterIndex, [[maybe_unused]] float beforeValue, [[maybe_unused]] float afterValue) {}; + virtual void OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] size_t parameterIndex, [[maybe_unused]] float beforeValue, [[maybe_unused]] float afterValue) {}; /// Notifies listeners when a bool parameter changes /// \param animGraphInstance - pointer to anim graph instance /// \param parameterIndex - index of changed parameter /// \param beforeValue - value before the change /// \param afterValue - value after the change - virtual void OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] AZ::u32 parameterIndex, [[maybe_unused]] bool beforeValue, [[maybe_unused]] bool afterValue) {}; + virtual void OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] size_t parameterIndex, [[maybe_unused]] bool beforeValue, [[maybe_unused]] bool afterValue) {}; /// Notifies listeners when a string parameter changes /// \param animGraphInstance - pointer to anim graph instance /// \param parameterIndex - index of changed parameter /// \param beforeValue - value before the change /// \param afterValue - value after the change - virtual void OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] AZ::u32 parameterIndex, [[maybe_unused]] const char* beforeValue, [[maybe_unused]] const char* afterValue) {}; + virtual void OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] size_t parameterIndex, [[maybe_unused]] const char* beforeValue, [[maybe_unused]] const char* afterValue) {}; /// Notifies listeners when a vector2 parameter changes /// \param animGraphInstance - pointer to anim graph instance /// \param parameterIndex - index of changed parameter /// \param beforeValue - value before the change /// \param afterValue - value after the change - virtual void OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] AZ::u32 parameterIndex, [[maybe_unused]] const AZ::Vector2& beforeValue, [[maybe_unused]] const AZ::Vector2& afterValue) {}; + virtual void OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] size_t parameterIndex, [[maybe_unused]] const AZ::Vector2& beforeValue, [[maybe_unused]] const AZ::Vector2& afterValue) {}; /// Notifies listeners when a vector3 parameter changes /// \param animGraphInstance - pointer to anim graph instance /// \param parameterIndex - index of changed parameter /// \param beforeValue - value before the change /// \param afterValue - value after the change - virtual void OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] AZ::u32 parameterIndex, [[maybe_unused]] const AZ::Vector3& beforeValue, [[maybe_unused]] const AZ::Vector3& afterValue) {}; + virtual void OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] size_t parameterIndex, [[maybe_unused]] const AZ::Vector3& beforeValue, [[maybe_unused]] const AZ::Vector3& afterValue) {}; /// Notifies listeners when a rotation parameter changes /// \param animGraphInstance - pointer to anim graph instance /// \param parameterIndex - index of changed parameter /// \param beforeValue - value before the change /// \param afterValue - value after the change - virtual void OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] AZ::u32 parameterIndex, [[maybe_unused]] const AZ::Quaternion& beforeValue, [[maybe_unused]] const AZ::Quaternion& afterValue) {}; + virtual void OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance* /*animGraphInstance*/, [[maybe_unused]] size_t parameterIndex, [[maybe_unused]] const AZ::Quaternion& beforeValue, [[maybe_unused]] const AZ::Quaternion& afterValue) {}; /// Notifies listeners when an another anim graph trying to sync this graph /// \param animGraphInstance - pointer to the follower anim graph instance diff --git a/Gems/EMotionFX/Code/MCore/Source/AABB.h b/Gems/EMotionFX/Code/MCore/Source/AABB.h index 04df59f453..3e6af3bc96 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AABB.h +++ b/Gems/EMotionFX/Code/MCore/Source/AABB.h @@ -38,8 +38,8 @@ namespace MCore * @param maxPnt The maximum point. */ MCORE_INLINE AABB(const AZ::Vector3& minPnt, const AZ::Vector3& maxPnt) - : mMin(minPnt) - , mMax(maxPnt) {} + : m_min(minPnt) + , m_max(maxPnt) {} /** * Initialize the box minimum and maximum points. @@ -47,7 +47,7 @@ namespace MCore * Note, that the default constructor already calls this method. So you should only call it when you want to 'reset' the minimum and * maximum points of the box. */ - MCORE_INLINE void Init() { mMin.Set(FLT_MAX, FLT_MAX, FLT_MAX); mMax.Set(-FLT_MAX, -FLT_MAX, -FLT_MAX); } + MCORE_INLINE void Init() { m_min.Set(FLT_MAX, FLT_MAX, FLT_MAX); m_max.Set(-FLT_MAX, -FLT_MAX, -FLT_MAX); } /** * Check if this is a valid AABB or not. @@ -56,15 +56,15 @@ namespace MCore */ MCORE_INLINE bool CheckIfIsValid() const { - if (mMin.GetX() > mMax.GetX()) + if (m_min.GetX() > m_max.GetX()) { return false; } - if (mMin.GetY() > mMax.GetY()) + if (m_min.GetY() > m_max.GetY()) { return false; } - if (mMin.GetZ() > mMax.GetZ()) + if (m_min.GetZ() > m_max.GetZ()) { return false; } @@ -83,7 +83,7 @@ namespace MCore * This method automatically adjusts the minimum and maximum point of the box after 'adding' the given AABB to this box. * @param box The AABB to 'add' to this box. */ - MCORE_INLINE void Encapsulate(const AABB& box) { Encapsulate(box.mMin); Encapsulate(box.mMax); } + MCORE_INLINE void Encapsulate(const AABB& box) { Encapsulate(box.m_min); Encapsulate(box.m_max); } /** * Widen the box in all dimensions with a given number of units. @@ -91,12 +91,12 @@ namespace MCore */ MCORE_INLINE void Widen(float delta) { - mMin.SetX(mMin.GetX() - delta); - mMin.SetY(mMin.GetY() - delta); - mMin.SetZ(mMin.GetZ() - delta); - mMax.SetX(mMax.GetX() + delta); - mMax.SetY(mMax.GetY() + delta); - mMax.SetZ(mMax.GetZ() + delta); + m_min.SetX(m_min.GetX() - delta); + m_min.SetY(m_min.GetY() - delta); + m_min.SetZ(m_min.GetZ() - delta); + m_max.SetX(m_max.GetX() + delta); + m_max.SetY(m_max.GetY() + delta); + m_max.SetZ(m_max.GetZ() + delta); } /** @@ -104,7 +104,7 @@ namespace MCore * This means the middle of the box will be moved by the given vector. * @param offset The offset vector to translate (move) the box with. */ - MCORE_INLINE void Translate(const AZ::Vector3& offset) { mMin += offset; mMax += offset; } + MCORE_INLINE void Translate(const AZ::Vector3& offset) { m_min += offset; m_max += offset; } /** * Checks if a given point is inside this box or not. @@ -112,7 +112,7 @@ namespace MCore * @param v The vector (3D point) to perform the test with. * @result Returns true when the given point is inside the box, otherwise false is returned. */ - MCORE_INLINE bool Contains(const AZ::Vector3& v) const { return (InRange(v.GetX(), mMin.GetX(), mMax.GetX()) && InRange(v.GetZ(), mMin.GetZ(), mMax.GetZ()) && InRange(v.GetY(), mMin.GetY(), mMax.GetY())); } + MCORE_INLINE bool Contains(const AZ::Vector3& v) const { return (InRange(v.GetX(), m_min.GetX(), m_max.GetX()) && InRange(v.GetZ(), m_min.GetZ(), m_max.GetZ()) && InRange(v.GetY(), m_min.GetY(), m_max.GetY())); } /** * Checks if a given AABB is COMPLETELY inside this box or not. @@ -120,7 +120,7 @@ namespace MCore * @param box The AABB to perform the test with. * @result Returns true when the AABB 'b' is COMPLETELY inside this box. If it's completely or partially outside, false will be returned. */ - MCORE_INLINE bool Contains(const AABB& box) const { return (Contains(box.mMin) && Contains(box.mMax)); } + MCORE_INLINE bool Contains(const AABB& box) const { return (Contains(box.m_min) && Contains(box.m_max)); } /** * Checks if a given AABB partially or completely contains, so intersects, this box or not. @@ -128,35 +128,35 @@ namespace MCore * @param box The AABB to perform the test with. * @result Returns true when the given AABB 'b' is completely or partially inside this box. Only false will be returned when the given AABB 'b' is COMPLETELY outside this box. */ - MCORE_INLINE bool Intersects(const AABB& box) const { return !(mMin.GetX() > box.mMax.GetX() || mMax.GetX() < box.mMin.GetX() || mMin.GetY() > box.mMax.GetY() || mMax.GetY() < box.mMin.GetY() || mMin.GetZ() > box.mMax.GetZ() || mMax.GetZ() < box.mMin.GetZ()); } + MCORE_INLINE bool Intersects(const AABB& box) const { return !(m_min.GetX() > box.m_max.GetX() || m_max.GetX() < box.m_min.GetX() || m_min.GetY() > box.m_max.GetY() || m_max.GetY() < box.m_min.GetY() || m_min.GetZ() > box.m_max.GetZ() || m_max.GetZ() < box.m_min.GetZ()); } /** * Calculates and returns the width of the box. * The width is the distance between the minimum and maximum point, along the X-axis. * @result The width of the box. */ - MCORE_INLINE float CalcWidth() const { return mMax.GetX() - mMin.GetX(); } + MCORE_INLINE float CalcWidth() const { return m_max.GetX() - m_min.GetX(); } /** * Calculates and returns the height of the box. * The height is the distance between the minimum and maximum point, along the Z-axis. * @result The height of the box. */ - MCORE_INLINE float CalcHeight() const { return mMax.GetZ() - mMin.GetZ(); } + MCORE_INLINE float CalcHeight() const { return m_max.GetZ() - m_min.GetZ(); } /** * Calculates and returns the depth of the box. * The depth is the distance between the minimum and maximum point, along the Y-axis. * @result The depth of the box. */ - MCORE_INLINE float CalcDepth() const { return mMax.GetY() - mMin.GetY(); } + MCORE_INLINE float CalcDepth() const { return m_max.GetY() - m_min.GetY(); } /** * Calculate the volume of the box. * This equals width x height x depth. * @result The volume of the box. */ - MCORE_INLINE float CalcVolume() const { return (mMax.GetX() - mMin.GetX()) * (mMax.GetY() - mMin.GetY()) * (mMax.GetZ() - mMin.GetZ()); } + MCORE_INLINE float CalcVolume() const { return (m_max.GetX() - m_min.GetX()) * (m_max.GetY() - m_min.GetY()) * (m_max.GetZ() - m_min.GetZ()); } /** * Calculate the surface area of the box. @@ -164,9 +164,9 @@ namespace MCore */ MCORE_INLINE float CalcSurfaceArea() const { - const float width = mMax.GetX() - mMin.GetX(); - const float height = mMax.GetY() - mMin.GetY(); - const float depth = mMax.GetZ() - mMin.GetZ(); + const float width = m_max.GetX() - m_min.GetX(); + const float height = m_max.GetY() - m_min.GetY(); + const float depth = m_max.GetZ() - m_min.GetZ(); return (2.0f * height * width) + (2.0f * height * depth) + (2.0f * width * depth); } @@ -175,14 +175,14 @@ namespace MCore * This is simply done by taking the average of the minimum and maximum point along each axis. * @result The center (or middle) point of this box. */ - MCORE_INLINE AZ::Vector3 CalcMiddle() const { return (mMin + mMax) * 0.5f; } + MCORE_INLINE AZ::Vector3 CalcMiddle() const { return (m_min + m_max) * 0.5f; } /** * Calculates the extents of the box. * This is the vector from the center to a corner of the box. * @result The vector containing the extents. */ - MCORE_INLINE AZ::Vector3 CalcExtents() const { return (mMax - mMin) * 0.5f; } + MCORE_INLINE AZ::Vector3 CalcExtents() const { return (m_max - m_min) * 0.5f; } /** * Calculates the radius of this box. @@ -191,60 +191,60 @@ namespace MCore * get the minimum sphere which exactly contains this box. * @result The length of the center of the box to one of the extreme points. So the minimum radius of the bounding sphere containing this box. */ - MCORE_INLINE float CalcRadius() const { return SafeLength(mMax - mMin) * 0.5f; } + MCORE_INLINE float CalcRadius() const { return SafeLength(m_max - m_min) * 0.5f; } /** * Get the minimum point of the box. * @result The minimum point of the box. */ - MCORE_INLINE const AZ::Vector3& GetMin() const { return mMin; } + MCORE_INLINE const AZ::Vector3& GetMin() const { return m_min; } /** * Get the maximum point of the box. * @result The maximum point of the box. */ - MCORE_INLINE const AZ::Vector3& GetMax() const { return mMax; } + MCORE_INLINE const AZ::Vector3& GetMax() const { return m_max; } /** * Set the minimum point of the box. * @param minVec The vector representing the minimum point of the box. */ - MCORE_INLINE void SetMin(const AZ::Vector3& minVec) { mMin = minVec; } + MCORE_INLINE void SetMin(const AZ::Vector3& minVec) { m_min = minVec; } /** * Set the maximum point of the box. * @param maxVec The vector representing the maximum point of the box. */ - MCORE_INLINE void SetMax(const AZ::Vector3& maxVec) { mMax = maxVec; } + MCORE_INLINE void SetMax(const AZ::Vector3& maxVec) { m_max = maxVec; } void CalcCornerPoints(AZ::Vector3* outPoints) const { - outPoints[0].Set(mMin.GetX(), mMin.GetY(), mMax.GetZ()); // 4-------------5 - outPoints[1].Set(mMax.GetX(), mMin.GetY(), mMax.GetZ()); // /| / | - outPoints[2].Set(mMax.GetX(), mMin.GetY(), mMin.GetZ()); // 0------------1 | - outPoints[3].Set(mMin.GetX(), mMin.GetY(), mMin.GetZ()); // | | | | - outPoints[4].Set(mMin.GetX(), mMax.GetY(), mMax.GetZ()); // | 7----------|--6 - outPoints[5].Set(mMax.GetX(), mMax.GetY(), mMax.GetZ()); // | / | / - outPoints[6].Set(mMax.GetX(), mMax.GetY(), mMin.GetZ()); // |/ |/ - outPoints[7].Set(mMin.GetX(), mMax.GetY(), mMin.GetZ()); // 3------------2 + outPoints[0].Set(m_min.GetX(), m_min.GetY(), m_max.GetZ()); // 4-------------5 + outPoints[1].Set(m_max.GetX(), m_min.GetY(), m_max.GetZ()); // /| / | + outPoints[2].Set(m_max.GetX(), m_min.GetY(), m_min.GetZ()); // 0------------1 | + outPoints[3].Set(m_min.GetX(), m_min.GetY(), m_min.GetZ()); // | | | | + outPoints[4].Set(m_min.GetX(), m_max.GetY(), m_max.GetZ()); // | 7----------|--6 + outPoints[5].Set(m_max.GetX(), m_max.GetY(), m_max.GetZ()); // | / | / + outPoints[6].Set(m_max.GetX(), m_max.GetY(), m_min.GetZ()); // |/ |/ + outPoints[7].Set(m_min.GetX(), m_max.GetY(), m_min.GetZ()); // 3------------2 } private: - AZ::Vector3 mMin; /**< The minimum point. */ - AZ::Vector3 mMax; /**< The maximum point. */ + AZ::Vector3 m_min; /**< The minimum point. */ + AZ::Vector3 m_max; /**< The maximum point. */ }; // encapsulate a point in the box MCORE_INLINE void AABB::Encapsulate(const AZ::Vector3& v) { - mMin.SetX(Min(mMin.GetX(), v.GetX())); - mMin.SetY(Min(mMin.GetY(), v.GetY())); - mMin.SetZ(Min(mMin.GetZ(), v.GetZ())); + m_min.SetX(Min(m_min.GetX(), v.GetX())); + m_min.SetY(Min(m_min.GetY(), v.GetY())); + m_min.SetZ(Min(m_min.GetZ(), v.GetZ())); - mMax.SetX(Max(mMax.GetX(), v.GetX())); - mMax.SetY(Max(mMax.GetY(), v.GetY())); - mMax.SetZ(Max(mMax.GetZ(), v.GetZ())); + m_max.SetX(Max(m_max.GetX(), v.GetX())); + m_max.SetY(Max(m_max.GetY(), v.GetY())); + m_max.SetZ(Max(m_max.GetZ(), v.GetZ())); } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AbstractData.h b/Gems/EMotionFX/Code/MCore/Source/AbstractData.h deleted file mode 100644 index c11173f99a..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/AbstractData.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -// include required headers -#include "StandardHeaders.h" - - -namespace MCore -{ - /** - * The abstract data class, which represents a continuous block of memory. - * Anything can be stored inside this piece of memory. - */ - class MCORE_API AbstractData - { - public: - AbstractData() - : mData(nullptr) - , mNumBytes(0) - , mMaxNumBytes(0) { } - AbstractData(uint32 numBytes) - : mData(nullptr) - , mNumBytes(0) - , mMaxNumBytes(0) { Resize(numBytes); } - AbstractData(void* data, uint32 numBytes) - : mData(nullptr) - , mNumBytes(0) - , mMaxNumBytes(0) { InitFrom(data, numBytes); } - AbstractData(const AbstractData& other) - : mData(nullptr) - , mNumBytes(0) - , mMaxNumBytes(0) { InitFrom(other.GetPointer(), other.GetNumBytes()); } - ~AbstractData() { Release(); } - - void Release() { MCore::Free(mData); mData = nullptr; mNumBytes = 0; mMaxNumBytes = 0; } - void Clear() { mNumBytes = 0; } - void Resize(uint32 numBytes) - { - // if we need to empty it - if (numBytes == 0) - { - mNumBytes = 0; - return; - } - - //Release(); - if (mMaxNumBytes < numBytes) - { - mData = MCore::Realloc(mData, numBytes, MCORE_MEMCATEGORY_ABSTRACTDATA); - mNumBytes = numBytes; - mMaxNumBytes = numBytes; - } - else - { - mNumBytes = numBytes; - } - } - - void Reserve(uint32 numBytes) - { - if (mMaxNumBytes < numBytes) - { - mData = MCore::Realloc(mData, numBytes, MCORE_MEMCATEGORY_ABSTRACTDATA); - mMaxNumBytes = numBytes; - } - } - - void Shrink() - { - if (mMaxNumBytes > mNumBytes) - { - mData = MCore::Realloc(mData, mNumBytes, MCORE_MEMCATEGORY_ABSTRACTDATA); - mMaxNumBytes = mNumBytes; - } - } - - MCORE_INLINE void* GetPointer() const { return mData; } - MCORE_INLINE void* GetPointer() { return mData; } - MCORE_INLINE void CopyDataFrom(const void* data) { MCORE_ASSERT(mData); MCore::MemCopy(mData, data, mNumBytes); } - MCORE_INLINE void InitFrom(const void* data, uint32 numBytes) - { - Resize(numBytes); - if (numBytes == 0) - { - return; - } - MCORE_ASSERT(mData); - MCore::MemCopy(mData, data, mNumBytes); - } - MCORE_INLINE uint32 GetNumBytes() const { return mNumBytes; } - MCORE_INLINE uint32 GetMaxNumBytes() const { return mMaxNumBytes; } - - MCORE_INLINE const AbstractData& operator=(const AbstractData& other) { InitFrom(other.GetPointer(), other.GetNumBytes()); return *this; } - - private: - void* mData; - uint32 mNumBytes; - uint32 mMaxNumBytes; - }; -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Algorithms.cpp b/Gems/EMotionFX/Code/MCore/Source/Algorithms.cpp index d1a4e6b30e..dd82385092 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Algorithms.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Algorithms.cpp @@ -253,10 +253,10 @@ namespace MCore // check if a given point is inside a 2d convex/concave polygon // it does this by checking how many times a line intersects with the poly (how many times it goes inside and outside again) - bool PointInPoly(AZ::Vector2* verts, uint32 numVerts, const AZ::Vector2& point) + bool PointInPoly(AZ::Vector2* verts, size_t numVerts, const AZ::Vector2& point) { - uint32 c = 0; - for (uint32 i = 0, j = numVerts - 1; i < numVerts; j = i++) + bool c = false; + for (size_t i = 0, j = numVerts - 1; i < numVerts; j = i++) { if (((verts[i].GetY() > point.GetY()) != (verts[j].GetY() > point.GetY())) && (point.GetX() < (verts[j].GetX() - verts[i].GetX()) * (point.GetY() - verts[i].GetY()) / (verts[j].GetY() - verts[i].GetY()) + verts[i].GetX())) { @@ -264,7 +264,7 @@ namespace MCore } } - return (c > 0); + return c; } @@ -291,11 +291,11 @@ namespace MCore // check if the test point is inside the polygon - AZ::Vector2 ClosestPointToPoly(const AZ::Vector2* polyPoints, uint32 numPoints, const AZ::Vector2& testPoint) + AZ::Vector2 ClosestPointToPoly(const AZ::Vector2* polyPoints, size_t numPoints, const AZ::Vector2& testPoint) { AZ::Vector2 result; float closestDist = FLT_MAX; - for (uint32 i = 0; i < numPoints; ++i) + for (size_t i = 0; i < numPoints; ++i) { AZ::Vector2 edgePointA; AZ::Vector2 edgePointB; @@ -336,85 +336,4 @@ namespace MCore return result; } - - - // static CRC lookup table - /*static uint32 CRC32Table[256] = - { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, - 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, - 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, - 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, - 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, - 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, - 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, - 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, - 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, - 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, - 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, - 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, - 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, - 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, - 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, - 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, - 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, - 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, - 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, - 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, - 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, - 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, - 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, - 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, - 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, - }; - - - - // calculate the CRC32 - void CalcCRC32(uint8 byteValue, uint32& CRC) - { - CRC = ((CRC) >> 8) ^ MCore::CRC32Table[(byteValue) ^ ((CRC) & 0x000000FF)]; - }*/ } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Algorithms.h b/Gems/EMotionFX/Code/MCore/Source/Algorithms.h index 2776614087..c67ad950de 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Algorithms.h +++ b/Gems/EMotionFX/Code/MCore/Source/Algorithms.h @@ -58,24 +58,11 @@ namespace MCore AZ::Vector3 MCORE_API StereographicUnproject(const AZ::Vector2& uv); // - bool MCORE_API PointInPoly(AZ::Vector2* verts, uint32 numVerts, const AZ::Vector2& point); + bool MCORE_API PointInPoly(AZ::Vector2* verts, size_t numVerts, const AZ::Vector2& point); float MCORE_API DistanceToEdge(const AZ::Vector2& edgePointA, const AZ::Vector2& edgePointB, const AZ::Vector2& testPoint); - AZ::Vector2 MCORE_API ClosestPointToPoly(const AZ::Vector2* polyPoints, uint32 numPoints, const AZ::Vector2& testPoint); + AZ::Vector2 MCORE_API ClosestPointToPoly(const AZ::Vector2* polyPoints, size_t numPoints, const AZ::Vector2& testPoint); - /** - * Calculates the CRC value of a given byte. - * It inputs and modifies the current CRC value passed as parameter. - * @param byteValue The byte value to generate the CRC for. - * @param CRC The CRC value to modify. - * - * The calculation performed is: - *
-     * CRC = ((CRC) >> 8) ^ MCore::CRC32Table[(byteValue) ^ ((CRC) & 0x000000FF)];
-     * 
- */ - //void MCORE_API CalcCRC32(uint8 byteValue, uint32& CRC); - /** * Calculate the cube root, which basically is pow(x, 1/3). * This also allows negative and zero values. diff --git a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h index 00663ffca9..5ffaac2e40 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h +++ b/Gems/EMotionFX/Code/MCore/Source/AlignedArray.h @@ -19,7 +19,7 @@ namespace MCore /** * Dynamic array template, using aligned memory allocations. * This array template allows dynamic sizing. It also stores the memory category of the data. - * It can theoretically store 4294967296 items (maximum uint32 value). + * It can theoretically store 18446744073709551614 items (maximum size_t value - 1 for the invalid index). */ template class AlignedArray @@ -40,10 +40,10 @@ namespace MCore * Initializes the array so it's empty and has no memory allocated. */ MCORE_INLINE AlignedArray() - : mData(nullptr) - , mLength(0) - , mMaxLength(0) - , mMemCategory(MCORE_MEMCATEGORY_ARRAY) {} + : m_data(nullptr) + , m_length(0) + , m_maxLength(0) + , m_memCategory(MCORE_MEMCATEGORY_ARRAY) {} /** * Constructor which creates a given number of elements. @@ -51,13 +51,13 @@ namespace MCore * @param num The number of elements in 'elems'. * @param memCategory The memory category the array is in. */ - MCORE_INLINE explicit AlignedArray(T* elems, uint32 num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : mLength(num) - , mMaxLength(AllocSize(num)) - , mMemCategory(memCategory) + MCORE_INLINE explicit AlignedArray(T* elems, size_t num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) + : m_length(num) + , m_maxLength(AllocSize(num)) + , m_memCategory(memCategory) { - mData = (T*)AlignedAllocate(mMaxLength * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - for (uint32 i = 0; i < mLength; ++i) + m_data = (T*)AlignedAllocate(m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); + for (size_t i = 0; i < m_length; ++i) { Construct(i, elems[i]); } @@ -68,16 +68,16 @@ namespace MCore * @param initSize The number of ellements to allocate space for. * @param memCategory The memory category the array is in. */ - MCORE_INLINE explicit AlignedArray(uint32 initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : mData(nullptr) - , mLength(initSize) - , mMaxLength(initSize) - , mMemCategory(memCategory) + MCORE_INLINE explicit AlignedArray(size_t initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) + : m_data(nullptr) + , m_length(initSize) + , m_maxLength(initSize) + , m_memCategory(memCategory) { - if (mMaxLength > 0) + if (m_maxLength > 0) { - mData = (T*)AlignedAllocate(mMaxLength * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - for (uint32 i = 0; i < mLength; ++i) + m_data = (T*)AlignedAllocate(m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); + for (size_t i = 0; i < m_length; ++i) { Construct(i); } @@ -89,16 +89,16 @@ namespace MCore * @param other The other array to copy the data from. */ AlignedArray(const AlignedArray& other) - : mData(nullptr) - , mLength(0) - , mMaxLength(0) - , mMemCategory(MCORE_MEMCATEGORY_ARRAY) { *this = other; } + : m_data(nullptr) + , m_length(0) + , m_maxLength(0) + , m_memCategory(MCORE_MEMCATEGORY_ARRAY) { *this = other; } /** * Move constructor. * @param other The array to move the data from. */ - AlignedArray(AlignedArray&& other) { mData = other.mData; mLength = other.mLength; mMaxLength = other.mMaxLength; mMemCategory = other.mMemCategory; other.mData = nullptr; other.mLength = 0; other.mMaxLength = 0; } + AlignedArray(AlignedArray&& other) { m_data = other.m_data; m_length = other.m_length; m_maxLength = other.m_maxLength; m_memCategory = other.m_memCategory; other.m_data = nullptr; other.m_length = 0; other.m_maxLength = 0; } /** * Destructor. Deletes all entry data. @@ -106,26 +106,26 @@ namespace MCore * Example:
*
          * AlignedArray< Object*, 16 > data;
-         * for (uint32 i=0; i<10; i++)
+         * for (size_t i=0; i<10; i++)
          *    data.Add( new Object() );
          * 
* Now when the array 'data' will be destructed, it will NOT free up the memory of the integers which you allocated by hand, using new. * In order to free up this memory, you can do this: *
-         * for (uint32 i=0; i
          */
         ~AlignedArray()
         {
-            for (uint32 i = 0; i < mLength; ++i)
+            for (size_t i = 0; i < m_length; ++i)
             {
                 Destruct(i);
             }
-            if (mData)
+            if (m_data)
             {
-                AlignedFree(mData);
+                AlignedFree(m_data);
             }
         }
 
@@ -134,89 +134,89 @@ namespace MCore
          * On default the memory category is 0, which means unknown.
          * @result The memory category ID.
          */
-        MCORE_INLINE uint16 GetMemoryCategory() const                           { return mMemCategory; }
+        MCORE_INLINE uint16 GetMemoryCategory() const                           { return m_memCategory; }
 
         /**
          * Set the memory category ID, where allocations made by this array will belong to.
          * On default, after construction of the array, the category ID is 0, which means it is unknown.
          * @param categoryID The memory category ID where this arrays allocations belong to.
          */
-        MCORE_INLINE void SetMemoryCategory(uint16 categoryID)                  { mMemCategory = categoryID; }
+        MCORE_INLINE void SetMemoryCategory(uint16 categoryID)                  { m_memCategory = categoryID; }
 
         /**
          * Get a pointer to the first element.
          * @result A pointer to the first element.
          */
-        MCORE_INLINE T* GetPtr()                                                { return mData; }
+        MCORE_INLINE T* GetPtr()                                                { return m_data; }
 
         /**
          * Get a pointer to the first element.
          * @result A pointer to the first element.
          */
-        MCORE_INLINE T* GetPtr() const                                          { return mData; }
+        MCORE_INLINE T* GetPtr() const                                          { return m_data; }
 
         /**
          * Get a given item/element.
          * @param pos The item/element number.
          * @result A reference to the element.
          */
-        MCORE_INLINE T& GetItem(uint32 pos)                                     { return mData[pos]; }
+        MCORE_INLINE T& GetItem(size_t pos)                                     { return m_data[pos]; }
 
         /**
          * Get the first element.
          * @result A reference to the first element.
          */
-        MCORE_INLINE T& GetFirst()                                              { return mData[0]; }
+        MCORE_INLINE T& GetFirst()                                              { return m_data[0]; }
 
         /**
          * Get the last element.
          * @result A reference to the last element.
          */
-        MCORE_INLINE T& GetLast()                                               { return mData[mLength - 1]; }
+        MCORE_INLINE T& GetLast()                                               { return m_data[m_length - 1]; }
 
         /**
          * Get a read-only pointer to the first element.
          * @result A read-only pointer to the first element.
          */
-        MCORE_INLINE const T* GetReadPtr() const                                { return mData; }
+        MCORE_INLINE const T* GetReadPtr() const                                { return m_data; }
 
         /**
          * Get a read-only reference to a given element number.
          * @param pos The element number.
          * @result A read-only reference to the given element.
          */
-        MCORE_INLINE const T& GetItem(uint32 pos) const                         { return mData[pos]; }
+        MCORE_INLINE const T& GetItem(size_t pos) const                         { return m_data[pos]; }
 
         /**
          * Get a read-only reference to the first element.
          * @result A read-only reference to the first element.
          */
-        MCORE_INLINE const T& GetFirst() const                                  { return mData[0]; }
+        MCORE_INLINE const T& GetFirst() const                                  { return m_data[0]; }
 
         /**
          * Get a read-only reference to the last element.
          * @result A read-only reference to the last element.
          */
-        MCORE_INLINE const T& GetLast() const                                   { return mData[mLength - 1]; }
+        MCORE_INLINE const T& GetLast() const                                   { return m_data[m_length - 1]; }
 
         /**
          * Check if the array is empty or not.
          * @result Returns true when there are no elements in the array, otherwise false is returned.
          */
-        MCORE_INLINE bool GetIsEmpty() const                                    { return (mLength == 0); }
+        MCORE_INLINE bool GetIsEmpty() const                                    { return (m_length == 0); }
 
         /**
          * Checks if the passed index is in the array's range.
          * @param index The index to check.
          * @return True if the passed index is valid, false if not.
          */
-        MCORE_INLINE bool GetIsValidIndex(uint32 index) const                   { return (index < mLength); }
+        MCORE_INLINE bool GetIsValidIndex(size_t index) const                   { return (index < m_length); }
 
         /**
          * Get the number of elements in the array.
          * @result The number of elements in the array.
          */
-        MCORE_INLINE uint32 GetLength() const                                   { return mLength; }
+        MCORE_INLINE size_t GetLength() const                                   { return m_length; }
 
         /**
          * Get the maximum number of elements. This is the number of elements there currently is space for to store.
@@ -224,16 +224,16 @@ namespace MCore
          * This purely has to do with pre-allocating, to reduce the number of reallocs.
          * @result The maximum array length.
          */
-        MCORE_INLINE uint32 GetMaxLength() const                                { return mMaxLength; }
+        MCORE_INLINE size_t GetMaxLength() const                                { return m_maxLength; }
 
         /**
          * Calculates the memory usage used by this array.
          * @param includeMembers Include the class members in the calculation? (default=true).
          * @result The number of bytes allocated by this array.
          */
-        MCORE_INLINE uint32 CalcMemoryUsage(bool includeMembers = true) const
+        MCORE_INLINE size_t CalcMemoryUsage(bool includeMembers = true) const
         {
-            uint32 result = mMaxLength * sizeof(T);
+            size_t result = m_maxLength * sizeof(T);
             if (includeMembers)
             {
                 result += sizeof(AlignedArray);
@@ -246,19 +246,19 @@ namespace MCore
          * @param pos The element number.
          * @param value The value to store at that element number.
          */
-        MCORE_INLINE void SetElem(uint32 pos, const T& value)                   { mData[pos] = value; }
+        MCORE_INLINE void SetElem(size_t pos, const T& value)                   { m_data[pos] = value; }
 
         /**
          * Add a given element to the back of the array.
          * @param x The element to add.
          */
-        MCORE_INLINE void Add(const T& x)                                       { Grow(++mLength); Construct(mLength - 1, x); }
+        MCORE_INLINE void Add(const T& x)                                       { Grow(++m_length); Construct(m_length - 1, x); }
 
         /**
          * Add a given element to the back of the array, but without pre-allocation caching.
          * @param x The element to add.
          */
-        MCORE_INLINE void AddExact(const T& x)                                  { GrowExact(++mLength); Construct(mLength - 1, x); }
+        MCORE_INLINE void AddExact(const T& x)                                  { GrowExact(++m_length); Construct(m_length - 1, x); }
 
         /**
          * Add a given array to the back of this array.
@@ -266,9 +266,9 @@ namespace MCore
          */
         MCORE_INLINE void Add(const AlignedArray& a)
         {
-            uint32 l = mLength;
-            Grow(mLength + a.mLength);
-            for (uint32 i = 0; i < a.GetLength(); ++i)
+            size_t l = m_length;
+            Grow(m_length + a.m_length);
+            for (size_t i = 0; i < a.GetLength(); ++i)
             {
                 Construct(l + i, a[i]);
             }
@@ -277,21 +277,21 @@ namespace MCore
         /**
          * Add an empty (default constructed) element to the back of the array.
          */
-        MCORE_INLINE void AddEmpty()                                            { Grow(++mLength); Construct(mLength - 1); }
+        MCORE_INLINE void AddEmpty()                                            { Grow(++m_length); Construct(m_length - 1); }
 
         /**
          * Add an empty (default constructed) element to the back of the array, but without pre-allocation caching.
          */
-        MCORE_INLINE void AddEmptyExact()                                       { GrowExact(++mLength); Construct(mLength - 1); }
+        MCORE_INLINE void AddEmptyExact()                                       { GrowExact(++m_length); Construct(m_length - 1); }
 
         /**
          * Remove the first array element.
          */
         MCORE_INLINE void RemoveFirst()
         {
-            if (mLength > 0)
+            if (m_length > 0)
             {
-                Remove((uint32)0);
+                Remove(0);
             }
         }
 
@@ -300,9 +300,9 @@ namespace MCore
          */
         MCORE_INLINE void RemoveLast()
         {
-            if (mLength > 0)
+            if (m_length > 0)
             {
-                Destruct(--mLength);
+                Destruct(--m_length);
             }
         }
 
@@ -310,27 +310,27 @@ namespace MCore
          * Insert an empty element (default constructed) at a given position in the array.
          * @param pos The position to create the empty element.
          */
-        MCORE_INLINE void Insert(uint32 pos)                                    { Grow(mLength + 1); MoveElements(pos + 1, pos, mLength - pos - 1); Construct(pos); }
+        MCORE_INLINE void Insert(size_t pos)                                    { Grow(m_length + 1); MoveElements(pos + 1, pos, m_length - pos - 1); Construct(pos); }
 
         /**
          * Insert a given element at a given position in the array.
          * @param pos The position to insert the empty element.
          * @param x The element to store at this position.
          */
-        MCORE_INLINE void Insert(uint32 pos, const T& x)                        { Grow(mLength + 1); MoveElements(pos + 1, pos, mLength - pos - 1); Construct(pos, x); }
+        MCORE_INLINE void Insert(size_t pos, const T& x)                        { Grow(m_length + 1); MoveElements(pos + 1, pos, m_length - pos - 1); Construct(pos, x); }
 
         /**
          * Remove an element at a given position.
          * @param pos The element number to remove.
          */
-        MCORE_INLINE void Remove(uint32 pos)
+        MCORE_INLINE void Remove(size_t pos)
         {
             Destruct(pos);
-            if (mLength > 1)
+            if (m_length > 1)
             {
-                MoveElements(pos, pos + 1, mLength - pos - 1);
+                MoveElements(pos, pos + 1, m_length - pos - 1);
             }
-            mLength--;
+            m_length--;
         }
 
         /**
@@ -338,14 +338,14 @@ namespace MCore
          * @param pos The start element, so to start removing from.
          * @param num The number of elements to remove from this position.
          */
-        MCORE_INLINE void Remove(uint32 pos, uint32 num)
+        MCORE_INLINE void Remove(size_t pos, size_t num)
         {
-            for (uint32 i = pos; i < pos + num; ++i)
+            for (size_t i = pos; i < pos + num; ++i)
             {
                 Destruct(i);
             }
-            MoveElements(pos, pos + num, mLength - pos - num);
-            mLength -= num;
+            MoveElements(pos, pos + num, m_length - pos - num);
+            m_length -= num;
         }
 
         /**
@@ -355,8 +355,8 @@ namespace MCore
          */
         MCORE_INLINE bool RemoveByValue(const T& item)
         {
-            uint32 index = Find(item);
-            if (index == MCORE_INVALIDINDEX32)
+            size_t index = Find(item);
+            if (index == InvalidIndex)
             {
                 return false;
             }
@@ -372,15 +372,15 @@ namespace MCore
          * AB.DEFG [where . is empty, after we did the SwapRemove(2)]
* ABGDEF [this is the result. G has been moved to the empty position]. */ - MCORE_INLINE void SwapRemove(uint32 pos) + MCORE_INLINE void SwapRemove(size_t pos) { Destruct(pos); - if (pos != mLength - 1) + if (pos != m_length - 1) { - Construct(pos, mData[mLength - 1]); - Destruct(mLength - 1); + Construct(pos, m_data[m_length - 1]); + Destruct(m_length - 1); } - mLength--; + m_length--; } // remove element at and place the last element of the array in that position /** @@ -388,7 +388,7 @@ namespace MCore * @param pos1 The first element number. * @param pos2 The second element number. */ - MCORE_INLINE void Swap(uint32 pos1, uint32 pos2) + MCORE_INLINE void Swap(size_t pos1, size_t pos2) { if (pos1 != pos2) { @@ -403,11 +403,11 @@ namespace MCore */ MCORE_INLINE void Clear(bool clearMem = true) { - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < m_length; ++i) { Destruct(i); } - mLength = 0; + m_length = 0; if (clearMem) { this->Free(); @@ -418,15 +418,15 @@ namespace MCore * Make sure the array has enough space to store a given number of elements. * @param newLength The number of elements we want to make sure that will fit in the array. */ - MCORE_INLINE void AssureSize(uint32 newLength) + MCORE_INLINE void AssureSize(size_t newLength) { - if (mLength >= newLength) + if (m_length >= newLength) { return; } - uint32 oldLen = mLength; + size_t oldLen = m_length; Grow(newLength); - for (uint32 i = oldLen; i < newLength; ++i) + for (size_t i = oldLen; i < newLength; ++i) { Construct(i); } @@ -436,9 +436,9 @@ namespace MCore * Make sure this array has enough allocated storage to grow to a given number of elements elements without having to realloc. * @param minLength The minimum length the array should have (actually the minimum maxLength, because this has no influence on what GetLength() will return). */ - MCORE_INLINE void Reserve(uint32 minLength) + MCORE_INLINE void Reserve(size_t minLength) { - if (mMaxLength < minLength) + if (m_maxLength < minLength) { Realloc(minLength); } @@ -449,12 +449,12 @@ namespace MCore */ MCORE_INLINE void Shrink() { - if (mLength == mMaxLength) + if (m_length == m_maxLength) { return; } - MCORE_ASSERT(mMaxLength >= mLength); - Realloc(mLength); + MCORE_ASSERT(m_maxLength >= m_length); + Realloc(m_length); } /** @@ -462,23 +462,23 @@ namespace MCore * @param x The element to check. * @result Returns true when the array contains the element, otherwise false is returned. */ - MCORE_INLINE bool Contains(const T& x) const { return (Find(x) != MCORE_INVALIDINDEX32); } + MCORE_INLINE bool Contains(const T& x) const { return (Find(x) != InvalidIndex); } /** * Find the position of a given element. * @param x The element to find. - * @result Returns the index in the array, ranging from [0 to GetLength()-1] when found, otherwise MCORE_INVALIDINDEX32 is returned. + * @result Returns the index in the array, ranging from [0 to GetLength()-1] when found, otherwise InvalidIndex is returned. */ - MCORE_INLINE uint32 Find(const T& x) const + MCORE_INLINE size_t Find(const T& x) const { - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < m_length; ++i) { - if (mData[i] == x) + if (m_data[i] == x) { return i; } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } /** @@ -487,7 +487,7 @@ namespace MCore * This resizes this array to be the exact length of the array we will copy the data from. * @param other The array to copy the data from. */ - MCORE_INLINE void MemCopyContentsFrom(const AlignedArray& other) { Resize(other.GetLength()); MemCopy((uint8*)mData, (uint8*)other.mData, sizeof(T) * other.mLength); } + MCORE_INLINE void MemCopyContentsFrom(const AlignedArray& other) { Resize(other.GetLength()); MemCopy((uint8*)m_data, (uint8*)other.m_data, sizeof(T) * other.m_length); } // sort function and standard sort function typedef int32 (MCORE_CDECL * CmpFunc)(const T& itemA, const T& itemB); @@ -526,21 +526,21 @@ namespace MCore * Sort the complete array using a given sort function. * @param cmp The sort function to use. */ - MCORE_INLINE void Sort(CmpFunc cmp) { InnerSort(0, mLength - 1, cmp); } + MCORE_INLINE void Sort(CmpFunc cmp) { InnerSort(0, m_length - 1, cmp); } /** * Sort a given part of the array using a given sort function. * The default parameters are set so that it will sort the compelete array with a default compare function (which uses the < and > operators). * The method will sort all elements between the given 'first' and 'last' element (first and last are also included in the sort). * @param first The first element to start sorting. - * @param last The last element to sort (when set to MCORE_INVALIDINDEX32, GetLength()-1 will be used). + * @param last The last element to sort (when set to InvalidIndex, GetLength()-1 will be used). * @param cmp The compare function. */ - MCORE_INLINE void Sort(uint32 first = 0, uint32 last = MCORE_INVALIDINDEX32, CmpFunc cmp = StdCmp) + MCORE_INLINE void Sort(size_t first = 0, size_t last = InvalidIndex, CmpFunc cmp = StdCmp) { - if (last == MCORE_INVALIDINDEX32) + if (last == InvalidIndex) { - last = mLength - 1; + last = m_length - 1; } InnerSort(first, last, cmp); } @@ -563,19 +563,19 @@ namespace MCore } // resize in a fast way that doesn't call constructors or destructors - void ResizeFast(uint32 newLength) + void ResizeFast(size_t newLength) { - if (mLength == newLength) + if (m_length == newLength) { return; } - if (newLength > mLength) + if (newLength > m_length) { GrowExact(newLength); } - mLength = newLength; + m_length = newLength; } /** @@ -583,20 +583,20 @@ namespace MCore * This does not mean an actual realloc will be made. This will only happen when the new length is bigger than the maxLength of the array. * @param newLength The new length the array should be. */ - void Resize(uint32 newLength) + void Resize(size_t newLength) { - if (mLength == newLength) + if (m_length == newLength) { return; } // check for growing or shrinking array - if (newLength > mLength) + if (newLength > m_length) { // growing array, construct empty elements at end of array - const uint32 oldLen = mLength; + const size_t oldLen = m_length; GrowExact(newLength); - for (uint32 i = oldLen; i < newLength; ++i) + for (size_t i = oldLen; i < newLength; ++i) { Construct(i); } @@ -604,12 +604,12 @@ namespace MCore else { // shrinking array, destruct elements at end of array - for (uint32 i = newLength; i < mLength; ++i) + for (size_t i = newLength; i < m_length; ++i) { Destruct(i); } - mLength = newLength; + m_length = newLength; } } @@ -620,24 +620,24 @@ namespace MCore * @param sourceIndex The source index, where the source elements start. * @param numElements The number of elements to move. */ - MCORE_INLINE void MoveElements(uint32 destIndex, uint32 sourceIndex, uint32 numElements) + MCORE_INLINE void MoveElements(size_t destIndex, size_t sourceIndex, size_t numElements) { if (numElements > 0) { - MemMove(mData + destIndex, mData + sourceIndex, numElements * sizeof(T)); + MemMove(m_data + destIndex, m_data + sourceIndex, numElements * sizeof(T)); } } // operators bool operator==(const AlignedArray& other) const { - if (mLength != other.mLength) + if (m_length != other.m_length) { return false; } - for (uint32 i = 0; i < mLength; ++i) + for (size_t i = 0; i < m_length; ++i) { - if (mData[i] != other.mData[i]) + if (m_data[i] != other.m_data[i]) { return false; } @@ -649,11 +649,11 @@ namespace MCore if (&other != this) { Clear(false); - mMemCategory = other.mMemCategory; - Grow(other.mLength); - for (uint32 i = 0; i < mLength; ++i) + m_memCategory = other.m_memCategory; + Grow(other.m_length); + for (size_t i = 0; i < m_length; ++i) { - Construct(i, other.mData[i]); + Construct(i, other.m_data[i]); } } return *this; @@ -661,94 +661,94 @@ namespace MCore AlignedArray& operator= (AlignedArray&& other) { MCORE_ASSERT(&other != this); - if (mData) + if (m_data) { - AlignedFree(mData); + AlignedFree(m_data); } - mData = other.mData; - mMemCategory = other.mMemCategory; - mLength = other.mLength; - mMaxLength = other.mMaxLength; - other.mData = nullptr; - other.mLength = 0; - other.mMaxLength = 0; + m_data = other.m_data; + m_memCategory = other.m_memCategory; + m_length = other.m_length; + m_maxLength = other.m_maxLength; + other.m_data = nullptr; + other.m_length = 0; + other.m_maxLength = 0; return *this; } AlignedArray& operator+=(const T& other) { Add(other); return *this; } AlignedArray& operator+=(const AlignedArray& other) { Add(other); return *this; } - MCORE_INLINE T& operator[](uint32 index) { MCORE_ASSERT(index < mLength); return mData[index]; } - MCORE_INLINE const T& operator[](uint32 index) const { MCORE_ASSERT(index < mLength); return mData[index]; } + MCORE_INLINE T& operator[](size_t index) { MCORE_ASSERT(index < m_length); return m_data[index]; } + MCORE_INLINE const T& operator[](size_t index) const { MCORE_ASSERT(index < m_length); return m_data[index]; } private: - T* mData; /**< The element data. */ - uint32 mLength; /**< The number of used elements in the array. */ - uint32 mMaxLength; /**< The number of elements that we have allocated memory for. */ - uint16 mMemCategory; /**< The memory category ID. */ + T* m_data; /**< The element data. */ + size_t m_length; /**< The number of used elements in the array. */ + size_t m_maxLength; /**< The number of elements that we have allocated memory for. */ + uint16 m_memCategory; /**< The memory category ID. */ // private functions - MCORE_INLINE void Grow(uint32 newLength) + MCORE_INLINE void Grow(size_t newLength) { - mLength = newLength; - if (mMaxLength >= newLength) + m_length = newLength; + if (m_maxLength >= newLength) { return; } Realloc(AllocSize(newLength)); } - MCORE_INLINE void GrowExact(uint32 newLength) + MCORE_INLINE void GrowExact(size_t newLength) { - mLength = newLength; - if (mMaxLength < newLength) + m_length = newLength; + if (m_maxLength < newLength) { Realloc(newLength); } } - MCORE_INLINE uint32 AllocSize(uint32 num) { return 1 + num /*+num/8*/; } - MCORE_INLINE void Alloc(uint32 num) { mData = (T*)AlignedAllocate(num * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } - MCORE_INLINE void Realloc(uint32 newSize) + MCORE_INLINE size_t AllocSize(size_t num) { return 1 + num /*+num/8*/; } + MCORE_INLINE void Alloc(size_t num) { m_data = (T*)AlignedAllocate(num * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } + MCORE_INLINE void Realloc(size_t newSize) { if (newSize == 0) { this->Free(); return; } - if (mData) + if (m_data) { - mData = (T*)AlignedRealloc(mData, newSize * sizeof(T), mMaxLength * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); + m_data = (T*)AlignedRealloc(m_data, newSize * sizeof(T), m_maxLength * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } else { - mData = (T*)AlignedAllocate(newSize * sizeof(T), alignment, mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); + m_data = (T*)AlignedAllocate(newSize * sizeof(T), alignment, m_memCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } - mMaxLength = newSize; + m_maxLength = newSize; } void Free() { - mLength = 0; - mMaxLength = 0; - if (mData) + m_length = 0; + m_maxLength = 0; + if (m_data) { - AlignedFree(mData); - mData = nullptr; + AlignedFree(m_data); + m_data = nullptr; } } - MCORE_INLINE void Construct(uint32 index, const T& original) { ::new(mData + index)T(original); } // copy-construct an element at which is a copy of - MCORE_INLINE void Construct(uint32 index) { ::new(mData + index)T; } // construct an element at place - MCORE_INLINE void Destruct(uint32 index) + MCORE_INLINE void Construct(size_t index, const T& original) { ::new(m_data + index)T(original); } // copy-construct an element at which is a copy of + MCORE_INLINE void Construct(size_t index) { ::new(m_data + index)T; } // construct an element at place + MCORE_INLINE void Destruct(size_t index) { #if (MCORE_COMPILER == MCORE_COMPILER_MSVC) MCORE_UNUSED(index); // work around an MSVC compiler bug, where it triggers a warning that parameter 'index' is unused #endif - (mData + index)->~T(); + (m_data + index)->~T(); } // partition part of array (for sorting) int32 Partition(int32 left, int32 right, CmpFunc cmp) { - ::MCore::Swap(mData[left], mData[ (left + right) >> 1 ]); + ::MCore::Swap(m_data[left], m_data[ (left + right) >> 1 ]); - T& target = mData[right]; + T& target = m_data[right]; int32 i = left - 1; int32 j = right; @@ -757,14 +757,14 @@ namespace MCore { while (i < j) { - if (cmp(mData[++i], target) >= 0) + if (cmp(m_data[++i], target) >= 0) { break; } } while (j > i) { - if (cmp(mData[--j], target) <= 0) + if (cmp(m_data[--j], target) <= 0) { break; } @@ -773,10 +773,10 @@ namespace MCore { break; } - ::MCore::Swap(mData[i], mData[j]); + ::MCore::Swap(m_data[i], m_data[j]); } - ::MCore::Swap(mData[i], mData[right]); + ::MCore::Swap(m_data[i], m_data[right]); return i; } }; diff --git a/Gems/EMotionFX/Code/MCore/Source/Array.h b/Gems/EMotionFX/Code/MCore/Source/Array.h deleted file mode 100644 index ef2f58119c..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/Array.h +++ /dev/null @@ -1,799 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include "StandardHeaders.h" -#include "MCoreSystem.h" -#include "Algorithms.h" -#include "MemoryManager.h" - -#include - -namespace MCore -{ - /** - * Dynamic array template. - * This array template allows dynamic sizing. It also stores the memory category of the data. - * It can theoretically store 4294967296 items (maximum uint32 value). - */ - template - class Array - { - public: - /** - * The memory block ID, used inside the memory manager. - * This will make all arrays remain in the same memory blocks, which is more efficient in a lot of cases. - * However, array data can still remain in other blocks. - */ - enum - { - MEMORYBLOCK_ID = 2 - }; - - /** - * Default constructor. - * Initializes the array so it's empty and has no memory allocated. - */ - MCORE_INLINE Array() - : mData(nullptr) - , mLength(0) - , mMaxLength(0) - , mMemCategory(MCORE_MEMCATEGORY_ARRAY) {} - - /** - * Constructor which creates a given number of elements. - * @param elems The element data. - * @param num The number of elements in 'elems'. - * @param memCategory The memory category the array is in. - */ - MCORE_INLINE explicit Array(T* elems, uint32 num, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : mLength(num) - , mMaxLength(AllocSize(num)) - , mMemCategory(memCategory) - { - mData = (T*)MCore::Allocate(mMaxLength * sizeof(T), mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - for (uint32 i = 0; i < mLength; ++i) - { - Construct(i, elems[i]); - } - } - - /** - * Constructor which initializes the length of the array on a given number. - * @param initSize The number of ellements to allocate space for. - * @param memCategory The memory category the array is in. - */ - MCORE_INLINE explicit Array(uint32 initSize, uint16 memCategory = MCORE_MEMCATEGORY_ARRAY) - : mData(nullptr) - , mLength(initSize) - , mMaxLength(initSize) - , mMemCategory(memCategory) - { - if (mMaxLength > 0) - { - mData = (T*)MCore::Allocate(mMaxLength * sizeof(T), mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - for (uint32 i = 0; i < mLength; ++i) - { - Construct(i); - } - } - } - - /** - * Copy constructor. - * @param other The other array to copy the data from. - */ - Array(const Array& other) - : mData(nullptr) - , mLength(0) - , mMaxLength(0) - , mMemCategory(MCORE_MEMCATEGORY_ARRAY) { *this = other; } - - /** - * Move constructor. - * @param other The array to move the data from. - */ - Array(Array&& other) { mData = other.mData; mLength = other.mLength; mMaxLength = other.mMaxLength; mMemCategory = other.mMemCategory; other.mData = nullptr; other.mLength = 0; other.mMaxLength = 0; } - - /** - * Destructor. Deletes all entry data. - * However, if you store pointers to objects, these objects won't be deleted.
- * Example:
- *
-         * Array< Object* > data;
-         * for (uint32 i=0; i<10; i++)
-         *    data.Add( new Object() );
-         * 
- * Now when the array 'data' will be destructed, it will NOT free up the memory of the integers which you allocated by hand, using new. - * In order to free up this memory, you can do this: - *
-         * for (uint32 i=0; i
-         */
-        ~Array()
-        {
-            for (uint32 i = 0; i < mLength; ++i)
-            {
-                Destruct(i);
-            }
-            if (mData)
-            {
-                MCore::Free(mData);
-            }
-        }
-
-        /**
-         * Get the memory category ID where allocations made by this array belong to.
-         * On default the memory category is 0, which means unknown.
-         * @result The memory category ID.
-         */
-        MCORE_INLINE uint16 GetMemoryCategory() const                           { return mMemCategory; }
-
-        /**
-         * Set the memory category ID, where allocations made by this array will belong to.
-         * On default, after construction of the array, the category ID is 0, which means it is unknown.
-         * @param categoryID The memory category ID where this arrays allocations belong to.
-         */
-        MCORE_INLINE void SetMemoryCategory(uint16 categoryID)                  { mMemCategory = categoryID; }
-
-        /**
-         * Get a pointer to the first element.
-         * @result A pointer to the first element.
-         */
-        MCORE_INLINE T* GetPtr()                                                { return mData; }
-
-        /**
-         * Get a pointer to the first element.
-         * @result A pointer to the first element.
-         */
-        MCORE_INLINE T* GetPtr() const                                          { return mData; }
-
-        /**
-         * Get a given item/element.
-         * @param pos The item/element number.
-         * @result A reference to the element.
-         */
-        MCORE_INLINE T& GetItem(uint32 pos)                                     { return mData[pos]; }
-
-        /**
-         * Get the first element.
-         * @result A reference to the first element.
-         */
-        MCORE_INLINE T& GetFirst()                                              { return mData[0]; }
-
-        /**
-         * Get the last element.
-         * @result A reference to the last element.
-         */
-        MCORE_INLINE T& GetLast()                                               { return mData[mLength - 1]; }
-
-        /**
-         * Get a read-only pointer to the first element.
-         * @result A read-only pointer to the first element.
-         */
-        MCORE_INLINE const T* GetReadPtr() const                                { return mData; }
-
-        /**
-         * Get a read-only reference to a given element number.
-         * @param pos The element number.
-         * @result A read-only reference to the given element.
-         */
-        MCORE_INLINE const T& GetItem(uint32 pos) const                         { return mData[pos]; }
-
-        /**
-         * Get a read-only reference to the first element.
-         * @result A read-only reference to the first element.
-         */
-        MCORE_INLINE const T& GetFirst() const                                  { return mData[0]; }
-
-        /**
-         * Get a read-only reference to the last element.
-         * @result A read-only reference to the last element.
-         */
-        MCORE_INLINE const T& GetLast() const                                   { return mData[mLength - 1]; }
-
-        /**
-         * Check if the array is empty or not.
-         * @result Returns true when there are no elements in the array, otherwise false is returned.
-         */
-        MCORE_INLINE bool GetIsEmpty() const                                    { return (mLength == 0); }
-
-        /**
-         * Checks if the passed index is in the array's range.
-         * @param index The index to check.
-         * @return True if the passed index is valid, false if not.
-         */
-        MCORE_INLINE bool GetIsValidIndex(uint32 index) const                   { return (index < mLength); }
-
-        /**
-         * Get the number of elements in the array.
-         * @result The number of elements in the array.
-         */
-        MCORE_INLINE uint32 GetLength() const                                   { return mLength; }
-
-        /**
-         * Get the maximum number of elements. This is the number of elements there currently is space for to store.
-         * However, never use this to make for-loops to iterate through all elements. Use GetLength() instead for that.
-         * This purely has to do with pre-allocating, to reduce the number of reallocs.
-         * @result The maximum array length.
-         */
-        MCORE_INLINE uint32 GetMaxLength() const                                { return mMaxLength; }
-
-        /**
-         * Calculates the memory usage used by this array.
-         * @param includeMembers Include the class members in the calculation? (default=true).
-         * @result The number of bytes allocated by this array.
-         */
-        MCORE_INLINE uint32 CalcMemoryUsage(bool includeMembers = true) const
-        {
-            uint32 result = mMaxLength * sizeof(T);
-            if (includeMembers)
-            {
-                result += sizeof(MCore::Array);
-            }
-            return result;
-        }
-
-        /**
-         * Set a given element to a given value.
-         * @param pos The element number.
-         * @param value The value to store at that element number.
-         */
-        MCORE_INLINE void SetElem(uint32 pos, const T& value)                   { mData[pos] = value; }
-
-        /**
-         * Add a given element to the back of the array.
-         * @param x The element to add.
-         */
-        MCORE_INLINE void Add(const T& x)                                       { Grow(++mLength); Construct(mLength - 1, x); }
-
-        /**
-         * Add a given element to the back of the array, but without pre-allocation caching.
-         * @param x The element to add.
-         */
-        MCORE_INLINE void AddExact(const T& x)                                  { GrowExact(++mLength); Construct(mLength - 1, x); }
-
-        /**
-         * Add a given array to the back of this array.
-         * @param a The array to add.
-         */
-        MCORE_INLINE void Add(const Array& a)
-        {
-            uint32 l = mLength;
-            Grow(mLength + a.mLength);
-            for (uint32 i = 0; i < a.GetLength(); ++i)
-            {
-                Construct(l + i, a[i]);
-            }
-        }                                                                                                                                                                                   // TODO: a.GetLength() can be precaled before loop?
-
-        /**
-         * Add an empty (default constructed) element to the back of the array.
-         */
-        MCORE_INLINE void AddEmpty()                                            { Grow(++mLength); Construct(mLength - 1); }
-
-        /**
-         * Add an empty (default constructed) element to the back of the array, but without pre-allocation caching.
-         */
-        MCORE_INLINE void AddEmptyExact()                                       { GrowExact(++mLength); Construct(mLength - 1); }
-
-        /**
-         * Remove the first array element.
-         */
-        MCORE_INLINE void RemoveFirst()
-        {
-            if (mLength > 0)
-            {
-                Remove((uint32)0);
-            }
-        }
-
-        /**
-         * Remove the last array element.
-         */
-        MCORE_INLINE void RemoveLast()
-        {
-            if (mLength > 0)
-            {
-                Destruct(--mLength);
-            }
-        }
-
-        /**
-         * Insert an empty element (default constructed) at a given position in the array.
-         * @param pos The position to create the empty element.
-         */
-        MCORE_INLINE void Insert(uint32 pos)                                    { Grow(mLength + 1); MoveElements(pos + 1, pos, mLength - pos - 1); Construct(pos); }
-
-        /**
-         * Insert a given element at a given position in the array.
-         * @param pos The position to insert the empty element.
-         * @param x The element to store at this position.
-         */
-        MCORE_INLINE void Insert(uint32 pos, const T& x)                        { Grow(mLength + 1); MoveElements(pos + 1, pos, mLength - pos - 1); Construct(pos, x); }
-
-        /**
-         * Remove an element at a given position.
-         * @param pos The element number to remove.
-         */
-        MCORE_INLINE void Remove(uint32 pos)
-        {
-            AZ_Assert(pos < mLength, "Array index out of bounds");
-            Destruct(pos);
-            if (mLength > 1)
-            {
-                MoveElements(pos, pos + 1, mLength - pos - 1);
-            }
-            mLength--;
-        }
-
-        /**
-         * Remove a given number of elements starting at a given position in the array.
-         * @param pos The start element, so to start removing from.
-         * @param num The number of elements to remove from this position.
-         */
-        MCORE_INLINE void Remove(uint32 pos, uint32 num)
-        {
-            for (uint32 i = pos; i < pos + num; ++i)
-            {
-                Destruct(i);
-            }
-            MoveElements(pos, pos + num, mLength - pos - num);
-            mLength -= num;
-        }
-
-        /**
-         * Remove a given element with a given value.
-         * Only the first element with the given value will be removed.
-         * @param item The item/element to remove.
-         */
-        MCORE_INLINE bool RemoveByValue(const T& item)
-        {
-            const uint32 index = Find(item);
-            if (index == MCORE_INVALIDINDEX32)
-            {
-                return false;
-            }
-            Remove(index);
-            return true;
-        }
-
-        /**
-         * Remove a given element in the array and place the last element in the array at the created empty position.
-         * So if we have an array with the following characters : ABCDEFG
- * And we perform a SwapRemove(2), we will remove element C and place the last element (G) at the empty created position where C was located. - * So we will get this:
- * AB.DEFG [where . is empty, after we did the SwapRemove(2)]
- * ABGDEF [this is the result. G has been moved to the empty position]. - */ - MCORE_INLINE void SwapRemove(uint32 pos) - { - Destruct(pos); - if (pos != mLength - 1) - { - Construct(pos, mData[mLength - 1]); - Destruct(mLength - 1); - } - mLength--; - } // remove element at and place the last element of the array in that position - - /** - * Swap two elements. - * @param pos1 The first element number. - * @param pos2 The second element number. - */ - MCORE_INLINE void Swap(uint32 pos1, uint32 pos2) - { - if (pos1 != pos2) - { - MCore::Swap(GetItem(pos1), GetItem(pos2)); - } - } - - /** - * Clear the array contents. So GetLength() will return 0 after performing this method. - * @param clearMem If set to true (default) the allocated memory will also be released. If set to false, GetMaxLength() will still return the number of elements - * which the array contained before calling the Clear() method. - */ - MCORE_INLINE void Clear(bool clearMem = true) - { - for (uint32 i = 0; i < mLength; ++i) - { - Destruct(i); - } - mLength = 0; - if (clearMem) - { - Free(); - } - } - - /** - * Make sure the array has enough space to store a given number of elements. - * @param newLength The number of elements we want to make sure that will fit in the array. - */ - MCORE_INLINE void AssureSize(uint32 newLength) - { - if (mLength >= newLength) - { - return; - } - uint32 oldLen = mLength; - Grow(newLength); - for (uint32 i = oldLen; i < newLength; ++i) - { - Construct(i); - } - } - - /** - * Make sure this array has enough allocated storage to grow to a given number of elements elements without having to realloc. - * @param minLength The minimum length the array should have (actually the minimum maxLength, because this has no influence on what GetLength() will return). - */ - MCORE_INLINE void Reserve(uint32 minLength) - { - if (mMaxLength < minLength) - { - Realloc(minLength); - } - } - - /** - * The same as Reserve, except that this also can shrink the memory to the specified size if more has been allocated already. - * If the current length is larger than the specified minLength nothing will happen. - * @param minLength The minimum length the array should have. - */ - MCORE_INLINE void ReserveExact(uint32 minLength) - { - if (mLength > minLength) - { - return; - } - Realloc(minLength); - } - - /** - * Make the array as small as possible. So remove all extra pre-allocated data, so that the array consumes the least possible amount of memory. - */ - MCORE_INLINE void Shrink() - { - if (mLength == mMaxLength) - { - return; - } - Realloc(mLength); - } - - /** - * Check if the array contains a given element. - * @param x The element to check. - * @result Returns true when the array contains the element, otherwise false is returned. - */ - MCORE_INLINE bool Contains(const T& x) const { return (Find(x) != MCORE_INVALIDINDEX32); } - - /** - * Find the position of a given element. - * @param x The element to find. - * @result Returns the index in the array, ranging from [0 to GetLength()-1] when found, otherwise MCORE_INVALIDINDEX32 is returned. - */ - MCORE_INLINE uint32 Find(const T& x) const - { - for (uint32 i = 0; i < mLength; ++i) - { - if (mData[i] == x) - { - return i; - } - } - return MCORE_INVALIDINDEX32; - } - - - // sort function and standard sort function - typedef int32 (MCORE_CDECL * CmpFunc)(const T& itemA, const T& itemB); - static int32 MCORE_CDECL StdCmp(const T& itemA, const T& itemB) - { - if (itemA < itemB) - { - return -1; - } - else if (itemA == itemB) - { - return 0; - } - else - { - return 1; - } - } - static int32 MCORE_CDECL StdPtrObjCmp(const T& itemA, const T& itemB) - { - if (*itemA < *itemB) - { - return -1; - } - else if (*itemA == *itemB) - { - return 0; - } - else - { - return 1; - } - } - - /** - * Sort the complete array using a given sort function. - * @param cmp The sort function to use. - */ - MCORE_INLINE void Sort(CmpFunc cmp) { InnerSort(0, mLength - 1, cmp); } - - /** - * Sort a given part of the array using a given sort function. - * The default parameters are set so that it will sort the compelete array with a default compare function (which uses the < and > operators). - * The method will sort all elements between the given 'first' and 'last' element (first and last are also included in the sort). - * @param first The first element to start sorting. - * @param last The last element to sort (when set to MCORE_INVALIDINDEX32, GetLength()-1 will be used). - * @param cmp The compare function. - */ - MCORE_INLINE void Sort(uint32 first = 0, uint32 last = MCORE_INVALIDINDEX32, CmpFunc cmp = StdCmp) - { - if (last == MCORE_INVALIDINDEX32) - { - last = mLength - 1; - } - InnerSort(first, last, cmp); - } - - /** - * Performs a sort on a given part of the array. - * @param first The first element to start the sorting at. - * @param last The last element to end the sorting. - * @param cmp The compare function. - */ - MCORE_INLINE void InnerSort(int32 first, int32 last, CmpFunc cmp) - { - if (first >= last) - { - return; - } - int32 split = Partition(first, last, cmp); - InnerSort(first, split - 1, cmp); - InnerSort(split + 1, last, cmp); - } - - // resize in a fast way that doesn't call constructors or destructors - void ResizeFast(uint32 newLength) - { - if (mLength == newLength) - { - return; - } - - if (newLength > mLength) - { - GrowExact(newLength); - } - - mLength = newLength; - } - - /** - * Resize the array to a given size. - * This does not mean an actual realloc will be made. This will only happen when the new length is bigger than the maxLength of the array. - * @param newLength The new length the array should be. - * @result returns false if the allocation/reallocation of the array failed - */ - bool Resize(uint32 newLength) - { - if (mLength == newLength) - { - return true; - } - - // check for growing or shrinking array - if (newLength > mLength) - { - // growing array, construct empty elements at end of array - const uint32 oldLen = mLength; - GrowExact(newLength); - if (mData == nullptr) - { - return false; - } - for (uint32 i = oldLen; i < newLength; ++i) - { - Construct(i); - } - } - else - { - // shrinking array, destruct elements at end of array - for (uint32 i = newLength; i < mLength; ++i) - { - Destruct(i); - } - - mLength = newLength; - } - return true; - } - - /** - * Move "numElements" elements starting from the source index, to the dest index. - * Please note that the array has to be large enough. You can't move data past the end of the array. - * @param destIndex The destination index. - * @param sourceIndex The source index, where the source elements start. - * @param numElements The number of elements to move. - */ - MCORE_INLINE void MoveElements(uint32 destIndex, uint32 sourceIndex, uint32 numElements) - { - if (numElements > 0) - { - MCore::MemMove(mData + destIndex, mData + sourceIndex, numElements * sizeof(T)); - } - } - - // operators - bool operator==(const Array& other) const - { - if (mLength != other.mLength) - { - return false; - } - for (uint32 i = 0; i < mLength; ++i) - { - if (mData[i] != other.mData[i]) - { - return false; - } - } - return true; - } - //Array& operator= (const Array& other) { if (&other != this) { Clear(); mMemCategory = other.mMemCategory; Grow(other.mLength); for (uint32 i=0; i& operator= (const Array& other) - { - if (&other != this) - { - Clear(false); - mMemCategory = other.mMemCategory; - Grow(other.mLength); - for (uint32 i = 0; i < mLength; ++i) - { - Construct(i, other.mData[i]); - } - } - return *this; - } - Array& operator= (Array&& other) - { - AZ_Assert(&other != this, "Cannot assign array to itself."); - if (mData) - { - MCore::Free(mData); - } - mData = other.mData; - mMemCategory = other.mMemCategory; - mLength = other.mLength; - mMaxLength = other.mMaxLength; - other.mData = nullptr; - other.mLength = 0; - other.mMaxLength = 0; - return *this; - } - //Array& operator+ (const Array& other) const { Array newArray; newArray.Grow(mLength+other.mLength); uint32 i; for (i=0; i& operator+=(const T& other) { Add(other); return *this; } - Array& operator+=(const Array& other) { Add(other); return *this; } - MCORE_INLINE T& operator[](uint32 index) { AZ_Assert(index < mLength, "Array index out of bounds"); return mData[index]; } - MCORE_INLINE const T& operator[](uint32 index) const { AZ_Assert(index < mLength, "Array index out of bounds"); return mData[index]; } - - private: - T* mData; /**< The element data. */ - uint32 mLength; /**< The number of used elements in the array. */ - uint32 mMaxLength; /**< The number of elements that we have allocated memory for. */ - uint16 mMemCategory; /**< The memory category ID. */ - - // private functions - MCORE_INLINE void Grow(uint32 newLength) - { - mLength = newLength; - if (mMaxLength >= newLength) - { - return; - } - Realloc(AllocSize(newLength)); - } - MCORE_INLINE void GrowExact(uint32 newLength) - { - mLength = newLength; - if (mMaxLength < newLength) - { - Realloc(newLength); - } - } - MCORE_INLINE uint32 AllocSize(uint32 num) { return 1 + num /*+num/8*/; } - MCORE_INLINE void Alloc(uint32 num) { mData = (T*)MCore::Allocate(num * sizeof(T), mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } - MCORE_INLINE void Realloc(uint32 newSize) - { - if (newSize == 0) - { - this->Free(); - return; - } - if (mData) - { - mData = (T*)MCore::Realloc(mData, newSize * sizeof(T), mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - else - { - mData = (T*)MCore::Allocate(newSize * sizeof(T), mMemCategory, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); - } - - mMaxLength = newSize; - } - MCORE_INLINE void Free() - { - mLength = 0; - mMaxLength = 0; - if (mData) - { - MCore::Free(mData); - mData = nullptr; - } - } - MCORE_INLINE void Construct(uint32 index, const T& original) { ::new(mData + index)T(original); } // copy-construct an element at which is a copy of - MCORE_INLINE void Construct(uint32 index) { ::new(mData + index)T; } // construct an element at place - MCORE_INLINE void Destruct(uint32 index) - { - #if (MCORE_COMPILER == MCORE_COMPILER_MSVC) - MCORE_UNUSED(index); // work around an MSVC compiler bug, where it triggers a warning that parameter 'index' is unused - #endif - (mData + index)->~T(); - } // destruct an element at - - // partition part of array (for sorting) - int32 Partition(int32 left, int32 right, CmpFunc cmp) - { - ::MCore::Swap(mData[left], mData[ (left + right) >> 1 ]); - - T& target = mData[right]; - int32 i = left - 1; - int32 j = right; - - bool neverQuit = true; // workaround to disable a "warning C4127: conditional expression is constant" - while (neverQuit) - { - while (i < j) - { - if (cmp(mData[++i], target) >= 0) - { - break; - } - } - while (j > i) - { - if (cmp(mData[--j], target) <= 0) - { - break; - } - } - if (i >= j) - { - break; - } - ::MCore::Swap(mData[i], mData[j]); - } - - ::MCore::Swap(mData[i], mData[right]); - return i; - } - }; -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Array2D.h b/Gems/EMotionFX/Code/MCore/Source/Array2D.h index a2bad5a5c2..f6c9234067 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Array2D.h +++ b/Gems/EMotionFX/Code/MCore/Source/Array2D.h @@ -45,8 +45,8 @@ namespace MCore */ struct TableEntry { - size_t mStartIndex; /**< The index offset where the data for this row starts. */ - size_t mNumElements; /**< The number of elements to follow. */ + size_t m_startIndex; /**< The index offset where the data for this row starts. */ + size_t m_numElements; /**< The number of elements to follow. */ }; /** @@ -67,7 +67,7 @@ namespace MCore * */ Array2D(size_t numRows, size_t numPreAllocatedElemsPerRow = 2) - : mNumPreCachedElements(numPreAllocatedElemsPerRow) { Resize(numRows); } + : m_numPreCachedElements(numPreAllocatedElemsPerRow) { Resize(numRows); } /** * Resize the array in one dimension (the number of rows). @@ -126,7 +126,7 @@ namespace MCore * speedup adding of new elements and prevent memory reallocs. The default value is set to 2 when creating an array, unless specified differently. * @param numElemsPerRow The number of elements per row that should be pre-allocated. */ - void SetNumPreCachedElements(size_t numElemsPerRow) { mNumPreCachedElements = numElemsPerRow; } + void SetNumPreCachedElements(size_t numElemsPerRow) { m_numPreCachedElements = numElemsPerRow; } /** * Get the number of pre-cached/allocated elements per row, when creating new rows. @@ -134,14 +134,14 @@ namespace MCore * @result The number of elements per row that will be pre-allocated/cached when adding a new row. * @see SetNumPreCachedElements. */ - size_t GetNumPreCachedElements() const { return mNumPreCachedElements; } + size_t GetNumPreCachedElements() const { return m_numPreCachedElements; } /** * Get the number of stored elements inside a given row. * @param rowIndex The row number. * @result The number of elements stored inside this row. */ - size_t GetNumElements(size_t rowIndex) const { return mIndexTable[rowIndex].mNumElements; } + size_t GetNumElements(size_t rowIndex) const { return m_indexTable[rowIndex].m_numElements; } /** * Get a pointer to the element data stored in a given row. @@ -152,7 +152,7 @@ namespace MCore * @param rowIndex the row number. * @result A pointer to the element data for the given row. */ - T* GetElements(size_t rowIndex) { return &mData[ mIndexTable[rowIndex].mStartIndex ]; } + T* GetElements(size_t rowIndex) { return &m_data[ m_indexTable[rowIndex].m_startIndex ]; } /** * Get the data of a given element. @@ -160,7 +160,7 @@ namespace MCore * @param elementNr The element number inside this row to retrieve. * @result A reference to the element data. */ - T& GetElement(size_t rowIndex, size_t elementNr) { return mData[ mIndexTable[rowIndex].mStartIndex + elementNr ]; } + T& GetElement(size_t rowIndex, size_t elementNr) { return m_data[ m_indexTable[rowIndex].m_startIndex + elementNr ]; } /** * Get the data of a given element. @@ -168,7 +168,7 @@ namespace MCore * @param elementNr The element number inside this row to retrieve. * @result A const reference to the element data. */ - const T& GetElement(size_t rowIndex, size_t elementNr) const { return mData[ mIndexTable[rowIndex].mStartIndex + elementNr ]; } + const T& GetElement(size_t rowIndex, size_t elementNr) const { return m_data[ m_indexTable[rowIndex].m_startIndex + elementNr ]; } /** * Set the value for a given element in the array. @@ -176,13 +176,13 @@ namespace MCore * @param elementNr The element number to set the value for. * @param value The value to set the element to. */ - void SetElement(size_t rowIndex, size_t elementNr, const T& value) { MCORE_ASSERT(rowIndex < mIndexTable.GetLength()); MCORE_ASSERT(elementNr < mIndexTable[rowIndex].mNumElements); mData[ mIndexTable[rowIndex].mStartIndex + elementNr ] = value; } + void SetElement(size_t rowIndex, size_t elementNr, const T& value) { MCORE_ASSERT(rowIndex < m_indexTable.GetLength()); MCORE_ASSERT(elementNr < m_indexTable[rowIndex].m_numElements); m_data[ m_indexTable[rowIndex].m_startIndex + elementNr ] = value; } /** * Get the number of rows in the 2D array. * @result The number of rows. */ - size_t GetNumRows() const { return mIndexTable.size(); } + size_t GetNumRows() const { return m_indexTable.size(); } /** * Calculate the percentage of memory that is filled with element data. @@ -192,7 +192,7 @@ namespace MCore * would be most optimal. * @result The percentage (in range of 0..100) of used element memory. */ - float CalcUsedElementMemoryPercentage() const { return (mData.GetLength() ? (CalcTotalNumElements() / (float)mData.GetLength()) * 100.0f : 0); } + float CalcUsedElementMemoryPercentage() const { return (m_data.GetLength() ? (CalcTotalNumElements() / (float)m_data.GetLength()) * 100.0f : 0); } /** * Swap the element data of two rows. @@ -220,12 +220,12 @@ namespace MCore */ void Clear(bool freeMem = true) { - mIndexTable.clear(); - mData.clear(); + m_indexTable.clear(); + m_data.clear(); if (freeMem) { - mIndexTable.shrink_to_fit(); - mData.shrink_to_fit(); + m_indexTable.shrink_to_fit(); + m_data.shrink_to_fit(); } } @@ -242,7 +242,7 @@ namespace MCore * The length of the array equals the value returned by GetNumRows(). * @result The array of index table entries, which specify the start indices and number of entries per row. */ - AZStd::vector& GetIndexTable() { return mIndexTable; } + AZStd::vector& GetIndexTable() { return m_indexTable; } /** * Get the data array. @@ -250,12 +250,12 @@ namespace MCore * Normally you shouldn't be using this method. However it is useful in some specific cases. * @result The data array that contains all elements. */ - AZStd::vector& GetData() { return mData; } + AZStd::vector& GetData() { return m_data; } private: - AZStd::vector mData; /**< The element data. */ - AZStd::vector mIndexTable; /**< The index table that let's us know where what data is inside the element data array. */ - size_t mNumPreCachedElements = 2; /**< The number of elements per row to pre-allocate when resizing this array. This prevents some re-allocs. */ + AZStd::vector m_data; /**< The element data. */ + AZStd::vector m_indexTable; /**< The index table that let's us know where what data is inside the element data array. */ + size_t m_numPreCachedElements = 2; /**< The number of elements per row to pre-allocate when resizing this array. This prevents some re-allocs. */ }; diff --git a/Gems/EMotionFX/Code/MCore/Source/Array2D.inl b/Gems/EMotionFX/Code/MCore/Source/Array2D.inl index 47a3fd7015..5682ab54b0 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Array2D.inl +++ b/Gems/EMotionFX/Code/MCore/Source/Array2D.inl @@ -11,7 +11,7 @@ template void Array2D::Resize(size_t numRows, bool autoShrink) { // get the current (old) number of rows - const size_t oldNumRows = mIndexTable.size(); + const size_t oldNumRows = m_indexTable.size(); // don't do anything when we don't need to if (numRows == oldNumRows) @@ -20,7 +20,7 @@ void Array2D::Resize(size_t numRows, bool autoShrink) } // resize the index table - mIndexTable.resize(numRows); + m_indexTable.resize(numRows); // check if we decreased the number of rows or not if (numRows < oldNumRows) @@ -36,13 +36,13 @@ void Array2D::Resize(size_t numRows, bool autoShrink) // init the new table entries for (size_t i = oldNumRows; i < numRows; ++i) { - mIndexTable[i].mStartIndex = mData.size() + (i * mNumPreCachedElements); - mIndexTable[i].mNumElements = 0; + m_indexTable[i].m_startIndex = m_data.size() + (i * m_numPreCachedElements); + m_indexTable[i].m_numElements = 0; } // grow the data array const size_t numNewRows = numRows - oldNumRows; - mData.resize(mData.size() + numNewRows * mNumPreCachedElements); + m_data.resize(m_data.size() + numNewRows * m_numPreCachedElements); } } @@ -51,20 +51,20 @@ void Array2D::Resize(size_t numRows, bool autoShrink) template void Array2D::Add(size_t rowIndex, const T& element) { - AZ_Assert(rowIndex < mIndexTable.size(), "Array index out of bounds"); + AZ_Assert(rowIndex < m_indexTable.size(), "Array index out of bounds"); // find the insert location inside the data array - size_t insertPos = mIndexTable[rowIndex].mStartIndex + mIndexTable[rowIndex].mNumElements; - if (insertPos >= mData.size()) + size_t insertPos = m_indexTable[rowIndex].m_startIndex + m_indexTable[rowIndex].m_numElements; + if (insertPos >= m_data.size()) { - mData.resize(insertPos + 1); + m_data.resize(insertPos + 1); } // check if we need to insert for real bool needRealInsert = true; - if (rowIndex < mIndexTable.size() - 1) // if there are still entries coming after the one we have to add to + if (rowIndex < m_indexTable.size() - 1) // if there are still entries coming after the one we have to add to { - if (insertPos < mIndexTable[rowIndex + 1].mStartIndex) // if basically there are empty unused element we can use + if (insertPos < m_indexTable[rowIndex + 1].m_startIndex) // if basically there are empty unused element we can use { needRealInsert = false; // then we don't need to do any reallocs } @@ -72,9 +72,9 @@ void Array2D::Add(size_t rowIndex, const T& element) else { // if we're dealing with the last row - if (rowIndex == mIndexTable.size() - 1) + if (rowIndex == m_indexTable.size() - 1) { - if (insertPos < mData.size()) // if basically there are empty unused element we can use + if (insertPos < m_data.size()) // if basically there are empty unused element we can use { needRealInsert = false; } @@ -85,22 +85,22 @@ void Array2D::Add(size_t rowIndex, const T& element) if (needRealInsert) { // insert the element inside the data array - mData.insert(AZStd::next(begin(mData), insertPos), element); + m_data.insert(AZStd::next(begin(m_data), insertPos), element); // adjust the index table entries - const size_t numRows = mIndexTable.size(); + const size_t numRows = m_indexTable.size(); for (size_t i = rowIndex + 1; i < numRows; ++i) { - mIndexTable[i].mStartIndex++; + m_indexTable[i].m_startIndex++; } } else { - mData[insertPos] = element; + m_data[insertPos] = element; } // increase the number of elements in the index table - mIndexTable[rowIndex].mNumElements++; + m_indexTable[rowIndex].m_numElements++; } @@ -108,21 +108,21 @@ void Array2D::Add(size_t rowIndex, const T& element) template void Array2D::Remove(size_t rowIndex, size_t elementIndex) { - AZ_Assert(rowIndex < mIndexTable.size(), "Array2D<>::Remove: array index out of bounds"); - AZ_Assert(elementIndex < mIndexTable[rowIndex].mNumElements, "Array2D<>::Remove: element index out of bounds"); - AZ_Assert(mIndexTable[rowIndex].mNumElements > 0, "Array2D<>::Remove: array index out of bounds"); + AZ_Assert(rowIndex < m_indexTable.size(), "Array2D<>::Remove: array index out of bounds"); + AZ_Assert(elementIndex < m_indexTable[rowIndex].m_numElements, "Array2D<>::Remove: element index out of bounds"); + AZ_Assert(m_indexTable[rowIndex].m_numElements > 0, "Array2D<>::Remove: array index out of bounds"); - const size_t startIndex = mIndexTable[rowIndex].mStartIndex; - const size_t maxElementIndex = mIndexTable[rowIndex].mNumElements - 1; + const size_t startIndex = m_indexTable[rowIndex].m_startIndex; + const size_t maxElementIndex = m_indexTable[rowIndex].m_numElements - 1; // swap the last element with the one to be removed if (elementIndex != maxElementIndex) { - mData[startIndex + elementIndex] = mData[startIndex + maxElementIndex]; + m_data[startIndex + elementIndex] = m_data[startIndex + maxElementIndex]; } // decrease the number of elements - mIndexTable[rowIndex].mNumElements--; + m_indexTable[rowIndex].m_numElements--; } @@ -130,8 +130,8 @@ void Array2D::Remove(size_t rowIndex, size_t elementIndex) template void Array2D::RemoveRow(size_t rowIndex, bool autoShrink) { - AZ_Assert(rowIndex < mIndexTable.GetLength(), "Array2D<>::RemoveRow: rowIndex out of bounds"); - mIndexTable.Remove(rowIndex); + AZ_Assert(rowIndex < m_indexTable.GetLength(), "Array2D<>::RemoveRow: rowIndex out of bounds"); + m_indexTable.Remove(rowIndex); // optimize memory usage when desired if (autoShrink) @@ -145,19 +145,19 @@ void Array2D::RemoveRow(size_t rowIndex, bool autoShrink) template void Array2D::RemoveRows(size_t startRow, size_t endRow, bool autoShrink) { - AZ_Assert(startRow < mIndexTable.size(), "Array2D<>::RemoveRows: startRow out of bounds"); - AZ_Assert(endRow < mIndexTable.size(), "Array2D<>::RemoveRows: endRow out of bounds"); + AZ_Assert(startRow < m_indexTable.size(), "Array2D<>::RemoveRows: startRow out of bounds"); + AZ_Assert(endRow < m_indexTable.size(), "Array2D<>::RemoveRows: endRow out of bounds"); // check if the start row is smaller than the end row if (startRow < endRow) { const size_t numToRemove = (endRow - startRow) + 1; - mIndexTable.erase(AZStd::next(begin(mIndexTable), startRow), AZStd::next(AZStd::next(begin(mIndexTable), startRow), numToRemove)); + m_indexTable.erase(AZStd::next(begin(m_indexTable), startRow), AZStd::next(AZStd::next(begin(m_indexTable), startRow), numToRemove)); } else // if the end row is smaller than the start row { const size_t numToRemove = (startRow - endRow) + 1; - mIndexTable.erase(AZStd::next(begin(mIndexTable), endRow), AZStd::next(AZStd::next(begin(mIndexTable), endRow), numToRemove)); + m_indexTable.erase(AZStd::next(begin(m_indexTable), endRow), AZStd::next(AZStd::next(begin(m_indexTable), endRow), numToRemove)); } // optimize memory usage when desired @@ -173,7 +173,7 @@ template void Array2D::Shrink() { // for all attributes, except for the last one - const size_t numRows = mIndexTable.size(); + const size_t numRows = m_indexTable.size(); if (numRows == 0) { return; @@ -183,20 +183,20 @@ void Array2D::Shrink() const size_t numRowsMinusOne = numRows - 1; for (size_t a = 0; a < numRowsMinusOne; ++a) { - const size_t firstUnusedIndex = mIndexTable[a ].mStartIndex + mIndexTable[a].mNumElements; - const size_t numUnusedElements = mIndexTable[a + 1].mStartIndex - firstUnusedIndex; + const size_t firstUnusedIndex = m_indexTable[a ].m_startIndex + m_indexTable[a].m_numElements; + const size_t numUnusedElements = m_indexTable[a + 1].m_startIndex - firstUnusedIndex; // if we have pre-cached/unused elements, remove those by moving memory to remove the "holes" if (numUnusedElements > 0) { // remove the unused elements from the array - mData.erase(AZStd::next(begin(mData), firstUnusedIndex), AZStd::next(AZStd::next(begin(mData), firstUnusedIndex), numUnusedElements)); + m_data.erase(AZStd::next(begin(m_data), firstUnusedIndex), AZStd::next(AZStd::next(begin(m_data), firstUnusedIndex), numUnusedElements)); // change the start indices for all the rows coming after the current one - const size_t numTotalRows = mIndexTable.size(); + const size_t numTotalRows = m_indexTable.size(); for (size_t i = a + 1; i < numTotalRows; ++i) { - mIndexTable[i].mStartIndex -= numUnusedElements; + m_indexTable[i].m_startIndex -= numUnusedElements; } } } @@ -207,25 +207,25 @@ void Array2D::Shrink() for (size_t row = 0; row < numRows; ++row) { // if the data starts after the place where it could start, move it to the place where it could start - if (mIndexTable[row].mStartIndex > dataPos) + if (m_indexTable[row].m_startIndex > dataPos) { - AZStd::move(AZStd::next(begin(mData), this->mIndexTable[row].mStartIndex), AZStd::next(AZStd::next(begin(mData), this->mIndexTable[row].mStartIndex), this->mIndexTable[row].mNumElements), AZStd::next(begin(mData), dataPos)); - mIndexTable[row].mStartIndex = dataPos; + AZStd::move(AZStd::next(begin(m_data), this->m_indexTable[row].m_startIndex), AZStd::next(AZStd::next(begin(m_data), this->m_indexTable[row].m_startIndex), this->m_indexTable[row].m_numElements), AZStd::next(begin(m_data), dataPos)); + m_indexTable[row].m_startIndex = dataPos; } // increase the data pos - dataPos += mIndexTable[row].mNumElements; + dataPos += m_indexTable[row].m_numElements; } // remove all unused data items - if (dataPos < mData.size()) + if (dataPos < m_data.size()) { - mData.erase(AZStd::next(begin(mData), dataPos), end(mData)); + m_data.erase(AZStd::next(begin(m_data), dataPos), end(m_data)); } // shrink the arrays - mData.shrink_to_fit(); - mIndexTable.shrink_to_fit(); + m_data.shrink_to_fit(); + m_indexTable.shrink_to_fit(); } @@ -236,10 +236,10 @@ size_t Array2D::CalcTotalNumElements() const size_t totalElements = 0; // add all number of row elements together - const size_t numRows = mIndexTable.size(); + const size_t numRows = m_indexTable.size(); for (size_t i = 0; i < numRows; ++i) { - totalElements += mIndexTable[i].mNumElements; + totalElements += m_indexTable[i].m_numElements; } return totalElements; @@ -251,14 +251,14 @@ template void Array2D::Swap(size_t rowA, size_t rowB) { // get the original number of elements from both rows - const size_t numElementsA = mIndexTable[rowA].mNumElements; - const size_t numElementsB = mIndexTable[rowB].mNumElements; + const size_t numElementsA = m_indexTable[rowA].m_numElements; + const size_t numElementsB = m_indexTable[rowB].m_numElements; // move the element data of rowA into a temp buffer AZStd::vector tempData(numElementsA); AZStd::move( - AZStd::next(mData.begin(), mIndexTable[rowA].mStartIndex), - AZStd::next(mData.begin(), mIndexTable[rowA].mStartIndex + numElementsA), + AZStd::next(m_data.begin(), m_indexTable[rowA].m_startIndex), + AZStd::next(m_data.begin(), m_indexTable[rowA].m_startIndex + numElementsA), tempData.begin() ); diff --git a/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp b/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp index ed2bc1a535..ac6772e44e 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Attribute.cpp @@ -8,14 +8,12 @@ #include "Attribute.h" #include "AttributeFactory.h" -#include "AttributeString.h" -#include "StringConversions.h" namespace MCore { - Attribute::Attribute(uint32 typeID) + Attribute::Attribute(AZ::u32 typeID) { - mTypeID = typeID; + m_typeId = typeID; } Attribute::~Attribute() diff --git a/Gems/EMotionFX/Code/MCore/Source/Attribute.h b/Gems/EMotionFX/Code/MCore/Source/Attribute.h index c245e7d778..e1ea970044 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Attribute.h +++ b/Gems/EMotionFX/Code/MCore/Source/Attribute.h @@ -28,7 +28,7 @@ namespace MCore class AttributeSettings; // the attribute interface types - enum : uint32 + enum : AZ::u32 { ATTRIBUTE_INTERFACETYPE_FLOATSPINNER = 0, // MCore::AttributeFloat ATTRIBUTE_INTERFACETYPE_FLOATSLIDER = 1, // MCore::AttributeFloat @@ -55,20 +55,20 @@ namespace MCore virtual Attribute* Clone() const = 0; virtual const char* GetTypeString() const = 0; - MCORE_INLINE uint32 GetType() const { return mTypeID; } + MCORE_INLINE AZ::u32 GetType() const { return m_typeId; } virtual bool InitFromString(const AZStd::string& valueString) = 0; virtual bool ConvertToString(AZStd::string& outString) const = 0; virtual bool InitFrom(const Attribute* other) = 0; - virtual uint32 GetClassSize() const = 0; - virtual uint32 GetDefaultInterfaceType() const = 0; + virtual size_t GetClassSize() const = 0; + virtual AZ::u32 GetDefaultInterfaceType() const = 0; Attribute& operator=(const Attribute& other); virtual void NetworkSerialize(EMotionFX::Network::AnimGraphSnapshotChunkSerializer&) {}; protected: - uint32 mTypeID; /**< The unique type ID of the attribute class. */ + AZ::u32 m_typeId; /**< The unique type ID of the attribute class. */ - Attribute(uint32 typeID); + Attribute(AZ::u32 typeID); }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeBool.cpp b/Gems/EMotionFX/Code/MCore/Source/AttributeBool.cpp index d91e188aae..cc9a7f88b7 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeBool.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeBool.cpp @@ -20,13 +20,13 @@ namespace MCore switch (other->GetType()) { case TYPE_ID: - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; case MCore::AttributeFloat::TYPE_ID: - mValue = !MCore::Math::IsFloatZero(static_cast(other)->GetValue()); + m_value = !MCore::Math::IsFloatZero(static_cast(other)->GetValue()); return true; case MCore::AttributeInt32::TYPE_ID: - mValue = static_cast(other)->GetValue() != 0; + m_value = static_cast(other)->GetValue() != 0; return true; default: return false; diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h b/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h index 9a923b5fda..bf5d13d8fe 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeBool.h @@ -35,33 +35,33 @@ namespace MCore static AttributeBool* Create(bool value = false); // adjust values - MCORE_INLINE bool GetValue() const { return mValue; } - MCORE_INLINE void SetValue(bool value) { mValue = value; } + MCORE_INLINE bool GetValue() const { return m_value; } + MCORE_INLINE void SetValue(bool value) { m_value = value; } - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(bool); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(bool); } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeBool::Create(mValue); } + Attribute* Clone() const override { return AttributeBool::Create(m_value); } const char* GetTypeString() const override { return "AttributeBool"; } bool InitFrom(const Attribute* other); bool InitFromString(const AZStd::string& valueString) override { - return AzFramework::StringFunc::LooksLikeBool(valueString.c_str(), &mValue); + return AzFramework::StringFunc::LooksLikeBool(valueString.c_str(), &m_value); } - bool ConvertToString(AZStd::string& outString) const override { outString = AZStd::string::format("%d", (mValue) ? 1 : 0); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeBool); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_CHECKBOX; } + bool ConvertToString(AZStd::string& outString) const override { outString = AZStd::string::format("%d", (m_value) ? 1 : 0); return true; } + size_t GetClassSize() const override { return sizeof(AttributeBool); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_CHECKBOX; } private: - bool mValue; /**< The boolean value, false on default. */ + bool m_value; /**< The boolean value, false on default. */ AttributeBool() : Attribute(TYPE_ID) - , mValue(false) {} + , m_value(false) {} AttributeBool(bool value) : Attribute(TYPE_ID) - , mValue(value) {} + , m_value(value) {} ~AttributeBool() {} }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h b/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h index 6287239bf8..31205a088e 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeColor.h @@ -38,14 +38,14 @@ namespace MCore static AttributeColor* Create(const RGBAColor& value); // adjust values - MCORE_INLINE const RGBAColor& GetValue() const { return mValue; } - MCORE_INLINE void SetValue(const RGBAColor& value) { mValue = value; } + MCORE_INLINE const RGBAColor& GetValue() const { return m_value; } + MCORE_INLINE void SetValue(const RGBAColor& value) { m_value = value; } - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(RGBAColor); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(RGBAColor); } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeColor::Create(mValue); } + Attribute* Clone() const override { return AttributeColor::Create(m_value); } const char* GetTypeString() const override { return "AttributeColor"; } bool InitFrom(const Attribute* other) override { @@ -53,7 +53,7 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override @@ -63,21 +63,21 @@ namespace MCore { return false; } - mValue.Set(vec4.GetX(), vec4.GetY(), vec4.GetZ(), vec4.GetW()); + m_value.Set(vec4.GetX(), vec4.GetY(), vec4.GetZ(), vec4.GetW()); return true; } - bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, AZ::Vector4(mValue.r, mValue.g, mValue.b, mValue.a)); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeColor); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_COLOR; } + bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, AZ::Vector4(m_value.m_r, m_value.m_g, m_value.m_b, m_value.m_a)); return true; } + size_t GetClassSize() const override { return sizeof(AttributeColor); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_COLOR; } private: - RGBAColor mValue; /**< The color value. */ + RGBAColor m_value; /**< The color value. */ AttributeColor() - : Attribute(TYPE_ID) { mValue.Set(0.0f, 0.0f, 0.0f, 1.0f); } + : Attribute(TYPE_ID) { m_value.Set(0.0f, 0.0f, 0.0f, 1.0f); } AttributeColor(const RGBAColor& value) : Attribute(TYPE_ID) - , mValue(value) { } + , m_value(value) { } ~AttributeColor() {} }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp index d0129bdb03..860d067671 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.cpp @@ -41,35 +41,35 @@ namespace MCore { if (delFromMem) { - for (Attribute* attribute : mRegistered) + for (Attribute* attribute : m_registered) { delete attribute; } } - mRegistered.clear(); + m_registered.clear(); } void AttributeFactory::RegisterAttribute(Attribute* attribute) { // check first if the type hasn't already been registered - const uint32 attribIndex = FindAttributeIndexByType(attribute->GetType()); - if (attribIndex != MCORE_INVALIDINDEX32) + const size_t attribIndex = FindAttributeIndexByType(attribute->GetType()); + if (attribIndex != InvalidIndex) { - MCore::LogWarning("MCore::AttributeFactory::RegisterAttribute() - There is already an attribute of the same type registered (typeID %d vs %d - typeString '%s' vs '%s')", attribute->GetType(), mRegistered[attribIndex]->GetType(), attribute->GetTypeString(), mRegistered[attribIndex]->GetTypeString()); + MCore::LogWarning("MCore::AttributeFactory::RegisterAttribute() - There is already an attribute of the same type registered (typeID %d vs %d - typeString '%s' vs '%s')", attribute->GetType(), m_registered[attribIndex]->GetType(), attribute->GetTypeString(), m_registered[attribIndex]->GetTypeString()); return; } - mRegistered.emplace_back(attribute); + m_registered.emplace_back(attribute); } void AttributeFactory::UnregisterAttribute(Attribute* attribute, bool delFromMem) { // check first if the type hasn't already been registered - const uint32 attribIndex = FindAttributeIndexByType(attribute->GetType()); - if (attribIndex == MCORE_INVALIDINDEX32) + const size_t attribIndex = FindAttributeIndexByType(attribute->GetType()); + if (attribIndex == InvalidIndex) { MCore::LogWarning("MCore::AttributeFactory::UnregisterAttribute() - No attribute with the given type found (typeID=%d - typeString='%s'", attribute->GetType(), attribute->GetTypeString()); return; @@ -77,44 +77,39 @@ namespace MCore if (delFromMem) { - delete mRegistered[attribIndex]; + delete m_registered[attribIndex]; } - mRegistered.erase(mRegistered.begin() + attribIndex); + m_registered.erase(m_registered.begin() + attribIndex); } - uint32 AttributeFactory::FindAttributeIndexByType(uint32 typeID) const + size_t AttributeFactory::FindAttributeIndexByType(size_t typeID) const { - const size_t numAttributes = mRegistered.size(); - for (size_t i = 0; i < numAttributes; ++i) + const auto foundAttribute = AZStd::find_if(begin(m_registered), end(m_registered), [typeID](const Attribute* registeredAttribute) { - if (mRegistered[i]->GetType() == typeID) // we found one with the same type - { - return static_cast(i); - } - } + return registeredAttribute->GetType() == typeID; + }); - // no attribute of this type found - return MCORE_INVALIDINDEX32; + return foundAttribute != end(m_registered) ? AZStd::distance(begin(m_registered), foundAttribute) : InvalidIndex; } - Attribute* AttributeFactory::CreateAttributeByType(uint32 typeID) const + Attribute* AttributeFactory::CreateAttributeByType(size_t typeID) const { - const uint32 attribIndex = FindAttributeIndexByType(typeID); - if (attribIndex == MCORE_INVALIDINDEX32) + const size_t attribIndex = FindAttributeIndexByType(typeID); + if (attribIndex == InvalidIndex) { return nullptr; } - return mRegistered[attribIndex]->Clone(); + return m_registered[attribIndex]->Clone(); } void AttributeFactory::RegisterStandardTypes() { - mRegistered.reserve(10); + m_registered.reserve(10); RegisterAttribute(aznew AttributeFloat()); RegisterAttribute(aznew AttributeInt32()); RegisterAttribute(aznew AttributeString()); diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h index 596ac24902..cb4c234267 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFactory.h @@ -30,13 +30,13 @@ namespace MCore void UnregisterAttribute(Attribute* attribute, bool delFromMem = true); void RegisterStandardTypes(); - size_t GetNumRegisteredAttributes() const { return mRegistered.size(); } - Attribute* GetRegisteredAttribute(uint32 index) const { return mRegistered[index]; } + size_t GetNumRegisteredAttributes() const { return m_registered.size(); } + Attribute* GetRegisteredAttribute(size_t index) const { return m_registered[index]; } - uint32 FindAttributeIndexByType(uint32 typeID) const; - Attribute* CreateAttributeByType(uint32 typeID) const; + size_t FindAttributeIndexByType(size_t typeID) const; + Attribute* CreateAttributeByType(size_t typeID) const; private: - AZStd::vector mRegistered; + AZStd::vector m_registered; }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.cpp b/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.cpp index d8310d0744..fdfdc8a03b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.cpp @@ -21,13 +21,13 @@ namespace MCore switch (other->GetType()) { case TYPE_ID: - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; case MCore::AttributeBool::TYPE_ID: - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; case MCore::AttributeInt32::TYPE_ID: - mValue = static_cast(static_cast(other)->GetValue()); + m_value = static_cast(static_cast(other)->GetValue()); return true; default: return false; diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h b/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h index ef650a1430..97a68a9673 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeFloat.h @@ -36,33 +36,33 @@ namespace MCore static AttributeFloat* Create(float value = 0.0f); // adjust values - MCORE_INLINE float GetValue() const { return mValue; } - MCORE_INLINE void SetValue(float value) { mValue = value; } + MCORE_INLINE float GetValue() const { return m_value; } + MCORE_INLINE void SetValue(float value) { m_value = value; } - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(float); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(float); } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeFloat::Create(mValue); } + Attribute* Clone() const override { return AttributeFloat::Create(m_value); } const char* GetTypeString() const override { return "AttributeFloat"; } bool InitFrom(const Attribute* other) override; bool InitFromString(const AZStd::string& valueString) override { - return AzFramework::StringFunc::LooksLikeFloat(valueString.c_str(), &mValue); + return AzFramework::StringFunc::LooksLikeFloat(valueString.c_str(), &m_value); } - bool ConvertToString(AZStd::string& outString) const override { outString = AZStd::string::format("%.8f", mValue); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeFloat); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_FLOATSPINNER; } + bool ConvertToString(AZStd::string& outString) const override { outString = AZStd::string::format("%.8f", m_value); return true; } + size_t GetClassSize() const override { return sizeof(AttributeFloat); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_FLOATSPINNER; } private: - float mValue; /**< The float value. */ + float m_value; /**< The float value. */ AttributeFloat() : Attribute(TYPE_ID) - , mValue(0.0f) {} + , m_value(0.0f) {} AttributeFloat(float value) : Attribute(TYPE_ID) - , mValue(value) {} + , m_value(value) {} ~AttributeFloat() {} }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.cpp b/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.cpp index d932c98a43..2297aca522 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.cpp @@ -21,13 +21,13 @@ namespace MCore switch (other->GetType()) { case TYPE_ID: - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; case MCore::AttributeBool::TYPE_ID: - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; case MCore::AttributeFloat::TYPE_ID: - mValue = static_cast(static_cast(other)->GetValue()); + m_value = static_cast(static_cast(other)->GetValue()); return true; default: return false; diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h b/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h index f13246d438..e195d584a5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeInt32.h @@ -36,33 +36,33 @@ namespace MCore static AttributeInt32* Create(int32 value = 0); // adjust values - MCORE_INLINE int32 GetValue() const { return mValue; } - MCORE_INLINE void SetValue(int32 value) { mValue = value; } + MCORE_INLINE int32 GetValue() const { return m_value; } + MCORE_INLINE void SetValue(int32 value) { m_value = value; } - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(int32); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(int32); } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeInt32::Create(mValue); } + Attribute* Clone() const override { return AttributeInt32::Create(m_value); } const char* GetTypeString() const override { return "AttributeInt32"; } bool InitFrom(const Attribute* other); bool InitFromString(const AZStd::string& valueString) override { - return AzFramework::StringFunc::LooksLikeInt(valueString.c_str(), &mValue); + return AzFramework::StringFunc::LooksLikeInt(valueString.c_str(), &m_value); } - bool ConvertToString(AZStd::string& outString) const override { outString = AZStd::string::format("%d", mValue); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeInt32); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_INTSPINNER; } + bool ConvertToString(AZStd::string& outString) const override { outString = AZStd::string::format("%d", m_value); return true; } + size_t GetClassSize() const override { return sizeof(AttributeInt32); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_INTSPINNER; } private: - int32 mValue; /**< The signed integer value. */ + int32 m_value; /**< The signed integer value. */ AttributeInt32() : Attribute(TYPE_ID) - , mValue(0) {} + , m_value(0) {} AttributeInt32(int32 value) : Attribute(TYPE_ID) - , mValue(value) {} + , m_value(value) {} ~AttributeInt32() {} }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h b/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h index 8f7a6cbc65..d0cf2d5194 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributePointer.h @@ -36,11 +36,11 @@ namespace MCore static AttributePointer* Create(void* value = nullptr); // adjust values - MCORE_INLINE void* GetValue() const { return mValue; } - MCORE_INLINE void SetValue(void* value) { mValue = value; } + MCORE_INLINE void* GetValue() const { return m_value; } + MCORE_INLINE void SetValue(void* value) { m_value = value; } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributePointer::Create(mValue); } + Attribute* Clone() const override { return AttributePointer::Create(m_value); } const char* GetTypeString() const override { return "AttributePointer"; } bool InitFrom(const Attribute* other) override { @@ -48,23 +48,23 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override { MCORE_UNUSED(valueString); MCORE_ASSERT(false); return false; } // currently unsupported bool ConvertToString(AZStd::string& outString) const override { MCORE_UNUSED(outString); MCORE_ASSERT(false); return false; } // currently unsupported - uint32 GetClassSize() const override { return sizeof(AttributePointer); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_DEFAULT; } + size_t GetClassSize() const override { return sizeof(AttributePointer); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_DEFAULT; } private: - void* mValue; /**< The pointer value. */ + void* m_value; /**< The pointer value. */ AttributePointer() : Attribute(TYPE_ID) - , mValue(nullptr) { } + , m_value(nullptr) { } AttributePointer(void* pointer) : Attribute(TYPE_ID) - , mValue(pointer) { } + , m_value(pointer) { } ~AttributePointer() {} }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h b/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h index 3380cac957..1efbe7f690 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeQuaternion.h @@ -38,15 +38,15 @@ namespace MCore static AttributeQuaternion* Create(float x, float y, float z, float w); static AttributeQuaternion* Create(const AZ::Quaternion& value); - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(AZ::Quaternion); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(AZ::Quaternion); } // adjust values - MCORE_INLINE const AZ::Quaternion& GetValue() const { return mValue; } - MCORE_INLINE void SetValue(const AZ::Quaternion& value) { mValue = value; } + MCORE_INLINE const AZ::Quaternion& GetValue() const { return m_value; } + MCORE_INLINE void SetValue(const AZ::Quaternion& value) { m_value = value; } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeQuaternion::Create(mValue); } + Attribute* Clone() const override { return AttributeQuaternion::Create(m_value); } const char* GetTypeString() const override { return "AttributeQuaternion"; } bool InitFrom(const Attribute* other) override { @@ -54,7 +54,7 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override @@ -64,23 +64,23 @@ namespace MCore { return false; } - mValue.Set(vec4.GetX(), vec4.GetY(), vec4.GetZ(), vec4.GetW()); + m_value.Set(vec4.GetX(), vec4.GetY(), vec4.GetZ(), vec4.GetW()); return true; } - bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, mValue); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeQuaternion); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_DEFAULT; } + bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, m_value); return true; } + size_t GetClassSize() const override { return sizeof(AttributeQuaternion); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_DEFAULT; } private: - AZ::Quaternion mValue; /**< The Quaternion value. */ + AZ::Quaternion m_value; /**< The Quaternion value. */ AttributeQuaternion() : Attribute(TYPE_ID) - , mValue(AZ::Quaternion::CreateIdentity()) + , m_value(AZ::Quaternion::CreateIdentity()) {} AttributeQuaternion(const AZ::Quaternion& value) : Attribute(TYPE_ID) - , mValue(value) {} + , m_value(value) {} ~AttributeQuaternion() { } }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeString.h b/Gems/EMotionFX/Code/MCore/Source/AttributeString.h index 4f3f8df6f9..916b9ad2fd 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeString.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeString.h @@ -35,16 +35,16 @@ namespace MCore static AttributeString* Create(const AZStd::string& value); static AttributeString* Create(const char* value = ""); - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(mValue.data()); } - MCORE_INLINE uint32 GetRawDataSize() const { return static_cast(mValue.size()); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(m_value.data()); } + MCORE_INLINE size_t GetRawDataSize() const { return m_value.size(); } // adjust values - MCORE_INLINE const char* AsChar() const { return mValue.c_str(); } - MCORE_INLINE const AZStd::string& GetValue() const { return mValue; } - MCORE_INLINE void SetValue(const AZStd::string& value) { mValue = value; } + MCORE_INLINE const char* AsChar() const { return m_value.c_str(); } + MCORE_INLINE const AZStd::string& GetValue() const { return m_value; } + MCORE_INLINE void SetValue(const AZStd::string& value) { m_value = value; } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeString::Create(mValue); } + Attribute* Clone() const override { return AttributeString::Create(m_value); } const char* GetTypeString() const override { return "AttributeString"; } bool InitFrom(const Attribute* other) override { @@ -52,25 +52,25 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } - bool InitFromString(const AZStd::string& valueString) override { mValue = valueString; return true; } - bool ConvertToString(AZStd::string& outString) const override { outString = mValue; return true; } - uint32 GetClassSize() const override { return sizeof(AttributeString); } + bool InitFromString(const AZStd::string& valueString) override { m_value = valueString; return true; } + bool ConvertToString(AZStd::string& outString) const override { outString = m_value; return true; } + size_t GetClassSize() const override { return sizeof(AttributeString); } uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_STRING; } private: - AZStd::string mValue; /**< The string value. */ + AZStd::string m_value; /**< The string value. */ AttributeString() : Attribute(TYPE_ID) { } AttributeString(const AZStd::string& value) : Attribute(TYPE_ID) - , mValue(value) { } + , m_value(value) { } AttributeString(const char* value) : Attribute(TYPE_ID) - , mValue(value) { } - ~AttributeString() { mValue.clear(); } + , m_value(value) { } + ~AttributeString() { m_value.clear(); } }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h b/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h index b82c7778f7..2d12e7a268 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeVector2.h @@ -42,15 +42,15 @@ namespace MCore static AttributeVector2* Create(const AZ::Vector2& value); static AttributeVector2* Create(float x, float y); - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeofVector2; } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeofVector2; } // adjust values - MCORE_INLINE const AZ::Vector2& GetValue() const { return mValue; } - MCORE_INLINE void SetValue(const AZ::Vector2& value) { mValue = value; } + MCORE_INLINE const AZ::Vector2& GetValue() const { return m_value; } + MCORE_INLINE void SetValue(const AZ::Vector2& value) { m_value = value; } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeVector2::Create(mValue); } + Attribute* Clone() const override { return AttributeVector2::Create(m_value); } const char* GetTypeString() const override { return "AttributeVector2"; } bool InitFrom(const Attribute* other) override { @@ -58,25 +58,25 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override { - return AzFramework::StringFunc::LooksLikeVector2(valueString.c_str(), &mValue); + return AzFramework::StringFunc::LooksLikeVector2(valueString.c_str(), &m_value); } - bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, mValue); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeVector2); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR2; } + bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, m_value); return true; } + size_t GetClassSize() const override { return sizeof(AttributeVector2); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR2; } private: - AZ::Vector2 mValue; /**< The Vector2 value. */ + AZ::Vector2 m_value; /**< The Vector2 value. */ AttributeVector2() - : Attribute(TYPE_ID) { mValue.Set(0.0f, 0.0f); } + : Attribute(TYPE_ID) { m_value.Set(0.0f, 0.0f); } AttributeVector2(const AZ::Vector2& value) : Attribute(TYPE_ID) - , mValue(value) { } + , m_value(value) { } ~AttributeVector2() { } }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h b/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h index ea6b820944..481a4e4665 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeVector3.h @@ -37,15 +37,15 @@ namespace MCore static AttributeVector3* Create(const AZ::Vector3& value); static AttributeVector3* Create(float x, float y, float z); - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(AZ::Vector3); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(AZ::Vector3); } // adjust values - MCORE_INLINE const AZ::Vector3& GetValue() const { return mValue; } - MCORE_INLINE void SetValue(const AZ::Vector3& value) { mValue = value; } + MCORE_INLINE const AZ::Vector3& GetValue() const { return m_value; } + MCORE_INLINE void SetValue(const AZ::Vector3& value) { m_value = value; } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeVector3::Create(mValue); } + Attribute* Clone() const override { return AttributeVector3::Create(m_value); } const char* GetTypeString() const override { return "AttributeVector3"; } bool InitFrom(const Attribute* other) override { @@ -53,7 +53,7 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override @@ -63,21 +63,21 @@ namespace MCore { return false; } - mValue.Set(vec3.GetX(), vec3.GetY(), vec3.GetZ()); + m_value.Set(vec3.GetX(), vec3.GetY(), vec3.GetZ()); return true; } - bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, mValue); return true; } - uint32 GetClassSize() const override { return sizeof(AttributeVector3); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR3; } + bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, m_value); return true; } + size_t GetClassSize() const override { return sizeof(AttributeVector3); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR3; } private: - AZ::Vector3 mValue; /**< The Vector3 value. */ + AZ::Vector3 m_value; /**< The Vector3 value. */ AttributeVector3() - : Attribute(TYPE_ID) { mValue.Set(0.0f, 0.0f, 0.0f); } + : Attribute(TYPE_ID) { m_value.Set(0.0f, 0.0f, 0.0f); } AttributeVector3(const AZ::Vector3& value) : Attribute(TYPE_ID) - , mValue(value) { } + , m_value(value) { } ~AttributeVector3() { } }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h b/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h index 93dc4a527b..cc38fb92ab 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h +++ b/Gems/EMotionFX/Code/MCore/Source/AttributeVector4.h @@ -38,15 +38,15 @@ namespace MCore static AttributeVector4* Create(const AZ::Vector4& value); static AttributeVector4* Create(float x, float y, float z, float w); - MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&mValue); } - MCORE_INLINE uint32 GetRawDataSize() const { return sizeof(AZ::Vector4); } + MCORE_INLINE uint8* GetRawDataPointer() { return reinterpret_cast(&m_value); } + MCORE_INLINE size_t GetRawDataSize() const { return sizeof(AZ::Vector4); } // adjust values - MCORE_INLINE const AZ::Vector4& GetValue() const { return mValue; } - MCORE_INLINE void SetValue(const AZ::Vector4& value) { mValue = value; } + MCORE_INLINE const AZ::Vector4& GetValue() const { return m_value; } + MCORE_INLINE void SetValue(const AZ::Vector4& value) { m_value = value; } // overloaded from the attribute base class - Attribute* Clone() const override { return AttributeVector4::Create(mValue); } + Attribute* Clone() const override { return AttributeVector4::Create(m_value); } const char* GetTypeString() const override { return "AttributeVector4"; } bool InitFrom(const Attribute* other) override { @@ -54,26 +54,25 @@ namespace MCore { return false; } - mValue = static_cast(other)->GetValue(); + m_value = static_cast(other)->GetValue(); return true; } bool InitFromString(const AZStd::string& valueString) override { - return AzFramework::StringFunc::LooksLikeVector4(valueString.c_str(), &mValue); + return AzFramework::StringFunc::LooksLikeVector4(valueString.c_str(), &m_value); } - bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, mValue); return true; } - // void ConvertCoordinateSystem() { GetCoordinateSystem().ConvertVector4(&mValue); } - uint32 GetClassSize() const override { return sizeof(AttributeVector4); } - uint32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR4; } + bool ConvertToString(AZStd::string& outString) const override { AZStd::to_string(outString, m_value); return true; } + size_t GetClassSize() const override { return sizeof(AttributeVector4); } + AZ::u32 GetDefaultInterfaceType() const override { return ATTRIBUTE_INTERFACETYPE_VECTOR4; } private: - AZ::Vector4 mValue; /**< The Vector4 value. */ + AZ::Vector4 m_value; /**< The Vector4 value. */ AttributeVector4() - : Attribute(TYPE_ID) { mValue.Set(0.0f, 0.0f, 0.0f, 0.0f); } + : Attribute(TYPE_ID) { m_value.Set(0.0f, 0.0f, 0.0f, 0.0f); } AttributeVector4(const AZ::Vector4& value) : Attribute(TYPE_ID) - , mValue(value) { } + , m_value(value) { } ~AttributeVector4() { } }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h b/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h index d185a804b8..bbc874dfdd 100644 --- a/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h +++ b/Gems/EMotionFX/Code/MCore/Source/AzCoreConversions.h @@ -29,7 +29,7 @@ namespace MCore { AZ_FORCE_INLINE AZ::Color EmfxColorToAzColor(const RGBAColor& emfxColor) { - return AZ::Color(emfxColor.r, emfxColor.g, emfxColor.b, emfxColor.a); + return AZ::Color(emfxColor.m_r, emfxColor.m_g, emfxColor.m_b, emfxColor.m_a); } AZ_FORCE_INLINE RGBAColor AzColorToEmfxColor(const AZ::Color& azColor) @@ -39,10 +39,10 @@ namespace MCore AZ_FORCE_INLINE AZ::Transform EmfxTransformToAzTransform(const EMotionFX::Transform& emfxTransform) { - AZ::Transform transform = AZ::Transform::CreateFromQuaternionAndTranslation(emfxTransform.mRotation, emfxTransform.mPosition); + AZ::Transform transform = AZ::Transform::CreateFromQuaternionAndTranslation(emfxTransform.m_rotation, emfxTransform.m_position); EMFX_SCALECODE ( - transform.MultiplyByUniformScale(emfxTransform.mScale.GetMaxElement()); + transform.MultiplyByUniformScale(emfxTransform.m_scale.GetMaxElement()); ) return transform; } diff --git a/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp b/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp index f462e5499f..376052563f 100644 --- a/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.cpp @@ -17,26 +17,26 @@ namespace MCore void BoundingSphere::Encapsulate(const AZ::Vector3& v) { // calculate the squared distance from the center to the point - const AZ::Vector3 diff = v - mCenter; + const AZ::Vector3 diff = v - m_center; const float dist = diff.Dot(diff); // if the current sphere doesn't contain the point, grow the sphere so that it contains the point - if (dist > mRadiusSq) + if (dist > m_radiusSq) { - const AZ::Vector3 diff2 = diff.GetNormalized() * mRadius; + const AZ::Vector3 diff2 = diff.GetNormalized() * m_radius; const AZ::Vector3 delta = 0.5f * (diff - diff2); - mCenter += delta; + m_center += delta; // TODO: KB- Was a 'safe' function, is there an AZ equivalent? float length = delta.GetLengthSq(); if (length >= FLT_EPSILON) { - mRadius += sqrtf(length); + m_radius += sqrtf(length); } else { - mRadius = 0.0f; + m_radius = 0.0f; } - mRadiusSq = mRadius * mRadius; + m_radiusSq = m_radius * m_radius; } } @@ -46,13 +46,13 @@ namespace MCore { float distance = 0.0f; - for (uint32 t = 0; t < 3; ++t) + for (int32_t t = 0; t < 3; ++t) { const AZ::Vector3& minVec = b.GetMin(); - if (mCenter.GetElement(t) < minVec.GetElement(t)) + if (m_center.GetElement(t) < minVec.GetElement(t)) { - distance += (mCenter.GetElement(t) - minVec.GetElement(t)) * (mCenter.GetElement(t) - minVec.GetElement(t)); - if (distance > mRadiusSq) + distance += (m_center.GetElement(t) - minVec.GetElement(t)) * (m_center.GetElement(t) - minVec.GetElement(t)); + if (distance > m_radiusSq) { return false; } @@ -60,10 +60,10 @@ namespace MCore else { const AZ::Vector3& maxVec = b.GetMax(); - if (mCenter.GetElement(t) > maxVec.GetElement(t)) + if (m_center.GetElement(t) > maxVec.GetElement(t)) { - distance += (mCenter.GetElement(t) - maxVec.GetElement(t)) * (mCenter.GetElement(t) - maxVec.GetElement(t)); - if (distance > mRadiusSq) + distance += (m_center.GetElement(t) - maxVec.GetElement(t)) * (m_center.GetElement(t) - maxVec.GetElement(t)); + if (distance > m_radiusSq) { return false; } @@ -79,23 +79,23 @@ namespace MCore bool BoundingSphere::Contains(const AABB& b) const { float distance = 0.0f; - for (uint32 t = 0; t < 3; ++t) + for (int32_t t = 0; t < 3; ++t) { const AZ::Vector3& maxVec = b.GetMax(); - if (mCenter.GetElement(t) < maxVec.GetElement(t)) + if (m_center.GetElement(t) < maxVec.GetElement(t)) { - distance += (mCenter.GetElement(t) - maxVec.GetElement(t)) * (mCenter.GetElement(t) - maxVec.GetElement(t)); + distance += (m_center.GetElement(t) - maxVec.GetElement(t)) * (m_center.GetElement(t) - maxVec.GetElement(t)); } else { const AZ::Vector3& minVec = b.GetMin(); - if (mCenter.GetElement(t) > minVec.GetElement(t)) + if (m_center.GetElement(t) > minVec.GetElement(t)) { - distance += (mCenter.GetElement(t) - minVec.GetElement(t)) * (mCenter.GetElement(t) - minVec.GetElement(t)); + distance += (m_center.GetElement(t) - minVec.GetElement(t)) * (m_center.GetElement(t) - minVec.GetElement(t)); } } - if (distance > mRadiusSq) + if (distance > m_radiusSq) { return false; } diff --git a/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.h b/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.h index db8aee70cc..1687f72799 100644 --- a/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.h +++ b/Gems/EMotionFX/Code/MCore/Source/BoundingSphere.h @@ -32,9 +32,9 @@ namespace MCore * Sets the sphere center to (0,0,0) and makes the radius 0. */ MCORE_INLINE BoundingSphere() - : mCenter(AZ::Vector3::CreateZero()) - , mRadius(0.0f) - , mRadiusSq(0.0f) {} + : m_center(AZ::Vector3::CreateZero()) + , m_radius(0.0f) + , m_radiusSq(0.0f) {} /** * Constructor which sets the center of the sphere and it's radius. @@ -43,9 +43,9 @@ namespace MCore * @param rad The radius of the sphere. */ MCORE_INLINE BoundingSphere(const AZ::Vector3& pos, float rad) - : mCenter(pos) - , mRadius(rad) - , mRadiusSq(rad * rad) {} + : m_center(pos) + , m_radius(rad) + , m_radiusSq(rad * rad) {} /** * Constructor which sets the center, radius and squared radius. @@ -55,16 +55,16 @@ namespace MCore * @param radSq The squared radius of the sphere (rad*rad). */ MCORE_INLINE BoundingSphere(const AZ::Vector3& pos, float rad, float radSq) - : mCenter(pos) - , mRadius(rad) - , mRadiusSq(radSq) {} + : m_center(pos) + , m_radius(rad) + , m_radiusSq(radSq) {} /** * Initialize the spheres center, radius and square radius. * This will set the center position to (0,0,0) and both the radius and squared radius to 0. * Call this method when you want to reset the sphere. Note that this is already done by the default constructor. */ - MCORE_INLINE void Init() { mCenter = AZ::Vector3::CreateZero(); mRadius = mRadiusSq = 0.0f; } + MCORE_INLINE void Init() { m_center = AZ::Vector3::CreateZero(); m_radius = m_radiusSq = 0.0f; } /** * Encapsulate a 3D point to the sphere. @@ -75,12 +75,12 @@ namespace MCore */ MCORE_INLINE void EncapsulateFast(const AZ::Vector3& v) { - AZ::Vector3 diff = (mCenter - v); + AZ::Vector3 diff = (m_center - v); const float dist = diff.Dot(diff); - if (dist > mRadiusSq) + if (dist > m_radiusSq) { - mRadiusSq = dist; - mRadius = Math::Sqrt(dist); + m_radiusSq = dist; + m_radius = Math::Sqrt(dist); } } @@ -90,7 +90,7 @@ namespace MCore * @param v The vector representing the 3D point to perform the test with. * @result Returns true when 'v' is inside the spheres volume, otherwise false is returned. */ - MCORE_INLINE bool Contains(const AZ::Vector3& v) { return ((mCenter - v).GetLengthSq() <= mRadiusSq); } + MCORE_INLINE bool Contains(const AZ::Vector3& v) { return ((m_center - v).GetLengthSq() <= m_radiusSq); } /** * Check if the sphere COMPLETELY contains a given other sphere. @@ -98,7 +98,7 @@ namespace MCore * @param s The sphere to perform the test with. * @result Returns true when 's' is completely inside this sphere. False is returned in any other case. */ - MCORE_INLINE bool Contains(const BoundingSphere& s) const { return ((mCenter - s.mCenter).GetLengthSq() <= (mRadiusSq - s.mRadiusSq)); } + MCORE_INLINE bool Contains(const BoundingSphere& s) const { return ((m_center - s.m_center).GetLengthSq() <= (m_radiusSq - s.m_radiusSq)); } /** * Check if a given sphere intersects with this sphere. @@ -106,7 +106,7 @@ namespace MCore * @param s The sphere to perform the intersection test with. * @result Returns true when 's' intersects this sphere. So if it's partially or completely inside this sphere or if the borders overlap. */ - MCORE_INLINE bool Intersects(const BoundingSphere& s) const { return ((mCenter - s.mCenter).GetLengthSq() <= (mRadiusSq + s.mRadiusSq)); } + MCORE_INLINE bool Intersects(const BoundingSphere& s) const { return ((m_center - s.m_center).GetLengthSq() <= (m_radiusSq + s.m_radiusSq)); } /** * Encapsulate a given 3D point with this sphere. @@ -138,36 +138,36 @@ namespace MCore * Get the radius of the sphere. * @result Returns the radius of the sphere. */ - MCORE_INLINE float GetRadius() const { return mRadius; } + MCORE_INLINE float GetRadius() const { return m_radius; } /** * Get the squared radius of the sphere. * @result Returns the squared radius of the sphere (no calculations done for this), since it's already known. */ - MCORE_INLINE float GetRadiusSquared() const { return mRadiusSq; } + MCORE_INLINE float GetRadiusSquared() const { return m_radiusSq; } /** * Get the center of the sphere. So the position of the sphere. * @result Returns the center position of the sphere. */ - MCORE_INLINE const AZ::Vector3& GetCenter() const { return mCenter; } + MCORE_INLINE const AZ::Vector3& GetCenter() const { return m_center; } /** * Set the center of the sphere. * @param center The center position of the sphere. */ - MCORE_INLINE void SetCenter(const AZ::Vector3& center) { mCenter = center; } + MCORE_INLINE void SetCenter(const AZ::Vector3& center) { m_center = center; } /** * Set the radius of the sphere. * The squared radius will automatically be updated inside this method. * @param radius The radius of the sphere. */ - MCORE_INLINE void SetRadius(float radius) { mRadius = radius; mRadiusSq = radius * radius; } + MCORE_INLINE void SetRadius(float radius) { m_radius = radius; m_radiusSq = radius * radius; } private: - AZ::Vector3 mCenter; /**< The center of the sphere. */ - float mRadius; /**< The radius of the sphere. */ - float mRadiusSq; /**< The squared radius of the sphere (mRadius*mRadius).*/ + AZ::Vector3 m_center; /**< The center of the sphere. */ + float m_radius; /**< The radius of the sphere. */ + float m_radiusSq; /**< The squared radius of the sphere (m_radius*m_radius).*/ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Color.cpp b/Gems/EMotionFX/Code/MCore/Source/Color.cpp index 77249bddfb..504142528c 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Color.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Color.cpp @@ -13,7 +13,7 @@ namespace MCore { // the color table - uint32 RGBAColor::mColorTable[128] = + uint32 RGBAColor::s_colorTable[128] = { 0xFF000080, 0xFF00008B, diff --git a/Gems/EMotionFX/Code/MCore/Source/Color.h b/Gems/EMotionFX/Code/MCore/Source/Color.h index 8845d1f41b..ee8b88cc47 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Color.h +++ b/Gems/EMotionFX/Code/MCore/Source/Color.h @@ -48,20 +48,20 @@ namespace MCore * Default constructor. Color will be set to black (0,0,0,0). */ MCORE_INLINE RGBAColor() - : r(0.0f) - , g(0.0f) - , b(0.0f) - , a(1.0f) {} + : m_r(0.0f) + , m_g(0.0f) + , m_b(0.0f) + , m_a(1.0f) {} /** * Constructor which sets all components to the same given value. * @param value The value to put in all components (r,g,b,a). */ MCORE_INLINE RGBAColor(float value) - : r(value) - , g(value) - , b(value) - , a(value) {} + : m_r(value) + , m_g(value) + , m_b(value) + , m_a(value) {} /** * Constructor which sets each color component. @@ -71,40 +71,40 @@ namespace MCore * @param cA The value for alpha [default=1.0] */ MCORE_INLINE RGBAColor(float cR, float cG, float cB, float cA = 1.0f) - : r(cR) - , g(cG) - , b(cB) - , a(cA) {} + : m_r(cR) + , m_g(cG) + , m_b(cB) + , m_a(cA) {} /** * Copy constructor. * @param col The color to copy the component values from. */ MCORE_INLINE RGBAColor(const RGBAColor& col) - : r(col.r) - , g(col.g) - , b(col.b) - , a(col.a) {} + : m_r(col.m_r) + , m_g(col.m_g) + , m_b(col.m_b) + , m_a(col.m_a) {} /** * Constructor to convert a 32-bits DWORD to a high precision color. * @param col The 32-bits DWORD, for example constructed using the MCore::RGBA(...) function. */ RGBAColor(uint32 col) - : r(ExtractRed(col) / 255.0f) - , g(ExtractGreen(col) / 255.0f) - , b(ExtractBlue(col) / 255.0f) - , a(ExtractAlpha(col) / 255.0f) {} + : m_r(ExtractRed(col) / 255.0f) + , m_g(ExtractGreen(col) / 255.0f) + , m_b(ExtractBlue(col) / 255.0f) + , m_a(ExtractAlpha(col) / 255.0f) {} /** * Constructor to convert from AZ::Color. This constructor is convenient until we replace the usage of this class with AZ::Color * @param color The AZ::Color to construct from */ RGBAColor(const AZ::Color& color) - : r(color.GetR()) - , g(color.GetG()) - , b(color.GetB()) - , a(color.GetA()) + : m_r(color.GetR()) + , m_g(color.GetG()) + , m_b(color.GetB()) + , m_a(color.GetA()) {} /** @@ -112,7 +112,7 @@ namespace MCore */ operator AZ::Color() const { - return AZ::Color(r, g, b, a); + return AZ::Color(m_r, m_g, m_b, m_a); } /** @@ -122,18 +122,18 @@ namespace MCore * @param cB The value for blue. * @param cA The value for alpha. */ - MCORE_INLINE void Set(float cR, float cG, float cB, float cA) { r = cR; g = cG; b = cB; a = cA; } + MCORE_INLINE void Set(float cR, float cG, float cB, float cA) { m_r = cR; m_g = cG; m_b = cB; m_a = cA; } /** * Set the color component values. * @param color The color to set. */ - MCORE_INLINE void Set(const RGBAColor& color) { r = color.r; g = color.g; b = color.b; a = color.a; } + MCORE_INLINE void Set(const RGBAColor& color) { m_r = color.m_r; m_g = color.m_g; m_b = color.m_b; m_a = color.m_a; } /** * Clear the color component values. Set them all to zero, so the color turns into black. */ - MCORE_INLINE void Zero() { r = g = b = a = 0.0f; } + MCORE_INLINE void Zero() { m_r = m_g = m_b = m_a = 0.0f; } /** * Clamp all color component values in a range of 0..1 @@ -141,20 +141,20 @@ namespace MCore * the Exposure method for exposure control or the Normalize method. * @result The clamped color. */ - MCORE_INLINE RGBAColor& Clamp() { r = MCore::Clamp(r, 0.0f, 1.0f); g = MCore::Clamp(g, 0.0f, 1.0f); b = MCore::Clamp(b, 0.0f, 1.0f); a = MCore::Clamp(a, 0.0f, 1.0f); return *this; } + MCORE_INLINE RGBAColor& Clamp() { m_r = MCore::Clamp(m_r, 0.0f, 1.0f); m_g = MCore::Clamp(m_g, 0.0f, 1.0f); m_b = MCore::Clamp(m_b, 0.0f, 1.0f); m_a = MCore::Clamp(m_a, 0.0f, 1.0f); return *this; } /** * Returns the length of the color components (r, g, b), just like you calculate the length of a vector. * The higher the length value, the more bright the color will be. * @result The length of the vector constructed by the r, g and b components. */ - MCORE_INLINE float CalcLength() const { return Math::Sqrt(r * r + g * g + b * b); } + MCORE_INLINE float CalcLength() const { return Math::Sqrt(m_r * m_r + m_g * m_g + m_b * m_b); } /** * Calculates and returns the intensity of the color. This gives an idea of how bright the color would be on the screen. * @result The intensity. */ - MCORE_INLINE float CalcIntensity() const { return r * 0.212671f + g * 0.715160f + b * 0.072169f; } + MCORE_INLINE float CalcIntensity() const { return m_r * 0.212671f + m_g * 0.715160f + m_b * 0.072169f; } /** * Checks if this color is close to another given color. @@ -164,25 +164,25 @@ namespace MCore */ MCORE_INLINE bool CheckIfIsClose(const RGBAColor& col, float distSq = 0.0001f) const { - float cR = (r - col.r); + float cR = (m_r - col.m_r); cR *= cR; if (cR > distSq) { return false; } - float cG = (g - col.g); + float cG = (m_g - col.m_g); cR += cG * cG; if (cR > distSq) { return false; } - float cB = (b - col.b); + float cB = (m_b - col.m_b); cR += cB * cB; if (cR > distSq) { return false; } - float cA = (a - col.a); + float cA = (m_a - col.m_a); cR += cA * cA; return (cR < distSq); } @@ -192,7 +192,7 @@ namespace MCore * In order to work correctly, the color component values must be in range of 0..1. So they have to be clamped, normalized or exposure controlled before calling this method. * @result The 32-bit integer value where each byte is a color component. */ - MCORE_INLINE uint32 ToInt() const { return MCore::RGBA((uint8)(r * 255), (uint8)(g * 255), (uint8)(b * 255), (uint8)(a * 255)); } + MCORE_INLINE uint32 ToInt() const { return MCore::RGBA((uint8)(m_r * 255), (uint8)(m_g * 255), (uint8)(m_b * 255), (uint8)(m_a * 255)); } /** * Perform exposure control on the color components. @@ -202,9 +202,9 @@ namespace MCore */ MCORE_INLINE RGBAColor& Exposure(float exposure = 1.5f) { - r = 1.0f - Math::Exp(-r * exposure); - g = 1.0f - Math::Exp(-g * exposure); - b = 1.0f - Math::Exp(-b * exposure); + m_r = 1.0f - Math::Exp(-m_r * exposure); + m_g = 1.0f - Math::Exp(-m_g * exposure); + m_b = 1.0f - Math::Exp(-m_b * exposure); return *this; } @@ -220,67 +220,67 @@ namespace MCore { float maxVal = 1.0f; - if (r > maxVal) + if (m_r > maxVal) { - maxVal = r; + maxVal = m_r; } - if (g > maxVal) + if (m_g > maxVal) { - maxVal = g; + maxVal = m_g; } - if (b > maxVal) + if (m_b > maxVal) { - maxVal = b; + maxVal = m_b; } float mul = 1.0f / maxVal; - r *= mul; - g *= mul; - b *= mul; + m_r *= mul; + m_g *= mul; + m_b *= mul; return *this; } // operators - MCORE_INLINE bool operator==(const RGBAColor& col) const { return ((r == col.r) && (g == col.g) && (b == col.b) && (a == col.a)); } - MCORE_INLINE const RGBAColor& operator*=(const RGBAColor& col) { r *= col.r; g *= col.g; b *= col.b; a *= col.a; return *this; } - MCORE_INLINE const RGBAColor& operator+=(const RGBAColor& col) { r += col.r; g += col.g; b += col.b; a += col.a; return *this; } - MCORE_INLINE const RGBAColor& operator-=(const RGBAColor& col) { r -= col.r; g -= col.g; b -= col.b; a -= col.a; return *this; } - MCORE_INLINE const RGBAColor& operator*=(float m) { r *= m; g *= m; b *= m; a *= m; return *this; } + MCORE_INLINE bool operator==(const RGBAColor& col) const { return ((m_r == col.m_r) && (m_g == col.m_g) && (m_b == col.m_b) && (m_a == col.m_a)); } + MCORE_INLINE const RGBAColor& operator*=(const RGBAColor& col) { m_r *= col.m_r; m_g *= col.m_g; m_b *= col.m_b; m_a *= col.m_a; return *this; } + MCORE_INLINE const RGBAColor& operator+=(const RGBAColor& col) { m_r += col.m_r; m_g += col.m_g; m_b += col.m_b; m_a += col.m_a; return *this; } + MCORE_INLINE const RGBAColor& operator-=(const RGBAColor& col) { m_r -= col.m_r; m_g -= col.m_g; m_b -= col.m_b; m_a -= col.m_a; return *this; } + MCORE_INLINE const RGBAColor& operator*=(float m) { m_r *= m; m_g *= m; m_b *= m; m_a *= m; return *this; } //MCORE_INLINE const RGBAColor& operator*=(double m) { r*=m; g*=m; b*=m; a*=m; return *this; } - MCORE_INLINE const RGBAColor& operator/=(float d) { float ooD = 1.0f / d; r *= ooD; g *= ooD; b *= ooD; a *= ooD; return *this; } + MCORE_INLINE const RGBAColor& operator/=(float d) { float ooD = 1.0f / d; m_r *= ooD; m_g *= ooD; m_b *= ooD; m_a *= ooD; return *this; } //MCORE_INLINE const RGBAColor& operator/=(double d) { float ooD=1.0f/d; r*=ooD; g*=ooD; b*=ooD; a*=ooD; return *this; } - MCORE_INLINE const RGBAColor& operator= (const RGBAColor& col) { r = col.r; g = col.g; b = col.b; a = col.a; return *this; } - MCORE_INLINE const RGBAColor& operator= (float colorValue) { r = colorValue; g = colorValue; b = colorValue; a = colorValue; return *this; } + MCORE_INLINE const RGBAColor& operator= (const RGBAColor& col) { m_r = col.m_r; m_g = col.m_g; m_b = col.m_b; m_a = col.m_a; return *this; } + MCORE_INLINE const RGBAColor& operator= (float colorValue) { m_r = colorValue; m_g = colorValue; m_b = colorValue; m_a = colorValue; return *this; } - MCORE_INLINE float& operator[](int32 row) { return ((float*)&r)[row]; } - MCORE_INLINE operator float*() { return (float*)&r; } - MCORE_INLINE operator const float*() const { return (const float*)&r; } + MCORE_INLINE float& operator[](int32 row) { return ((float*)&m_r)[row]; } + MCORE_INLINE operator float*() { return (float*)&m_r; } + MCORE_INLINE operator const float*() const { return (const float*)&m_r; } - static uint32 mColorTable[128]; + static uint32 s_colorTable[128]; // attributes - float r; /**< Red component. */ - float g; /**< Green component. */ - float b; /**< Blue component. */ - float a; /**< Alpha component. */ + float m_r; /**< Red component. */ + float m_g; /**< Green component. */ + float m_b; /**< Blue component. */ + float m_a; /**< Alpha component. */ }; /** * Picks a random color from a table of 128 different colors. * @result The generated color. */ - MCORE_INLINE uint32 GenerateColor() { return RGBAColor::mColorTable[rand() % 128]; } + MCORE_INLINE uint32 GenerateColor() { return RGBAColor::s_colorTable[rand() % 128]; } // operators - MCORE_INLINE RGBAColor operator*(const RGBAColor& colA, const RGBAColor& colB) { return RGBAColor(colA.r * colB.r, colA.g * colB.g, colA.b * colB.b, colA.a * colB.a); } - MCORE_INLINE RGBAColor operator+(const RGBAColor& colA, const RGBAColor& colB) { return RGBAColor(colA.r + colB.r, colA.g + colB.g, colA.b + colB.b, colA.a + colB.a); } - MCORE_INLINE RGBAColor operator-(const RGBAColor& colA, const RGBAColor& colB) { return RGBAColor(colA.r - colB.r, colA.g - colB.g, colA.b - colB.b, colA.b - colB.b); } - MCORE_INLINE RGBAColor operator*(const RGBAColor& colA, float m) { return RGBAColor(colA.r * m, colA.g * m, colA.b * m, colA.a * m); } + MCORE_INLINE RGBAColor operator*(const RGBAColor& colA, const RGBAColor& colB) { return RGBAColor(colA.m_r * colB.m_r, colA.m_g * colB.m_g, colA.m_b * colB.m_b, colA.m_a * colB.m_a); } + MCORE_INLINE RGBAColor operator+(const RGBAColor& colA, const RGBAColor& colB) { return RGBAColor(colA.m_r + colB.m_r, colA.m_g + colB.m_g, colA.m_b + colB.m_b, colA.m_a + colB.m_a); } + MCORE_INLINE RGBAColor operator-(const RGBAColor& colA, const RGBAColor& colB) { return RGBAColor(colA.m_r - colB.m_r, colA.m_g - colB.m_g, colA.m_b - colB.m_b, colA.m_b - colB.m_b); } + MCORE_INLINE RGBAColor operator*(const RGBAColor& colA, float m) { return RGBAColor(colA.m_r * m, colA.m_g * m, colA.m_b * m, colA.m_a * m); } //MCORE_INLINE RGBAColor operator*(const RGBAColor& colA, double m) { return RGBAColor(colA.r*m, colA.g*m, colA.b*m, colA.a*m); } - MCORE_INLINE RGBAColor operator*(float m, const RGBAColor& colB) { return RGBAColor(m * colB.r, m * colB.g, m * colB.b, m * colB.a); } + MCORE_INLINE RGBAColor operator*(float m, const RGBAColor& colB) { return RGBAColor(m * colB.m_r, m * colB.m_g, m * colB.m_b, m * colB.m_a); } //MCORE_INLINE RGBAColor operator*(double m, const RGBAColor& colB) { return RGBAColor(m*colB.r, m*colB.g, m*colB.b, m*colB.a); } - MCORE_INLINE RGBAColor operator/(const RGBAColor& colA, float d) { float ooD = 1.0f / d; return RGBAColor(colA.r * ooD, colA.g * ooD, colA.b * ooD, colA.a * ooD); } + MCORE_INLINE RGBAColor operator/(const RGBAColor& colA, float d) { float ooD = 1.0f / d; return RGBAColor(colA.m_r * ooD, colA.m_g * ooD, colA.m_b * ooD, colA.m_a * ooD); } //MCORE_INLINE RGBAColor operator/(const RGBAColor& colA, double d) { float ooD=1.0f/d; return RGBAColor(colA.r*ooD, colA.g*ooD, colA.b*ooD, colA.a*ooD); } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Command.cpp b/Gems/EMotionFX/Code/MCore/Source/Command.cpp index 39e9fde965..d53477b1e1 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Command.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Command.cpp @@ -8,6 +8,7 @@ // include the required headers #include "Command.h" +#include #include @@ -16,8 +17,8 @@ namespace MCore // constructor Command::Callback::Callback(bool executePreUndo, bool executePreCommand) { - mPreUndoExecute = executePreUndo; - mPreCommandExecute = executePreCommand; + m_preUndoExecute = executePreUndo; + m_preCommandExecute = executePreCommand; } @@ -29,8 +30,8 @@ namespace MCore // constructor Command::Command(AZStd::string commandName, Command* originalCommand) - : mOrgCommand(originalCommand) - , mCommandName(AZStd::move(commandName)) + : m_orgCommand(originalCommand) + , m_commandName(AZStd::move(commandName)) { } @@ -58,13 +59,13 @@ namespace MCore const char* Command::GetName() const { - return mCommandName.c_str(); + return m_commandName.c_str(); } const AZStd::string& Command::GetNameString() const { - return mCommandName; + return m_commandName; } @@ -81,27 +82,27 @@ namespace MCore } - uint32 Command::GetNumCallbacks() const + size_t Command::GetNumCallbacks() const { - return static_cast(mCallbacks.size()); + return m_callbacks.size(); } void Command::AddCallback(Command::Callback* callback) { - mCallbacks.push_back(callback); + m_callbacks.push_back(callback); } bool Command::CheckIfHasCallback(Command::Callback* callback) const { - return (AZStd::find(mCallbacks.begin(), mCallbacks.end(), callback) != mCallbacks.end()); + return (AZStd::find(m_callbacks.begin(), m_callbacks.end(), callback) != m_callbacks.end()); } void Command::RemoveCallback(Command::Callback* callback, bool delFromMem) { - mCallbacks.erase(AZStd::remove(mCallbacks.begin(), mCallbacks.end(), callback), mCallbacks.end()); + m_callbacks.erase(AZStd::remove(m_callbacks.begin(), m_callbacks.end(), callback), m_callbacks.end()); if (delFromMem) { delete callback; @@ -111,49 +112,30 @@ namespace MCore void Command::RemoveAllCallbacks() { - const size_t numCallbacks = mCallbacks.size(); + const size_t numCallbacks = m_callbacks.size(); for (size_t i = 0; i < numCallbacks; ++i) { // If it crashes here, you probably created your callback in another dll and didn't remove it from memory there as well. - delete mCallbacks[i]; + delete m_callbacks[i]; } - mCallbacks.clear(); + m_callbacks.clear(); } // calculate the number of registered pre-execute callbacks - uint32 Command::CalcNumPreCommandCallbacks() const + size_t Command::CalcNumPreCommandCallbacks() const { - uint32 result = 0; - - const size_t numCallbacks = mCallbacks.size(); - for (size_t i = 0; i < numCallbacks; ++i) + return AZStd::accumulate(begin(m_callbacks), end(m_callbacks), size_t{0}, [](size_t total, const Callback* callback) { - if (mCallbacks[i]->GetExecutePreCommand()) - { - result++; - } - } - - return result; + return callback->GetExecutePreCommand() ? total + 1 : total; + }); } // calculate the number of registered post-execute callbacks - uint32 Command::CalcNumPostCommandCallbacks() const + size_t Command::CalcNumPostCommandCallbacks() const { - uint32 result = 0; - - const size_t numCallbacks = mCallbacks.size(); - for (size_t i = 0; i < numCallbacks; ++i) - { - if (mCallbacks[i]->GetExecutePreCommand() == false) - { - result++; - } - } - - return result; + return m_callbacks.size() - CalcNumPreCommandCallbacks(); } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Command.h b/Gems/EMotionFX/Code/MCore/Source/Command.h index 7309c5dc91..615156223d 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Command.h +++ b/Gems/EMotionFX/Code/MCore/Source/Command.h @@ -68,9 +68,9 @@ namespace MCore const char* GetHistoryName() const { return HISTORYNAME; } \ const char* GetDescription() const; \ MCore::Command* Create() { return new CLASSNAME(this); } \ - OLDVALUETYPE& GetData() { return mData; } \ + OLDVALUETYPE& GetData() { return m_data; } \ protected: \ - OLDVALUETYPE mData; \ + OLDVALUETYPE m_data; \ #define MCORE_DEFINECOMMAND_1_END }; @@ -167,17 +167,17 @@ namespace MCore * Get the flag which controls if the callback gets executed before the command or after it. * @return True in case the callback gets called before the command, false when it gets called afterwards. */ - MCORE_INLINE bool GetExecutePreCommand() const { return mPreCommandExecute; } + MCORE_INLINE bool GetExecutePreCommand() const { return m_preCommandExecute; } /** * Get the flag which controls if the callback gets executed before undo or after it. * @return True in case the callback gets called before undo, false when it gets called afterwards. */ - MCORE_INLINE bool GetExecutePreUndo() const { return mPreUndoExecute; } + MCORE_INLINE bool GetExecutePreUndo() const { return m_preUndoExecute; } private: - bool mPreCommandExecute; /**< Flag which controls if the callback gets executed before the command (true) or after it (false). */ - bool mPreUndoExecute; /**< Flag which controls if the callback gets executed before the undo (true) or after it (false). */ + bool m_preCommandExecute; /**< Flag which controls if the callback gets executed before the command (true) or after it (false). */ + bool m_preUndoExecute; /**< Flag which controls if the callback gets executed before the undo (true) or after it (false). */ }; /** @@ -273,32 +273,32 @@ namespace MCore * Also it can verify and show info about these parameters. * @result The syntax object. */ - MCORE_INLINE CommandSyntax& GetSyntax() { return mSyntax; } + MCORE_INLINE CommandSyntax& GetSyntax() { return m_syntax; } /** * Get the number of registered/added command callbacks. * @result The number of command callbacks that have been added. */ - uint32 GetNumCallbacks() const; + size_t GetNumCallbacks() const; /** * Calculate the number of registered pre-execute callbacks. * @result The number of registered pre-execute callbacks. */ - uint32 CalcNumPreCommandCallbacks() const; + size_t CalcNumPreCommandCallbacks() const; /** * Calculate the number of registered post-execute callbacks. * @result The number of registered post-execute callbacks. */ - uint32 CalcNumPostCommandCallbacks() const; + size_t CalcNumPostCommandCallbacks() const; /** * Get a given command callback. * @param index The callback number, which must be in range of [0..GetNumCallbacks()-1]. * @result A pointer to the command callback object. */ - MCORE_INLINE Command::Callback* GetCallback(uint32 index) { return mCallbacks[index]; } + MCORE_INLINE Command::Callback* GetCallback(size_t index) { return m_callbacks[index]; } /** * Add (register) a command callback. @@ -325,7 +325,7 @@ namespace MCore */ void RemoveAllCallbacks(); - void SetOriginalCommand(Command* orgCommand) { mOrgCommand = orgCommand; } + void SetOriginalCommand(Command* orgCommand) { m_orgCommand = orgCommand; } /** * Get the original command where this command has been cloned from. @@ -335,9 +335,9 @@ namespace MCore */ MCORE_INLINE Command* GetOriginalCommand() { - if (mOrgCommand) + if (m_orgCommand) { - return mOrgCommand; + return m_orgCommand; } else { @@ -359,9 +359,9 @@ namespace MCore } private: - Command* mOrgCommand; /**< The original command, or nullptr when this is the original. */ - AZStd::string mCommandName; /**< The unique command name used to identify the command. */ - CommandSyntax mSyntax; /**< The command syntax, which contains info about the possible parameters etc. */ - AZStd::vector mCallbacks; /**< The command callbacks. */ + Command* m_orgCommand; /**< The original command, or nullptr when this is the original. */ + AZStd::string m_commandName; /**< The unique command name used to identify the command. */ + CommandSyntax m_syntax; /**< The command syntax, which contains info about the possible parameters etc. */ + AZStd::vector m_callbacks; /**< The command callbacks. */ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandGroup.cpp b/Gems/EMotionFX/Code/MCore/Source/CommandGroup.cpp index e69b91278d..e12b2b5ed8 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandGroup.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/CommandGroup.cpp @@ -35,144 +35,144 @@ namespace MCore { if (numToReserve > 0) { - mCommands.reserve(numToReserve); + m_commands.reserve(numToReserve); } } void CommandGroup::AddCommandString(const char* commandString) { - mCommands.emplace_back(CommandEntry()); - mCommands.back().mCommandString = commandString; + m_commands.emplace_back(CommandEntry()); + m_commands.back().m_commandString = commandString; } void CommandGroup::AddCommandString(const AZStd::string& commandString) { - mCommands.emplace_back(CommandEntry()); - mCommands.back().mCommandString = commandString; + m_commands.emplace_back(CommandEntry()); + m_commands.back().m_commandString = commandString; } void CommandGroup::AddCommand(MCore::Command* command) { - mCommands.emplace_back(CommandEntry()); - mCommands.back().mCommand = command; + m_commands.emplace_back(CommandEntry()); + m_commands.back().m_command = command; } const char* CommandGroup::GetCommandString(size_t index) const { - return mCommands[index].mCommandString.c_str(); + return m_commands[index].m_commandString.c_str(); } const AZStd::string& CommandGroup::GetCommandStringAsString(size_t index) const { - return mCommands[index].mCommandString; + return m_commands[index].m_commandString; } Command* CommandGroup::GetCommand(size_t index) { - return mCommands[index].mCommand; + return m_commands[index].m_command; } const CommandLine& CommandGroup::GetParameters(size_t index) const { - return mCommands[index].mCommandLine; + return m_commands[index].m_commandLine; } const char* CommandGroup::GetGroupName() const { - return mGroupName.c_str(); + return m_groupName.c_str(); } const AZStd::string& CommandGroup::GetGroupNameString() const { - return mGroupName; + return m_groupName; } void CommandGroup::SetGroupName(const char* groupName) { - mGroupName = groupName; + m_groupName = groupName; } void CommandGroup::SetGroupName(const AZStd::string& groupName) { - mGroupName = groupName; + m_groupName = groupName; } void CommandGroup::SetCommandString(size_t index, const char* commandString) { - mCommands[index].mCommandString = commandString; + m_commands[index].m_commandString = commandString; } void CommandGroup::SetParameters(size_t index, const CommandLine& params) { - mCommands[index].mCommandLine = params; + m_commands[index].m_commandLine = params; } void CommandGroup::SetCommand(size_t index, Command* command) { - mCommands[index].mCommand = command; + m_commands[index].m_command = command; } size_t CommandGroup::GetNumCommands() const { - return mCommands.size(); + return m_commands.size(); } void CommandGroup::RemoveAllCommands(bool delFromMem) { if (delFromMem) { - for (CommandEntry& commandEntry : mCommands) + for (CommandEntry& commandEntry : m_commands) { - delete commandEntry.mCommand; + delete commandEntry.m_command; } } - mCommands.clear(); + m_commands.clear(); } CommandGroup* CommandGroup::Clone() const { - CommandGroup* newGroup = new CommandGroup(mGroupName, 0); - newGroup->mCommands = mCommands; - newGroup->mHistoryAfterError = mHistoryAfterError; - newGroup->mContinueAfterError = mContinueAfterError; - newGroup->mReturnFalseAfterError = mReturnFalseAfterError; + CommandGroup* newGroup = new CommandGroup(m_groupName, 0); + newGroup->m_commands = m_commands; + newGroup->m_historyAfterError = m_historyAfterError; + newGroup->m_continueAfterError = m_continueAfterError; + newGroup->m_returnFalseAfterError = m_returnFalseAfterError; return newGroup; } // continue execution of the remaining commands after one fails to execute? void CommandGroup::SetContinueAfterError(bool continueAfter) { - mContinueAfterError = continueAfter; + m_continueAfterError = continueAfter; } // add group to the history even when one internal command failed to execute? void CommandGroup::SetAddToHistoryAfterError(bool addAfterError) { - mHistoryAfterError = addAfterError; + m_historyAfterError = addAfterError; } // check to see if we continue executing internal commands even if one failed bool CommandGroup::GetContinueAfterError() const { - return mContinueAfterError; + return m_continueAfterError; } // check if we add this group to the history, even if one internal command failed bool CommandGroup::GetAddToHistoryAfterError() const { - return mHistoryAfterError; + return m_historyAfterError; } // set if the command group shall return false after an error occurred or not void CommandGroup::SetReturnFalseAfterError(bool returnAfterError) { - mReturnFalseAfterError = returnAfterError; + m_returnFalseAfterError = returnAfterError; } // returns true in case the group returns false when executing it bool CommandGroup::GetReturnFalseAfterError() const { - return mReturnFalseAfterError; + return m_returnFalseAfterError; } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandGroup.h b/Gems/EMotionFX/Code/MCore/Source/CommandGroup.h index 5a4ef0a201..0d7b8683b1 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandGroup.h +++ b/Gems/EMotionFX/Code/MCore/Source/CommandGroup.h @@ -219,15 +219,15 @@ namespace MCore */ struct MCORE_API CommandEntry { - MCore::Command* mCommand = nullptr; /**< The command object, which gets set when you execute the group inside the command manager. */ - MCore::CommandLine mCommandLine{}; /**< The command line that was used when executing this command. */ - AZStd::string mCommandString{}; /**< The command string that we will execute. */ + MCore::Command* m_command = nullptr; /**< The command object, which gets set when you execute the group inside the command manager. */ + MCore::CommandLine m_commandLine{}; /**< The command line that was used when executing this command. */ + AZStd::string m_commandString{}; /**< The command string that we will execute. */ }; - AZStd::vector mCommands; /**< The set of commands inside the group. */ - AZStd::string mGroupName; /**< The name of the group as it will appear inside the command history. */ - bool mContinueAfterError; /**< */ - bool mHistoryAfterError; /**< */ - bool mReturnFalseAfterError; + AZStd::vector m_commands; /**< The set of commands inside the group. */ + AZStd::string m_groupName; /**< The name of the group as it will appear inside the command history. */ + bool m_continueAfterError; /**< */ + bool m_historyAfterError; /**< */ + bool m_returnFalseAfterError; }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp b/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp index 25ae5f548f..a55d066cdc 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/CommandLine.cpp @@ -26,22 +26,22 @@ namespace MCore void CommandLine::GetValue(const char* paramName, const char* defaultValue, AZStd::string* outResult) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { *outResult = defaultValue; return; } // return the default value if the parameter value is empty - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { *outResult = defaultValue; return; } // return the parameter value - *outResult = m_parameters[paramIndex].mValue; + *outResult = m_parameters[paramIndex].m_value; } @@ -49,22 +49,22 @@ namespace MCore void CommandLine::GetValue(const char* paramName, const char* defaultValue, AZStd::string& outResult) const { // Try to find the parameter index. - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { outResult = defaultValue; return; } // Return the default value if the parameter value is empty. - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { outResult = defaultValue; return; } // Return the actual parameter value. - outResult = m_parameters[paramIndex].mValue.c_str(); + outResult = m_parameters[paramIndex].m_value.c_str(); } @@ -72,20 +72,20 @@ namespace MCore int32 CommandLine::GetValueAsInt(const char* paramName, int32 defaultValue) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return defaultValue; } // return the default value if the parameter value is empty - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { return defaultValue; } // return the parameter value - return AzFramework::StringFunc::ToInt(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToInt(m_parameters[paramIndex].m_value.c_str()); } @@ -93,20 +93,20 @@ namespace MCore float CommandLine::GetValueAsFloat(const char* paramName, float defaultValue) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return defaultValue; } // return the default value if the parameter value is empty - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { return defaultValue; } // return the parameter value - return AzFramework::StringFunc::ToFloat(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToFloat(m_parameters[paramIndex].m_value.c_str()); } @@ -114,20 +114,20 @@ namespace MCore bool CommandLine::GetValueAsBool(const char* paramName, bool defaultValue) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return defaultValue; } // return the default value if the parameter value is empty - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { return true; } // return the parameter value - return AzFramework::StringFunc::ToBool(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToBool(m_parameters[paramIndex].m_value.c_str()); } @@ -135,21 +135,21 @@ namespace MCore AZ::Vector3 CommandLine::GetValueAsVector3(const char* paramName, const AZ::Vector3& defaultValue) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return defaultValue; } // return the default value if the parameter value is empty - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { return defaultValue; } // return the parameter value - return AzFramework::StringFunc::ToVector3(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToVector3(m_parameters[paramIndex].m_value.c_str()); } @@ -157,20 +157,20 @@ namespace MCore AZ::Vector4 CommandLine::GetValueAsVector4(const char* paramName, const AZ::Vector4& defaultValue) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return defaultValue; } // return the default value if the parameter value is empty - if (m_parameters[paramIndex].mValue.empty()) + if (m_parameters[paramIndex].m_value.empty()) { return defaultValue; } // return the parameter value - return AzFramework::StringFunc::ToVector4(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToVector4(m_parameters[paramIndex].m_value.c_str()); } @@ -178,15 +178,15 @@ namespace MCore void CommandLine::GetValue(const char* paramName, Command* command, AZStd::string* outResult) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName, *outResult); return; } // return the parameter value - *outResult = m_parameters[paramIndex].mValue; + *outResult = m_parameters[paramIndex].m_value; } @@ -198,10 +198,10 @@ namespace MCore AZ::Outcome CommandLine::GetValueIfExists(const char* paramName, Command* command) const { AZ_UNUSED(command); - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex != MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex != InvalidIndex) { - return AZ::Success(m_parameters[paramIndex].mValue); + return AZ::Success(m_parameters[paramIndex].m_value); } return AZ::Failure(); @@ -211,14 +211,14 @@ namespace MCore const AZStd::string& CommandLine::GetValue(const char* paramName, Command* command) const { // Try to find the parameter index. - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName); } // return the parameter value - return m_parameters[paramIndex].mValue; + return m_parameters[paramIndex].m_value; } @@ -226,8 +226,8 @@ namespace MCore int32 CommandLine::GetValueAsInt(const char* paramName, Command* command) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { AZStd::string result; if (command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName, result)) @@ -236,20 +236,20 @@ namespace MCore } else { - return MCORE_INVALIDINDEX32; + return InvalidIndexT; } } // return the parameter value - return AzFramework::StringFunc::ToInt(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToInt(m_parameters[paramIndex].m_value.c_str()); } // get the value as float float CommandLine::GetValueAsFloat(const char* paramName, Command* command) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { AZStd::string result; if (command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName, result)) @@ -263,7 +263,7 @@ namespace MCore } // return the parameter value - return AzFramework::StringFunc::ToFloat(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToFloat(m_parameters[paramIndex].m_value.c_str()); } @@ -271,8 +271,8 @@ namespace MCore bool CommandLine::GetValueAsBool(const char* paramName, Command* command) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { AZStd::string result; if (command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName, result)) @@ -286,7 +286,7 @@ namespace MCore } // return the parameter value - return AzFramework::StringFunc::ToBool(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToBool(m_parameters[paramIndex].m_value.c_str()); } @@ -294,8 +294,8 @@ namespace MCore AZ::Vector3 CommandLine::GetValueAsVector3(const char* paramName, Command* command) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { AZStd::string result; if (command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName, result)) @@ -309,7 +309,7 @@ namespace MCore } // return the parameter value - return AzFramework::StringFunc::ToVector3(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToVector3(m_parameters[paramIndex].m_value.c_str()); } @@ -317,8 +317,8 @@ namespace MCore AZ::Vector4 CommandLine::GetValueAsVector4(const char* paramName, Command* command) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { AZStd::string result; if (command->GetOriginalCommand()->GetSyntax().GetDefaultValue(paramName, result)) @@ -332,28 +332,28 @@ namespace MCore } // return the parameter value - return AzFramework::StringFunc::ToVector4(m_parameters[paramIndex].mValue.c_str()); + return AzFramework::StringFunc::ToVector4(m_parameters[paramIndex].m_value.c_str()); } // get the number of parameters - uint32 CommandLine::GetNumParameters() const + size_t CommandLine::GetNumParameters() const { - return static_cast(m_parameters.size()); + return m_parameters.size(); } // get the parameter name for a given parameter - const AZStd::string& CommandLine::GetParameterName(uint32 nr) const + const AZStd::string& CommandLine::GetParameterName(size_t nr) const { - return m_parameters[nr].mName; + return m_parameters[nr].m_name; } // get the parameter value for a given parameter number - const AZStd::string& CommandLine::GetParameterValue(uint32 nr) const + const AZStd::string& CommandLine::GetParameterValue(size_t nr) const { - return m_parameters[nr].mValue; + return m_parameters[nr].m_value; } @@ -361,54 +361,49 @@ namespace MCore bool CommandLine::CheckIfHasValue(const char* paramName) const { // try to find the parameter index - const uint32 paramIndex = FindParameterIndex(paramName); - if (paramIndex == MCORE_INVALIDINDEX32) + const size_t paramIndex = FindParameterIndex(paramName); + if (paramIndex == InvalidIndex) { return false; } // return true the parameter has a value that is not empty - return (m_parameters[paramIndex].mValue.empty() == false); + return (m_parameters[paramIndex].m_value.empty() == false); } // try to find a given parameter's index into the parameter array - uint32 CommandLine::FindParameterIndex(const char* paramName) const + size_t CommandLine::FindParameterIndex(const char* paramName) const { // compare all parameter names on a non-case sensitive way - const size_t numParams = m_parameters.size(); - for (size_t i = 0; i < numParams; ++i) + const auto foundParameter = AZStd::find_if(begin(m_parameters), end(m_parameters), [paramName](const Parameter& parameter) { - if (AzFramework::StringFunc::Equal(m_parameters[i].mName.c_str(), paramName, false /* no case */)) - { - return static_cast(i); - } - } + return AzFramework::StringFunc::Equal(parameter.m_name, paramName, false /* no case */); + }); - // not found - return MCORE_INVALIDINDEX32; + return foundParameter != end(m_parameters) ? AZStd::distance(begin(m_parameters), foundParameter) : InvalidIndex; } // check if we have a parameter with a given name defined bool CommandLine::CheckIfHasParameter(const char* paramName) const { - return (FindParameterIndex(paramName) != MCORE_INVALIDINDEX32); + return (FindParameterIndex(paramName) != InvalidIndex); } bool CommandLine::CheckIfHasParameter(const AZStd::string& paramName) const { - return (FindParameterIndex(paramName.c_str()) != MCORE_INVALIDINDEX32); + return (FindParameterIndex(paramName.c_str()) != InvalidIndex); } // extract the next parameter, starting from a given offset - bool CommandLine::ExtractNextParam(const AZStd::string& paramString, AZStd::string& outParamName, AZStd::string& outParamValue, uint32* inOutStartOffset) + bool CommandLine::ExtractNextParam(const AZStd::string& paramString, AZStd::string& outParamName, AZStd::string& outParamValue, size_t* inOutStartOffset) { outParamName.clear(); outParamValue.clear(); // check if we already reached the end of the string - uint32 offset = *inOutStartOffset; + size_t offset = *inOutStartOffset; if (offset >= paramString.size()) { return false; @@ -416,8 +411,8 @@ namespace MCore // filter out the next parameter AZStd::string::const_iterator iterator = paramString.begin() + offset; - uint32 paramNameStart = MCORE_INVALIDINDEX32; - uint32 paramValueStart = MCORE_INVALIDINDEX32; + size_t paramNameStart = InvalidIndex; + size_t paramValueStart = InvalidIndex; bool readingParamName = false; bool readingParamValue = false; bool foundNextParam = false; @@ -528,7 +523,7 @@ namespace MCore // extract all parameters AZStd::string paramName; AZStd::string paramValue; - uint32 offset = 0; + size_t offset = 0; while (ExtractNextParam(commandLine, paramName, paramValue, &offset)) { // if the parameter name is empty then it isn't a real parameter @@ -545,9 +540,9 @@ namespace MCore { const size_t numParameters = m_parameters.size(); LogInfo("Command line '%s' has %d parameters", debugName, numParameters); - for (uint32 i = 0; i < numParameters; ++i) + for (size_t i = 0; i < numParameters; ++i) { - LogInfo("Param %d (name='%s' value='%s'", i, m_parameters[i].mName.c_str(), m_parameters[i].mValue.c_str()); + LogInfo("Param %d (name='%s' value='%s'", i, m_parameters[i].m_name.c_str(), m_parameters[i].m_value.c_str()); } } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandLine.h b/Gems/EMotionFX/Code/MCore/Source/CommandLine.h index 8eef67ca3c..07b22ce9e5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandLine.h +++ b/Gems/EMotionFX/Code/MCore/Source/CommandLine.h @@ -207,21 +207,21 @@ namespace MCore * to the extended constructor or to the SetCommandLine function. * @result The number of parameters that have been detected. */ - uint32 GetNumParameters() const; + size_t GetNumParameters() const; /** * Get the name of a given parameter. * @param nr The parameter number, which must be in range of [0 .. GetNumParameters()-1]. * @result The name of the parameter. */ - const AZStd::string& GetParameterName(uint32 nr) const; + const AZStd::string& GetParameterName(size_t nr) const; /** * Get the value for a given parameter. * @param nr The parameter number, which must be in range of [0 .. GetNumParameters()-1]. * @return The value of the parameter, or "" (an empty string) when no value has been specified. */ - const AZStd::string& GetParameterValue(uint32 nr) const; + const AZStd::string& GetParameterValue(size_t nr) const; /** * Find the parameter index for a parameter with a specific name. @@ -229,7 +229,7 @@ namespace MCore * @param paramName The name of the parameter to search for. * @result The index/number of the parameter, or MCORE_INVALIDINDEX32 when no parameter with the specific name has been found. */ - uint32 FindParameterIndex(const char* paramName) const; + size_t FindParameterIndex(const char* paramName) const; /** * Check whether a given parameter has a value specified or not. @@ -271,13 +271,13 @@ namespace MCore */ struct MCORE_API Parameter { - AZStd::string mName; /**< The parameter name, for example "XRES". */ - AZStd::string mValue; /**< The parameter value, for example "1024". */ + AZStd::string m_name; /**< The parameter name, for example "XRES". */ + AZStd::string m_value; /**< The parameter value, for example "1024". */ }; AZStd::vector m_parameters; /**< The parameters that have been detected in the command line string. */ // extract the next parameter, starting from a given offset - bool ExtractNextParam(const AZStd::string& paramString, AZStd::string& outParamName, AZStd::string& outParamValue, uint32* inOutStartOffset); + bool ExtractNextParam(const AZStd::string& paramString, AZStd::string& outParamName, AZStd::string& outParamValue, size_t* inOutStartOffset); }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandManagerCallback.h b/Gems/EMotionFX/Code/MCore/Source/CommandManagerCallback.h index e08abde94d..b604465c75 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandManagerCallback.h +++ b/Gems/EMotionFX/Code/MCore/Source/CommandManagerCallback.h @@ -83,19 +83,19 @@ namespace MCore * @param command The command that is linked with this history item. * @param commandLine The command line that is linked to this history item. */ - virtual void OnAddCommandToHistory(uint32 historyIndex, CommandGroup* group, Command* command, const CommandLine& commandLine) = 0; + virtual void OnAddCommandToHistory(size_t historyIndex, CommandGroup* group, Command* command, const CommandLine& commandLine) = 0; /** * This callback is executed when a command is being removed from the command history. * @param historyIndex The history index of the command that is being removed. */ - virtual void OnRemoveCommand(uint32 historyIndex) = 0; + virtual void OnRemoveCommand(size_t historyIndex) = 0; /** * This callback is executed when we step back or forth in the command history. * @param index The new history index which will be the current state the system will be in. */ - virtual void OnSetCurrentCommand(uint32 index) = 0; + virtual void OnSetCurrentCommand(size_t index) = 0; /** * This callback is executed before the error array is getting cleared and the interfaces shall show some error reporting window or something similar. diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp index 676366ff8a..0bc228898c 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.cpp @@ -8,6 +8,7 @@ // include the required headers #include "CommandSyntax.h" +#include #include "LogManager.h" #include "Algorithms.h" #include "StringConversions.h" @@ -15,7 +16,7 @@ namespace MCore { // the constructor - CommandSyntax::CommandSyntax(uint32 numParamsToReserve) + CommandSyntax::CommandSyntax(size_t numParamsToReserve) { ReserveParameters(numParamsToReserve); } @@ -29,7 +30,7 @@ namespace MCore // reserve parameter space - void CommandSyntax::ReserveParameters(uint32 numParamsToReserve) + void CommandSyntax::ReserveParameters(size_t numParamsToReserve) { if (numParamsToReserve > 0) { @@ -65,28 +66,28 @@ namespace MCore // check if this param is a required one or not - bool CommandSyntax::GetParamRequired(uint32 index) const + bool CommandSyntax::GetParamRequired(size_t index) const { - return m_parameters[index].mRequired; + return m_parameters[index].m_required; } // get the parameter name - const char* CommandSyntax::GetParamName(uint32 index) const + const char* CommandSyntax::GetParamName(size_t index) const { - return m_parameters[index].mName.c_str(); + return m_parameters[index].m_name.c_str(); } // get the parameter description - const char* CommandSyntax::GetParamDescription(uint32 index) const + const char* CommandSyntax::GetParamDescription(size_t index) const { - return m_parameters[index].mDescription.c_str(); + return m_parameters[index].m_description.c_str(); } // get the parameter type string - const char* CommandSyntax::GetParamTypeString(uint32 index) const + const char* CommandSyntax::GetParamTypeString(size_t index) const { return GetParamTypeString(m_parameters[index]); } @@ -94,7 +95,7 @@ namespace MCore const char* CommandSyntax::GetParamTypeString(const Parameter& parameter) const { // check the type - switch (parameter.mParamType) + switch (parameter.m_paramType) { case PARAMTYPE_STRING: return "String"; @@ -128,47 +129,41 @@ namespace MCore // get the parameter type CommandSyntax::EParamType CommandSyntax::GetParamType(size_t index) const { - return m_parameters[index].mParamType; + return m_parameters[index].m_paramType; } // check if we have a given parameter with a given name in this syntax bool CommandSyntax::CheckIfHasParameter(const char* parameter) const { - return (FindParameterIndex(parameter) != MCORE_INVALIDINDEX32); + return (FindParameterIndex(parameter) != InvalidIndex); } // find the parameter index of a given parameter name - uint32 CommandSyntax::FindParameterIndex(const char* parameter) const + size_t CommandSyntax::FindParameterIndex(const char* parameter) const { - // try to find the parameter with the given name - const size_t numParams = m_parameters.size(); - for (size_t i = 0; i < numParams; ++i) + const auto foundParameter = AZStd::find_if(begin(m_parameters), end(m_parameters), [parameter](const Parameter& p) { - if (AzFramework::StringFunc::Equal(m_parameters[i].mName.c_str(), parameter, false /* no case */)) - { - return static_cast(i); - } - } - - return MCORE_INVALIDINDEX32; + return AzFramework::StringFunc::Equal(p.m_name, parameter, false /* no case */); + }); + return foundParameter != end(m_parameters) ? AZStd::distance(begin(m_parameters), foundParameter) : InvalidIndex; } // get the default value for a given parameter - const AZStd::string& CommandSyntax::GetDefaultValue(uint32 index) const + const AZStd::string& CommandSyntax::GetDefaultValue(size_t index) const { - return m_parameters[index].mDefaultValue; + return m_parameters[index].m_defaultValue; } const AZStd::string& CommandSyntax::GetDefaultValue(const char* paramName) const { - const uint32 index = FindParameterIndex(paramName); - if (index != MCORE_INVALIDINDEX32) + const size_t index = FindParameterIndex(paramName); + if (index != InvalidIndex) { - return m_parameters[index].mDefaultValue; + return m_parameters[index].m_defaultValue; } static const AZStd::string empty; @@ -179,13 +174,13 @@ namespace MCore // get the default value for a given parameter name bool CommandSyntax::GetDefaultValue(const char* paramName, AZStd::string& outDefaultValue) const { - const uint32 index = FindParameterIndex(paramName); - if (index == MCORE_INVALIDINDEX32) + const size_t index = FindParameterIndex(paramName); + if (index == InvalidIndex) { return false; } - outDefaultValue = m_parameters[index].mDefaultValue; + outDefaultValue = m_parameters[index].m_defaultValue; return true; } @@ -208,28 +203,28 @@ namespace MCore for (const Parameter& parameter : m_parameters) { // if the required parameter hasn't been specified - if (parameter.mRequired && commandLine.CheckIfHasParameter(parameter.mName) == false) + if (parameter.m_required && commandLine.CheckIfHasParameter(parameter.m_name) == false) { - outResult += AZStd::string::format("Required parameter '%s' has not been specified.\n", parameter.mName.c_str()); + outResult += AZStd::string::format("Required parameter '%s' has not been specified.\n", parameter.m_name.c_str()); } else { // find the parameter index - const uint32 paramIndex = commandLine.FindParameterIndex(parameter.mName.c_str()); - if (paramIndex != MCORE_INVALIDINDEX32) + const size_t paramIndex = commandLine.FindParameterIndex(parameter.m_name.c_str()); + if (paramIndex != InvalidIndex) { const AZStd::string& value = commandLine.GetParameterValue(paramIndex); - const AZStd::string& paramName = parameter.mName; + const AZStd::string& paramName = parameter.m_name; // if the parameter value has not been specified and it is not a boolean parameter - if ((value.empty()) && parameter.mParamType != PARAMTYPE_BOOLEAN && parameter.mParamType != PARAMTYPE_STRING) + if ((value.empty()) && parameter.m_paramType != PARAMTYPE_BOOLEAN && parameter.m_paramType != PARAMTYPE_STRING) { outResult += AZStd::string::format("Parameter '%s' has no value specified.\n", paramName.c_str()); } else { // check if we specified a valid int - if (parameter.mParamType == PARAMTYPE_INT) + if (parameter.m_paramType == PARAMTYPE_INT) { if (!AzFramework::StringFunc::LooksLikeInt(value.c_str())) { @@ -238,7 +233,7 @@ namespace MCore } // check if the specified float is valid - if (parameter.mParamType == PARAMTYPE_FLOAT) + if (parameter.m_paramType == PARAMTYPE_FLOAT) { if (!AzFramework::StringFunc::LooksLikeFloat(value.c_str())) { @@ -247,7 +242,7 @@ namespace MCore } // check if this is a valid boolean - if (parameter.mParamType == PARAMTYPE_BOOLEAN) + if (parameter.m_paramType == PARAMTYPE_BOOLEAN) { if (!value.empty() && !AzFramework::StringFunc::LooksLikeBool(value.c_str())) { @@ -256,7 +251,7 @@ namespace MCore } // check if this is a valid boolean - if (parameter.mParamType == PARAMTYPE_CHAR) + if (parameter.m_paramType == PARAMTYPE_CHAR) { if (value.size() > 1) { @@ -265,7 +260,7 @@ namespace MCore } // check if the specified vector3 is valid - if (parameter.mParamType == PARAMTYPE_VECTOR3) + if (parameter.m_paramType == PARAMTYPE_VECTOR3) { if (!AzFramework::StringFunc::LooksLikeVector3(value.c_str())) { @@ -274,7 +269,7 @@ namespace MCore } // check if the specified vector3 is valid - if (parameter.mParamType == PARAMTYPE_VECTOR4) + if (parameter.m_paramType == PARAMTYPE_VECTOR4) { if (!AzFramework::StringFunc::LooksLikeVector4(value.c_str())) { @@ -282,13 +277,13 @@ namespace MCore } } } - } // if (paramIndex != MCORE_INVALIDINDEX32) + } // if (paramIndex != InvalidIndex) } } // now add parameters that we specified but that are not defined in the syntax - const uint32 numCommandLineParams = commandLine.GetNumParameters(); - for (uint32 p = 0; p < numCommandLineParams; ++p) + const size_t numCommandLineParams = commandLine.GetNumParameters(); + for (size_t p = 0; p < numCommandLineParams; ++p) { if (CheckIfHasParameter(commandLine.GetParameterName(p).c_str()) == false) { @@ -305,14 +300,13 @@ namespace MCore void CommandSyntax::LogSyntax() { // find the longest command name - uint32 offset = 0; - for (const Parameter& parameter : m_parameters) + size_t offset = AZStd::minmax_element(begin(m_parameters), end(m_parameters), [](const Parameter& left, const Parameter& right) { - offset = MCore::Max(static_cast(parameter.mName.size()), offset); - } + return left.m_name.size() < right.m_name.size(); + }).second->m_name.size(); - uint32 offset2 = offset; - uint32 offset3 = offset; + size_t offset2 = offset; + size_t offset3 = offset; // log the header AZStd::string header = "Name"; @@ -336,19 +330,19 @@ namespace MCore for (const Parameter& parameter : m_parameters) { offset2 = offset3; - final = parameter.mName; + final = parameter.m_name; offset2 += 5; final.append(offset2 - final.size(), MCore::CharacterConstants::space); final += GetParamTypeString(parameter); offset2 += 15; final.append(offset2 - final.size(), MCore::CharacterConstants::space); - final += parameter.mRequired ? "Yes" : "No"; + final += parameter.m_required ? "Yes" : "No"; offset2 += 10; final.append(offset2 - final.size(), MCore::CharacterConstants::space); - final += parameter.mDefaultValue; + final += parameter.m_defaultValue; offset2 += 20; final.append(offset2 - final.size(), MCore::CharacterConstants::space); - final += parameter.mDescription; + final += parameter.m_description; MCore::LogInfo(final.c_str()); } diff --git a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h index a077f0212a..ded4c1ee02 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h +++ b/Gems/EMotionFX/Code/MCore/Source/CommandSyntax.h @@ -47,15 +47,15 @@ namespace MCore struct MCORE_API Parameter { Parameter(AZStd::string name, AZStd::string description, AZStd::string defaultValue, EParamType paramType, bool required) - : mName(AZStd::move(name)), mDescription(AZStd::move(description)), mDefaultValue(AZStd::move(defaultValue)), mParamType(paramType), mRequired(required) + : m_name(AZStd::move(name)), m_description(AZStd::move(description)), m_defaultValue(AZStd::move(defaultValue)), m_paramType(paramType), m_required(required) { } - AZStd::string mName; /**< The name of the parameter. */ - AZStd::string mDescription; /**< The description of the parameter. */ - AZStd::string mDefaultValue; /**< The default value. */ - EParamType mParamType; /**< The parameter type. */ - bool mRequired; /**< Is this parameter required or optional? */ + AZStd::string m_name; /**< The name of the parameter. */ + AZStd::string m_description; /**< The description of the parameter. */ + AZStd::string m_defaultValue; /**< The default value. */ + EParamType m_paramType; /**< The parameter type. */ + bool m_required; /**< Is this parameter required or optional? */ }; public: @@ -63,7 +63,7 @@ namespace MCore * The constructor. * @param numParamsToReserve The amount of parameters to pre-allocate memory for. This can reduce the number of reallocs needed when registering new paramters. */ - CommandSyntax(uint32 numParamsToReserve = 5); + CommandSyntax(size_t numParamsToReserve = 5); /** * The destructor. @@ -74,7 +74,7 @@ namespace MCore * Reserve space for a given number of parameters, to prevent memory reallocs when adding new parameters. * @param numParamsToReserve The number of parameters to reserve space for. */ - void ReserveParameters(uint32 numParamsToReserve); + void ReserveParameters(size_t numParamsToReserve); /** * Add a new optional parameter to this syntax. @@ -99,28 +99,28 @@ namespace MCore * @param index The parameter number to check. * @result Returns true when the parameter is required, or false when it is optional. */ - bool GetParamRequired(uint32 index) const; + bool GetParamRequired(size_t index) const; /** * Get the name of a given parameter. * @param index The parameter number to get the name for. * @result The string containing the name of the parameter. */ - const char* GetParamName(uint32 index) const; + const char* GetParamName(size_t index) const; /** * Get the description of a given parameter. * @param index The parameter number to get the description for. * @result A string containing the description of the parameter. */ - const char* GetParamDescription(uint32 index) const; + const char* GetParamDescription(size_t index) const; /** * Get the default value for a given parameter. * @param index The parameter number to get the default value from. * @result The string containing the default value. */ - const AZStd::string& GetDefaultValue(uint32 index) const; + const AZStd::string& GetDefaultValue(size_t index) const; /** * Get the default value for a parameter with a given name. @@ -141,7 +141,7 @@ namespace MCore * Get the number of parameters registered to this syntax. * @result The number of added/registered parameters. */ - MCORE_INLINE uint32 GetNumParameters() const { return static_cast(m_parameters.size()); } + MCORE_INLINE size_t GetNumParameters() const { return m_parameters.size(); } /** * Get the parameter type string of a given parameter. @@ -149,7 +149,7 @@ namespace MCore * @param index The parameter number to get the type string for. * @result The parameter type string. */ - const char* GetParamTypeString(uint32 index) const; + const char* GetParamTypeString(size_t index) const; const char* GetParamTypeString(const Parameter& parameter) const; /** @@ -189,7 +189,7 @@ namespace MCore * @param parameter The name of the parameter, non-case-sensitive. * @result Returns the index of the parameter, in range of [0..GetNumParameters()-1], or MCORE_INVALIDINDEX32 in case it hasn't been found. */ - uint32 FindParameterIndex(const char* parameter) const; + size_t FindParameterIndex(const char* parameter) const; /** * Log the currently registered syntax using MCore::LogInfo(...). diff --git a/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.h b/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.h index 0ad5d2c5fd..99ef631e39 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.h +++ b/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.h @@ -82,7 +82,7 @@ namespace MCore MCORE_INLINE float ToFloat(float minValue, float maxValue) const; public: - StorageType mValue; /**< The compressed/packed value. */ + StorageType m_value; /**< The compressed/packed value. */ // the number of steps within the specified range enum diff --git a/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.inl b/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.inl index 54bb5ec3ea..61b971b2aa 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.inl +++ b/Gems/EMotionFX/Code/MCore/Source/CompressedFloat.inl @@ -19,7 +19,7 @@ MCORE_INLINE TCompressedFloat::TCompressedFloat(float value, float { // TODO: make sure due to rounding/floating point errors the result is not negative? const StorageType f = (1.0f / (maxValue - minValue)) * CONVERT_VALUE; - mValue = (value - minValue) * f; + m_value = (value - minValue) * f; } @@ -27,7 +27,7 @@ MCORE_INLINE TCompressedFloat::TCompressedFloat(float value, float template MCORE_INLINE TCompressedFloat::TCompressedFloat(StorageType value) { - mValue = value; + m_value = value; } @@ -37,7 +37,7 @@ MCORE_INLINE void TCompressedFloat::FromFloat(float value, float mi { // TODO: make sure due to rounding/floating point errors the result is not negative? const StorageType f = (StorageType)(1.0f / (maxValue - minValue)) * CONVERT_VALUE; - mValue = (StorageType)((value - minValue) * f); + m_value = (StorageType)((value - minValue) * f); } @@ -47,7 +47,7 @@ MCORE_INLINE void TCompressedFloat::UnCompress(float* output, float { // unpack and normalize const float f = (1.0f / (float)CONVERT_VALUE) * (maxValue - minValue); - *output = ((float)mValue * f) + minValue; + *output = ((float)m_value * f) + minValue; } @@ -56,5 +56,5 @@ template MCORE_INLINE float TCompressedFloat::ToFloat(float minValue, float maxValue) const { const float f = (1.0f / (float)CONVERT_VALUE) * (maxValue - minValue); - return ((mValue * f) + minValue); + return ((m_value * f) + minValue); } diff --git a/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.h b/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.h index ce3304dd8f..0b25283410 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.h +++ b/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.h @@ -73,7 +73,7 @@ namespace MCore AZ_INLINE operator AZ::Quaternion() const { return ToQuaternion(); } public: - StorageType mX, mY, mZ, mW; /**< The compressed/packed quaternion components values. */ + StorageType m_x, m_y, m_z, m_w; /**< The compressed/packed quaternion components values. */ // the number of steps within the specified range enum diff --git a/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.inl b/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.inl index 4dc1c2d867..2f8499b6ba 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.inl +++ b/Gems/EMotionFX/Code/MCore/Source/CompressedQuaternion.inl @@ -9,10 +9,10 @@ // constructor template MCORE_INLINE TCompressedQuaternion::TCompressedQuaternion() - : mX(0) - , mY(0) - , mZ(0) - , mW(CONVERT_VALUE) + : m_x(0) + , m_y(0) + , m_z(0) + , m_w(CONVERT_VALUE) { } @@ -20,10 +20,10 @@ MCORE_INLINE TCompressedQuaternion::TCompressedQuaternion() // constructor template MCORE_INLINE TCompressedQuaternion::TCompressedQuaternion(float xVal, float yVal, float zVal, float wVal) - : mX((StorageType)xVal) - , mY((StorageType)yVal) - , mZ((StorageType)zVal) - , mW((StorageType)wVal) + : m_x((StorageType)xVal) + , m_y((StorageType)yVal) + , m_z((StorageType)zVal) + , m_w((StorageType)wVal) { } @@ -31,10 +31,10 @@ MCORE_INLINE TCompressedQuaternion::TCompressedQuaternion(float xVa // constructor template MCORE_INLINE TCompressedQuaternion::TCompressedQuaternion(const AZ::Quaternion& quat) - : mX((StorageType)(static_cast(quat.GetX()) * CONVERT_VALUE)) - , mY((StorageType)(static_cast(quat.GetY()) * CONVERT_VALUE)) - , mZ((StorageType)(static_cast(quat.GetZ()) * CONVERT_VALUE)) - , mW((StorageType)(static_cast(quat.GetW()) * CONVERT_VALUE)) + : m_x((StorageType)(static_cast(quat.GetX()) * CONVERT_VALUE)) + , m_y((StorageType)(static_cast(quat.GetY()) * CONVERT_VALUE)) + , m_z((StorageType)(static_cast(quat.GetZ()) * CONVERT_VALUE)) + , m_w((StorageType)(static_cast(quat.GetW()) * CONVERT_VALUE)) { } @@ -44,10 +44,10 @@ template MCORE_INLINE void TCompressedQuaternion::FromQuaternion(const AZ::Quaternion& quat) { // pack it - mX = (StorageType)(static_cast(quat.GetX()) * CONVERT_VALUE); - mY = (StorageType)(static_cast(quat.GetY()) * CONVERT_VALUE); - mZ = (StorageType)(static_cast(quat.GetZ()) * CONVERT_VALUE); - mW = (StorageType)(static_cast(quat.GetW()) * CONVERT_VALUE); + m_x = (StorageType)(static_cast(quat.GetX()) * CONVERT_VALUE); + m_y = (StorageType)(static_cast(quat.GetY()) * CONVERT_VALUE); + m_z = (StorageType)(static_cast(quat.GetZ()) * CONVERT_VALUE); + m_w = (StorageType)(static_cast(quat.GetW()) * CONVERT_VALUE); } // uncompress into a quaternion @@ -55,7 +55,7 @@ template MCORE_INLINE void TCompressedQuaternion::UnCompress(AZ::Quaternion* output) const { const float f = 1.0f / (float)CONVERT_VALUE; - output->Set(mX * f, mY * f, mZ * f, mW * f); + output->Set(m_x * f, m_y * f, m_z * f, m_w * f); } @@ -63,7 +63,7 @@ MCORE_INLINE void TCompressedQuaternion::UnCompress(AZ::Quaternion* template <> MCORE_INLINE void TCompressedQuaternion::UnCompress(AZ::Quaternion* output) const { - output->Set(mX * 0.000030518509448f, mY * 0.000030518509448f, mZ * 0.000030518509448f, mW * 0.000030518509448f); + output->Set(m_x * 0.000030518509448f, m_y * 0.000030518509448f, m_z * 0.000030518509448f, m_w * 0.000030518509448f); } @@ -72,7 +72,7 @@ template MCORE_INLINE AZ::Quaternion TCompressedQuaternion::ToQuaternion() const { const float f = 1.0f / (float)CONVERT_VALUE; - return AZ::Quaternion(mX * f, mY * f, mZ * f, mW * f); + return AZ::Quaternion(m_x * f, m_y * f, m_z * f, m_w * f); } @@ -80,5 +80,5 @@ MCORE_INLINE AZ::Quaternion TCompressedQuaternion::ToQuaternion() c template <> MCORE_INLINE AZ::Quaternion TCompressedQuaternion::ToQuaternion() const { - return AZ::Quaternion(mX * 0.000030518509448f, mY * 0.000030518509448f, mZ * 0.000030518509448f, mW * 0.000030518509448f); + return AZ::Quaternion(m_x * 0.000030518509448f, m_y * 0.000030518509448f, m_z * 0.000030518509448f, m_w * 0.000030518509448f); } diff --git a/Gems/EMotionFX/Code/MCore/Source/CompressedVector.h b/Gems/EMotionFX/Code/MCore/Source/CompressedVector.h index 32fc2d71f7..d38a0a1862 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CompressedVector.h +++ b/Gems/EMotionFX/Code/MCore/Source/CompressedVector.h @@ -46,9 +46,9 @@ namespace MCore * @param z The compressed z component. */ MCORE_INLINE TCompressedVector3(StorageType x, StorageType y, StorageType z) - : mX(x) - , mY(y) - , mZ(z) {} + : m_x(x) + , m_y(y) + , m_z(z) {} /** * Create a compressed vector from an uncompressed one. @@ -78,7 +78,7 @@ namespace MCore public: - StorageType mX, mY, mZ; /**< The compressed/packed vector components. */ + StorageType m_x, m_y, m_z; /**< The compressed/packed vector components. */ // the number of steps within the specified range enum diff --git a/Gems/EMotionFX/Code/MCore/Source/CompressedVector.inl b/Gems/EMotionFX/Code/MCore/Source/CompressedVector.inl index 693e2ac832..ce9adc60c9 100644 --- a/Gems/EMotionFX/Code/MCore/Source/CompressedVector.inl +++ b/Gems/EMotionFX/Code/MCore/Source/CompressedVector.inl @@ -19,9 +19,9 @@ MCORE_INLINE TCompressedVector3::TCompressedVector3(const AZ::Vecto { // TODO: make sure due to rounding/floating point errors the result is not negative? const float f = static_cast(CONVERT_VALUE) / (maxValue - minValue); - mX = static_cast((vec.GetX() - minValue) * f); - mY = static_cast((vec.GetY() - minValue) * f); - mZ = static_cast((vec.GetZ() - minValue) * f); + m_x = static_cast((vec.GetX() - minValue) * f); + m_y = static_cast((vec.GetY() - minValue) * f); + m_z = static_cast((vec.GetZ() - minValue) * f); } @@ -31,9 +31,9 @@ MCORE_INLINE void TCompressedVector3::FromVector3(const AZ::Vector3 { // TODO: make sure due to rounding/floating point errors the result is not negative? const float f = static_cast(CONVERT_VALUE) / (maxValue - minValue); - mX = static_cast((vec.GetX() - minValue) * f); - mY = static_cast((vec.GetY() - minValue) * f); - mZ = static_cast((vec.GetZ() - minValue) * f); + m_x = static_cast((vec.GetX() - minValue) * f); + m_y = static_cast((vec.GetY() - minValue) * f); + m_z = static_cast((vec.GetZ() - minValue) * f); } @@ -42,6 +42,6 @@ template MCORE_INLINE AZ::Vector3 TCompressedVector3::ToVector3(float minValue, float maxValue) const { const float f = (maxValue - minValue) / static_cast(CONVERT_VALUE); - return AZ::Vector3(static_cast(mX) * f + minValue, static_cast(mY) * f + minValue, static_cast(mZ) * f + minValue); + return AZ::Vector3(static_cast(m_x) * f + minValue, static_cast(m_y) * f + minValue, static_cast(m_z) * f + minValue); } diff --git a/Gems/EMotionFX/Code/MCore/Source/Config.h b/Gems/EMotionFX/Code/MCore/Source/Config.h index d01bab61fc..c753a45ec3 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Config.h +++ b/Gems/EMotionFX/Code/MCore/Source/Config.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include @@ -275,23 +276,35 @@ typedef uintptr_t uintPointer; // mark as unused to prevent compiler warnings #define MCORE_UNUSED(x) static_cast(x) +namespace MCore +{ + template + inline static constexpr IndexType InvalidIndexT = static_cast(-1); + + inline static constexpr const size_t InvalidIndex = InvalidIndexT; + inline static constexpr const AZ::u64 InvalidIndex64 = InvalidIndexT; + inline static constexpr const AZ::u32 InvalidIndex32 = InvalidIndexT; + inline static constexpr const AZ::u16 InvalidIndex16 = InvalidIndexT; + inline static constexpr const AZ::u8 InvalidIndex8 = InvalidIndexT; +} // namespace MCore + /** * Often there are functions that allow you to search for objects. Such functions return some index value that points * inside for example the array of objects. However, in case the object we are searching for cannot be found, some * value has to be returned that identifies that the object cannot be found. The MCORE_INVALIDINDEX32 value is used * used as this value. The real value is 0xFFFFFFFF. */ -#define MCORE_INVALIDINDEX32 0xFFFFFFFF +#define MCORE_INVALIDINDEX32 MCore::InvalidIndex32 /** * The 16 bit index variant of MCORE_INVALIDINDEX32. * The real value is 0xFFFF. */ -#define MCORE_INVALIDINDEX16 0xFFFF +#define MCORE_INVALIDINDEX16 MCore::InvalidIndex16 /** * The 8 bit index variant of MCORE_INVALIDINDEX32. * The real value is 0xFF. */ -#define MCORE_INVALIDINDEX8 0xFF +#define MCORE_INVALIDINDEX8 MCore::InvalidIndex8 diff --git a/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp b/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp index f1fd5543a8..6fd0c59085 100644 --- a/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/DiskFile.cpp @@ -15,7 +15,7 @@ namespace MCore // constructor DiskFile::DiskFile() : File() - , mFile(nullptr) + , m_file(nullptr) { } @@ -38,75 +38,54 @@ namespace MCore bool DiskFile::Open(const char* fileName, EMode mode) { // if the file already is open, close it first - if (mFile) + if (m_file) { Close(); } - //String fileMode; - char fileMode[4]; - uint32 numChars = 0; - - if (mode == READ) - { - fileMode[0] = 'r'; - numChars = 1; - } // open for reading, file must exist - if (mode == WRITE) - { - fileMode[0] = 'w'; - numChars = 1; - } // open for writing, file will be overwritten if it already exists - if (mode == READWRITE) - { - fileMode[0] = 'r'; - fileMode[1] = '+'; - numChars = 2; - } // open for reading and writing, file must exist - if (mode == READWRITECREATE) + const char* fileMode = [mode]() -> const char* { - fileMode[0] = 'w'; - fileMode[1] = '+'; - numChars = 2; - } // open for reading and writing, file will be overwritten when already exists, or created when it doesn't - if (mode == APPEND) - { - fileMode[0] = 'a'; - numChars = 1; - } // open for writing at the end of the file, file will be created when it doesn't exist - if (mode == READWRITEAPPEND) - { - fileMode[0] = 'a'; - fileMode[1] = '+'; - numChars = 2; - } // open for reading and appending (writing), file will be created if it doesn't exist - - // construct the filemode string - fileMode[numChars++] = 'b'; // open in binary mode - fileMode[numChars++] = '\0'; + switch(mode) + { + case READ: // open for reading, file must exist + return "rb"; + case WRITE: // open for writing, file will be overwritten if it already exists + return "wb"; + case READWRITE: // open for reading and writing, file must exist + return "r+b"; + case READWRITECREATE: // open for reading and writing, file will be overwritten when already exists, or created when it doesn't + return "w+b"; + case APPEND: // open for writing at the end of the file, file will be created when it doesn't exist + return "ab"; + case READWRITEAPPEND: // open for reading and appending (writing), file will be created if it doesn't exist + return "a+b"; + default: + return ""; + } + }(); // set the file mode we used - mFileMode = mode; + m_fileMode = mode; // set the filename - mFileName = fileName; + m_fileName = fileName; // try to open the file - mFile = nullptr; - azfopen(&mFile, fileName, fileMode); + m_file = nullptr; + azfopen(&m_file, fileName, fileMode); // check on success - return (mFile != nullptr); + return (m_file != nullptr); } // close the file void DiskFile::Close() { - if (mFile) + if (m_file) { - fclose(mFile); - mFile = nullptr; + fclose(m_file); + m_file = nullptr; } } @@ -114,41 +93,41 @@ namespace MCore // flush the file void DiskFile::Flush() { - MCORE_ASSERT(mFile); - fflush(mFile); + MCORE_ASSERT(m_file); + fflush(m_file); } bool DiskFile::GetIsOpen() const { - return (mFile != nullptr); + return (m_file != nullptr); } // return true when we have reached the end of the file bool DiskFile::GetIsEOF() const { - MCORE_ASSERT(mFile); - return (feof(mFile) != 0); + MCORE_ASSERT(m_file); + return (feof(m_file) != 0); } // returns the next byte in the file uint8 DiskFile::GetNextByte() { - MCORE_ASSERT(mFile); - MCORE_ASSERT((mFileMode == READ) || (mFileMode == READWRITE) || (mFileMode == READWRITEAPPEND) || (mFileMode == APPEND) || (mFileMode == READWRITECREATE)); // make sure we opened the file in read mode - return static_cast(fgetc(mFile)); + MCORE_ASSERT(m_file); + MCORE_ASSERT((m_fileMode == READ) || (m_fileMode == READWRITE) || (m_fileMode == READWRITEAPPEND) || (m_fileMode == APPEND) || (m_fileMode == READWRITECREATE)); // make sure we opened the file in read mode + return static_cast(fgetc(m_file)); } // write a given byte to the file bool DiskFile::WriteByte(uint8 value) { - MCORE_ASSERT(mFile); - MCORE_ASSERT((mFileMode == WRITE) || (mFileMode == READWRITE) || (mFileMode == READWRITEAPPEND) || (mFileMode == READWRITECREATE)); // make sure we opened the file in write mode + MCORE_ASSERT(m_file); + MCORE_ASSERT((m_fileMode == WRITE) || (m_fileMode == READWRITE) || (m_fileMode == READWRITEAPPEND) || (m_fileMode == READWRITECREATE)); // make sure we opened the file in write mode - if (fputc(value, mFile) == EOF) + if (fputc(value, m_file) == EOF) { return false; } @@ -160,10 +139,10 @@ namespace MCore // write data to the file size_t DiskFile::Write(const void* data, size_t length) { - MCORE_ASSERT(mFile); - MCORE_ASSERT((mFileMode == WRITE) || (mFileMode == READWRITE) || (mFileMode == READWRITEAPPEND) || (mFileMode == READWRITECREATE)); // make sure we opened the file in write mode + MCORE_ASSERT(m_file); + MCORE_ASSERT((m_fileMode == WRITE) || (m_fileMode == READWRITE) || (m_fileMode == READWRITEAPPEND) || (m_fileMode == READWRITECREATE)); // make sure we opened the file in write mode - if (fwrite(data, length, 1, mFile) == 0) + if (fwrite(data, length, 1, m_file) == 0) { return 0; } @@ -175,10 +154,10 @@ namespace MCore // read data from the file size_t DiskFile::Read(void* data, size_t length) { - MCORE_ASSERT(mFile); - MCORE_ASSERT((mFileMode == READ) || (mFileMode == READWRITE) || (mFileMode == READWRITEAPPEND) || (mFileMode == APPEND) || (mFileMode == READWRITECREATE)); // make sure we opened the file in read mode + MCORE_ASSERT(m_file); + MCORE_ASSERT((m_fileMode == READ) || (m_fileMode == READWRITE) || (m_fileMode == READWRITEAPPEND) || (m_fileMode == APPEND) || (m_fileMode == READWRITECREATE)); // make sure we opened the file in read mode - if (fread(data, length, 1, mFile) == 0) + if (fread(data, length, 1, m_file) == 0) { return 0; } @@ -190,13 +169,13 @@ namespace MCore // get the file mode DiskFile::EMode DiskFile::GetFileMode() const { - return mFileMode; + return m_fileMode; } // get the file name const AZStd::string& DiskFile::GetFileName() const { - return mFileName; + return m_fileName; } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/DiskFile.h b/Gems/EMotionFX/Code/MCore/Source/DiskFile.h index d17ff7f1f8..4f09a73f3b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/DiskFile.h +++ b/Gems/EMotionFX/Code/MCore/Source/DiskFile.h @@ -162,8 +162,8 @@ namespace MCore const AZStd::string& GetFileName() const; protected: - AZStd::string mFileName; /**< The filename */ - FILE* mFile; /**< The file handle. */ - EMode mFileMode; /**< The mode we opened the file with. */ + AZStd::string m_fileName; /**< The filename */ + FILE* m_file; /**< The file handle. */ + EMode m_fileMode; /**< The mode we opened the file with. */ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/Distance.cpp b/Gems/EMotionFX/Code/MCore/Source/Distance.cpp index e2a966b370..d73a4db601 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Distance.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Distance.cpp @@ -16,8 +16,8 @@ namespace MCore // convert it into another unit type const MCore::Distance& Distance::ConvertTo(EUnitType targetUnitType) { - mDistance = mDistanceMeters * GetConversionFactorFromMeters(targetUnitType); - mUnitType = targetUnitType; + m_distance = m_distanceMeters * GetConversionFactorFromMeters(targetUnitType); + m_unitType = targetUnitType; return *this; } @@ -166,7 +166,7 @@ namespace MCore // update the distance in meters void Distance::UpdateDistanceMeters() { - mDistanceMeters = mDistance * GetConversionFactorToMeters(mUnitType); + m_distanceMeters = m_distance * GetConversionFactorToMeters(m_unitType); } diff --git a/Gems/EMotionFX/Code/MCore/Source/Distance.h b/Gems/EMotionFX/Code/MCore/Source/Distance.h index 3f26295201..6548fc251d 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Distance.h +++ b/Gems/EMotionFX/Code/MCore/Source/Distance.h @@ -38,21 +38,21 @@ namespace MCore }; MCORE_INLINE Distance() - : mDistance(0.0) - , mDistanceMeters(0.0) - , mUnitType(UNITTYPE_METERS) { } + : m_distance(0.0) + , m_distanceMeters(0.0) + , m_unitType(UNITTYPE_METERS) { } MCORE_INLINE Distance(double units, EUnitType unitType) - : mDistance(units) - , mDistanceMeters(0.0) - , mUnitType(unitType) { UpdateDistanceMeters(); } + : m_distance(units) + , m_distanceMeters(0.0) + , m_unitType(unitType) { UpdateDistanceMeters(); } MCORE_INLINE Distance(float units, EUnitType unitType) - : mDistance(units) - , mDistanceMeters(0.0) - , mUnitType(unitType) { UpdateDistanceMeters(); } + : m_distance(units) + , m_distanceMeters(0.0) + , m_unitType(unitType) { UpdateDistanceMeters(); } MCORE_INLINE Distance(const Distance& other) - : mDistance(other.mDistance) - , mDistanceMeters(other.mDistanceMeters) - , mUnitType(other.mUnitType) {} + : m_distance(other.m_distance) + , m_distanceMeters(other.m_distanceMeters) + , m_unitType(other.m_unitType) {} const Distance& ConvertTo(EUnitType targetUnitType); MCORE_INLINE Distance ConvertedTo(EUnitType targetUnitType) const { Distance result(*this); result.ConvertTo(targetUnitType); return result; } @@ -65,46 +65,46 @@ namespace MCore static const char* UnitTypeToString(EUnitType unitType); static bool StringToUnitType(const AZStd::string& str, EUnitType* outUnitType); - MCORE_INLINE double GetDistance() const { return mDistance; } - MCORE_INLINE EUnitType GetUnitType() const { return mUnitType; } - - MCORE_INLINE void Set(double dist, EUnitType unitType) { mDistance = dist; mUnitType = unitType; UpdateDistanceMeters(); } - MCORE_INLINE void SetDistance(double dist) { mDistance = dist; UpdateDistanceMeters(); } - MCORE_INLINE void SetUnitType(EUnitType unitType) { mUnitType = unitType; UpdateDistanceMeters(); } - - MCORE_INLINE double CalcDistanceInUnitType(EUnitType targetUnitType) const { return mDistanceMeters * GetConversionFactorFromMeters(targetUnitType); } - MCORE_INLINE double CalcNumMillimeters() const { return mDistanceMeters * 1000.0; } - MCORE_INLINE double CalcNumCentimeters() const { return mDistanceMeters * 100.0; } - MCORE_INLINE double CalcNumDecimeters() const { return mDistanceMeters * 10.0; } - MCORE_INLINE double CalcNumMeters() const { return mDistanceMeters; } - MCORE_INLINE double CalcNumKilometers() const { return mDistanceMeters * 0.001; } - MCORE_INLINE double CalcNumInches() const { return mDistanceMeters * 39.370078740157; } - MCORE_INLINE double CalcNumFeet() const { return mDistanceMeters * 3.2808398950131; } - MCORE_INLINE double CalcNumYards() const { return mDistanceMeters * 1.0936132983377; } - MCORE_INLINE double CalcNumMiles() const { return mDistanceMeters * 0.00062137119223733; } - - MCORE_INLINE Distance operator - () const { return Distance(-mDistance, mUnitType); } - MCORE_INLINE const Distance& operator = (const Distance& other) { mDistance = other.mDistance; mDistanceMeters = other.mDistanceMeters; mUnitType = other.mUnitType; return *this; } - - MCORE_INLINE const Distance& operator *= (double f) { mDistance *= f; UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator /= (double f) { mDistance /= f; UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator += (double f) { mDistance += f; UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator -= (double f) { mDistance -= f; UpdateDistanceMeters(); return *this; } - - MCORE_INLINE const Distance& operator *= (float f) { mDistance *= f; UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator /= (float f) { mDistance /= f; UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator += (float f) { mDistance += f; UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator -= (float f) { mDistance -= f; UpdateDistanceMeters(); return *this; } - - MCORE_INLINE const Distance& operator *= (const Distance& other) { mDistance *= other.ConvertedTo(mUnitType).GetDistance(); UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator /= (const Distance& other) { mDistance /= other.ConvertedTo(mUnitType).GetDistance(); UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator += (const Distance& other) { mDistance += other.ConvertedTo(mUnitType).GetDistance(); UpdateDistanceMeters(); return *this; } - MCORE_INLINE const Distance& operator -= (const Distance& other) { mDistance -= other.ConvertedTo(mUnitType).GetDistance(); UpdateDistanceMeters(); return *this; } + MCORE_INLINE double GetDistance() const { return m_distance; } + MCORE_INLINE EUnitType GetUnitType() const { return m_unitType; } + + MCORE_INLINE void Set(double dist, EUnitType unitType) { m_distance = dist; m_unitType = unitType; UpdateDistanceMeters(); } + MCORE_INLINE void SetDistance(double dist) { m_distance = dist; UpdateDistanceMeters(); } + MCORE_INLINE void SetUnitType(EUnitType unitType) { m_unitType = unitType; UpdateDistanceMeters(); } + + MCORE_INLINE double CalcDistanceInUnitType(EUnitType targetUnitType) const { return m_distanceMeters * GetConversionFactorFromMeters(targetUnitType); } + MCORE_INLINE double CalcNumMillimeters() const { return m_distanceMeters * 1000.0; } + MCORE_INLINE double CalcNumCentimeters() const { return m_distanceMeters * 100.0; } + MCORE_INLINE double CalcNumDecimeters() const { return m_distanceMeters * 10.0; } + MCORE_INLINE double CalcNumMeters() const { return m_distanceMeters; } + MCORE_INLINE double CalcNumKilometers() const { return m_distanceMeters * 0.001; } + MCORE_INLINE double CalcNumInches() const { return m_distanceMeters * 39.370078740157; } + MCORE_INLINE double CalcNumFeet() const { return m_distanceMeters * 3.2808398950131; } + MCORE_INLINE double CalcNumYards() const { return m_distanceMeters * 1.0936132983377; } + MCORE_INLINE double CalcNumMiles() const { return m_distanceMeters * 0.00062137119223733; } + + MCORE_INLINE Distance operator - () const { return Distance(-m_distance, m_unitType); } + MCORE_INLINE const Distance& operator = (const Distance& other) { m_distance = other.m_distance; m_distanceMeters = other.m_distanceMeters; m_unitType = other.m_unitType; return *this; } + + MCORE_INLINE const Distance& operator *= (double f) { m_distance *= f; UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator /= (double f) { m_distance /= f; UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator += (double f) { m_distance += f; UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator -= (double f) { m_distance -= f; UpdateDistanceMeters(); return *this; } + + MCORE_INLINE const Distance& operator *= (float f) { m_distance *= f; UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator /= (float f) { m_distance /= f; UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator += (float f) { m_distance += f; UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator -= (float f) { m_distance -= f; UpdateDistanceMeters(); return *this; } + + MCORE_INLINE const Distance& operator *= (const Distance& other) { m_distance *= other.ConvertedTo(m_unitType).GetDistance(); UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator /= (const Distance& other) { m_distance /= other.ConvertedTo(m_unitType).GetDistance(); UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator += (const Distance& other) { m_distance += other.ConvertedTo(m_unitType).GetDistance(); UpdateDistanceMeters(); return *this; } + MCORE_INLINE const Distance& operator -= (const Distance& other) { m_distance -= other.ConvertedTo(m_unitType).GetDistance(); UpdateDistanceMeters(); return *this; } private: - double mDistance; /**< The actual distance in the current unit type. */ - double mDistanceMeters; /**< The distance in meters. */ - EUnitType mUnitType; /**< The actual unit type. */ + double m_distance; /**< The actual distance in the current unit type. */ + double m_distanceMeters; /**< The distance in meters. */ + EUnitType m_unitType; /**< The actual unit type. */ void UpdateDistanceMeters(); }; diff --git a/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.cpp b/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.cpp index bf4d249472..43c33b1a08 100644 --- a/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.cpp @@ -16,12 +16,12 @@ namespace MCore // calculate the inverse DualQuaternion& DualQuaternion::Inverse() { - const float realLength = mReal.GetLength(); - const float dotProduct = mReal.Dot(mDual); + const float realLength = m_real.GetLength(); + const float dotProduct = m_real.Dot(m_dual); const float dualFactor = realLength - 2.0f * dotProduct; - mReal.Set(-mReal.GetX() * realLength, -mReal.GetY() * realLength, -mReal.GetZ() * realLength, mReal.GetW() * realLength); - mDual.Set(-mDual.GetX() * dualFactor, -mDual.GetY() * dualFactor, -mDual.GetZ() * dualFactor, mDual.GetW() * dualFactor); + m_real.Set(-m_real.GetX() * realLength, -m_real.GetY() * realLength, -m_real.GetZ() * realLength, m_real.GetW() * realLength); + m_dual.Set(-m_dual.GetX() * dualFactor, -m_dual.GetY() * dualFactor, -m_dual.GetZ() * dualFactor, m_dual.GetW() * dualFactor); return *this; } @@ -30,26 +30,26 @@ namespace MCore // calculate the inversed version DualQuaternion DualQuaternion::Inversed() const { - const float realLength = mReal.GetLength(); - const float dotProduct = mReal.Dot(mDual); + const float realLength = m_real.GetLength(); + const float dotProduct = m_real.Dot(m_dual); const float dualFactor = realLength - 2.0f * dotProduct; - return DualQuaternion(AZ::Quaternion(-mReal.GetX() * realLength, -mReal.GetY() * realLength, -mReal.GetZ() * realLength, mReal.GetW() * realLength), - AZ::Quaternion(-mDual.GetX() * dualFactor, -mDual.GetY() * dualFactor, -mDual.GetZ() * dualFactor, mDual.GetW() * dualFactor)); + return DualQuaternion(AZ::Quaternion(-m_real.GetX() * realLength, -m_real.GetY() * realLength, -m_real.GetZ() * realLength, m_real.GetW() * realLength), + AZ::Quaternion(-m_dual.GetX() * dualFactor, -m_dual.GetY() * dualFactor, -m_dual.GetZ() * dualFactor, m_dual.GetW() * dualFactor)); } // convert the dual quaternion to a matrix AZ::Transform DualQuaternion::ToTransform() const { - const float sqLen = mReal.Dot(mReal); - const float x = mReal.GetX(); - const float y = mReal.GetY(); - const float z = mReal.GetZ(); - const float w = mReal.GetW(); - const float t0 = mDual.GetW(); - const float t1 = mDual.GetX(); - const float t2 = mDual.GetY(); - const float t3 = mDual.GetZ(); + const float sqLen = m_real.Dot(m_real); + const float x = m_real.GetX(); + const float y = m_real.GetY(); + const float z = m_real.GetZ(); + const float w = m_real.GetW(); + const float t0 = m_dual.GetW(); + const float t1 = m_dual.GetX(); + const float t2 = m_dual.GetY(); + const float t3 = m_dual.GetZ(); AZ::Matrix3x3 matrix3x3; matrix3x3.SetElement(0, 0, w * w + x * x - y * y - z * z); @@ -85,12 +85,12 @@ namespace MCore // normalizes the dual quaternion DualQuaternion& DualQuaternion::Normalize() { - const float length = mReal.GetLength(); + const float length = m_real.GetLength(); const float invLength = 1.0f / length; - mReal.Set(mReal.GetX() * invLength, mReal.GetY() * invLength, mReal.GetZ() * invLength, mReal.GetW() * invLength); - mDual.Set(mDual.GetX() * invLength, mDual.GetY() * invLength, mDual.GetZ() * invLength, mDual.GetW() * invLength); - mDual += mReal * (mReal.Dot(mDual) * -1.0f); + m_real.Set(m_real.GetX() * invLength, m_real.GetY() * invLength, m_real.GetZ() * invLength, m_real.GetW() * invLength); + m_dual.Set(m_dual.GetX() * invLength, m_dual.GetY() * invLength, m_dual.GetZ() * invLength, m_dual.GetW() * invLength); + m_dual += m_real * (m_real.Dot(m_dual) * -1.0f); return *this; } @@ -98,11 +98,11 @@ namespace MCore // convert back into rotation and translation void DualQuaternion::ToRotationTranslation(AZ::Quaternion* outRot, AZ::Vector3* outPos) const { - const float invLength = 1.0f / mReal.GetLength(); - *outRot = mReal * invLength; - outPos->Set(2.0f * (-mDual.GetW() * mReal.GetX() + mDual.GetX() * mReal.GetW() - mDual.GetY() * mReal.GetZ() + mDual.GetZ() * mReal.GetY()) * invLength, - 2.0f * (-mDual.GetW() * mReal.GetY() + mDual.GetX() * mReal.GetZ() + mDual.GetY() * mReal.GetW() - mDual.GetZ() * mReal.GetX()) * invLength, - 2.0f * (-mDual.GetW() * mReal.GetZ() - mDual.GetX() * mReal.GetY() + mDual.GetY() * mReal.GetX() + mDual.GetZ() * mReal.GetW()) * invLength); + const float invLength = 1.0f / m_real.GetLength(); + *outRot = m_real * invLength; + outPos->Set(2.0f * (-m_dual.GetW() * m_real.GetX() + m_dual.GetX() * m_real.GetW() - m_dual.GetY() * m_real.GetZ() + m_dual.GetZ() * m_real.GetY()) * invLength, + 2.0f * (-m_dual.GetW() * m_real.GetY() + m_dual.GetX() * m_real.GetZ() + m_dual.GetY() * m_real.GetW() - m_dual.GetZ() * m_real.GetX()) * invLength, + 2.0f * (-m_dual.GetW() * m_real.GetZ() - m_dual.GetX() * m_real.GetY() + m_dual.GetY() * m_real.GetX() + m_dual.GetZ() * m_real.GetW()) * invLength); } @@ -110,10 +110,10 @@ namespace MCore // only works with normalized dual quaternions void DualQuaternion::NormalizedToRotationTranslation(AZ::Quaternion* outRot, AZ::Vector3* outPos) const { - *outRot = mReal; - outPos->Set(2.0f * (-mDual.GetW() * mReal.GetX() + mDual.GetX() * mReal.GetW() - mDual.GetY() * mReal.GetZ() + mDual.GetZ() * mReal.GetY()), - 2.0f * (-mDual.GetW() * mReal.GetY() + mDual.GetX() * mReal.GetZ() + mDual.GetY() * mReal.GetW() - mDual.GetZ() * mReal.GetX()), - 2.0f * (-mDual.GetW() * mReal.GetZ() - mDual.GetX() * mReal.GetY() + mDual.GetY() * mReal.GetX() + mDual.GetZ() * mReal.GetW())); + *outRot = m_real; + outPos->Set(2.0f * (-m_dual.GetW() * m_real.GetX() + m_dual.GetX() * m_real.GetW() - m_dual.GetY() * m_real.GetZ() + m_dual.GetZ() * m_real.GetY()), + 2.0f * (-m_dual.GetW() * m_real.GetY() + m_dual.GetX() * m_real.GetZ() + m_dual.GetY() * m_real.GetW() - m_dual.GetZ() * m_real.GetX()), + 2.0f * (-m_dual.GetW() * m_real.GetZ() - m_dual.GetX() * m_real.GetY() + m_dual.GetY() * m_real.GetX() + m_dual.GetZ() * m_real.GetW())); } diff --git a/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.h b/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.h index af16713363..74caa715e5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.h +++ b/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.h @@ -37,16 +37,16 @@ namespace MCore * This automatically initializes the dual quaternion to identity. */ MCORE_INLINE DualQuaternion() - : mReal(0.0f, 0.0f, 0.0f, 1.0f) - , mDual(0.0f, 0.0f, 0.0f, 0.0f) {} + : m_real(0.0f, 0.0f, 0.0f, 1.0f) + , m_dual(0.0f, 0.0f, 0.0f, 0.0f) {} /** * Copy constructor. * @param other The dual quaternion to copy the data from. */ MCORE_INLINE DualQuaternion(const DualQuaternion& other) - : mReal(other.mReal) - , mDual(other.mDual) {} + : m_real(other.m_real) + , m_dual(other.m_dual) {} /** * Extended constructor. @@ -56,8 +56,8 @@ namespace MCore * or use the FromRotationTranslation method. */ MCORE_INLINE DualQuaternion(const AZ::Quaternion& real, const AZ::Quaternion& dual) - : mReal(real) - , mDual(dual) {} + : m_real(real) + , m_dual(dual) {} /** * Constructor which takes a matrix as input parameter. @@ -81,7 +81,7 @@ namespace MCore * @note Please keep in mind that you should not set the translation directly into the dual part. If you want to initialize the dual quaternion from * a rotation and translation, please use the special constructor for this, or the FromRotationTranslation method. */ - MCORE_INLINE void Set(const AZ::Quaternion& real, const AZ::Quaternion& dual) { mReal = real; mDual = dual; } + MCORE_INLINE void Set(const AZ::Quaternion& real, const AZ::Quaternion& dual) { m_real = real; m_dual = dual; } /** * Normalize the dual quaternion. @@ -102,7 +102,7 @@ namespace MCore * The default constructor already puts the dual quaternion in its identity transform. * @result A reference to this quaternion, but now having an identity transform. */ - MCORE_INLINE DualQuaternion& Identity() { mReal = AZ::Quaternion::CreateIdentity(); mDual.Set(0.0f, 0.0f, 0.0f, 0.0f); return *this; } + MCORE_INLINE DualQuaternion& Identity() { m_real = AZ::Quaternion::CreateIdentity(); m_dual.Set(0.0f, 0.0f, 0.0f, 0.0f); return *this; } /** * Get the dot product between the two dual quaternions. @@ -112,7 +112,7 @@ namespace MCore * @result A 2D vector containing the result of the dot products. The x component contains the result of the dot between the real part and the y component * contains the result of the dot product between the dual parts. */ - MCORE_INLINE AZ::Vector2 Dot(const DualQuaternion& other) const { return AZ::Vector2(mReal.Dot(other.mReal), mDual.Dot(other.mDual)); } + MCORE_INLINE AZ::Vector2 Dot(const DualQuaternion& other) const { return AZ::Vector2(m_real.Dot(other.m_real), m_dual.Dot(other.m_dual)); } /** * Calculate the length of the dual quaternion. @@ -120,7 +120,7 @@ namespace MCore * The result of the real part will be stored in the x component of the 2D vector, and the result of the dual part will be stored in the y component. * @result The 2D vector containing the length of the real and dual part. */ - MCORE_INLINE AZ::Vector2 Length() const { const float realLen = mReal.GetLength(); return AZ::Vector2(realLen, mReal.Dot(mDual) / realLen); } + MCORE_INLINE AZ::Vector2 Length() const { const float realLen = m_real.GetLength(); return AZ::Vector2(realLen, m_real.Dot(m_dual) / realLen); } /** * Inverse this dual quaternion. @@ -139,14 +139,14 @@ namespace MCore * @result A reference to this dual quaternion, but now conjugaged. * @note If you want to inverse a unit quaternion, you can use the conjugate instead, as that gives the same result, but is much faster to calculate. */ - MCORE_INLINE DualQuaternion& Conjugate() { mReal = mReal.GetConjugate(); mDual = mDual.GetConjugate(); return *this; } + MCORE_INLINE DualQuaternion& Conjugate() { m_real = m_real.GetConjugate(); m_dual = m_dual.GetConjugate(); return *this; } /** * Calculate a conjugated version of this dual quaternion. * @result A copy of this dual quaternion, but conjugated. * @note If you want to inverse a unit quaternion, you can use the conjugate instead, as that gives the same result, but is much faster to calculate. */ - MCORE_INLINE DualQuaternion Conjugated() const { return DualQuaternion(mReal.GetConjugate(), mDual.GetConjugate()); } + MCORE_INLINE DualQuaternion Conjugated() const { return DualQuaternion(m_real.GetConjugate(), m_dual.GetConjugate()); } /** * Initialize the current quaternion from a specified matrix. @@ -228,28 +228,27 @@ namespace MCore // operators MCORE_INLINE const DualQuaternion& operator=(const AZ::Transform& transform) { FromTransform(transform); return *this; } - MCORE_INLINE const DualQuaternion& operator=(const DualQuaternion& other) { mReal = other.mReal; mDual = other.mDual; return *this; } - MCORE_INLINE DualQuaternion operator-() const { return DualQuaternion(-mReal, -mDual); } - MCORE_INLINE const DualQuaternion& operator+=(const DualQuaternion& q) { mReal += q.mReal; mDual += q.mDual; return *this; } - MCORE_INLINE const DualQuaternion& operator-=(const DualQuaternion& q) { mReal -= q.mReal; mDual -= q.mDual; return *this; } - MCORE_INLINE const DualQuaternion& operator*=(const DualQuaternion& q) { const AZ::Quaternion orgReal(mReal); mReal *= q.mReal; mDual = orgReal * q.mDual + q.mReal * mDual; return *this; } - MCORE_INLINE const DualQuaternion& operator*=(float f) { mReal *= f; mDual *= f; return *this; } - //MCORE_INLINE const DualQuaternion& operator*=(double f) { mReal*=f; mDual*=f; return *this; } + MCORE_INLINE const DualQuaternion& operator=(const DualQuaternion& other) { m_real = other.m_real; m_dual = other.m_dual; return *this; } + MCORE_INLINE DualQuaternion operator-() const { return DualQuaternion(-m_real, -m_dual); } + MCORE_INLINE const DualQuaternion& operator+=(const DualQuaternion& q) { m_real += q.m_real; m_dual += q.m_dual; return *this; } + MCORE_INLINE const DualQuaternion& operator-=(const DualQuaternion& q) { m_real -= q.m_real; m_dual -= q.m_dual; return *this; } + MCORE_INLINE const DualQuaternion& operator*=(const DualQuaternion& q) { const AZ::Quaternion orgReal(m_real); m_real *= q.m_real; m_dual = orgReal * q.m_dual + q.m_real * m_dual; return *this; } + MCORE_INLINE const DualQuaternion& operator*=(float f) { m_real *= f; m_dual *= f; return *this; } // attributes - AZ::Quaternion mReal; /**< The real value, which you can see as the regular rotation quaternion. */ - AZ::Quaternion mDual; /**< The dual part, which you can see as the translation part. */ + AZ::Quaternion m_real; /**< The real value, which you can see as the regular rotation quaternion. */ + AZ::Quaternion m_dual; /**< The dual part, which you can see as the translation part. */ }; // operators - MCORE_INLINE DualQuaternion operator*(const DualQuaternion& a, float f) { return DualQuaternion(a.mReal * f, a.mDual * f); } - MCORE_INLINE DualQuaternion operator*(float f, const DualQuaternion& b) { return DualQuaternion(b.mReal * f, b.mDual * f); } - MCORE_INLINE DualQuaternion operator+(const DualQuaternion& a, const DualQuaternion& b) { return DualQuaternion(a.mReal + b.mReal, a.mDual + b.mDual); } - MCORE_INLINE DualQuaternion operator-(const DualQuaternion& a, const DualQuaternion& b) { return DualQuaternion(a.mReal - b.mReal, a.mDual - b.mDual); } + MCORE_INLINE DualQuaternion operator*(const DualQuaternion& a, float f) { return DualQuaternion(a.m_real * f, a.m_dual * f); } + MCORE_INLINE DualQuaternion operator*(float f, const DualQuaternion& b) { return DualQuaternion(b.m_real * f, b.m_dual * f); } + MCORE_INLINE DualQuaternion operator+(const DualQuaternion& a, const DualQuaternion& b) { return DualQuaternion(a.m_real + b.m_real, a.m_dual + b.m_dual); } + MCORE_INLINE DualQuaternion operator-(const DualQuaternion& a, const DualQuaternion& b) { return DualQuaternion(a.m_real - b.m_real, a.m_dual - b.m_dual); } MCORE_INLINE DualQuaternion operator*(const DualQuaternion& a, const DualQuaternion& b) { - return DualQuaternion(a.mReal * b.mReal, a.mReal * b.mDual + b.mReal * a.mDual); + return DualQuaternion(a.m_real * b.m_real, a.m_real * b.m_dual + b.m_real * a.m_dual); } // include the inline code diff --git a/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.inl b/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.inl index d928bae6d9..1c0c378852 100644 --- a/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.inl +++ b/Gems/EMotionFX/Code/MCore/Source/DualQuaternion.inl @@ -8,9 +8,9 @@ // extended constructor MCORE_INLINE DualQuaternion::DualQuaternion(const AZ::Quaternion& rotation, const AZ::Vector3& translation) - : mReal(rotation) + : m_real(rotation) { - mDual = 0.5f * (AZ::Quaternion(translation.GetX(), translation.GetY(), translation.GetZ(), 0.0f) * rotation); + m_dual = 0.5f * (AZ::Quaternion(translation.GetX(), translation.GetY(), translation.GetZ(), 0.0f) * rotation); } @@ -18,10 +18,10 @@ MCORE_INLINE DualQuaternion::DualQuaternion(const AZ::Quaternion& rotation, cons // transform a 3D point with the dual quaternion MCORE_INLINE AZ::Vector3 DualQuaternion::TransformPoint(const AZ::Vector3& point) const { - const AZ::Vector3 realVector(mReal.GetX(), mReal.GetY(), mReal.GetZ()); - const AZ::Vector3 dualVector(mDual.GetX(), mDual.GetY(), mDual.GetZ()); - const AZ::Vector3 position = point + 2.0f * (realVector.Cross(realVector.Cross(point) + (mReal.GetW() * point))); - const AZ::Vector3 displacement = 2.0f * (mReal.GetW() * dualVector - mDual.GetW() * realVector + realVector.Cross(dualVector)); + const AZ::Vector3 realVector(m_real.GetX(), m_real.GetY(), m_real.GetZ()); + const AZ::Vector3 dualVector(m_dual.GetX(), m_dual.GetY(), m_dual.GetZ()); + const AZ::Vector3 position = point + 2.0f * (realVector.Cross(realVector.Cross(point) + (m_real.GetW() * point))); + const AZ::Vector3 displacement = 2.0f * (m_real.GetW() * dualVector - m_dual.GetW() * realVector + realVector.Cross(dualVector)); return position + displacement; } @@ -29,8 +29,8 @@ MCORE_INLINE AZ::Vector3 DualQuaternion::TransformPoint(const AZ::Vector3& point // transform a vector with this dual quaternion MCORE_INLINE AZ::Vector3 DualQuaternion::TransformVector(const AZ::Vector3& v) const { - const AZ::Vector3 realVector(mReal.GetX(), mReal.GetY(), mReal.GetZ()); - const AZ::Vector3 dualVector(mDual.GetX(), mDual.GetY(), mDual.GetZ()); - return v + 2.0f * (realVector.Cross(realVector.Cross(v) + mReal.GetW() * v)); + const AZ::Vector3 realVector(m_real.GetX(), m_real.GetY(), m_real.GetZ()); + const AZ::Vector3 dualVector(m_dual.GetX(), m_dual.GetY(), m_dual.GetZ()); + return v + 2.0f * (realVector.Cross(realVector.Cross(v) + m_real.GetW() * v)); } diff --git a/Gems/EMotionFX/Code/MCore/Source/Endian.h b/Gems/EMotionFX/Code/MCore/Source/Endian.h index 296f53a208..ba93fbed97 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Endian.h +++ b/Gems/EMotionFX/Code/MCore/Source/Endian.h @@ -53,6 +53,8 @@ namespace MCore */ static MCORE_INLINE void ConvertUnsignedInt32(uint32* value, uint32 count = 1); + static MCORE_INLINE void ConvertUnsignedInt64(uint64* value, uint32 count = 1); + /** * Swap the endian of one or more shorts. * @param value The value to convert the endian for. @@ -178,6 +180,8 @@ namespace MCore */ static MCORE_INLINE void ConvertUnsignedInt32(uint32* value, EEndianType sourceEndianType, uint32 count = 1); + static MCORE_INLINE void ConvertUnsignedInt64(uint64* value, EEndianType sourceEndianType, uint32 count = 1); + /** * Convert one or more 16 bit short values into the endian used by our current platform. * @param value The value(s) to convert. The number of values to follow at the specified address must be at least the number @@ -273,6 +277,8 @@ namespace MCore */ static MCORE_INLINE void ConvertUnsignedInt32(uint32* value, EEndianType sourceEndianType, EEndianType targetEndianType, uint32 count = 1); + static MCORE_INLINE void ConvertUnsignedInt64(uint64* value, EEndianType sourceEndianType, EEndianType targetEndianType, uint32 count = 1); + /** * Convert an 16 bit short into another endian type. * @param value A pointer to the object to convert/modify. diff --git a/Gems/EMotionFX/Code/MCore/Source/Endian.inl b/Gems/EMotionFX/Code/MCore/Source/Endian.inl index bafd816398..e0dd5acb0a 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Endian.inl +++ b/Gems/EMotionFX/Code/MCore/Source/Endian.inl @@ -28,6 +28,17 @@ MCORE_INLINE void Endian::ConvertUnsignedInt32(uint32* value, uint32 count) } } +MCORE_INLINE void Endian::ConvertUnsignedInt64(uint64* value, uint32 count) +{ + for (uint32 i = 0; i < count; ++i) + { + uint64 arg = *value; + *value = (arg >> 56) + ((arg >> 40) & 0xFF00) + ((arg >> 24) & 0xFF0000) + ((arg >> 8) & 0xFF000000) + + ((arg & 0xFF000000) << 8) + ((arg & 0xFF0000) << 24) + ((arg & 0xFF00) << 40) + (arg << 56); + value++; + } +} + // swap bytes for a short MCORE_INLINE void Endian::ConvertSignedInt16(int16* value, uint32 count) @@ -168,6 +179,20 @@ MCORE_INLINE void Endian::ConvertUnsignedInt32(uint32* value, Endian::EEndianTyp ; } +MCORE_INLINE void Endian::ConvertUnsignedInt64(uint64* value, Endian::EEndianType sourceEndianType, uint32 count) +{ + // convert into the new endian, depending on the platform we are running on + switch (sourceEndianType) + { + case ENDIAN_LITTLE: + MCORE_FROM_LITTLE_ENDIAN64((uint8*)value, count); + break; + case ENDIAN_BIG: + MCORE_FROM_BIG_ENDIAN64 ((uint8*)value, count); + break; + } +} + // convert a short MCORE_INLINE void Endian::ConvertSignedInt16(int16* value, EEndianType sourceEndianType, uint32 count) @@ -364,6 +389,19 @@ MCORE_INLINE void Endian::ConvertUnsignedInt32(uint32* value, EEndianType source ConvertUnsignedInt32(value, count); } +// convert an uint64 into another endian type +MCORE_INLINE void Endian::ConvertUnsignedInt64(uint64* value, EEndianType sourceEndianType, EEndianType targetEndianType, uint32 count) +{ + // if we don't need to convert anything + if (sourceEndianType == targetEndianType) + { + return; + } + + // perform conversion + ConvertUnsignedInt64(value, count); +} + // convert a short into another endian type MCORE_INLINE void Endian::ConvertSignedInt16(int16* value, EEndianType sourceEndianType, EEndianType targetEndianType, uint32 count) diff --git a/Gems/EMotionFX/Code/MCore/Source/FastMath.h b/Gems/EMotionFX/Code/MCore/Source/FastMath.h index 22637d5b5b..e1bac33306 100644 --- a/Gems/EMotionFX/Code/MCore/Source/FastMath.h +++ b/Gems/EMotionFX/Code/MCore/Source/FastMath.h @@ -300,24 +300,15 @@ namespace MCore static MCORE_INLINE float SafeFMod(float x, float y); /** - * Align a given uint32 value to a given alignment. - * For example when the input value of inOutValue contains a value of 50, and the alignment is set to 16, then the - * value is modified to be 64. - * @param inOutValue The input value to align. This will also be the output, so the value is modified. - * @param alignment The alignment to use, for example 16, 32 or 64, etc. - */ - static MCORE_INLINE void Align(uint32* inOutValue, uint32 alignment); - - - /** - * Align a given uint32 value to a given alignment. + * Align a given size_t value to a given alignment. * For example when the input value of inOutValue contains a value of 50, and the alignment is set to 16, then the * aligned return value would be 64. * @param inValue The input value, which would be 50 in our above example. * @param alignment The alignment touse, which would be 16 in our above example. * @result The value returned is the input value aligned to the given alignment. In our example it would return a value of 64. */ - static MCORE_INLINE uint32 Align(uint32 inValue, uint32 alignment); + template + static MCORE_INLINE T Align(T inValue, T alignment); /** * Multiply a float value by its sign. diff --git a/Gems/EMotionFX/Code/MCore/Source/FastMath.inl b/Gems/EMotionFX/Code/MCore/Source/FastMath.inl index 31365761b9..d672d59985 100644 --- a/Gems/EMotionFX/Code/MCore/Source/FastMath.inl +++ b/Gems/EMotionFX/Code/MCore/Source/FastMath.inl @@ -310,19 +310,10 @@ MCORE_INLINE float Math::FastSqrt(float x) // align a value -MCORE_INLINE void Math::Align(uint32* inOutValue, uint32 alignment) +template +MCORE_INLINE T Math::Align(T inValue, T alignment) { - const uint32 modValue = *inOutValue % alignment; - if (modValue > 0) - { - *inOutValue += alignment - modValue; - } -} - -// align a value -MCORE_INLINE uint32 Math::Align(uint32 inValue, uint32 alignment) -{ - const uint32 modValue = inValue % alignment; + const T modValue = inValue % alignment; if (modValue > 0) { return inValue + (alignment - modValue); diff --git a/Gems/EMotionFX/Code/MCore/Source/FileSystem.cpp b/Gems/EMotionFX/Code/MCore/Source/FileSystem.cpp index 71b426e532..d97cd7c9a9 100644 --- a/Gems/EMotionFX/Code/MCore/Source/FileSystem.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/FileSystem.cpp @@ -18,13 +18,13 @@ namespace MCore { // The folder path used to keep a backup in SaveToFileSecured. - StaticString FileSystem::mSecureSavePath; + StaticString FileSystem::s_secureSavePath; // Save to file secured by a backup file. bool FileSystem::SaveToFileSecured(const char* filename, const AZStd::function& saveFunction, CommandManager* commandManager) { // If the secure save path is not set, simply call the save function. - if (mSecureSavePath.empty()) + if (s_secureSavePath.empty()) { return saveFunction(); } @@ -45,12 +45,12 @@ namespace MCore // Find a unique backup filename. AZ::u32 backupFileIndex = 0; AZStd::string backupFileIndexString; - AZStd::string backupFilename = mSecureSavePath.c_str() + baseFilename + '.' + extension; + AZStd::string backupFilename = s_secureSavePath.c_str() + baseFilename + '.' + extension; while (fileIo->Exists(backupFilename.c_str())) { AZStd::to_string(backupFileIndexString, ++backupFileIndex); - backupFilename = mSecureSavePath.c_str() + baseFilename + backupFileIndexString + '.' + extension; + backupFilename = s_secureSavePath.c_str() + baseFilename + backupFileIndexString + '.' + extension; } // Copy the file to the backup filename. diff --git a/Gems/EMotionFX/Code/MCore/Source/FileSystem.h b/Gems/EMotionFX/Code/MCore/Source/FileSystem.h index 2fdf74ff46..3bf86577e5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/FileSystem.h +++ b/Gems/EMotionFX/Code/MCore/Source/FileSystem.h @@ -34,6 +34,6 @@ namespace MCore */ static bool SaveToFileSecured(const char* filename, const AZStd::function& saveFunction, CommandManager* commandManager = nullptr); - static StaticString mSecureSavePath; /**< The folder path used to keep a backup in SaveToFileSecured. */ + static StaticString s_secureSavePath; /**< The folder path used to keep a backup in SaveToFileSecured. */ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/HashFunctions.h b/Gems/EMotionFX/Code/MCore/Source/HashFunctions.h deleted file mode 100644 index 66f4a7bf73..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/HashFunctions.h +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -// include required headers -#include "StandardHeaders.h" -#include "Vector.h" -#include - - -namespace MCore -{ - /** - * The hash function. - * The hash function must return an non-negative (so positive) integer, based on a key value. - * Use partial template specialization to implement hashing functions for different data types. - */ - template - MCORE_INLINE uint32 Hash(const Key& key) - { - MCORE_ASSERT(false); // you should implement this function - MCORE_UNUSED(key); - //#pragma message (MCORE_ERROR "You should implement the Hash function for some specific Key type that you used") - return 0; - } - - - template<> - MCORE_INLINE uint32 Hash(const AZStd::string& key) - { - uint32 result = 0; - const size_t length = key.size(); - for (size_t i = 0; i < length; ++i) - { - result = (result << 4) + key[i]; - const uint32 g = result & 0xf0000000L; - if (g != 0) - { - result ^= g >> 24; - } - result &= ~g; - } - - return result; - } - - - template<> - MCORE_INLINE uint32 Hash(const int32& key) - { - return (uint32)Math::Abs(static_cast(key)); - } - - - template<> - MCORE_INLINE uint32 Hash(const uint32& key) - { - return key; - } - - - template<> - MCORE_INLINE uint32 Hash(const float& key) - { - return (uint32)Math::Abs(key * 12345.0f); - } - - - template<> - MCORE_INLINE uint32 Hash(const AZ::Vector3& key) - { - return (uint32)Math::Abs(key.GetX() * 101.0f + key.GetY() * 1002.0f + key.GetZ() * 10003.0f); - } -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/HashTable.h b/Gems/EMotionFX/Code/MCore/Source/HashTable.h deleted file mode 100644 index 5310935f50..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/HashTable.h +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -// include the needed headers -#include "StandardHeaders.h" -#include "Array.h" -#include "FastMath.h" -#include "HashFunctions.h" - - -namespace MCore -{ - /** - * The Hash Table template. - * Hash tables can be used to speedup searching of specific values based on a key. - * The table has an array of table elements, which each can contain multiple hash table entries. - * Each entry is identified by a unique key, which can be of any type, as long as the == operator is specified. - * Next to a unique key, every entry contains a value. The hash table implementation contains methods to add new - * entries and to retrieve the value for a given key. Hashing is used to speedup this search. - * The hash value of a given key is calculated based on a specified hashing function that you pass to the constructor. - * This hash function will return a non-negative (so positive) integer based on the input key. - * Performance tests have shown that you need at least 100 entries to make it faster than linear searches. This however - * also depends on the speed of your hash function and some other factors. But it is a good practise to replace your - * linear searches by a hash table when you have more than 100 items to search through. The more items to search through - * the bigger the advantage of hashing over linear searches will be. Here follows a small table that shows how much faster your - * searches can be compared to linear searches. - */ - template - class HashTable - { - public: - /** - * A hash table entry, which contains a unique key and a value for this key. - */ - class Entry - { - friend class HashTable; - MCORE_MEMORYOBJECTCATEGORY(HashTable, MCORE_DEFAULT_ALIGNMENT, MCORE_MEMCATEGORY_HASHTABLE) - - public: - /** - * The constructor. - * @param key The unique key of this entry. - * @param value The value linked to this key. - */ - MCORE_INLINE Entry(const Key& key, const Value& value) - : mKey(key) - , mValue(value) {} - - /** - * Set the value of this entry. - * @param value The value to set for this entry. - */ - MCORE_INLINE void SetValue(const Value& value) { mValue = value; } - - /** - * Get the value of this entry. - * @result The value that is linked to the key of this entry. - */ - MCORE_INLINE const Value& GetValue() const { return mValue; } - - /** - * Get the key of this entry. - * @result The unique key of this entry. - */ - MCORE_INLINE const Key& GetKey() const { return mKey; } - - private: - Key mKey; /**< The unique key. */ - Value mValue; /**< The value that is linked to the given key. */ - }; - - - /** - * The default constructor. - * This creates an empty hash table. You need to call the Init function before you can use the table. - * @see Init - */ - HashTable(); - - /** - * The extended constructor, which also initializes the table automatically. - * You do NOT need to call the Init function anymore when you use this constructor. - * @param maxElements The maximum number of table elements. The higher the value, the more gain when dealing with many entries. - * Values between 100 and 1000 are often good numbers, depending on the number of entries you are dealing with. - */ - HashTable(uint32 maxElements); - - /** - * Copy constructor. - * @param other The table to create a copy of. - */ - HashTable(const HashTable& other); - - /** - * The destructor. - * This automatically clears all table entries. - * The hash function object that was passed to the extended constructor or the Init function will be - * deleted from memory automatically. - */ - ~HashTable(); - - /** - * Clear the hash table. - * This removes all entries from the table. If you like to use the table again later on you will need to - * call the Init function again. - * This also automatically deletes the hash function object, that you passed to the extended constructor or init function, from memory. - * @see Init - */ - void Clear(); - - /** - * Locate an entry with a given key. - * When the entry cannot be found, this method will NOT modify the outElementNr and outEntryNr parameters. - * @param key The key to search for. - * @param outElementNr A pointer to an integer in which this method will store the table element number, in case the entry is found. - * @param outEntryNr A pointer to an integer in which this method will store the entry number (index) into the table element array, in case the entry is found. - * @result Returns true when the entry with the given key could be found, otherwise false is returned. - */ - MCORE_INLINE bool FindEntry(const Key& key, uint32* outElementNr, uint32* outEntryNr) const; - - /** - * Initialize the hash table. - * @param maxElements The maximum number of table elements. The higher the value, the more gain when dealing with many entries. - * Values between 100 and 1000 are often good numbers, depending on the number of entries you are dealing with. - */ - void Init(uint32 maxElements); - - /** - * Add an entry to the hash table. - * It is VERY important that the key is unique and does NOT already exist within this table! - * @param key The unique key of the entry. - * @param value The value that is linked to this key. - */ - void Add(const Key& key, const Value& value); - - /** - * Get a value from the table. - * @param inKey The key of the entry which contains the value. - * @param outValue A pointer to an object where this method will write the value of the entry in. - * @result Returns true when the value has been retrieved successfully. False will be returned when no entry with the specified - * key could be located. - */ - MCORE_INLINE bool GetValue(const Key& inKey, Value* outValue) const; - - /** - * Set the value that is linked to a given key. - * @param key The unique key of the entry to set the value for. - * @param value The value to link to the specified key. - * @result Returns true when the value has been set successfully, or false when there is no entry with the specified key inside this table. - */ - MCORE_INLINE bool SetValue(const Key& key, const Value& value); - - /** - * Check if this hash table contains an entry with a specified key. - * @param key The key of the entry to search for. - * @result Returns true when this hash table contains an entry with the specified key, otherwise false is returned. - */ - MCORE_INLINE bool Contains(const Key& key) const; - - /** - * Remove the entry which has the specified key. - * @param key The key of the entry to remove. - * @result Returns true when the entry with the specified key has been removed successfully, otherwise false is returned, which means - * that there is no entry with the specified key. - */ - bool Remove(const Key& key); - - /** - * Get the number of table elements. - * @result The number of table elements. - */ - MCORE_INLINE uint32 GetNumTableElements() const; - - /** - * Get the number of entries in a given table element. - * @param tableElementNr The table element number to get the number of entries for. - * @result The number of entries for the specified table entry. - */ - MCORE_INLINE uint32 GetNumEntries(uint32 tableElementNr) const; - - /** - * Get the total number of entries inside the table. - * @result The total number of stored entries inside the table. - */ - uint32 GetTotalNumEntries() const; - - /** - * Calculate the load balance, which is a percentage that represents how many percent of the - * table elements are used. If the returned value equals 50, then it means that 50 percent of the - * table elements are storing entries. The other 50% are then not used. - * When you have added many entries (more than then the number of table elements), and the load balance - * is not 100% or anywhere near it, it means your hash function is very inefficient, because it does not spread - * the entries over the entire hash table, which might mean that there is some nasty clustering going on, which can - * greatly decrease performance. - * @result A floating point value in range of 0..100, which respresents the percentage of table elements that is in use. - */ - float CalcLoadBalance() const; - - /** - * Calculate the average number of entries per used table element. - * The more entries per table element, the slower your searches will be. - * The optimal value returned by this function would therefore be 1. - * @result The average number of entries per table element. - */ - float CalcAverageNumEntries() const; - - /** - * Get a given entry from the table, when you know its location in the table. - * @param tableElementNr The table element number. - * @param entryNr The entry number inside this table element. - * @result The reference to the entry, with write access. - */ - MCORE_INLINE Entry& GetEntry(uint32 tableElementNr, uint32 entryNr); - - /** - * The assignment operator. - * This clones the entire table. - * @param other The table to create a copy of. - * @result The copied version of the specified table. - */ - HashTable& operator = (const HashTable& other); - - protected: - MCore::Array< MCore::Array* > mElements; /**< The table elements, where nullptr means the element is empty. */ - uint32 mTotalNumEntries; /**< The cached number of entries in the table. */ - }; - - - // include the inline code -#include "HashTable.inl" -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/HashTable.inl b/Gems/EMotionFX/Code/MCore/Source/HashTable.inl deleted file mode 100644 index 580f5e964c..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/HashTable.inl +++ /dev/null @@ -1,338 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// default constructor -template -HashTable::HashTable() -{ - mElements.SetMemoryCategory(MCORE_MEMCATEGORY_HASHTABLE); - mTotalNumEntries = 0; -} - - -// extended constructor -template -HashTable::HashTable(uint32 maxElements) -{ - mElements.SetMemoryCategory(MCORE_MEMCATEGORY_HASHTABLE); - mTotalNumEntries = 0; - Init(maxElements); -} - - -// copy constructor -template -HashTable::HashTable(const HashTable& other) - : mTotalNumEntries(0) -{ - *this = other; -} - - -// destructor -template -HashTable::~HashTable() -{ - Clear(); -} - - -// clear the table -template -void HashTable::Clear() -{ - // get rid of existing elements - const uint32 numElems = mElements.GetLength(); - for (uint32 i = 0; i < numElems; ++i) - { - if (mElements[i]) - { - delete mElements[i]; - } - } - - // clear the array - mElements.Clear(); - - mTotalNumEntries = 0; -} - - -// find the entry with a given key -template -bool HashTable::FindEntry(const Key& key, uint32* outElementNr, uint32* outEntryNr) const -{ - // calculate the hash value - uint32 hashResult = Hash(key) % mElements.GetLength(); - - // check if the we have an entry at this hash position - if (mElements[hashResult] == nullptr) - { - return false; - } - - // search inside the array of entries - const uint32 numElements = mElements[hashResult]->GetLength(); - for (uint32 i = 0; i < numElements; ++i) - { - // if we found the one we are searching for - if (mElements[hashResult]->GetItem(i).mKey == key) - { - *outElementNr = hashResult; - *outEntryNr = i; - return true; - } - } - - return false; -} - - -// initialize the table at a given maximum amount of elements -template -void HashTable::Init(uint32 maxElements) -{ - // get rid of existing elements - Clear(); - - // resize the array - mElements.Resize(maxElements); - mElements.Shrink(); - - // reset all the elements - for (uint32 i = 0; i < maxElements; ++i) - { - mElements[i] = nullptr; - } -} - - -// add an entry to the table -template -void HashTable::Add(const Key& key, const Value& value) -{ - // calculate the hash value - uint32 hashResult = Hash(key) % mElements.GetLength(); - - // make sure there isn't already an element with this key - MCORE_ASSERT(Contains(key) == false); - - // if the array isn't allocated yet, do so - if (mElements[hashResult] == nullptr) - { - mElements[hashResult] = new MCore::Array< Entry >(); - mElements[hashResult]->SetMemoryCategory(MCORE_MEMCATEGORY_HASHTABLE); - } - - // add the entry to the array - mElements[hashResult]->Add(Entry(key, value)); - - // increase the total number of entries - mTotalNumEntries++; -} - - -// get a value -template -bool HashTable::GetValue(const Key& inKey, Value* outValue) const -{ - // try to find the element - uint32 elementNr, entryNr; - if (FindEntry(inKey, &elementNr, &entryNr)) - { - *outValue = mElements[elementNr]->GetItem(entryNr).mValue; - return true; - } - - // nothing found - return false; -} - - -// check if there is an entry using the specified key -template -bool HashTable::Contains(const Key& key) const -{ - uint32 elementNr, entryNr; - return FindEntry(key, &elementNr, &entryNr); -} - - -template -bool HashTable::Remove(const Key& key) -{ - uint32 elementNr, entryNr; - if (FindEntry(key, &elementNr, &entryNr)) - { - // remove the element - mElements[elementNr]->Remove(entryNr); - - // remove the array if it is empty - if (mElements[elementNr]->GetLength() == 0) - { - delete mElements[elementNr]; - mElements[elementNr] = nullptr; - } - - // decrease the total number of entries - mTotalNumEntries--; - - // yeah, we successfully removed it - return true; - } - - // the element wasn't found, so cannot be removed - return false; -} - - -// get the number of table elements -template -uint32 HashTable::GetNumTableElements() const -{ - return mElements.GetLength(); -} - - -// get the get the number of entries for a given table element -template -uint32 HashTable::GetNumEntries(uint32 tableElementNr) const -{ - if (mElements[tableElementNr] == nullptr) - { - return 0; - } - - return mElements[tableElementNr]->GetLength(); -} - - -// get the number of entries in the table -template -uint32 HashTable::GetTotalNumEntries() const -{ - return mTotalNumEntries; -} - - -// calculate the load balance -template -float HashTable::CalcLoadBalance() const -{ - uint32 numUsedElements = 0; - - // traverse all elements - const uint32 numElements = mElements.GetLength(); - for (uint32 i = 0; i < numElements; ++i) - { - if (mElements[i]) - { - numUsedElements++; - } - } - - if (numUsedElements == 0) - { - return 0; - } - - return (numUsedElements / (float)numElements) * 100.0f; -} - - -template -float HashTable::CalcAverageNumEntries() const -{ - uint32 numEntries = 0; - uint32 numUsedElements = 0; - - // traverse all elements - const uint32 numElements = mElements.GetLength(); - for (uint32 i = 0; i < numElements; ++i) - { - if (mElements[i]) - { - numUsedElements++; - numEntries += mElements[i]->GetLength(); - } - } - - if (numEntries == 0) - { - return 0; - } - - return numEntries / (float)numUsedElements; -} - - -// update the value of the entry with a given key -template -bool HashTable::SetValue(const Key& key, const Value& value) -{ - // try to find the element - uint32 elementNr, entryNr; - if (FindEntry(key, &elementNr, &entryNr)) - { - mElements[elementNr]->GetItem(entryNr).mValue = value; - return true; - } - - // nothing found - return false; -} - - -// get a given entry -template -MCORE_INLINE typename HashTable::Entry& HashTable::GetEntry(uint32 tableElementNr, uint32 entryNr) -{ - MCORE_ASSERT(tableElementNr < mElements.GetLength()); // make sure the values are in range - MCORE_ASSERT(mElements[tableElementNr]); // this table element must have entries - MCORE_ASSERT(entryNr < mElements[tableElementNr]->GetLength()); // - - return mElements[tableElementNr]->GetItem(entryNr); -} - - -// operator = -template -HashTable& HashTable::operator = (const HashTable& other) -{ - if (&other == this) - { - return *this; - } - - // get rid of old data - Clear(); - - // copy the number of entries - mTotalNumEntries = other.mTotalNumEntries; - - // resize the element array - mElements.Resize(other.mElements.GetLength()); - - // copy the element entries - const uint32 numElements = mElements.GetLength(); - for (uint32 i = 0; i < numElements; ++i) - { - if (other.mElements[i]) - { - // create the array and copy the entries - mElements[i] = new MCore::Array< Entry >(); - *mElements[i] = *other.mElements[i]; - } - else - { - mElements[i] = nullptr; - } - } - - return *this; -} diff --git a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp index 33dcf1e74d..dc25288c19 100644 --- a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.cpp @@ -15,8 +15,8 @@ namespace MCore { // constructor IDGenerator::IDGenerator() + : m_nextId{0} { - mNextID.SetValue(0); } @@ -27,10 +27,10 @@ namespace MCore // get a unique id - uint32 IDGenerator::GenerateID() + size_t IDGenerator::GenerateID() { - const uint32 result = mNextID.Increment(); - MCORE_ASSERT(result != MCORE_INVALIDINDEX32); // reached the limit + const size_t result = m_nextId++; + MCORE_ASSERT(result != InvalidIndex); // reached the limit return result; } } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h index 04f43a4995..5c392e45b1 100644 --- a/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h +++ b/Gems/EMotionFX/Code/MCore/Source/IDGenerator.h @@ -28,10 +28,10 @@ namespace MCore * This is thread safe. * @return The unique id. */ - uint32 GenerateID(); + size_t GenerateID(); private: - AtomicUInt32 mNextID; /**< The id used for the next GenerateID() call. */ + AZStd::atomic m_nextId; /**< The id used for the next GenerateID() call. */ /** * Default constructor. diff --git a/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp b/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp index a4e0a71cee..0621926fb2 100644 --- a/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/LogManager.cpp @@ -10,26 +10,24 @@ #include #include "LogManager.h" -#include - namespace MCore { // static mutex - Mutex LogManager::mGlobalMutex; + Mutex LogManager::s_globalMutex; //-------------------------------------------------------------------------------------------- // constructor LogCallback::LogCallback() { - mLogLevels = LOGLEVEL_DEFAULT; + m_logLevels = LOGLEVEL_DEFAULT; } // set the log levels this callback will accept and pass through void LogCallback::SetLogLevels(ELogLevel logLevels) { - mLogLevels = logLevels; + m_logLevels = logLevels; GetLogManager().InitLogLevels(); } @@ -60,8 +58,6 @@ namespace MCore // constructor LogManager::LogManager() { - mLogCallbacks.SetMemoryCategory(MCORE_MEMCATEGORY_LOGMANAGER); - // initialize the enabled log levels InitLogLevels(); } @@ -79,10 +75,10 @@ namespace MCore void LogManager::AddLogCallback(LogCallback* callback) { MCORE_ASSERT(callback); - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // add the callback to the stack - mLogCallbacks.Add(callback); + m_logCallbacks.emplace_back(callback); // collect the enabled log levels InitLogLevels(); @@ -90,16 +86,16 @@ namespace MCore // remove a specific log callback from the stack - void LogManager::RemoveLogCallback(uint32 index) + void LogManager::RemoveLogCallback(size_t index) { - MCORE_ASSERT(mLogCallbacks.GetIsValidIndex(index)); - LockGuard lock(mMutex); + MCORE_ASSERT(index < m_logCallbacks.size()); + LockGuard lock(m_mutex); // delete it from memory - delete mLogCallbacks[index]; + delete m_logCallbacks[index]; // remove the callback from the stack - mLogCallbacks.Remove(index); + m_logCallbacks.erase(AZStd::next(begin(m_logCallbacks), index)); // collect the enabled log levels InitLogLevels(); @@ -108,27 +104,18 @@ namespace MCore // remove all given log callbacks by type void LogManager::RemoveAllByType(uint32 type) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); - // iterate through all log callbacks - for (uint32 i = 0; i < mLogCallbacks.GetLength(); ) + // Put all the callbacks of the type to be removed at the end of the vector + m_logCallbacks.erase(AZStd::remove_if(begin(m_logCallbacks), end(m_logCallbacks), [type](const LogCallback* callback) { - LogCallback* callback = mLogCallbacks[i]; - - // check if we are dealing with a log file if (callback->GetType() == type) { - // get rid of the callback instance delete callback; - - // remove the callback from the stack - mLogCallbacks.Remove(i); + return true; } - else - { - i++; - } - } + return false; + })); // collect the enabled log levels InitLogLevels(); @@ -138,16 +125,15 @@ namespace MCore // remove all log callbacks from the stack void LogManager::ClearLogCallbacks() { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // get rid of the callbacks - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (auto* logCallback : m_logCallbacks) { - delete mLogCallbacks[i]; + delete logCallback; } - mLogCallbacks.Clear(true); + m_logCallbacks.clear(); // collect the enabled log levels InitLogLevels(); @@ -155,15 +141,15 @@ namespace MCore // retrieve a pointer to the given log callback - LogCallback* LogManager::GetLogCallback(uint32 index) + LogCallback* LogManager::GetLogCallback(size_t index) { - return mLogCallbacks[index]; + return m_logCallbacks[index]; } // return number of log callbacks in the stack - uint32 LogManager::GetNumLogCallbacks() const + size_t LogManager::GetNumLogCallbacks() const { - return mLogCallbacks.GetLength(); + return m_logCallbacks.size(); } // collect all enabled log levels @@ -173,13 +159,12 @@ namespace MCore int32 logLevels = LogCallback::LOGLEVEL_NONE; // enable all log levels that are enabled by any of the callbacks - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (auto* logCallback : m_logCallbacks) { - logLevels |= (int32)mLogCallbacks[i]->GetLogLevels(); + logLevels |= (int32)logCallback->GetLogLevels(); } - mLogLevels = (LogCallback::ELogLevel)logLevels; + m_logLevels = (LogCallback::ELogLevel)logLevels; } @@ -187,54 +172,51 @@ namespace MCore void LogManager::SetLogLevels(LogCallback::ELogLevel logLevels) { // iterate through all log callbacks and set it to the given log levels - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (auto* logCallback : m_logCallbacks) { - mLogCallbacks[i]->SetLogLevels(logLevels); + logCallback->SetLogLevels(logLevels); } // force set the log manager's log levels to the given one as well - mLogLevels = logLevels; + m_logLevels = logLevels; } // the main logging method void LogManager::LogMessage(const char* message, LogCallback::ELogLevel logLevel) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // iterate through all callbacks - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (auto* logCallback : m_logCallbacks) { - if (mLogCallbacks[i]->GetLogLevels() & logLevel) + if (logCallback->GetLogLevels() & logLevel) { - mLogCallbacks[i]->Log(message, logLevel); + logCallback->Log(message, logLevel); } } } // find the index of a given callback - uint32 LogManager::FindLogCallback(LogCallback* callback) const + size_t LogManager::FindLogCallback(LogCallback* callback) const { // iterate through all callbacks - const uint32 num = mLogCallbacks.GetLength(); - for (uint32 i = 0; i < num; ++i) + for (size_t i = 0; i < m_logCallbacks.size(); ++i) { - if (mLogCallbacks[i] == callback) + if (m_logCallbacks[i] == callback) { return i; } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } void LogFatalError(const char* what, ...) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_FATAL) @@ -254,7 +236,7 @@ namespace MCore void LogError(const char* what, ...) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_ERROR) @@ -274,7 +256,7 @@ namespace MCore void LogWarning(const char* what, ...) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_WARNING) @@ -294,7 +276,7 @@ namespace MCore void LogInfo(const char* what, ...) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_INFO) @@ -314,7 +296,7 @@ namespace MCore void LogDetailedInfo(const char* what, ...) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_DETAILEDINFO) @@ -334,7 +316,7 @@ namespace MCore void LogDebug(const char* what, ...) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_DEBUG) @@ -353,7 +335,7 @@ namespace MCore void LogDebugMsg(const char* msg) { - LockGuard lock(LogManager::mGlobalMutex); + LockGuard lock(LogManager::s_globalMutex); // skip the va list construction in case that the message won't be logged by any of the callbacks if (GetLogManager().GetLogLevels() & LogCallback::LOGLEVEL_DEBUG) diff --git a/Gems/EMotionFX/Code/MCore/Source/LogManager.h b/Gems/EMotionFX/Code/MCore/Source/LogManager.h index 1f8ac34cae..864aa50219 100644 --- a/Gems/EMotionFX/Code/MCore/Source/LogManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/LogManager.h @@ -10,8 +10,8 @@ // include the required headers #include +#include #include "StandardHeaders.h" -#include "Array.h" #include "MultiThreadManager.h" @@ -75,7 +75,7 @@ namespace MCore * To check if a log level is enabled use logical bitwise and comparison, example: if (GetLogLevels() & LOGLEVEL_EXAMPLE). * @result The log levels packed as bit flags which are enabled on the callback. */ - MCORE_INLINE ELogLevel GetLogLevels() const { return mLogLevels; } + MCORE_INLINE ELogLevel GetLogLevels() const { return m_logLevels; } /** * Set the log levels this callback will accept and pass through. @@ -86,7 +86,7 @@ namespace MCore void SetLogLevels(ELogLevel logLevels); protected: - ELogLevel mLogLevels; /**< The log levels that will pass the callback. All messages from log flags which are disabled won't be logged. The default value of the log level will be LOGLEVEL_DEFAULT. */ + ELogLevel m_logLevels; /**< The log levels that will pass the callback. All messages from log flags which are disabled won't be logged. The default value of the log level will be LOGLEVEL_DEFAULT. */ }; //---------------------------------------------------------------------------- @@ -187,7 +187,7 @@ namespace MCore * Remove the given callback from the stack. * @param index The index of the callback to remove. */ - void RemoveLogCallback(uint32 index); + void RemoveLogCallback(size_t index); /** * Remove all given log callbacks by type from the stack. @@ -205,20 +205,20 @@ namespace MCore * @param index The index of the callback. * @return A pointer to the callback. */ - LogCallback* GetLogCallback(uint32 index); + LogCallback* GetLogCallback(size_t index); /** * Find the index of a given callback. * @param callback The callback object to find. * @result Returns the index value, or MCORE_INVALIDINDEX32 when not found. */ - uint32 FindLogCallback(LogCallback* callback) const; + size_t FindLogCallback(LogCallback* callback) const; /** * Return the number of log callbacks managed by this class. * @return Number of log callbacks. */ - uint32 GetNumLogCallbacks() const; + size_t GetNumLogCallbacks() const; /** * Force set the log levels of all callbacks in the log manager. @@ -232,7 +232,7 @@ namespace MCore * To check if a log level is enabled by one of the callbacks use logical bitwise and comparison, example: if (GetLogLevels() & LOGLEVEL_EXAMPLE). * @result The log levels packed as bit flags which are enabled on the callback. */ - MCORE_INLINE LogCallback::ELogLevel GetLogLevels() const { return mLogLevels; } + MCORE_INLINE LogCallback::ELogLevel GetLogLevels() const { return m_logLevels; } /** * Iterate over all callbacks and collect the enabled log levels. @@ -249,11 +249,11 @@ namespace MCore void LogMessage(const char* message, LogCallback::ELogLevel logLevel = LogCallback::LOGLEVEL_INFO); public: - static Mutex mGlobalMutex; /**< The multithread mutex, used by some global Log functions. */ + static Mutex s_globalMutex; /**< The multithread mutex, used by some global Log functions. */ private: - Array mLogCallbacks; /**< A collection of log callback instances. */ - LogCallback::ELogLevel mLogLevels; /**< The log levels that will pass one of the callbacks. All messages from log flags which are disabled won't be logged. */ - Mutex mMutex; /**< The mutex for logging locally. */ + AZStd::vector m_logCallbacks; /**< A collection of log callback instances. */ + LogCallback::ELogLevel m_logLevels; /**< The log levels that will pass one of the callbacks. All messages from log flags which are disabled won't be logged. */ + Mutex m_mutex; /**< The mutex for logging locally. */ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp index cd64af15c6..5cdd9c2600 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.cpp @@ -15,28 +15,27 @@ namespace MCore { - CommandManager::CommandHistoryEntry::CommandHistoryEntry(CommandGroup* group, Command* command, const CommandLine& parameters, AZ::u32 historyItemNr) + CommandManager::CommandHistoryEntry::CommandHistoryEntry(CommandGroup* group, Command* command, const CommandLine& parameters, size_t historyItemNr) { - mCommandGroup = group; - mExecutedCommand = command; - mParameters = parameters; + m_commandGroup = group; + m_executedCommand = command; + m_parameters = parameters; m_historyItemNr = historyItemNr; } CommandManager::CommandHistoryEntry::~CommandHistoryEntry() { - // remark: the mCommand and mCommandGroup are automatically deleted after popping from the history } - AZStd::string CommandManager::CommandHistoryEntry::ToString(CommandGroup* group, Command* command, AZ::u32 historyItemNr) + AZStd::string CommandManager::CommandHistoryEntry::ToString(CommandGroup* group, Command* command, size_t historyItemNr) { if (group) { - return AZStd::string::format("%.3d - %s", historyItemNr, group->GetGroupName()); + return AZStd::string::format("%.3zu - %s", historyItemNr, group->GetGroupName()); } else if (command) { - return AZStd::string::format("%.3d - %s", historyItemNr, command->GetHistoryName()); + return AZStd::string::format("%.3zu - %s", historyItemNr, command->GetHistoryName()); } return ""; @@ -44,38 +43,38 @@ namespace MCore AZStd::string CommandManager::CommandHistoryEntry::ToString() const { - return ToString(mCommandGroup, mExecutedCommand, m_historyItemNr); + return ToString(m_commandGroup, m_executedCommand, m_historyItemNr); } CommandManager::CommandManager() { - mCommands.reserve(128); + m_commands.reserve(128); // set default values - mMaxHistoryEntries = 100; - mHistoryIndex = -1; + m_maxHistoryEntries = 100; + m_historyIndex = -1; m_totalNumHistoryItems = 0; // preallocate history entries - mCommandHistory.reserve(mMaxHistoryEntries); + m_commandHistory.reserve(m_maxHistoryEntries); m_commandsInExecution = 0; } CommandManager::~CommandManager() { - for (auto element : mRegisteredCommands) + for (auto element : m_registeredCommands) { Command* command = element.second; delete command; } - mRegisteredCommands.clear(); + m_registeredCommands.clear(); // remove all callbacks RemoveCallbacks(); // destroy the command history - while (!mCommandHistory.empty()) + while (!m_commandHistory.empty()) { PopCommandHistory(); } @@ -85,93 +84,93 @@ namespace MCore void CommandManager::PushCommandHistory(CommandGroup* commandGroup) { // if we reached the maximum number of history entries remove the oldest one - if (mCommandHistory.size() >= mMaxHistoryEntries) + if (m_commandHistory.size() >= m_maxHistoryEntries) { PopCommandHistory(); - mHistoryIndex = static_cast(mCommandHistory.size()) - 1; + m_historyIndex = static_cast(m_commandHistory.size()) - 1; } - if (!mCommandHistory.empty()) + if (!m_commandHistory.empty()) { // remove unneeded commandsnumToRemove - const size_t numToRemove = mCommandHistory.size() - mHistoryIndex - 1; - for (CommandManagerCallback* managerCallback : mCallbacks) + const size_t numToRemove = m_commandHistory.size() - m_historyIndex - 1; + for (CommandManagerCallback* managerCallback : m_callbacks) { for (size_t a = 0; a < numToRemove; ++a) { - managerCallback->OnRemoveCommand(mHistoryIndex + 1); + managerCallback->OnRemoveCommand(m_historyIndex + 1); } } for (size_t a = 0; a < numToRemove; ++a) { - delete mCommandHistory[mHistoryIndex + 1].mExecutedCommand; - delete mCommandHistory[mHistoryIndex + 1].mCommandGroup; - mCommandHistory.erase(mCommandHistory.begin() + mHistoryIndex + 1); + delete m_commandHistory[m_historyIndex + 1].m_executedCommand; + delete m_commandHistory[m_historyIndex + 1].m_commandGroup; + m_commandHistory.erase(m_commandHistory.begin() + m_historyIndex + 1); } } // resize the command history - mCommandHistory.resize(mHistoryIndex + 1); + m_commandHistory.resize(m_historyIndex + 1); // add a command history entry m_totalNumHistoryItems++; - mCommandHistory.push_back(CommandHistoryEntry(commandGroup, nullptr, CommandLine(), m_totalNumHistoryItems)); + m_commandHistory.push_back(CommandHistoryEntry(commandGroup, nullptr, CommandLine(), m_totalNumHistoryItems)); // increase the history index - mHistoryIndex++; + m_historyIndex++; // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnAddCommandToHistory(mHistoryIndex, commandGroup, nullptr, CommandLine()); + managerCallback->OnAddCommandToHistory(m_historyIndex, commandGroup, nullptr, CommandLine()); } } // save command in the history void CommandManager::PushCommandHistory(Command* command, const CommandLine& parameters) { - if (!mCommandHistory.empty()) + if (!m_commandHistory.empty()) { // if we reached the maximum number of history entries remove the oldest one - if (mCommandHistory.size() >= mMaxHistoryEntries) + if (m_commandHistory.size() >= m_maxHistoryEntries) { PopCommandHistory(); - mHistoryIndex = static_cast(mCommandHistory.size()) - 1; + m_historyIndex = static_cast(m_commandHistory.size()) - 1; } // remove unneeded commands - const size_t numToRemove = mCommandHistory.size() - mHistoryIndex - 1; - for (CommandManagerCallback* managerCallback : mCallbacks) + const size_t numToRemove = m_commandHistory.size() - m_historyIndex - 1; + for (CommandManagerCallback* managerCallback : m_callbacks) { for (size_t a = 0; a < numToRemove; ++a) { - managerCallback->OnRemoveCommand(mHistoryIndex + 1); + managerCallback->OnRemoveCommand(m_historyIndex + 1); } } for (size_t a = 0; a < numToRemove; ++a) { - delete mCommandHistory[mHistoryIndex + 1].mExecutedCommand; - delete mCommandHistory[mHistoryIndex + 1].mCommandGroup; - mCommandHistory.erase(mCommandHistory.begin() + mHistoryIndex + 1); + delete m_commandHistory[m_historyIndex + 1].m_executedCommand; + delete m_commandHistory[m_historyIndex + 1].m_commandGroup; + m_commandHistory.erase(m_commandHistory.begin() + m_historyIndex + 1); } } // resize the command history - mCommandHistory.resize(mHistoryIndex + 1); + m_commandHistory.resize(m_historyIndex + 1); // add a command history entry m_totalNumHistoryItems++; - mCommandHistory.push_back(CommandHistoryEntry(nullptr, command, parameters, m_totalNumHistoryItems)); + m_commandHistory.push_back(CommandHistoryEntry(nullptr, command, parameters, m_totalNumHistoryItems)); // increase the history index - mHistoryIndex++; + m_historyIndex++; // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnAddCommandToHistory(mHistoryIndex, nullptr, command, parameters); + managerCallback->OnAddCommandToHistory(m_historyIndex, nullptr, command, parameters); } } @@ -179,23 +178,23 @@ namespace MCore void CommandManager::PopCommandHistory() { // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnRemoveCommand(0); } // destroy the command and remove it from the command history - Command* command = mCommandHistory.front().mExecutedCommand; + Command* command = m_commandHistory.front().m_executedCommand; if (command) { delete command; } else { - delete mCommandHistory.front().mCommandGroup; + delete m_commandHistory.front().m_commandGroup; } - mCommandHistory.erase(mCommandHistory.begin()); + m_commandHistory.erase(m_commandHistory.begin()); } bool CommandManager::ExecuteCommand(const AZStd::string& command, AZStd::string& outCommandResult, bool addToHistory, Command** outExecutedCommand, CommandLine* outExecutedParameters, bool callFromCommandGroup, bool clearErrors, bool handleErrors) @@ -456,7 +455,7 @@ namespace MCore ++m_commandsInExecution; // execute command manager callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPreExecuteCommandGroup(&commandGroup, false); } @@ -540,7 +539,7 @@ namespace MCore break; } } - if (static_cast(i) < relativeIndex) + if (static_cast(i) < relativeIndex) { MCore::LogError("Execution of command '%s' failed, command trying to access results from %d commands back, but there are only %d", commandString.c_str(), relativeIndex, i - 1); hadError = true; @@ -581,25 +580,25 @@ namespace MCore delete newGroup; // execute command manager callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPostExecuteCommandGroup(&commandGroup, false); } // Let the callbacks handle error reporting (e.g. show an error report window). - if (handleErrors && !mErrors.empty()) + if (handleErrors && !m_errors.empty()) { // Execute error report callbacks. - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnShowErrorReport(mErrors); + managerCallback->OnShowErrorReport(m_errors); } } // Clear errors after reporting if specified. if (clearErrors) { - mErrors.clear(); + m_errors.clear(); } --m_commandsInExecution; @@ -642,19 +641,19 @@ namespace MCore } // execute command manager callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPostExecuteCommandGroup(&commandGroup, true); } // Let the callbacks handle error reporting (e.g. show an error report window). - const bool errorsOccured = !mErrors.empty(); + const bool errorsOccured = !m_errors.empty(); if (handleErrors && errorsOccured) { // Execute error report callbacks. - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnShowErrorReport(mErrors); + managerCallback->OnShowErrorReport(m_errors); } } @@ -665,7 +664,7 @@ namespace MCore // Clear errors after reporting if specified. if (clearErrors) { - mErrors.clear(); + m_errors.clear(); } --m_commandsInExecution; @@ -689,18 +688,18 @@ namespace MCore void CommandManager::ExecuteUndoCallbacks(Command* command, const CommandLine& parameters, bool preUndo) { Command* orgCommand = command->GetOriginalCommand(); - uint32 numFailed = 0; + size_t numFailed = 0; // get the number of callbacks and iterate through them - const uint32 numCommandCallbacks = orgCommand->GetNumCallbacks(); - for (uint32 i = 0; i < numCommandCallbacks; ++i) + const size_t numCommandCallbacks = orgCommand->GetNumCallbacks(); + for (size_t i = 0; i < numCommandCallbacks; ++i) { // get the current callback Command::Callback* callback = orgCommand->GetCallback(i); if (preUndo) { - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPreUndoCommand(command, parameters); } @@ -717,7 +716,7 @@ namespace MCore if (!preUndo) { - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPostUndoCommand(command, parameters); } @@ -734,11 +733,11 @@ namespace MCore void CommandManager::ExecuteCommandCallbacks(Command* command, const CommandLine& parameters, bool preCommand) { Command* orgCommand = command->GetOriginalCommand(); - uint32 numFailed = 0; + size_t numFailed = 0; // get the number of callbacks and iterate through them - const uint32 numCommandCallbacks = orgCommand->GetNumCallbacks(); - for (uint32 i = 0; i < numCommandCallbacks; ++i) + const size_t numCommandCallbacks = orgCommand->GetNumCallbacks(); + for (size_t i = 0; i < numCommandCallbacks; ++i) { // get the current callback Command::Callback* callback = orgCommand->GetCallback(i); @@ -762,15 +761,15 @@ namespace MCore bool CommandManager::Undo(AZStd::string& outCommandResult) { // check if we can undo - if (mCommandHistory.empty() && mHistoryIndex >= 0) + if (m_commandHistory.empty() && m_historyIndex >= 0) { outCommandResult = "Cannot undo command. The command history is empty"; return false; } // get the last called command from the command history - const CommandHistoryEntry& lastEntry = mCommandHistory[mHistoryIndex]; - Command* command = lastEntry.mExecutedCommand; + const CommandHistoryEntry& lastEntry = m_commandHistory[m_historyIndex]; + Command* command = lastEntry.m_executedCommand; ++m_commandsInExecution; @@ -779,28 +778,28 @@ namespace MCore if (command) { // execute pre-undo callbacks - ExecuteUndoCallbacks(command, lastEntry.mParameters, true); + ExecuteUndoCallbacks(command, lastEntry.m_parameters, true); // undo the command, get the result and reset it - result = command->Undo(lastEntry.mParameters, outCommandResult); + result = command->Undo(lastEntry.m_parameters, outCommandResult); // execute post-undo callbacks - ExecuteUndoCallbacks(command, lastEntry.mParameters, false); + ExecuteUndoCallbacks(command, lastEntry.m_parameters, false); } // we are dealing with a command group else { - CommandGroup* group = lastEntry.mCommandGroup; + CommandGroup* group = lastEntry.m_commandGroup; MCORE_ASSERT(group); // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPreExecuteCommandGroup(group, true); } - const int32 numCommands = static_cast(group->GetNumCommands() - 1); - for (int32 g = numCommands; g >= 0; --g) + const ptrdiff_t numCommands = static_cast(group->GetNumCommands()) - 1; + for (ptrdiff_t g = numCommands; g >= 0; --g) { Command* groupCommand = group->GetCommand(g); if (groupCommand == nullptr) @@ -827,29 +826,29 @@ namespace MCore } // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPostExecuteCommandGroup(group, result); } } // go one step back in the command history - mHistoryIndex--; + m_historyIndex--; // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnSetCurrentCommand(mHistoryIndex); + managerCallback->OnSetCurrentCommand(m_historyIndex); } // Let the callbacks handle error reporting (e.g. show an error report window). - if (!mErrors.empty()) + if (!m_errors.empty()) { - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnShowErrorReport(mErrors); + managerCallback->OnShowErrorReport(m_errors); } - mErrors.clear(); + m_errors.clear(); } --m_commandsInExecution; @@ -860,23 +859,16 @@ namespace MCore // redo the last undoed command bool CommandManager::Redo(AZStd::string& outCommandResult) { - /* // check if there are still commands to undo in the history - if (mHistoryIndex >= mCommandHistory.GetLength()) - { - outCommandResult = "Cannot redo command. Either the history is empty or the history index is out of range."; - return false; - }*/ - // get the last called command from the command history - const CommandHistoryEntry& lastEntry = mCommandHistory[mHistoryIndex + 1]; + const CommandHistoryEntry& lastEntry = m_commandHistory[m_historyIndex + 1]; // if we just redo one single command bool result = true; - if (lastEntry.mExecutedCommand) + if (lastEntry.m_executedCommand) { // redo the command, get the result and reset it - result = ExecuteCommand(lastEntry.mExecutedCommand, - lastEntry.mParameters, + result = ExecuteCommand(lastEntry.m_executedCommand, + lastEntry.m_parameters, outCommandResult, /*addToHistory=*/false, /*callFromCommandGroup=*/false, @@ -888,10 +880,10 @@ namespace MCore else { ++m_commandsInExecution; - CommandGroup* group = lastEntry.mCommandGroup; + CommandGroup* group = lastEntry.m_commandGroup; AZ_Assert(group, "Cannot redo. Command group is not valid."); - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPreExecuteCommandGroup(group, false); } @@ -917,29 +909,29 @@ namespace MCore } --m_commandsInExecution; - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPostExecuteCommandGroup(group, result); } } // go one step forward in the command history - mHistoryIndex++; + m_historyIndex++; // perform callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnSetCurrentCommand(mHistoryIndex); + managerCallback->OnSetCurrentCommand(m_historyIndex); } // Let the callbacks handle error reporting (e.g. show an error report window). - if (!mErrors.empty()) + if (!m_errors.empty()) { - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnShowErrorReport(mErrors); + managerCallback->OnShowErrorReport(m_errors); } - mErrors.clear(); + m_errors.clear(); } return result; @@ -970,17 +962,17 @@ namespace MCore } // add the command to the hash table - mRegisteredCommands.insert(AZStd::make_pair(command->GetNameString(), command)); + m_registeredCommands.insert(AZStd::make_pair(command->GetNameString(), command)); // we're going to insert the command in a sorted way now bool found = false; - const size_t numCommands = mCommands.size(); + const size_t numCommands = m_commands.size(); for (size_t i = 0; i < numCommands; ++i) { - if (azstricmp(mCommands[i]->GetName(), command->GetName()) > 0) + if (azstricmp(m_commands[i]->GetName(), command->GetName()) > 0) { found = true; - mCommands.insert(mCommands.begin() + i, command); + m_commands.insert(m_commands.begin() + i, command); break; } } @@ -988,7 +980,7 @@ namespace MCore // if no insert location has been found, add it to the back of the array if (!found) { - mCommands.push_back(command); + m_commands.push_back(command); } // initialize the command syntax @@ -1000,8 +992,8 @@ namespace MCore Command* CommandManager::FindCommand(const AZStd::string& commandName) { - auto iterator = mRegisteredCommands.find(commandName); - if (iterator == mRegisteredCommands.end()) + auto iterator = m_registeredCommands.find(commandName); + if (iterator == m_registeredCommands.end()) { return nullptr; } @@ -1046,7 +1038,7 @@ namespace MCore } // execute command manager callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPreExecuteCommand(nullptr, command, commandLine); } @@ -1081,25 +1073,25 @@ namespace MCore } // execute all post execute callbacks - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { managerCallback->OnPostExecuteCommand(nullptr, command, commandLine, result, outCommandResult); } // Let the callbacks handle error reporting (e.g. show an error report window). - if (handleErrors && !mErrors.empty()) + if (handleErrors && !m_errors.empty()) { // Execute error report callbacks. - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnShowErrorReport(mErrors); + managerCallback->OnShowErrorReport(m_errors); } } // Clear errors after reporting if specified. if (clearErrors) { - mErrors.clear(); + m_errors.clear(); } #ifdef MCORE_COMMANDMANAGER_PERFORMANCE @@ -1124,14 +1116,14 @@ namespace MCore LogDetailedInfo("----------------------------------"); // get the number of entries in the command history - const size_t numHistoryEntries = mCommandHistory.size(); + const size_t numHistoryEntries = m_commandHistory.size(); LogDetailedInfo("Command History (%d entries) - oldest (top entry) to newest (bottom entry):", numHistoryEntries); // print the command history entries for (size_t i = 0; i < numHistoryEntries; ++i) { - AZStd::string text = AZStd::string::format("%.3zu: name='%s', num parameters=%u", i, mCommandHistory[i].mExecutedCommand->GetName(), mCommandHistory[i].mParameters.GetNumParameters()); - if (i == (uint32)mHistoryIndex) + AZStd::string text = AZStd::string::format("%.3zu: name='%s', num parameters=%zu", i, m_commandHistory[i].m_executedCommand->GetName(), m_commandHistory[i].m_parameters.GetNumParameters()); + if (i == m_historyIndex) { LogDetailedInfo("-> %s", text.c_str()); } @@ -1146,22 +1138,22 @@ namespace MCore void CommandManager::RemoveCallbacks() { - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { delete managerCallback; } - mCallbacks.clear(); + m_callbacks.clear(); } void CommandManager::RegisterCallback(CommandManagerCallback* callback) { - mCallbacks.push_back(callback); + m_callbacks.push_back(callback); } void CommandManager::RemoveCallback(CommandManagerCallback* callback, bool delFromMem) { - mCallbacks.erase(AZStd::remove(mCallbacks.begin(), mCallbacks.end(), callback), mCallbacks.end()); + m_callbacks.erase(AZStd::remove(m_callbacks.begin(), m_callbacks.end(), callback), m_callbacks.end()); if (delFromMem) { @@ -1171,83 +1163,83 @@ namespace MCore size_t CommandManager::GetNumCallbacks() const { - return mCallbacks.size(); + return m_callbacks.size(); } CommandManagerCallback* CommandManager::GetCallback(size_t index) { - return mCallbacks[index]; + return m_callbacks[index]; } // set the max num history items - void CommandManager::SetMaxHistoryItems(uint32 maxItems) + void CommandManager::SetMaxHistoryItems(size_t maxItems) { - maxItems = AZStd::max(1u, maxItems); - mMaxHistoryEntries = maxItems; + maxItems = AZStd::max(size_t{1}, maxItems); + m_maxHistoryEntries = maxItems; - while (mCommandHistory.size() > mMaxHistoryEntries) + while (m_commandHistory.size() > m_maxHistoryEntries) { PopCommandHistory(); - mHistoryIndex = static_cast(mCommandHistory.size()) - 1; + m_historyIndex = static_cast(m_commandHistory.size()) - 1; } } size_t CommandManager::GetMaxHistoryItems() const { - return mMaxHistoryEntries; + return m_maxHistoryEntries; } - int32 CommandManager::GetHistoryIndex() const + ptrdiff_t CommandManager::GetHistoryIndex() const { - return mHistoryIndex; + return m_historyIndex; } size_t CommandManager::GetNumHistoryItems() const { - return mCommandHistory.size(); + return m_commandHistory.size(); } const CommandManager::CommandHistoryEntry& CommandManager::GetHistoryItem(size_t index) const { - return mCommandHistory[index]; + return m_commandHistory[index]; } Command* CommandManager::GetHistoryCommand(size_t historyIndex) { - return mCommandHistory[historyIndex].mExecutedCommand; + return m_commandHistory[historyIndex].m_executedCommand; } void CommandManager::ClearHistory() { // clear the command history - while (!mCommandHistory.empty()) + while (!m_commandHistory.empty()) { PopCommandHistory(); } // reset the history index - mHistoryIndex = -1; + m_historyIndex = -1; } - const CommandLine& CommandManager::GetHistoryCommandLine(uint32 historyIndex) const + const CommandLine& CommandManager::GetHistoryCommandLine(size_t historyIndex) const { - return mCommandHistory[historyIndex].mParameters; + return m_commandHistory[historyIndex].m_parameters; } size_t CommandManager::GetNumRegisteredCommands() const { - return mCommands.size(); + return m_commands.size(); } Command* CommandManager::GetCommand(size_t index) { - return mCommands[index]; + return m_commands[index]; } // delete the given callback from all commands void CommandManager::RemoveCommandCallback(Command::Callback* callback, bool delFromMem) { - for (Command* command : mCommands) + for (Command* command : m_commands) { command->RemoveCallback(callback, false); // false = don't delete from memory } @@ -1297,18 +1289,18 @@ namespace MCore bool CommandManager::ShowErrorReport() { // Let the callbacks handle error reporting (e.g. show an error report window). - const bool errorsOccured = !mErrors.empty(); + const bool errorsOccured = !m_errors.empty(); if (errorsOccured) { // Execute error report callbacks. - for (CommandManagerCallback* managerCallback : mCallbacks) + for (CommandManagerCallback* managerCallback : m_callbacks) { - managerCallback->OnShowErrorReport(mErrors); + managerCallback->OnShowErrorReport(m_errors); } } // clear errors after reporting - mErrors.clear(); + m_errors.clear(); return errorsOccured; } diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h index dfa99523fb..d59639dee5 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreCommandManager.h @@ -11,7 +11,7 @@ #include #include #include "StandardHeaders.h" -#include +#include #include "Command.h" #include "CommandGroup.h" @@ -38,9 +38,9 @@ namespace MCore struct MCORE_API CommandHistoryEntry { CommandHistoryEntry() - : mCommandGroup(nullptr) - , mExecutedCommand(nullptr) - , mParameters(nullptr) {} + : m_commandGroup(nullptr) + , m_executedCommand(nullptr) + , m_parameters(nullptr) {} /** * Extended Constructor. @@ -48,17 +48,17 @@ namespace MCore * @param command The command instance that has been created at execution time. When set to nullptr it will assume it is a group, and it will use the group you specified. * @param parameters The command arguments. */ - CommandHistoryEntry(CommandGroup* group, Command* command, const CommandLine& parameters, AZ::u32 historyItemNr); + CommandHistoryEntry(CommandGroup* group, Command* command, const CommandLine& parameters, size_t historyItemNr); ~CommandHistoryEntry(); - static AZStd::string ToString(CommandGroup* group, Command* command, AZ::u32 historyItemNr); + static AZStd::string ToString(CommandGroup* group, Command* command, size_t historyItemNr); AZStd::string ToString() const; - CommandGroup* mCommandGroup; /**< A pointer to the command group, or nullptr when no group is used (in that case it uses a single command). */ - Command* mExecutedCommand; /**< A pointer to the command object, or nullptr when no command is used (in that case it uses a group). */ - CommandLine mParameters; /**< The used command arguments, unused in case no command is used (in that case it uses a group). */ - AZ::u32 m_historyItemNr; /**< The global history item number. This number will neither change depending on the size of the history queue nor with undo/redo. */ + CommandGroup* m_commandGroup; /**< A pointer to the command group, or nullptr when no group is used (in that case it uses a single command). */ + Command* m_executedCommand; /**< A pointer to the command object, or nullptr when no command is used (in that case it uses a group). */ + CommandLine m_parameters; /**< The used command arguments, unused in case no command is used (in that case it uses a group). */ + size_t m_historyItemNr; /**< The global history item number. This number will neither change depending on the size of the history queue nor with undo/redo. */ }; @@ -183,7 +183,7 @@ namespace MCore * On default this value is 100. This means it will remember the last 100 executed commands, which can then be undo-ed and redo-ed. * @param maxItems The maximum number of items to remember. */ - void SetMaxHistoryItems(uint32 maxItems); + void SetMaxHistoryItems(size_t maxItems); /** * Get the maximum number of history items that the manager will remember. @@ -197,7 +197,7 @@ namespace MCore * This value will be in range of [0..GetMaxHistoryItems()-1]. * @result The current history index. */ - int32 GetHistoryIndex() const; + ptrdiff_t GetHistoryIndex() const; /** * Get the number of history items stored. @@ -225,7 +225,7 @@ namespace MCore * @param historyIndex The history index number, which must be in range of [0..GetNumHistoryItems()-1]. * @result A reference to the command line that was used when executing this command. */ - const CommandLine& GetHistoryCommandLine(uint32 historyIndex) const; + const CommandLine& GetHistoryCommandLine(size_t historyIndex) const; /** * Get the total number of registered commands. @@ -280,8 +280,8 @@ namespace MCore * Add error message to the internal callback based error handling system. * @param[in] errorLine The error line to add to the internal error handler. */ - MCORE_INLINE void AddError(const char* errorLine) { mErrors.push_back(errorLine); } - MCORE_INLINE void AddError(const AZStd::string& errorLine) { mErrors.push_back(errorLine); } + MCORE_INLINE void AddError(const char* errorLine) { m_errors.push_back(errorLine); } + MCORE_INLINE void AddError(const AZStd::string& errorLine) { m_errors.push_back(errorLine); } /** * Checks if an error occurred and calls the error handling callbacks. @@ -296,14 +296,14 @@ namespace MCore bool IsExecuting() const { return m_commandsInExecution > 0; } protected: - AZStd::unordered_map mRegisteredCommands; /**< A hash table storing the command objects for fast command object access. */ - AZStd::vector mCommandHistory; /**< The command history stack for undo/redo functionality. */ - AZStd::vector mCallbacks; /**< The command manager callbacks. */ - AZStd::vector mErrors; /**< List of errors that happened during command execution. */ - AZStd::vector mCommands; /**< A flat array of registered commands, for easy traversal. */ - size_t mMaxHistoryEntries; /**< The maximum remembered commands in the command history. */ - int32 mHistoryIndex; /**< The command history iterator. The current position in the undo/redo history. */ - AZ::u32 m_totalNumHistoryItems; /**< The number of history items since the application start. This number will neither change depending on the size of the history queue nor with undo/redo. */ + AZStd::unordered_map m_registeredCommands; /**< A hash table storing the command objects for fast command object access. */ + AZStd::vector m_commandHistory; /**< The command history stack for undo/redo functionality. */ + AZStd::vector m_callbacks; /**< The command manager callbacks. */ + AZStd::vector m_errors; /**< List of errors that happened during command execution. */ + AZStd::vector m_commands; /**< A flat array of registered commands, for easy traversal. */ + size_t m_maxHistoryEntries; /**< The maximum remembered commands in the command history. */ + ptrdiff_t m_historyIndex; /**< The command history iterator. The current position in the undo/redo history. */ + size_t m_totalNumHistoryItems; /**< The number of history items since the application start. This number will neither change depending on the size of the history queue nor with undo/redo. */ int m_commandsInExecution; /**< The number of commands currently in execution. */ /** diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.cpp b/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.cpp index f981a825c4..e84c7a9ff7 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.cpp @@ -27,10 +27,10 @@ namespace MCore Initializer::InitSettings::InitSettings() { - mMemAllocFunction = StandardAllocate; - mMemReallocFunction = StandardRealloc; - mMemFreeFunction = StandardFree; - mTrackMemoryUsage = false; // do not track memory usage on default, for maximum performance and pretty much zero tracking overhead + m_memAllocFunction = StandardAllocate; + m_memReallocFunction = StandardRealloc; + m_memFreeFunction = StandardFree; + m_trackMemoryUsage = false; // do not track memory usage on default, for maximum performance and pretty much zero tracking overhead } // static main init method @@ -47,7 +47,7 @@ namespace MCore { // create the main core object using placement new gMCore = AZ::Environment::CreateVariable(kMCoreInstanceVarName); - gMCore.Set(new(realSettings->mMemAllocFunction(sizeof(MCoreSystem), MCORE_MEMCATEGORY_MCORESYSTEM, 0, MCORE_FILE, MCORE_LINE))MCoreSystem()); + gMCore.Set(new(realSettings->m_memAllocFunction(sizeof(MCoreSystem), MCORE_MEMCATEGORY_MCORESYSTEM, 0, MCORE_FILE, MCORE_LINE))MCoreSystem()); } else { @@ -81,19 +81,19 @@ namespace MCore // constructor MCoreSystem::MCoreSystem() - : mAllocateFunction(StandardAllocate) - , mReallocFunction(StandardRealloc) - , mFreeFunction(StandardFree) + : m_allocateFunction(StandardAllocate) + , m_reallocFunction(StandardRealloc) + , m_freeFunction(StandardFree) { - mLogManager = nullptr; - mIDGenerator = nullptr; - mStringIdPool = nullptr; - mAttributeFactory = nullptr; - mMemoryTracker = nullptr; - mMemTempBuffer = nullptr; - mMemTempBufferSize = 0; - mTrackMemory = true; - mMemoryMutex = new Mutex(); + m_logManager = nullptr; + m_idGenerator = nullptr; + m_stringIdPool = nullptr; + m_attributeFactory = nullptr; + m_memoryTracker = nullptr; + m_memTempBuffer = nullptr; + m_memTempBufferSize = 0; + m_trackMemory = true; + m_memoryMutex = new Mutex(); } @@ -107,45 +107,45 @@ namespace MCore // init the mcore system bool MCoreSystem::Init(const MCore::Initializer::InitSettings& settings) { - if (settings.mMemAllocFunction) + if (settings.m_memAllocFunction) { - mAllocateFunction = settings.mMemAllocFunction; + m_allocateFunction = settings.m_memAllocFunction; } else { - mAllocateFunction = StandardAllocate; + m_allocateFunction = StandardAllocate; } - if (settings.mMemReallocFunction) + if (settings.m_memReallocFunction) { - mReallocFunction = settings.mMemReallocFunction; + m_reallocFunction = settings.m_memReallocFunction; } else { - mReallocFunction = StandardRealloc; + m_reallocFunction = StandardRealloc; } - if (settings.mMemFreeFunction) + if (settings.m_memFreeFunction) { - mFreeFunction = settings.mMemFreeFunction; + m_freeFunction = settings.m_memFreeFunction; } else { - mFreeFunction = StandardFree; + m_freeFunction = StandardFree; } // allocate new objects - mMemoryTracker = new MemoryTracker(); - mTrackMemory = settings.mTrackMemoryUsage; - mLogManager = new LogManager(); - mIDGenerator = new IDGenerator(); - mStringIdPool = new StringIdPool(); - mAttributeFactory = new AttributeFactory(); - mMemTempBufferSize = 256 * 1024; - mMemTempBuffer = Allocate(mMemTempBufferSize, MCORE_MEMCATEGORY_SYSTEM);// 256 kb - MCORE_ASSERT(mMemTempBuffer); - - if (mTrackMemory) + m_memoryTracker = new MemoryTracker(); + m_trackMemory = settings.m_trackMemoryUsage; + m_logManager = new LogManager(); + m_idGenerator = new IDGenerator(); + m_stringIdPool = new StringIdPool(); + m_attributeFactory = new AttributeFactory(); + m_memTempBufferSize = 256 * 1024; + m_memTempBuffer = Allocate(m_memTempBufferSize, MCORE_MEMCATEGORY_SYSTEM);// 256 kb + MCORE_ASSERT(m_memTempBuffer); + + if (m_trackMemory) { - RegisterMemoryCategories(*mMemoryTracker); + RegisterMemoryCategories(*m_memoryTracker); } return true; @@ -156,41 +156,41 @@ namespace MCore void MCoreSystem::Shutdown() { // free any mem temp buffer - MCore::Free(mMemTempBuffer); - mMemTempBuffer = nullptr; - mMemTempBufferSize = 0; + MCore::Free(m_memTempBuffer); + m_memTempBuffer = nullptr; + m_memTempBufferSize = 0; // shutdown the log manager - delete mLogManager; - mLogManager = nullptr; + delete m_logManager; + m_logManager = nullptr; // delete the ID generator - delete mIDGenerator; - mIDGenerator = nullptr; + delete m_idGenerator; + m_idGenerator = nullptr; // Delete the string based ID generator. - delete mStringIdPool; - mStringIdPool = nullptr; + delete m_stringIdPool; + m_stringIdPool = nullptr; // delete the attribute factory - delete mAttributeFactory; - mAttributeFactory = nullptr; + delete m_attributeFactory; + m_attributeFactory = nullptr; // Clear the memory of the file system secure save path. - FileSystem::mSecureSavePath.clear(); + FileSystem::s_secureSavePath.clear(); // log memory leaks - if (mTrackMemory) + if (m_trackMemory) { - mMemoryTracker->LogLeaks(); + m_memoryTracker->LogLeaks(); } // delete the memory tracker - delete mMemoryTracker; - mMemoryTracker = nullptr; + delete m_memoryTracker; + m_memoryTracker = nullptr; - delete mMemoryMutex; - mMemoryMutex = nullptr; + delete m_memoryMutex; + m_memoryMutex = nullptr; } @@ -198,25 +198,25 @@ namespace MCore void MCoreSystem::MemTempBufferAssureSize(size_t numBytes) { // if the buffer is already big enough, we can just return - if (mMemTempBufferSize >= numBytes) + if (m_memTempBufferSize >= numBytes) { return; } // resize the buffer (make it bigger) - mMemTempBuffer = Realloc(mMemTempBuffer, numBytes, MCORE_MEMCATEGORY_SYSTEM); - MCORE_ASSERT(mMemTempBuffer); + m_memTempBuffer = Realloc(m_memTempBuffer, numBytes, MCORE_MEMCATEGORY_SYSTEM); + MCORE_ASSERT(m_memTempBuffer); - mMemTempBufferSize = numBytes; + m_memTempBufferSize = numBytes; } // free the temp buffer void MCoreSystem::MemTempBufferFree() { - MCore::Free(mMemTempBuffer); - mMemTempBuffer = nullptr; - mMemTempBufferSize = 0; + MCore::Free(m_memTempBuffer); + m_memTempBuffer = nullptr; + m_memTempBufferSize = 0; } diff --git a/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.h b/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.h index 11fdc79988..496198c430 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.h +++ b/Gems/EMotionFX/Code/MCore/Source/MCoreSystem.h @@ -38,10 +38,10 @@ namespace MCore public: struct MCORE_API InitSettings { - AllocateCallback mMemAllocFunction; /**< The memory allocation function, defaults to nullptr, which means the standard malloc function will be used. */ - ReallocCallback mMemReallocFunction; /**< The memory reallocation function, defaults to nullptr, which means the standard realloc function will be used. */ - FreeCallback mMemFreeFunction; /**< The memory free function, defaults to nullptr, which means the standard free function will be used. */ - bool mTrackMemoryUsage; /**< Enable this to track memory usage statistics. This has a bit of an impact on memory allocation and release speed and memory usage though. You should really only use this in debug mode. On default it is disabled. */ + AllocateCallback m_memAllocFunction; /**< The memory allocation function, defaults to nullptr, which means the standard malloc function will be used. */ + ReallocCallback m_memReallocFunction; /**< The memory reallocation function, defaults to nullptr, which means the standard realloc function will be used. */ + FreeCallback m_memFreeFunction; /**< The memory free function, defaults to nullptr, which means the standard free function will be used. */ + bool m_trackMemoryUsage; /**< Enable this to track memory usage statistics. This has a bit of an impact on memory allocation and release speed and memory usage though. You should really only use this in debug mode. On default it is disabled. */ InitSettings(); }; @@ -80,59 +80,59 @@ namespace MCore * Get the log manager. * @result A reference to the log manager. */ - MCORE_INLINE LogManager& GetLogManager() { return *mLogManager; } + MCORE_INLINE LogManager& GetLogManager() { return *m_logManager; } /** * Get the ID generator. * @result A reference to the ID generator. */ - MCORE_INLINE IDGenerator& GetIDGenerator() { return *mIDGenerator; } + MCORE_INLINE IDGenerator& GetIDGenerator() { return *m_idGenerator; } /** * Get the string based ID generator. * @result A reference to the string based ID generator. */ - MCORE_INLINE StringIdPool& GetStringIdPool() { return *mStringIdPool; } + MCORE_INLINE StringIdPool& GetStringIdPool() { return *m_stringIdPool; } /** * Get the attribute factory. * @result A reference to the attribute factory, which is used to create attributes of a certain type. */ - MCORE_INLINE AttributeFactory& GetAttributeFactory() { return *mAttributeFactory; } + MCORE_INLINE AttributeFactory& GetAttributeFactory() { return *m_attributeFactory; } /** * Get the memory tracker. * @result A reference to the memory tracker, which can be used to track memory allocations and usage. */ - MCORE_INLINE MemoryTracker& GetMemoryTracker() { return *mMemoryTracker; } - MCORE_INLINE bool GetIsTrackingMemory() const { return mTrackMemory; } + MCORE_INLINE MemoryTracker& GetMemoryTracker() { return *m_memoryTracker; } + MCORE_INLINE bool GetIsTrackingMemory() const { return m_trackMemory; } - MCORE_INLINE void* GetMemTempBuffer() { return mMemTempBuffer; } - MCORE_INLINE size_t GetMemTempBufferSize() const { return mMemTempBufferSize; } + MCORE_INLINE void* GetMemTempBuffer() { return m_memTempBuffer; } + MCORE_INLINE size_t GetMemTempBufferSize() const { return m_memTempBufferSize; } void MemTempBufferAssureSize(size_t numBytes); void MemTempBufferFree(); void RegisterMemoryCategories(MemoryTracker& memTracker); - MCORE_INLINE Mutex& GetMemoryMutex() { return *mMemoryMutex; } + MCORE_INLINE Mutex& GetMemoryMutex() { return *m_memoryMutex; } - MCORE_INLINE AllocateCallback GetAllocateFunction() { return mAllocateFunction; } - MCORE_INLINE ReallocCallback GetReallocFunction() { return mReallocFunction; } - MCORE_INLINE FreeCallback GetFreeFunction() { return mFreeFunction; } + MCORE_INLINE AllocateCallback GetAllocateFunction() { return m_allocateFunction; } + MCORE_INLINE ReallocCallback GetReallocFunction() { return m_reallocFunction; } + MCORE_INLINE FreeCallback GetFreeFunction() { return m_freeFunction; } private: - LogManager* mLogManager; /**< The log manager. */ - IDGenerator* mIDGenerator; /**< The ID generator. */ - StringIdPool* mStringIdPool; /**< The string based ID generator. */ - AttributeFactory* mAttributeFactory; /**< The attribute factory. */ - MemoryTracker* mMemoryTracker; /**< The memory tracker. */ - Mutex* mMemoryMutex; - AllocateCallback mAllocateFunction; - ReallocCallback mReallocFunction; - FreeCallback mFreeFunction; - void* mMemTempBuffer; /**< A buffer with temp memory, used by the MCore::AlignedRealloc, to assure data integrity after reallocating memory. */ - size_t mMemTempBufferSize; /**< The size in bytes, of the MemTempBuffer. */ - bool mTrackMemory; /**< Check if we want to track memory or not. */ + LogManager* m_logManager; /**< The log manager. */ + IDGenerator* m_idGenerator; /**< The ID generator. */ + StringIdPool* m_stringIdPool; /**< The string based ID generator. */ + AttributeFactory* m_attributeFactory; /**< The attribute factory. */ + MemoryTracker* m_memoryTracker; /**< The memory tracker. */ + Mutex* m_memoryMutex; + AllocateCallback m_allocateFunction; + ReallocCallback m_reallocFunction; + FreeCallback m_freeFunction; + void* m_memTempBuffer; /**< A buffer with temp memory, used by the MCore::AlignedRealloc, to assure data integrity after reallocating memory. */ + size_t m_memTempBufferSize; /**< The size in bytes, of the MemTempBuffer. */ + bool m_trackMemory; /**< Check if we want to track memory or not. */ /** * The constructor. diff --git a/Gems/EMotionFX/Code/MCore/Source/Matrix4.cpp b/Gems/EMotionFX/Code/MCore/Source/Matrix4.cpp index 229f67ec0c..f454df04ab 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Matrix4.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Matrix4.cpp @@ -86,9 +86,9 @@ namespace MCore Matrix r; #if (AZ_TRAIT_USE_PLATFORM_SIMD_SSE && defined(MCORE_MATRIX_ROWMAJOR)) - const float* m = right.m16; - const float* n = m16; - float* t = r.m16; + const float* m = right.m_m16; + const float* n = m_m16; + float* t = r.m_m16; __m128 x0; __m128 x1; @@ -211,9 +211,9 @@ namespace MCore Matrix& Matrix::operator *= (const Matrix& right) { #if (AZ_TRAIT_USE_PLATFORM_SIMD_SSE && defined(MCORE_MATRIX_ROWMAJOR)) - const float* m = right.m16; - const float* n = m16; - float* t = this->m16; + const float* m = right.m_m16; + const float* n = m_m16; + float* t = this->m_m16; __m128 x0; __m128 x1; @@ -687,9 +687,9 @@ namespace MCore void Matrix::MultMatrix(const Matrix& right) { #if (AZ_TRAIT_USE_PLATFORM_SIMD_SSE && defined(MCORE_MATRIX_ROWMAJOR)) - const float* m = right.m16; - const float* n = m16; - float* t = this->m16; + const float* m = right.m_m16; + const float* n = m_m16; + float* t = this->m_m16; __m128 x0; __m128 x1; @@ -1246,9 +1246,9 @@ namespace MCore void Matrix::MultMatrix4x3(const Matrix& right) { #if (AZ_TRAIT_USE_PLATFORM_SIMD_SSE && defined(MCORE_MATRIX_ROWMAJOR)) - const float* m = right.m16; - const float* n = m16; - float* t = this->m16; + const float* m = right.m_m16; + const float* n = m_m16; + float* t = this->m_m16; __m128 x0; __m128 x1; @@ -1336,9 +1336,9 @@ namespace MCore void Matrix::MultMatrix(const Matrix& left, const Matrix& right) { #if (AZ_TRAIT_USE_PLATFORM_SIMD_SSE && defined(MCORE_MATRIX_ROWMAJOR)) - const float* m = right.m16; - const float* n = left.m16; - float* t = this->m16; + const float* m = right.m_m16; + const float* n = left.m_m16; + float* t = this->m_m16; __m128 x0; __m128 x1; @@ -1423,9 +1423,9 @@ namespace MCore void Matrix::MultMatrix4x3(const Matrix& left, const Matrix& right) { #if (AZ_TRAIT_USE_PLATFORM_SIMD_SSE && defined(MCORE_MATRIX_ROWMAJOR)) - const float* m = right.m16; - const float* n = left.m16; - float* t = this->m16; + const float* m = right.m_m16; + const float* n = left.m_m16; + float* t = this->m_m16; __m128 x0; __m128 x1; @@ -2052,10 +2052,10 @@ namespace MCore void Matrix::Log() const { MCore::LogDetailedInfo(""); - MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m16[0], m16[1], m16[2], m16[3]); - MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m16[4], m16[5], m16[6], m16[7]); - MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m16[8], m16[9], m16[10], m16[11]); - MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m16[12], m16[13], m16[14], m16[15]); + MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m_m16[0], m_m16[1], m_m16[2], m_m16[3]); + MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m_m16[4], m_m16[5], m_m16[6], m_m16[7]); + MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m_m16[8], m_m16[9], m_m16[10], m_m16[11]); + MCore::LogDetailedInfo("(%.8f, %.8f, %.8f, %.8f)", m_m16[12], m_m16[13], m_m16[14], m_m16[15]); MCore::LogDetailedInfo(""); } diff --git a/Gems/EMotionFX/Code/MCore/Source/Matrix4.h b/Gems/EMotionFX/Code/MCore/Source/Matrix4.h index 4be819bcc1..c136aa824e 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Matrix4.h +++ b/Gems/EMotionFX/Code/MCore/Source/Matrix4.h @@ -84,7 +84,7 @@ namespace MCore * The number of elements stored at the float pointer location that is used as parameter must be at least 16 floats in size. * @param elementData A pointer to the matrix float data, which must be 16 floats in size, or more, although only the first 16 floats are used. */ - MCORE_INLINE explicit Matrix(const float* elementData) { MCore::MemCopy(m16, elementData, sizeof(float) * 16); } + MCORE_INLINE explicit Matrix(const float* elementData) { MCore::MemCopy(m_m16, elementData, sizeof(float) * 16); } /** * Copy constructor. @@ -779,7 +779,7 @@ namespace MCore AZ::Matrix4x4 ToAzMatrix() const { #ifdef MCORE_MATRIX_ROWMAJOR - return AZ::Matrix4x4::CreateFromRowMajorFloat16(m16); + return AZ::Matrix4x4::CreateFromRowMajorFloat16(m_m16); #else return AZ::Matrix4x4::CreateFromColumnMajorFloat16(m16); #endif @@ -907,7 +907,7 @@ namespace MCore // attributes union { - float m16[16]; // 16 floats as 1D array + float m_m16[16]; // 16 floats as 1D array float m44[4][4]; // as 2D array }; } MCORE_ALIGN_POST(16); diff --git a/Gems/EMotionFX/Code/MCore/Source/Matrix4.inl b/Gems/EMotionFX/Code/MCore/Source/Matrix4.inl index 67f550c2d5..99900abcee 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Matrix4.inl +++ b/Gems/EMotionFX/Code/MCore/Source/Matrix4.inl @@ -8,13 +8,13 @@ MCORE_INLINE Matrix::Matrix(const Matrix& m) { - MCore::MemCopy(m16, m.m16, sizeof(Matrix)); + MCore::MemCopy(m_m16, m.m_m16, sizeof(Matrix)); } MCORE_INLINE void Matrix::operator = (const Matrix& right) { - MCore::MemCopy(m16, right.m16, sizeof(Matrix)); + MCore::MemCopy(m_m16, right.m_m16, sizeof(Matrix)); } @@ -301,7 +301,7 @@ MCORE_INLINE Matrix& Matrix::operator *= (float value) { for (uint32 i = 0; i < 16; ++i) { - m16[i] *= value; + m_m16[i] *= value; } return *this; diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp b/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp index 811dcbde42..f90336ea5d 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryFile.cpp @@ -24,25 +24,25 @@ namespace MCore // try to open the memory location bool MemoryFile::Open(uint8* memoryStart, size_t length) { - mMemoryStart = memoryStart; - mCurrentPos = memoryStart; - mLength = length; - mUsedLength = length; - mPreAllocSize = 1024; // pre-allocate 1 extra KB + m_memoryStart = memoryStart; + m_currentPos = memoryStart; + m_length = length; + m_usedLength = length; + m_preAllocSize = 1024; // pre-allocate 1 extra KB // if we need to create a new memory block if (memoryStart == nullptr) { - mAllocate = true; + m_allocate = true; if (length > 0) { - mMemoryStart = (uint8*)MCore::Allocate(length, MCORE_MEMCATEGORY_MEMORYFILE); - mCurrentPos = mMemoryStart; + m_memoryStart = (uint8*)MCore::Allocate(length, MCORE_MEMCATEGORY_MEMORYFILE); + m_currentPos = m_memoryStart; } } else { - mAllocate = false; + m_allocate = false; } return true; @@ -53,15 +53,15 @@ namespace MCore void MemoryFile::Close() { // get rid of the allocated memory - if (mAllocate) + if (m_allocate) { - MCore::Free(mMemoryStart); + MCore::Free(m_memoryStart); } - mMemoryStart = nullptr; - mCurrentPos = nullptr; - mLength = 0; - mUsedLength = 0; + m_memoryStart = nullptr; + m_currentPos = nullptr; + m_length = 0; + m_usedLength = 0; } @@ -73,7 +73,7 @@ namespace MCore bool MemoryFile::GetIsOpen() const { - return (mMemoryStart != nullptr); + return (m_memoryStart != nullptr); } @@ -87,8 +87,8 @@ namespace MCore // returns the next byte in the file uint8 MemoryFile::GetNextByte() { - uint8 value = *mCurrentPos; - mCurrentPos++; + uint8 value = *m_currentPos; + m_currentPos++; return value; } @@ -96,7 +96,7 @@ namespace MCore // returns the position (offset) in the file in bytes size_t MemoryFile::GetPos() const { - return (size_t)(mCurrentPos - mMemoryStart); + return (size_t)(m_currentPos - m_memoryStart); } @@ -111,13 +111,13 @@ namespace MCore // seek a given number of bytes ahead from it's current position bool MemoryFile::Forward(size_t numBytes) { - uint8* newPos = mCurrentPos + numBytes; - if (newPos > (mMemoryStart + mLength)) + uint8* newPos = m_currentPos + numBytes; + if (newPos > (m_memoryStart + m_length)) { return false; } - mCurrentPos = newPos; + m_currentPos = newPos; return true; } @@ -125,12 +125,12 @@ namespace MCore // seek to an absolute position in the file (offset in bytes) bool MemoryFile::Seek(size_t offset) { - if (offset > mLength) + if (offset > m_length) { return false; } - mCurrentPos = mMemoryStart + offset; + m_currentPos = m_memoryStart + offset; return true; } @@ -139,25 +139,25 @@ namespace MCore size_t MemoryFile::Write(const void* data, size_t length) { // if it won't fit in our allocated buffer, we have to enlarge it - if ((mCurrentPos + length > mMemoryStart + mLength) && mAllocate) + if ((m_currentPos + length > m_memoryStart + m_length) && m_allocate) { - size_t offset = mCurrentPos - mMemoryStart; - size_t numBytesExtra = mCurrentPos + length - mMemoryStart; - numBytesExtra += mPreAllocSize; - mMemoryStart = (uint8*)MCore::Realloc((uint8*)mMemoryStart, mLength + numBytesExtra, MCORE_MEMCATEGORY_MEMORYFILE); - mLength += numBytesExtra; - mCurrentPos = mMemoryStart + offset; + size_t offset = m_currentPos - m_memoryStart; + size_t numBytesExtra = m_currentPos + length - m_memoryStart; + numBytesExtra += m_preAllocSize; + m_memoryStart = (uint8*)MCore::Realloc((uint8*)m_memoryStart, m_length + numBytesExtra, MCORE_MEMCATEGORY_MEMORYFILE); + m_length += numBytesExtra; + m_currentPos = m_memoryStart + offset; } // memcopy over the data - MCORE_ASSERT((mCurrentPos + length) <= (mMemoryStart + mLength)); // make sure we don't write past the end of our buffer - MCore::MemCopy(mCurrentPos, data, length); + MCORE_ASSERT((m_currentPos + length) <= (m_memoryStart + m_length)); // make sure we don't write past the end of our buffer + MCore::MemCopy(m_currentPos, data, length); Forward(length); // only overwrite the used length in case we reached the boundary (don't do it in case we modify some data in the middle etc.) - if (mUsedLength < GetPos()) + if (m_usedLength < GetPos()) { - mUsedLength = GetPos(); + m_usedLength = GetPos(); } return length; @@ -167,17 +167,16 @@ namespace MCore // read data from the file size_t MemoryFile::Read(void* data, size_t length) { - // MCORE_ASSERT(mCurrentPos + length <= (uint8*)mMemoryStart + mLength); // make sure we don't read past the end of the memory block - if (mCurrentPos + length > (uint8*)mMemoryStart + mLength) + if (m_currentPos + length > (uint8*)m_memoryStart + m_length) { - const size_t numRead = length - ((mCurrentPos + length) - ((uint8*)mMemoryStart + mLength)); - MCore::MemCopy(data, mCurrentPos, numRead); - Forward(static_cast(numRead)); + const size_t numRead = length - ((m_currentPos + length) - ((uint8*)m_memoryStart + m_length)); + MCore::MemCopy(data, m_currentPos, numRead); + Forward(numRead); MCore::LogWarning("MCore::MemoryFile::Read() - We can only read %d bytes of the %d bytes requested, as we are reading past the end of the memory file!", numRead, length); - return static_cast(numRead); + return numRead; } - MCore::MemCopy(data, mCurrentPos, length); + MCore::MemCopy(data, m_currentPos, length); Forward(length); return length; } @@ -186,28 +185,28 @@ namespace MCore // returns the filesize in bytes size_t MemoryFile::GetFileSize() const { - return static_cast(mUsedLength); // TODO: convert to size_t later + return m_usedLength; } // get the memory start address uint8* MemoryFile::GetMemoryStart() const { - return mMemoryStart; + return m_memoryStart; } // get the pre-alloc size size_t MemoryFile::GetPreAllocSize() const { - return mPreAllocSize; + return m_preAllocSize; } // set the pre-alloc size void MemoryFile::SetPreAllocSize(size_t newSizeInBytes) { - mPreAllocSize = newSizeInBytes; + m_preAllocSize = newSizeInBytes; } diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryFile.h b/Gems/EMotionFX/Code/MCore/Source/MemoryFile.h index eba9580043..ea2855fd08 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryFile.h +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryFile.h @@ -39,12 +39,12 @@ namespace MCore */ MemoryFile() : File() - , mMemoryStart(nullptr) - , mCurrentPos(nullptr) - , mLength(0) - , mUsedLength(0) - , mPreAllocSize(1024) - , mAllocate(false) {} + , m_memoryStart(nullptr) + , m_currentPos(nullptr) + , m_length(0) + , m_usedLength(0) + , m_preAllocSize(1024) + , m_allocate(false) {} /** * Destructor. Automatically closes the file. @@ -187,11 +187,11 @@ namespace MCore bool SaveToDiskFile(const char* fileName); private: - uint8* mMemoryStart; /**< The location of the file */ - uint8* mCurrentPos; /**< The current location */ - size_t mLength; /**< The total length of the file. */ - size_t mUsedLength; /**< The actual used length of the memory file. */ - size_t mPreAllocSize; /**< The pre-allocation size (in bytes) when we have to reallocate memory. This prevents many allocations. The default=1024, which is 1kb.*/ - bool mAllocate; /**< Can we reallocate or not? */ + uint8* m_memoryStart; /**< The location of the file */ + uint8* m_currentPos; /**< The current location */ + size_t m_length; /**< The total length of the file. */ + size_t m_usedLength; /**< The actual used length of the memory file. */ + size_t m_preAllocSize; /**< The pre-allocation size (in bytes) when we have to reallocate memory. This prevents many allocations. The default=1024, which is 1kb.*/ + bool m_allocate; /**< Can we reallocate or not? */ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryManager.h b/Gems/EMotionFX/Code/MCore/Source/MemoryManager.h index 84db9ed20c..7129dffe24 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryManager.h @@ -133,7 +133,7 @@ public: * @param numBytes The number of bytes to fill. * @result The address as specified in the first parameter. */ - MCORE_INLINE void* MemSet(void* address, const uint32 value, size_t numBytes) + MCORE_INLINE void* MemSet(void* address, const int value, size_t numBytes) { return memset(address, value, numBytes); } diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryObject.cpp b/Gems/EMotionFX/Code/MCore/Source/MemoryObject.cpp index 017ef3f2e1..9afad03a39 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryObject.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryObject.cpp @@ -25,37 +25,37 @@ namespace MCore // constructor MemoryObject::MemoryObject() { - mReferenceCount.SetValue(1); + m_referenceCount.SetValue(1); } // destructor MemoryObject::~MemoryObject() { - MCORE_ASSERT(mReferenceCount.GetValue() == 0); + MCORE_ASSERT(m_referenceCount.GetValue() == 0); } // increase the reference count void MemoryObject::IncreaseReferenceCount() { - mReferenceCount.Increment(); + m_referenceCount.Increment(); } // decrease the reference count void MemoryObject::DecreaseReferenceCount() { - MCORE_ASSERT(mReferenceCount.GetValue() > 0); - mReferenceCount.Decrement(); + MCORE_ASSERT(m_referenceCount.GetValue() > 0); + m_referenceCount.Decrement(); } // destroy the object void MemoryObject::Destroy() { - MCORE_ASSERT(mReferenceCount.GetValue() > 0); - if (mReferenceCount.Decrement() == 1) + MCORE_ASSERT(m_referenceCount.GetValue() > 0); + if (m_referenceCount.Decrement() == 1) { Delete(); } @@ -65,7 +65,7 @@ namespace MCore // get the reference count uint32 MemoryObject::GetReferenceCount() const { - return mReferenceCount.GetValue(); + return m_referenceCount.GetValue(); } diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryObject.h b/Gems/EMotionFX/Code/MCore/Source/MemoryObject.h index 9dfa48284f..cf872da865 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryObject.h +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryObject.h @@ -61,7 +61,7 @@ namespace MCore virtual void Delete(); private: - AtomicUInt32 mReferenceCount; + AtomicUInt32 m_referenceCount; }; diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.cpp b/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.cpp index 2cecb43a69..d2f5b9efd8 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.cpp @@ -16,33 +16,33 @@ namespace MCore // global stats constructor MemoryTracker::GlobalStats::GlobalStats() { - mCurrentNumBytes = 0; - mCurrentNumAllocs = 0; - mTotalNumAllocs = 0; - mTotalNumReallocs = 0; - mTotalNumFrees = 0; + m_currentNumBytes = 0; + m_currentNumAllocs = 0; + m_totalNumAllocs = 0; + m_totalNumReallocs = 0; + m_totalNumFrees = 0; } // category stats constructor MemoryTracker::CategoryStats::CategoryStats() { - mCurrentNumBytes = 0; - mCurrentNumAllocs = 0; - mTotalNumAllocs = 0; - mTotalNumReallocs = 0; - mTotalNumFrees = 0; + m_currentNumBytes = 0; + m_currentNumAllocs = 0; + m_totalNumAllocs = 0; + m_totalNumReallocs = 0; + m_totalNumFrees = 0; } // group statistics MemoryTracker::GroupStats::GroupStats() { - mCurrentNumBytes = 0; - mCurrentNumAllocs = 0; - mTotalNumAllocs = 0; - mTotalNumReallocs = 0; - mTotalNumFrees = 0; + m_currentNumBytes = 0; + m_currentNumAllocs = 0; + m_totalNumAllocs = 0; + m_totalNumReallocs = 0; + m_totalNumFrees = 0; } @@ -63,7 +63,7 @@ namespace MCore void MemoryTracker::RegisterAlloc(void* memAddress, size_t numBytes, uint32 categoryID) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); RegisterAllocNoLock(memAddress, numBytes, categoryID); } @@ -73,40 +73,40 @@ namespace MCore { // insert the new allocation Allocation newAlloc; - newAlloc.mMemAddress = memAddress; - newAlloc.mNumBytes = numBytes; - newAlloc.mCategoryID = categoryID; - mAllocs.insert(std::make_pair(memAddress, newAlloc)); + newAlloc.m_memAddress = memAddress; + newAlloc.m_numBytes = numBytes; + newAlloc.m_categoryId = categoryID; + m_allocs.insert(std::make_pair(memAddress, newAlloc)); // update global stats - mGlobalStats.mTotalNumAllocs++; - mGlobalStats.mCurrentNumAllocs++; - mGlobalStats.mCurrentNumBytes += numBytes; + m_globalStats.m_totalNumAllocs++; + m_globalStats.m_currentNumAllocs++; + m_globalStats.m_currentNumBytes += numBytes; // update the category stats - auto categoryItem = mCategories.find(categoryID); - if (categoryItem != mCategories.end()) + auto categoryItem = m_categories.find(categoryID); + if (categoryItem != m_categories.end()) { CategoryStats& catStats = categoryItem->second; - catStats.mTotalNumAllocs++; - catStats.mCurrentNumAllocs++; - catStats.mCurrentNumBytes += numBytes; + catStats.m_totalNumAllocs++; + catStats.m_currentNumAllocs++; + catStats.m_currentNumBytes += numBytes; } else { // auto register the new category CategoryStats catStats; - catStats.mTotalNumAllocs++; - catStats.mCurrentNumAllocs++; - catStats.mCurrentNumBytes += numBytes; - mCategories.insert(std::make_pair(categoryID, catStats)); + catStats.m_totalNumAllocs++; + catStats.m_currentNumAllocs++; + catStats.m_currentNumBytes += numBytes; + m_categories.insert(std::make_pair(categoryID, catStats)); } } void MemoryTracker::RegisterRealloc(void* oldAddress, void* newAddress, size_t numBytes, uint32 categoryID) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); RegisterReallocNoLock(oldAddress, newAddress, numBytes, categoryID); } @@ -122,52 +122,52 @@ namespace MCore } // try to locate the allocation - auto item = mAllocs.find(oldAddress); + auto item = m_allocs.find(oldAddress); // if we found the item - if (item != mAllocs.end()) + if (item != m_allocs.end()) { const Allocation& allocation = item->second; - const size_t oldNumBytes = allocation.mNumBytes; + const size_t oldNumBytes = allocation.m_numBytes; // update the global stats - mGlobalStats.mCurrentNumBytes += (numBytes - oldNumBytes); - mGlobalStats.mTotalNumReallocs++; + m_globalStats.m_currentNumBytes += (numBytes - oldNumBytes); + m_globalStats.m_totalNumReallocs++; // the category got updated, unregister it from the old category - const bool categoryChanged = (categoryID != allocation.mCategoryID); + const bool categoryChanged = (categoryID != allocation.m_categoryId); if (categoryChanged) { - auto oldCategoryItem = mCategories.find(allocation.mCategoryID); - MCORE_ASSERT(oldCategoryItem != mCategories.end()); - oldCategoryItem->second.mCurrentNumBytes -= oldNumBytes; - oldCategoryItem->second.mCurrentNumAllocs--; + auto oldCategoryItem = m_categories.find(allocation.m_categoryId); + MCORE_ASSERT(oldCategoryItem != m_categories.end()); + oldCategoryItem->second.m_currentNumBytes -= oldNumBytes; + oldCategoryItem->second.m_currentNumAllocs--; } // remove the allocation - mAllocs.erase(item); + m_allocs.erase(item); // re-insert it using the new address (new key) Allocation newAlloc; - newAlloc.mCategoryID = categoryID; - newAlloc.mMemAddress = newAddress; - newAlloc.mNumBytes = numBytes; - mAllocs.insert(std::make_pair(newAddress, newAlloc)); + newAlloc.m_categoryId = categoryID; + newAlloc.m_memAddress = newAddress; + newAlloc.m_numBytes = numBytes; + m_allocs.insert(std::make_pair(newAddress, newAlloc)); // update the category stats - auto categoryItem = mCategories.find(categoryID); - MCORE_ASSERT(categoryItem != mCategories.end()); + auto categoryItem = m_categories.find(categoryID); + MCORE_ASSERT(categoryItem != m_categories.end()); CategoryStats& catStats = categoryItem->second; - catStats.mTotalNumReallocs++; + catStats.m_totalNumReallocs++; if (categoryChanged == false) { - catStats.mCurrentNumBytes += (numBytes - oldNumBytes); + catStats.m_currentNumBytes += (numBytes - oldNumBytes); } else { - catStats.mCurrentNumBytes += numBytes; - catStats.mCurrentNumAllocs++; + catStats.m_currentNumBytes += numBytes; + catStats.m_currentNumAllocs++; } } else // not found, we must just register this as a regular allocation @@ -179,7 +179,7 @@ namespace MCore void MemoryTracker::RegisterFree(void* memAddress) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); RegisterFreeNoLock(memAddress); } @@ -193,27 +193,27 @@ namespace MCore } // find the allocation using this address - auto item = mAllocs.find(memAddress); - if (item != mAllocs.end()) + auto item = m_allocs.find(memAddress); + if (item != m_allocs.end()) { Allocation& allocation = item->second; // update global stats - mGlobalStats.mCurrentNumBytes -= allocation.mNumBytes; - mGlobalStats.mTotalNumFrees++; - mGlobalStats.mCurrentNumAllocs--; + m_globalStats.m_currentNumBytes -= allocation.m_numBytes; + m_globalStats.m_totalNumFrees++; + m_globalStats.m_currentNumAllocs--; // update the category stats - auto categoryItem = mCategories.find(allocation.mCategoryID); - MCORE_ASSERT(categoryItem != mCategories.end()); // this should be impossible + auto categoryItem = m_categories.find(allocation.m_categoryId); + MCORE_ASSERT(categoryItem != m_categories.end()); // this should be impossible CategoryStats& catStats = categoryItem->second; - catStats.mCurrentNumAllocs--; - catStats.mTotalNumFrees++; - catStats.mCurrentNumBytes -= allocation.mNumBytes; + catStats.m_currentNumAllocs--; + catStats.m_totalNumFrees++; + catStats.m_currentNumBytes -= allocation.m_numBytes; // remove the allocation - mAllocs.erase(item); + m_allocs.erase(item); } else { @@ -227,25 +227,25 @@ namespace MCore // clear all stored allocations void MemoryTracker::Clear() { - LockGuard lock(mMutex); - mAllocs.clear(); - mCategories.clear(); - mGroups.clear(); - mGlobalStats = GlobalStats(); + LockGuard lock(m_mutex); + m_allocs.clear(); + m_categories.clear(); + m_groups.clear(); + m_globalStats = GlobalStats(); } // get the global stats const MemoryTracker::GlobalStats& MemoryTracker::GetGlobalStats() const { - return mGlobalStats; + return m_globalStats; } // get category statistics bool MemoryTracker::GetCategoryStatistics(uint32 categoryID, CategoryStats* outStats) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); return GetCategoryStatisticsNoLock(categoryID, outStats); } @@ -253,8 +253,8 @@ namespace MCore // get category statistics, without lock bool MemoryTracker::GetCategoryStatisticsNoLock(uint32 categoryID, CategoryStats* outStats) { - auto item = mCategories.find(categoryID); - if (item != mCategories.end()) + auto item = m_categories.find(categoryID); + if (item != m_categories.end()) { *outStats = item->second; return true; @@ -267,20 +267,20 @@ namespace MCore // register the name to a given category void MemoryTracker::RegisterCategory(uint32 categoryID, const char* name) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // try to see if the category exists already - auto item = mCategories.find(categoryID); - if (item == mCategories.end()) + auto item = m_categories.find(categoryID); + if (item == m_categories.end()) { // register the new category CategoryStats catStats; - catStats.mName = name; - mCategories.insert(std::make_pair(categoryID, catStats)); + catStats.m_name = name; + m_categories.insert(std::make_pair(categoryID, catStats)); } else { - item->second.mName = name; + item->second.m_name = name; } } @@ -288,30 +288,30 @@ namespace MCore // register a given group void MemoryTracker::RegisterGroup(uint32 groupID, const char* name, const std::vector& categories) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); - auto item = mGroups.find(groupID); - if (item == mGroups.end()) + auto item = m_groups.find(groupID); + if (item == m_groups.end()) { // create a new group Group newGroup; - newGroup.mName = name; + newGroup.m_name = name; for (auto& cat : categories) { - newGroup.mCategories.insert(cat); + newGroup.m_categories.insert(cat); } - mGroups.insert(std::make_pair(groupID, newGroup)); + m_groups.insert(std::make_pair(groupID, newGroup)); } else { // update the existing group by inserting categories that don't exist yet inside the group Group& group = item->second; - group.mName = name; + group.m_name = name; for (auto& cat : categories) { - if (group.mCategories.find(cat) == group.mCategories.end()) + if (group.m_categories.find(cat) == group.m_categories.end()) { - group.mCategories.insert(cat); + group.m_categories.insert(cat); } } } @@ -321,7 +321,7 @@ namespace MCore // update the statistics for all groups void MemoryTracker::UpdateGroupStatistics() { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); UpdateGroupStatisticsNoLock(); } @@ -330,24 +330,24 @@ namespace MCore void MemoryTracker::UpdateGroupStatisticsNoLock() { // for all registered groups - for (auto& item : mGroups) + for (auto& item : m_groups) { Group& group = item.second; // reset the totals - group.mStats = GroupStats(); + group.m_stats = GroupStats(); // for all categories - for (auto categoryID : group.mCategories) + for (auto categoryID : group.m_categories) { CategoryStats categoryStats; GetCategoryStatisticsNoLock(categoryID, &categoryStats); - group.mStats.mCurrentNumAllocs += categoryStats.mCurrentNumAllocs; - group.mStats.mCurrentNumBytes += categoryStats.mCurrentNumBytes; - group.mStats.mTotalNumAllocs += categoryStats.mTotalNumAllocs; - group.mStats.mTotalNumFrees += categoryStats.mTotalNumFrees; - group.mStats.mTotalNumReallocs += categoryStats.mTotalNumReallocs; + group.m_stats.m_currentNumAllocs += categoryStats.m_currentNumAllocs; + group.m_stats.m_currentNumBytes += categoryStats.m_currentNumBytes; + group.m_stats.m_totalNumAllocs += categoryStats.m_totalNumAllocs; + group.m_stats.m_totalNumFrees += categoryStats.m_totalNumFrees; + group.m_stats.m_totalNumReallocs += categoryStats.m_totalNumReallocs; } } } @@ -355,15 +355,15 @@ namespace MCore // get group statistics bool MemoryTracker::GetGroupStatistics(uint32 groupID, GroupStats* outGroupStats) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); - auto item = mGroups.find(groupID); - if (item == mGroups.end()) + auto item = m_groups.find(groupID); + if (item == m_groups.end()) { return false; } - const GroupStats& groupStats = item->second.mStats; + const GroupStats& groupStats = item->second.m_stats; *outGroupStats = groupStats; return true; @@ -373,67 +373,67 @@ namespace MCore // get the allocations const std::unordered_map& MemoryTracker::GetAllocations() const { - return mAllocs; + return m_allocs; } // get the groups const std::unordered_map& MemoryTracker::GetGroups() const { - return mGroups; + return m_groups; } // get the categories const std::map& MemoryTracker::GetCategories() const { - return mCategories; + return m_categories; } // multithread lock void MemoryTracker::Lock() { - mMutex.Lock(); + m_mutex.Lock(); } // multithread unlock void MemoryTracker::Unlock() { - mMutex.Unlock(); + m_mutex.Unlock(); } // log the stats void MemoryTracker::LogStatistics(bool currentlyAllocatedOnly) { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // update the group statistics (thread safe also) UpdateGroupStatisticsNoLock(); Print("--[ Memory Global Statistics ]-----------------------------------------------------------------------"); - Print(FormatStdString("Current Num Bytes Used = %d bytes (%d k or %.2f mb)", mGlobalStats.mCurrentNumBytes, mGlobalStats.mCurrentNumBytes / 1000, mGlobalStats.mCurrentNumBytes / 1000000.0f).c_str()); - Print(FormatStdString("Current Num Allocs = %d", mGlobalStats.mCurrentNumAllocs).c_str()); - Print(FormatStdString("Total Num Allocs = %d", mGlobalStats.mTotalNumAllocs).c_str()); - Print(FormatStdString("Total Num Reallocs = %d", mGlobalStats.mTotalNumReallocs).c_str()); - Print(FormatStdString("Total Num Frees = %d", mGlobalStats.mTotalNumFrees).c_str()); + Print(FormatStdString("Current Num Bytes Used = %d bytes (%d k or %.2f mb)", m_globalStats.m_currentNumBytes, m_globalStats.m_currentNumBytes / 1000, m_globalStats.m_currentNumBytes / 1000000.0f).c_str()); + Print(FormatStdString("Current Num Allocs = %d", m_globalStats.m_currentNumAllocs).c_str()); + Print(FormatStdString("Total Num Allocs = %d", m_globalStats.m_totalNumAllocs).c_str()); + Print(FormatStdString("Total Num Reallocs = %d", m_globalStats.m_totalNumReallocs).c_str()); + Print(FormatStdString("Total Num Frees = %d", m_globalStats.m_totalNumFrees).c_str()); - if (mCategories.empty() == false) + if (m_categories.empty() == false) { Print(""); Print("--[ Memory Category Statistics ]---------------------------------------------------------------------"); - for (auto& item : mCategories) + for (auto& item : m_categories) { const uint32 categoryID = item.first; const CategoryStats& stats = item.second; - if (stats.mTotalNumAllocs > 0) + if (stats.m_totalNumAllocs > 0) { bool display = true; if (currentlyAllocatedOnly) { - if (stats.mCurrentNumAllocs == 0) + if (stats.m_currentNumAllocs == 0) { display = false; } @@ -441,26 +441,26 @@ namespace MCore if (display) { - Print(FormatStdString("[Cat %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", categoryID, stats.mCurrentNumBytes, stats.mCurrentNumBytes / 1000, stats.mCurrentNumAllocs, stats.mTotalNumAllocs, stats.mTotalNumReallocs, stats.mTotalNumFrees, stats.mName.c_str()).c_str()); + Print(FormatStdString("[Cat %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", categoryID, stats.m_currentNumBytes, stats.m_currentNumBytes / 1000, stats.m_currentNumAllocs, stats.m_totalNumAllocs, stats.m_totalNumReallocs, stats.m_totalNumFrees, stats.m_name.c_str()).c_str()); } } } } - if (mGroups.empty() == false) + if (m_groups.empty() == false) { Print(""); Print("--[ Group Statistics ]-------------------------------------------------------------------------------"); - for (auto& item : mGroups) + for (auto& item : m_groups) { const uint32 groupID = item.first; const Group& group = item.second; - if (group.mStats.mTotalNumAllocs > 0) + if (group.m_stats.m_totalNumAllocs > 0) { bool display = true; if (currentlyAllocatedOnly) { - if (group.mStats.mCurrentNumAllocs == 0) + if (group.m_stats.m_currentNumAllocs == 0) { display = false; } @@ -468,7 +468,7 @@ namespace MCore if (display) { - Print(FormatStdString("[Group %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", groupID, group.mStats.mCurrentNumBytes, group.mStats.mCurrentNumBytes / 1000, group.mStats.mCurrentNumAllocs, group.mStats.mTotalNumAllocs, group.mStats.mTotalNumReallocs, group.mStats.mTotalNumFrees, group.mName.c_str()).c_str()); + Print(FormatStdString("[Group %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", groupID, group.m_stats.m_currentNumBytes, group.m_stats.m_currentNumBytes / 1000, group.m_stats.m_currentNumAllocs, group.m_stats.m_totalNumAllocs, group.m_stats.m_totalNumReallocs, group.m_stats.m_totalNumFrees, group.m_name.c_str()).c_str()); } } } @@ -479,12 +479,12 @@ namespace MCore // log the stats void MemoryTracker::LogLeaks() { - LockGuard lock(mMutex); + LockGuard lock(m_mutex); // update the group statistics (thread safe also) UpdateGroupStatisticsNoLock(); - if (mAllocs.size() == 0) + if (m_allocs.size() == 0) { Print("MCore::MemoryTracker::LogLeaks() - No memory leaks have been detected."); return; @@ -492,34 +492,34 @@ namespace MCore // log globals Print("--[ Memory Leak Global Statistics ]-----------------------------------------------------------------------"); - Print(FormatStdString("Leaking Num Bytes = %d bytes (%d k or %.2f mb)", mGlobalStats.mCurrentNumBytes, mGlobalStats.mCurrentNumBytes / 1000, mGlobalStats.mCurrentNumBytes / 1000000.0f).c_str()); - Print(FormatStdString("Leaking Num Allocs = %d", mGlobalStats.mCurrentNumAllocs).c_str()); + Print(FormatStdString("Leaking Num Bytes = %d bytes (%d k or %.2f mb)", m_globalStats.m_currentNumBytes, m_globalStats.m_currentNumBytes / 1000, m_globalStats.m_currentNumBytes / 1000000.0f).c_str()); + Print(FormatStdString("Leaking Num Allocs = %d", m_globalStats.m_currentNumAllocs).c_str()); Print(""); // log category totals Print("--[ Memory Category Leak Statistics ]---------------------------------------------------------------------"); - for (auto& item : mCategories) + for (auto& item : m_categories) { const uint32 categoryID = item.first; const CategoryStats& stats = item.second; - if (stats.mCurrentNumAllocs > 0) + if (stats.m_currentNumAllocs > 0) { - Print(FormatStdString("[Cat %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", categoryID, stats.mCurrentNumBytes, stats.mCurrentNumBytes / 1000, stats.mCurrentNumAllocs, stats.mTotalNumAllocs, stats.mTotalNumReallocs, stats.mTotalNumFrees, stats.mName.c_str()).c_str()); + Print(FormatStdString("[Cat %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", categoryID, stats.m_currentNumBytes, stats.m_currentNumBytes / 1000, stats.m_currentNumAllocs, stats.m_totalNumAllocs, stats.m_totalNumReallocs, stats.m_totalNumFrees, stats.m_name.c_str()).c_str()); } } Print(""); - if (mGroups.empty() == false) + if (m_groups.empty() == false) { Print(""); Print("--[ Group Statistics ]-------------------------------------------------------------------------------"); - for (auto& item : mGroups) + for (auto& item : m_groups) { const uint32 groupID = item.first; const Group& group = item.second; - if (group.mStats.mCurrentNumAllocs > 0) + if (group.m_stats.m_currentNumAllocs > 0) { - Print(FormatStdString("[Group %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", groupID, group.mStats.mCurrentNumBytes, group.mStats.mCurrentNumBytes / 1000, group.mStats.mCurrentNumAllocs, group.mStats.mTotalNumAllocs, group.mStats.mTotalNumReallocs, group.mStats.mTotalNumFrees, group.mName.c_str()).c_str()); + Print(FormatStdString("[Group %4d] - %8d bytes (%6d k) in %5d allocs [%6d / %6d / %6d] --> %s", groupID, group.m_stats.m_currentNumBytes, group.m_stats.m_currentNumBytes / 1000, group.m_stats.m_currentNumAllocs, group.m_stats.m_totalNumAllocs, group.m_stats.m_totalNumReallocs, group.m_stats.m_totalNumFrees, group.m_name.c_str()).c_str()); } } Print(""); @@ -528,7 +528,7 @@ namespace MCore // log individual leaks Print("--[ Memory Allocations ]----------------------------------------------------------------------------------"); uint32 allocNumber = 0; - for (auto& item : mAllocs) + for (auto& item : m_allocs) { const char* data = static_cast(item.first); const Allocation& allocation = item.second; @@ -536,7 +536,7 @@ namespace MCore char buffer[64]; memset(buffer, 0, 64); - const size_t numBytes = (allocation.mNumBytes >= 64) ? 63 : allocation.mNumBytes; + const size_t numBytes = (allocation.m_numBytes >= 64) ? 63 : allocation.m_numBytes; for (uint32 i = 0; i < numBytes; ++i) { char c = data[i]; @@ -547,9 +547,9 @@ namespace MCore buffer[i] = c; } - auto catItem = mCategories.find(allocation.mCategoryID); - MCORE_ASSERT(catItem != mCategories.end()); - Print(FormatStdString("#%-4d - %6d bytes (cat=%4d) - [%-66s] --> %s", allocNumber, allocation.mNumBytes, allocation.mCategoryID, buffer, catItem->second.mName.c_str()).c_str()); + auto catItem = m_categories.find(allocation.m_categoryId); + MCORE_ASSERT(catItem != m_categories.end()); + Print(FormatStdString("#%-4d - %6d bytes (cat=%4d) - [%-66s] --> %s", allocNumber, allocation.m_numBytes, allocation.m_categoryId, buffer, catItem->second.m_name.c_str()).c_str()); allocNumber++; } diff --git a/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.h b/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.h index 6a387ed508..e944306c14 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.h +++ b/Gems/EMotionFX/Code/MCore/Source/MemoryTracker.h @@ -41,9 +41,9 @@ namespace MCore */ struct MCORE_API Allocation { - void* mMemAddress; /**< The memory address of the allocation. */ - size_t mNumBytes; /**< The number of bytes allocated at this address. */ - uint32 mCategoryID; /**< The memory category of this allocation. */ + void* m_memAddress; /**< The memory address of the allocation. */ + size_t m_numBytes; /**< The number of bytes allocated at this address. */ + uint32 m_categoryId; /**< The memory category of this allocation. */ }; /** @@ -51,11 +51,11 @@ namespace MCore */ struct MCORE_API GlobalStats { - size_t mCurrentNumBytes; /**< Current number of bytes allocated. */ - uint32 mCurrentNumAllocs; /**< The current number of allocations. */ - uint32 mTotalNumAllocs; /**< Total number of allocations ever made. */ - uint32 mTotalNumReallocs; /**< Total number of reallocations ever made. */ - uint32 mTotalNumFrees; /**< Total number of frees ever made. */ + size_t m_currentNumBytes; /**< Current number of bytes allocated. */ + uint32 m_currentNumAllocs; /**< The current number of allocations. */ + uint32 m_totalNumAllocs; /**< Total number of allocations ever made. */ + uint32 m_totalNumReallocs; /**< Total number of reallocations ever made. */ + uint32 m_totalNumFrees; /**< Total number of frees ever made. */ GlobalStats(); }; @@ -65,12 +65,12 @@ namespace MCore */ struct MCORE_API CategoryStats { - size_t mCurrentNumBytes; /**< Current number of bytes allocated. */ - uint32 mCurrentNumAllocs; /**< Current number of allocations active. */ - uint32 mTotalNumAllocs; /**< Total number of allocations ever made in this category. */ - uint32 mTotalNumReallocs; /**< Total number of reallocations ever made in this category. */ - uint32 mTotalNumFrees; /**< Total number of frees ever made in this category. */ - std::string mName; /**< The name of the category, can be empty if not registered with RegisterCategory. */ + size_t m_currentNumBytes; /**< Current number of bytes allocated. */ + uint32 m_currentNumAllocs; /**< Current number of allocations active. */ + uint32 m_totalNumAllocs; /**< Total number of allocations ever made in this category. */ + uint32 m_totalNumReallocs; /**< Total number of reallocations ever made in this category. */ + uint32 m_totalNumFrees; /**< Total number of frees ever made in this category. */ + std::string m_name; /**< The name of the category, can be empty if not registered with RegisterCategory. */ CategoryStats(); }; @@ -80,11 +80,11 @@ namespace MCore */ struct MCORE_API GroupStats { - size_t mCurrentNumBytes; - uint32 mCurrentNumAllocs; - uint32 mTotalNumAllocs; /**< Total number of allocations ever made in this category. */ - uint32 mTotalNumReallocs; /**< Total number of reallocations ever made in this category. */ - uint32 mTotalNumFrees; /**< Total number of frees ever made in this category. */ + size_t m_currentNumBytes; + uint32 m_currentNumAllocs; + uint32 m_totalNumAllocs; /**< Total number of allocations ever made in this category. */ + uint32 m_totalNumReallocs; /**< Total number of reallocations ever made in this category. */ + uint32 m_totalNumFrees; /**< Total number of frees ever made in this category. */ GroupStats(); }; @@ -94,9 +94,9 @@ namespace MCore */ struct MCORE_API Group { - std::set mCategories; /**< The ID values of the categories that are part of this group. */ - std::string mName; /**< The name of the category. */ - GroupStats mStats; /**< The statistics. */ + std::set m_categories; /**< The ID values of the categories that are part of this group. */ + std::string m_name; /**< The name of the category. */ + GroupStats m_stats; /**< The statistics. */ }; //-------------------------------- @@ -254,11 +254,11 @@ namespace MCore void Unlock(); private: - std::unordered_map mAllocs; /**< The unordered map of allocations, with the memory address as key. */ - std::unordered_map mGroups; /**< The groups, with the group ID as key.*/ - std::map mCategories; /**< The ordered map of categories, with the category ID as key. */ - GlobalStats mGlobalStats; /**< The global memory statistics. */ - mutable Mutex mMutex; /**< The multithread mutex used to lock and unlock. */ + std::unordered_map m_allocs; /**< The unordered map of allocations, with the memory address as key. */ + std::unordered_map m_groups; /**< The groups, with the group ID as key.*/ + std::map m_categories; /**< The ordered map of categories, with the category ID as key. */ + GlobalStats m_globalStats; /**< The global memory statistics. */ + mutable Mutex m_mutex; /**< The multithread mutex used to lock and unlock. */ /** * Register a given memory allocation. diff --git a/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h b/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h index b97f7b2f22..eccfa9f5f3 100644 --- a/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h +++ b/Gems/EMotionFX/Code/MCore/Source/MultiThreadManager.h @@ -29,12 +29,12 @@ namespace MCore MCORE_INLINE Mutex() {} MCORE_INLINE ~Mutex() {} - MCORE_INLINE void Lock() { mMutex.lock(); } - MCORE_INLINE void Unlock() { mMutex.unlock(); } - MCORE_INLINE bool TryLock() { return mMutex.try_lock(); } + MCORE_INLINE void Lock() { m_mutex.lock(); } + MCORE_INLINE void Unlock() { m_mutex.unlock(); } + MCORE_INLINE bool TryLock() { return m_mutex.try_lock(); } private: - AZStd::mutex mMutex; + AZStd::mutex m_mutex; }; @@ -44,12 +44,12 @@ namespace MCore MCORE_INLINE MutexRecursive() {} MCORE_INLINE ~MutexRecursive() {} - MCORE_INLINE void Lock() { mMutex.lock(); } - MCORE_INLINE void Unlock() { mMutex.unlock(); } - MCORE_INLINE bool TryLock() { return mMutex.try_lock(); } + MCORE_INLINE void Lock() { m_mutex.lock(); } + MCORE_INLINE void Unlock() { m_mutex.unlock(); } + MCORE_INLINE bool TryLock() { return m_mutex.try_lock(); } private: - AZStd::recursive_mutex mMutex; + AZStd::recursive_mutex m_mutex; }; @@ -59,13 +59,13 @@ namespace MCore MCORE_INLINE ConditionVariable() {} MCORE_INLINE ~ConditionVariable() {} - MCORE_INLINE void Wait(Mutex& mtx, const AZStd::function& predicate) { AZStd::unique_lock lock(mtx.mMutex); mVariable.wait(lock, predicate); } - MCORE_INLINE void WaitWithTimeout(Mutex& mtx, uint32 microseconds, const AZStd::function& predicate) { AZStd::unique_lock lock(mtx.mMutex); mVariable.wait_for(lock, AZStd::chrono::microseconds(microseconds), predicate); } - MCORE_INLINE void NotifyOne() { mVariable.notify_one(); } - MCORE_INLINE void NotifyAll() { mVariable.notify_all(); } + MCORE_INLINE void Wait(Mutex& mtx, const AZStd::function& predicate) { AZStd::unique_lock lock(mtx.m_mutex); m_variable.wait(lock, predicate); } + MCORE_INLINE void WaitWithTimeout(Mutex& mtx, uint32 microseconds, const AZStd::function& predicate) { AZStd::unique_lock lock(mtx.m_mutex); m_variable.wait_for(lock, AZStd::chrono::microseconds(microseconds), predicate); } + MCORE_INLINE void NotifyOne() { m_variable.notify_one(); } + MCORE_INLINE void NotifyAll() { m_variable.notify_all(); } private: - AZStd::condition_variable mVariable; + AZStd::condition_variable m_variable; }; @@ -75,14 +75,14 @@ namespace MCore MCORE_INLINE AtomicInt32() { SetValue(0); } MCORE_INLINE ~AtomicInt32() {} - MCORE_INLINE void SetValue(int32 value) { mAtomic.store(value); } - MCORE_INLINE int32 GetValue() const { int32 value = mAtomic.load(); return value; } + MCORE_INLINE void SetValue(int32 value) { m_atomic.store(value); } + MCORE_INLINE int32 GetValue() const { int32 value = m_atomic.load(); return value; } - MCORE_INLINE int32 Increment() { return mAtomic++; } - MCORE_INLINE int32 Decrement() { return mAtomic--; } + MCORE_INLINE int32 Increment() { return m_atomic++; } + MCORE_INLINE int32 Decrement() { return m_atomic--; } private: - AZStd::atomic mAtomic; + AZStd::atomic m_atomic; }; @@ -93,14 +93,30 @@ namespace MCore MCORE_INLINE AtomicUInt32() { SetValue(0); } MCORE_INLINE ~AtomicUInt32() {} - MCORE_INLINE void SetValue(uint32 value) { mAtomic.store(value); } - MCORE_INLINE uint32 GetValue() const { uint32 value = mAtomic.load(); return value; } + MCORE_INLINE void SetValue(uint32 value) { m_atomic.store(value); } + MCORE_INLINE uint32 GetValue() const { uint32 value = m_atomic.load(); return value; } - MCORE_INLINE uint32 Increment() { return mAtomic++; } - MCORE_INLINE uint32 Decrement() { return mAtomic--; } + MCORE_INLINE uint32 Increment() { return m_atomic++; } + MCORE_INLINE uint32 Decrement() { return m_atomic--; } private: - AZStd::atomic mAtomic; + AZStd::atomic m_atomic; + }; + + + class MCORE_API AtomicSizeT + { + public: + MCORE_INLINE AtomicSizeT() { SetValue(0); } + + MCORE_INLINE void SetValue(size_t value) { m_atomic.store(value); } + MCORE_INLINE size_t GetValue() const { size_t value = m_atomic.load(); return value; } + + MCORE_INLINE size_t Increment() { return m_atomic++; } + MCORE_INLINE size_t Decrement() { return m_atomic--; } + + private: + AZStd::atomic m_atomic; }; @@ -111,58 +127,58 @@ namespace MCore Thread(const AZStd::function& threadFunction) { Init(threadFunction); } ~Thread() {} - void Init(const AZStd::function& threadFunction) { mThread = AZStd::thread(threadFunction); } - void Join() { mThread.join(); } + void Init(const AZStd::function& threadFunction) { m_thread = AZStd::thread(threadFunction); } + void Join() { m_thread.join(); } private: - AZStd::thread mThread; + AZStd::thread m_thread; }; class MCORE_API LockGuard { public: - MCORE_INLINE LockGuard(Mutex& mutex) { mMutex = &mutex; mutex.Lock(); } - MCORE_INLINE ~LockGuard() { mMutex->Unlock(); } + MCORE_INLINE LockGuard(Mutex& mutex) { m_mutex = &mutex; mutex.Lock(); } + MCORE_INLINE ~LockGuard() { m_mutex->Unlock(); } private: - Mutex* mMutex; + Mutex* m_mutex; }; class MCORE_API LockGuardRecursive { public: - MCORE_INLINE LockGuardRecursive(MutexRecursive& mutex) { mMutex = &mutex; mutex.Lock(); } - MCORE_INLINE ~LockGuardRecursive() { mMutex->Unlock(); } + MCORE_INLINE LockGuardRecursive(MutexRecursive& mutex) { m_mutex = &mutex; mutex.Lock(); } + MCORE_INLINE ~LockGuardRecursive() { m_mutex->Unlock(); } private: - MutexRecursive* mMutex; + MutexRecursive* m_mutex; }; class MCORE_API ConditionEvent { public: - ConditionEvent() { mConditionValue = false; } + ConditionEvent() { m_conditionValue = false; } ~ConditionEvent() { } - void Reset() { mConditionValue = false; } + void Reset() { m_conditionValue = false; } void Wait() { - mCV.Wait(mMutex, [this] { return mConditionValue; }); + m_cv.Wait(m_mutex, [this] { return m_conditionValue; }); } void WaitWithTimeout(uint32 microseconds) { - mCV.WaitWithTimeout(mMutex, microseconds, [this] { return mConditionValue; }); + m_cv.WaitWithTimeout(m_mutex, microseconds, [this] { return m_conditionValue; }); } - void NotifyAll() { { LockGuard lockMutex(mMutex); mConditionValue = true; } mCV.NotifyAll(); } - void NotifyOne() { { LockGuard lockMutex(mMutex); mConditionValue = true; } mCV.NotifyOne(); } + void NotifyAll() { { LockGuard lockMutex(m_mutex); m_conditionValue = true; } m_cv.NotifyAll(); } + void NotifyOne() { { LockGuard lockMutex(m_mutex); m_conditionValue = true; } m_cv.NotifyOne(); } private: - Mutex mMutex; - ConditionVariable mCV; - bool mConditionValue; + Mutex m_mutex; + ConditionVariable m_cv; + bool m_conditionValue; }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/OBB.cpp b/Gems/EMotionFX/Code/MCore/Source/OBB.cpp deleted file mode 100644 index 66c47e9475..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/OBB.cpp +++ /dev/null @@ -1,638 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// include required headers -#include "OBB.h" -#include "AABB.h" - -#include -#include -#include -#include - -namespace MCore -{ - // check if the box contains a given point - bool OBB::Contains(const AZ::Vector3& p) const - { - // translate to box space - AZ::Vector3 relPoint = p - mCenter; - - // convert the box into box space and test each axis - float f = mRotation.GetBasisX().Dot(relPoint); - if (f >= mExtents.GetX() || f <= -mExtents.GetX()) - { - return false; - } - - f = mRotation.GetBasisY().Dot(relPoint); - if (f >= mExtents.GetY() || f <= -mExtents.GetY()) - { - return false; - } - - f = mRotation.GetBasisZ().Dot(relPoint); - if (f >= mExtents.GetZ() || f <= -mExtents.GetZ()) - { - return false; - } - - return true; - } - - - void OBB::Create(const AABB& aabb, const AZ::Transform& mat) - { - // calculate the center and extents - mCenter = aabb.CalcMiddle(); - mExtents = aabb.CalcExtents(); - - // transform the center - mCenter = mat.TransformPoint(mCenter); - - // set the rotation - mRotation = mat; - } - - - void OBB::Transform(const AZ::Transform& transMatrix) - { - mCenter = transMatrix.TransformPoint(mCenter); - mRotation = transMatrix * mRotation; - } - - - void OBB::Transformed(const AZ::Transform& transMatrix, OBB* outOBB) const - { - outOBB->mExtents = mExtents; - outOBB->mCenter = transMatrix.TransformPoint(mCenter); - outOBB->mRotation = transMatrix * mRotation; - } - - - bool OBB::CheckIfIsInside(const OBB& box) const - { - // make a 4x4 from the box & inverse it - AZ::Transform M0 = box.mRotation; - M0.SetTranslation(box.mCenter); - AZ::Transform M0Inv = M0.GetInverse(); - - // with our inversed 4x4, create box1 in space of box0 - OBB _1in0; - Transformed(M0Inv, &_1in0); - - // this should cancel out box0's rotation, i.e. it's now an AABB - - // the two boxes are in the same space so now we can compare them - // create the AABB of (box1 in space of box0) - const AZ::Transform& mtx = _1in0.mRotation; - - AZ::Vector3 transformedAxisX = mtx.GetUniformScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisX())); - AZ::Vector3 transformedAxisY = mtx.GetUniformScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisY())); - AZ::Vector3 transformedAxisZ = mtx.GetUniformScale() * (mtx.GetRotation().GetConjugate().TransformVector(AZ::Vector3::CreateAxisZ())); - - float f = transformedAxisX.GetAbs().Dot(mExtents) - box.mExtents.GetX(); - if (f > _1in0.mCenter.GetX()) - { - return false; - } - if (-f < _1in0.mCenter.GetX()) - { - return false; - } - - f = transformedAxisY.GetAbs().Dot(mExtents) - box.mExtents.GetY(); - if (f > _1in0.mCenter.GetY()) - { - return false; - } - if (-f < _1in0.mCenter.GetY()) - { - return false; - } - - f = transformedAxisZ.GetAbs().Dot(mExtents) - box.mExtents.GetZ(); - if (f > _1in0.mCenter.GetZ()) - { - return false; - } - if (-f < _1in0.mCenter.GetZ()) - { - return false; - } - - return true; - } - - - // calculate the corner points for the OBB - void OBB::CalcCornerPoints(AZ::Vector3* outPoints) const - { - MCORE_ASSERT(outPoints); - MCORE_ASSERT(CheckIfIsValid()); - - AZ::Vector3 right = MCore::GetRight(mRotation); - AZ::Vector3 up = MCore::GetUp(mRotation); - AZ::Vector3 forward = MCore::GetForward(mRotation); - - right *= mExtents.GetX(); - up *= mExtents.GetZ(); - forward *= mExtents.GetY(); - - // 7+------+6 - // /| /| - // / | / | - // / 4+---/--+5 - // 3+------+2 / - // | / | / - // |/ |/ - // 0+------+1 - - outPoints[0] = mCenter - right - up - forward; - outPoints[1] = mCenter + right - up - forward; - outPoints[2] = mCenter + right + up - forward; - outPoints[3] = mCenter - right + up - forward; - outPoints[4] = mCenter - right - up + forward; - outPoints[5] = mCenter + right - up + forward; - outPoints[6] = mCenter + right + up + forward; - outPoints[7] = mCenter - right + up + forward; - } - - - //---------------------------------------------------------------------------------------------------------- - - // calculate the 3 eigen vectors - void OBB::GetRealSymmetricEigenvectors(const float A[6], AZ::Vector3& v1, AZ::Vector3& v2, AZ::Vector3& v3) - { - // compute coefficients for cubic equation - const float c2 = A[0] + A[3] + A[5]; - const float a12sq = A[1] * A[1]; - const float a13sq = A[2] * A[2]; - const float a23sq = A[4] * A[4]; - const float a11a22 = A[0] * A[3]; - const float c1 = a11a22 - a12sq + A[0] * A[5] - a13sq + A[3] * A[5] - a23sq; - const float c0 = a11a22 * A[5] + 2.0f * A[1] * A[2] * A[4] - A[0] * a23sq - A[3] * a13sq - A[5] * a12sq; - - // compute intermediate values for root solving - const float c2sq = c2 * c2; - const float a = (3.0f * c1 - c2sq) / 3.0f; - const float b = (9.0f * c1 * c2 - 2.0f * c2sq * c2 - 27.f * c0) / 27.0f; - const float halfb = b * 0.5f; - const float halfb2 = halfb * halfb; - const float Q = halfb2 + a * a * a / 27.0f; - - // determine type of eigenspaces - if (Q > 1.0e-6f) - { - // one eigenvalue, use standard basis - v1.Set(1.0f, 0.0f, 0.0f); - v2.Set(0.0f, 1.0f, 0.0f); - v3.Set(0.0f, 0.0f, 1.0f); - return; - } - else - if (Q < -1.0e-6f) - { - // three distinct eigenvalues - - // intermediate terms - const float theta_3 = Math::ATan2(Math::Sqrt(-Q), -halfb) / 3.0f; - float rho = Math::Sqrt(halfb2 - Q); - const float c2_3 = c2 / 3.0f; - float rho_13 = powf(Math::Abs(rho), 1.0f / 3.0f); - if (rho < 0.0f) - { - rho_13 = -rho_13; - } - float ct_3, st_3; - const float sqrt3 = Math::Sqrt(3.0f); - ct_3 = Math::Cos(theta_3); - st_3 = Math::Sin(theta_3); - - // compute each eigenvalue and eigenvector - // sort from largest to smallest - float lambda1 = c2_3 + 2.0f * rho_13 * ct_3; - CalcSymmetricEigenVector(A, lambda1, v1); - - float lambda2 = c2_3 - rho_13 * (ct_3 + sqrt3 * st_3); - if (lambda2 > lambda1) - { - v2 = v1; - float temp = lambda2; - lambda2 = lambda1; - lambda1 = temp; - CalcSymmetricEigenVector(A, lambda2, v1); - } - else - { - CalcSymmetricEigenVector(A, lambda2, v2); - } - - float lambda3 = c2_3 - rho_13 * (ct_3 - sqrt3 * st_3); - if (lambda3 > lambda1) - { - v3 = v2; - v2 = v1; - CalcSymmetricEigenVector(A, lambda3, v1); - } - else - if (lambda3 > lambda2) - { - v3 = v2; - CalcSymmetricEigenVector(A, lambda3, v2); - } - else - { - CalcSymmetricEigenVector(A, lambda3, v3); - } - } - else - { - // two distinct eigenvalues - - // intermediate terms - float c2_3 = c2 / 3.0f; - float halfb_13 = Math::Pow(Math::Abs(halfb), 1.0f / 3.0f); - if (halfb < 0.0f) - { - halfb_13 = -halfb_13; - } - - // compute each eigenvalue and eigenvector - // sort from largest to smallest - float lambda1 = c2_3 + halfb_13; - CalcSymmetricEigenPair(A, lambda1, v1, v2); - - float lambda2 = c2_3 - 2.0f * halfb_13; - if (lambda2 > lambda1) - { - v3 = v2; - v2 = v1; - CalcSymmetricEigenVector(A, lambda2, v1); - } - else - { - CalcSymmetricEigenVector(A, lambda2, v3); - } - } - - v1.Normalize(); - v2.Normalize(); - v3.Normalize(); - - if ((v1.Cross(v2)).Dot(v3) < 0.0f) - { - v3 = -v3; - } - } - - - // calculate the eigen vector from a symmetric matrix in combination with a given eigen value - void OBB::CalcSymmetricEigenVector(const float A[6], float eigenValue, AZ::Vector3& v1) - { - const float m11 = A[0] - eigenValue; - const float m12 = A[1]; - const float m13 = A[2]; - const float m22 = A[3] - eigenValue; - const float m23 = A[4]; - const float m33 = A[5] - eigenValue; - - // compute cross product matrix, and find column with maximal entry - const float u11 = m22 * m33 - m23 * m23; - float max = Math::Abs(u11); - int c = 1; - const float u12 = m13 * m23 - m12 * m33; - if (Math::Abs(u12) > max) - { - max = Math::Abs(u12); - c = 2; - } - - const float u13 = m12 * m23 - m13 * m22; - if (Math::Abs(u13) > max) - { - max = Math::Abs(u13); - c = 3; - } - - const float u22 = m11 * m33 - m13 * m13; - if (Math::Abs(u22) > max) - { - max = Math::Abs(u22); - c = 2; - } - - const float u23 = m12 * m13 - m23 * m11; - if (Math::Abs(u23) > max) - { - max = Math::Abs(u23); - c = 3; - } - - const float u33 = m11 * m22 - m12 * m12; - if (Math::Abs(u33) > max) - { - max = Math::Abs(u33); - c = 3; - } - - // return column with maximal entry - if (c == 1) - { - v1.Set(u11, u12, u13); - } - else - if (c == 2) - { - v1.Set(u12, u22, u23); - } - else - { - v1.Set(u13, u23, u33); - } - } - - - //------------------------------------------------------------------------------- - // Given symmetric matrix A and eigenvalue l, returns eigenvector pair - // Assumes that order of eigenvalue is 2 - //------------------------------------------------------------------------------- - void OBB::CalcSymmetricEigenPair(const float A[6], float eigenValue, AZ::Vector3& v1, AZ::Vector3& v2) - { - // find maximal entry in M - const float m11 = A[0] - eigenValue; - float max = Math::Abs(m11); - int r = 1, c = 1; - if (Math::Abs(A[1]) > max) - { - max = Math::Abs(A[1]); - r = 1; - c = 2; - } - - if (Math::Abs(A[2]) > max) - { - max = Math::Abs(A[2]); - r = 1; - c = 3; - } - - const float m22 = A[3] - eigenValue; - if (Math::Abs(m22) > max) - { - max = Math::Abs(m22); - r = 2; - c = 2; - } - - if (Math::Abs(A[4]) > max) - { - max = Math::Abs(A[4]); - r = 2; - c = 3; - } - - const float m33 = A[5] - eigenValue; - if (Math::Abs(m33) > max) - { - r = 3; - c = 3; - } - - // compute eigenvectors for each case - if (r == 1) - { - if (c == 3) - { - v1.Set(A[2], 0.0f, -m11); - v2.Set(-A[1] * m11, m11 * m11 + A[2] * A[2], -A[1] * A[2]); - } - else - { - v1.Set(-A[1], m11, 0.0f); - v2.Set(-A[2] * m11, -A[2] * A[1], m11 * m11 + A[1] * A[1]); - } - } - else - if (r == 2) - { - v1.Set(0.0f, -A[4], m22); - v2.Set(m22 * m22 + A[4] * A[4], -A[1] * m22, -A[1] * A[4]); - } - else - if (r == 3) - { - v1.Set(0.0f, -m33, A[4]); - v2.Set(A[4] * A[4] + m33 * m33, -A[2] * A[4], -A[2] * m33); - } - } - - //----------------------- - - //------------------------------------------------------------------------------- - // Compute covariance matrix for set of points - // Returns centroid and unique values of matrix - //------------------------------------------------------------------------------- - void OBB::CovarianceMatrix(const AZ::Vector3* points, uint32 numPoints, AZ::Vector3& mean, float C[6]) - { - uint32 i; - - // compute mean - mean = points[0]; - for (i = 1; i < numPoints; ++i) - { - mean += points[i]; - } - - mean *= 1.0f / numPoints; - - // compute each element of matrix - memset(C, 0, sizeof(float) * 6); - for (i = 0; i < numPoints; ++i) - { - const AZ::Vector3 diff = points[i] - mean; - C[0] += diff.GetX() * diff.GetX(); - C[1] += diff.GetX() * diff.GetY(); - C[2] += diff.GetX() * diff.GetZ(); - C[3] += diff.GetY() * diff.GetY(); - C[4] += diff.GetY() * diff.GetZ(); - C[5] += diff.GetZ() * diff.GetZ(); - } - - // normalize the matrix values - float maxC = 0.0f; - for (i = 0; i < 6; ++i) - { - if (Math::Abs(C[i]) > maxC) - { - maxC = Math::Abs(C[i]); - } - } - for (i = 0; i < 6; ++i) - { - C[i] /= maxC; - } - } - - - // calc the best fit for a given x rotation slice - void OBB::InitFromPointsRange(const AZ::Vector3* points, uint32 numPoints, float xDegrees, float* outMinArea, AABB* outMinBox, AZ::Transform* outMinMatrix) - { - // calculate the x rotation matrix - AZ::Transform rotMatrix = AZ::Transform::CreateRotationX(Math::DegreesToRadians(xDegrees)); - - // try the same over the z axis - for (float z = -180.0f; z < 180.0f; z += 5.0f) - { - // calculate the final rotation matrix - rotMatrix = AZ::Transform::CreateRotationZ(Math::DegreesToRadians(z)) * rotMatrix; - - // calculate the inverse so we can transform the point set into space of this current rotation - AZ::Transform invMatrix = rotMatrix.GetInverse(); - - // rotate the points into the space of the current rotation - AABB box; - box.Init(); - for (uint32 i = 0; i < numPoints; ++i) - { - box.Encapsulate(invMatrix.TransformPoint(points[i])); - } - - // check if the surface area of this box is smaller than the smallest one we have - const float area = box.CalcSurfaceArea(); - if (area < *outMinArea) - { - *outMinArea = area; - *outMinBox = box; - *outMinMatrix = rotMatrix; - } - } - } - - - // Compute bounding box for set of points - void OBB::InitFromPoints(const AZ::Vector3* points, uint32 numPoints) - { - // if we have no points, just init - if (numPoints == 0) - { - Init(); - return; - } - - // some values we need - const uint32 MAX_NUM = (360 / 5) + 1; - AABB minBoxes[MAX_NUM]; - AZ::Transform minRotMatrices[MAX_NUM]; - float minAreas[MAX_NUM]; - for (uint32 i = 0; i < MAX_NUM; ++i) - { - minAreas[i] = FLT_MAX; - } - - - // try all rotation on the x axis (multithreaded) - AZ::JobCompletion jobCompletion; - uint32 index = 0; - for (float x = -180.0f; x < 180.0f; x += 5.0f) - { - MCORE_ASSERT(index < MAX_NUM); - - // create the job and add it - AZ::JobContext* jobContext = nullptr; - AZ::Job* job = AZ::CreateJobFunction([this, &minAreas, &minBoxes, &minRotMatrices, &numPoints, &points, x, index]() - { - InitFromPointsRange(points, numPoints, x, &minAreas[index], &minBoxes[index], &minRotMatrices[index]); - }, true, jobContext); - - job->SetDependent(&jobCompletion); - job->Start(); - - index++; - } - - jobCompletion.StartAndWaitForCompletion(); - - // find the real minimum value (single threaded lookup) - float minimumArea = FLT_MAX; - uint32 minimumIndex = 0; - for (uint32 i = 0; i < MAX_NUM; ++i) - { - if (minAreas[i] < minimumArea) - { - minimumArea = minAreas[i]; - minimumIndex = i; - } - } - - // update - mRotation = minRotMatrices[minimumIndex]; - mCenter = mRotation.TransformPoint(minBoxes[minimumIndex].CalcMiddle()); - mExtents = minBoxes[minimumIndex].CalcExtents(); - - /* - // compute covariance matrix - float C[6]; - CovarianceMatrix( points, numPoints, mCenter, C ); - - // get principle axes - Vector3 basis[3]; - GetRealSymmetricEigenvectors( C, basis[0], basis[1], basis[2] ); - - // init the min and max vectors - Vector3 minVec; - Vector3 maxVec; - minVec.Set(FLT_MAX, FLT_MAX, FLT_MAX); - maxVec.Set(-FLT_MAX, -FLT_MAX, -FLT_MAX); - - // find the min and max - for (uint32 i=0; i maxVec[j]) - maxVec[j] = length; - else - if (length < minVec[j]) - minVec[j] = length; - } - } - - // build the matrix from the calculated basis vectors - mRotation.Identity(); - mRotation.SetRow(0, basis[0]); - mRotation.SetRow(1, basis[1]); - mRotation.SetRow(2, basis[2]); - - // calculate the extents - mExtents = (maxVec - minVec) * 0.5f; - */ - } - - - // calculate the minimum and maximum point - void OBB::CalcMinMaxPoints(AZ::Vector3* outMin, AZ::Vector3* outMax) const - { - AZ::Transform rotation = mRotation; - rotation.SetTranslation(AZ::Vector3::CreateZero()); - AZ::Vector3 rotatedExtents = rotation.TransformPoint(mExtents); - *outMax = mCenter + rotatedExtents; - *outMin = mCenter - rotatedExtents; - - // +------+MAX - // /| /| - // / | / | - // / +---/--+ - // +------+ / - // | / | / - // |/ |/ - //MIN+------+ - } -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/OBB.h b/Gems/EMotionFX/Code/MCore/Source/OBB.h deleted file mode 100644 index 64cf61fb20..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/OBB.h +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include "StandardHeaders.h" - - -namespace MCore -{ - // forward declarations - class AABB; - - - /** - * 3D Oriented Bounding Box (OBB) template. - * This is basically a AABB with an arbitrary rotation. - */ - class MCORE_API OBB - { - public: - /** - * The constructor. - * This automatically initializes the box. After initialization the box is invalid since it basically has no size yet. - * The IsValid() method will return false. - */ - MCORE_INLINE OBB() { Init(); } - - /** - * Construct the OBB from a given axis aligned bounding box and a transformation. - * @param aabb The axis aligned bounding box. - * @param transformation The transformation of the box. - */ - MCORE_INLINE OBB(const AABB& aabb, const AZ::Transform& transformation) { Create(aabb, transformation); } - - /** - * Construct the OBB from a center, extends and a rotation. - * @param center The center of the box. - * @param extents The extents of the box, which start at the center of the box. - * @param rot The matrix, representing the transformation of the box. - */ - MCORE_INLINE OBB(const AZ::Vector3& center, const AZ::Vector3& extents, const AZ::Transform& rot) - : mRotation(rot) - , mExtents(extents) - , mCenter(center) {} - - /** - * Reset the OBB with as center 0,0,0, infinite negative extents and no rotation. - * This makes the box an invalid box as well, because the extents have not been set. - */ - MCORE_INLINE void Init(); - - /** - * Initialize the box from a set of points. - * This uses the covariant matrix and eigen vectors to fit the box to the set of points. - * @param points The set of points to fit the box to. - * @param numPoints The number of points inside array specified as first parameter. - */ - void InitFromPoints(const AZ::Vector3* points, uint32 numPoints); - - /** - * Check if this box OBB contains a given point or not. - * @param p The point to check. - * @result Returns true when the point is inside this box, otherwise false is returned. - */ - bool Contains(const AZ::Vector3& p) const; - - /** - * Check if this OBB is inside another specified box. - * @param box The OBB to check. - * @result Returns true when this OBB is inside the box specified as parameter. - */ - bool CheckIfIsInside(const OBB& box) const; - - /** - * Create the OBB from a given AABB and a matrix. - * @param aabb The axis aligned bounding box. - * @param mat The matrix, which represents the orientation of the box. - */ - void Create(const AABB& aabb, const AZ::Transform& mat); - - /** - * Transform this OBB with a given matrix. - * This means the transformation specified as parameter will be applied to the current transformation of the OBB. - * So the transformation specified is NOT an absolute rotation, but a relative transformation. - * @param transMatrix The relative transformation matrix, to be applied to the current transformation. - */ - void Transform(const AZ::Transform& transMatrix); - - /** - * Calculate the transformed version of this OBB. - * @param rotMatrix The transformation matrix to be applied to the rotation of this OBB, so not an absolute rotation! - * @param outOBB A pointer to the OBB to fill with the rotated version of this OBB. - */ - void Transformed(const AZ::Transform& rotMatrix, OBB* outOBB) const; - - /** - * Check if this is a valid OBB or not. - * The box is only valid if the extents are non-negative. - * @result Returns true when the OBB is valid, otherwise false is returned. - */ - MCORE_INLINE bool CheckIfIsValid() const; - - /** - * Set the center of the box. - * @param center The new center of the box. - */ - MCORE_INLINE void SetCenter(const AZ::Vector3& center) { mCenter = center; } - - /** - * Set the extents of the box. - * @param extents The new extents of the box. - */ - MCORE_INLINE void SetExtents(const AZ::Vector3& extents) { mExtents = extents; } - - /** - * Set the transformation of the box. - * @param transform The new transformation of the box. - */ - MCORE_INLINE void SetTransformation(const AZ::Transform& transform) { mRotation = transform; } - - /** - * Get the center of the box. - * @result The center point of the box. - */ - MCORE_INLINE const AZ::Vector3& GetCenter() const { return mCenter; } - - /** - * Get the extents of the box. - * @result The extents of the box, which start at the center. - */ - MCORE_INLINE const AZ::Vector3& GetExtents() const { return mExtents; } - - /** - * Get the transformation of the box. - * @result The transformation of the box. - */ - MCORE_INLINE const AZ::Transform& GetTransformation() const { return mRotation; } - - /** - * Calculate the 8 corner points of the box. - * The layout is as follows: - *
-         *
-         *     7+------+6
-         *     /|     /|
-         *    / |    / |
-         *   / 4+---/--+5
-         * 3+------+2 /
-         *  | /    | /
-         *  |/     |/
-         * 0+------+1
-         *
-         * 
- * @param outPoints the array of at least 8 vectors to write the points in. - */ - void CalcCornerPoints(AZ::Vector3* outPoints) const; - - /** - * Calculate the rotated minimum and maximum points of the box. - * After rotation it is possible that the min point is not really the min anymore though. The same goes for max. - * But the main use for this method however is to quickly approximate an AABB from this OBB, without having to - * calculate all 8 corner points. - *
-         *
-         *        +------+MAX
-         *       /|     /|
-         *      / |    / |
-         *     /  +---/--+
-         *    +------+  /
-         *    | /    | /
-         *    |/     |/
-         * MIN+------+
-         *
-         * 
- * @param outMin The vector that we will write the minimum point to. - * @param outMax The vector that we will write the maximum point to. - */ - void CalcMinMaxPoints(AZ::Vector3* outMin, AZ::Vector3* outMax) const; - - private: - AZ::Transform mRotation; /**< The rotation of the box. */ // TODO: store the center inside the translation component and extents inside last column? - AZ::Vector3 mExtents; /**< The extents of the box. */ - AZ::Vector3 mCenter; /**< The center of the box. */ - - /** - * Calculate the three eigen vectors for a symmetric matrix. - * @param A The symmetric matrix values. - * @param v1 The first output eigen vector. - * @param v2 The second output eigen vector. - * @param v3 The third output eigen vector. - */ - void GetRealSymmetricEigenvectors(const float A[6], AZ::Vector3& v1, AZ::Vector3& v2, AZ::Vector3& v3); - - /** - * Calculate the eigen vector from a symmetric matrix. - * This assumes that the specified eigenvalue is of order 1. - * @param A The symmetric matrix values. - * @param eigenValue The eigen value. - * @param v1 The output eigen vector. - */ - void CalcSymmetricEigenVector(const float A[6], float eigenValue, AZ::Vector3& v1); - - /** - * Calculate the pair of eigen vectors from a symmetric matrix. - * This assumes that the specified eigen value is of order 2. - * @param A The symmetric matrix values. - * @param eigenValue The eigen value. - * @param v1 The first output eigen vector. - * @param v2 The second output eigen vector. - */ - void CalcSymmetricEigenPair(const float A[6], float eigenValue, AZ::Vector3& v1, AZ::Vector3& v2); - - /** - * Calculate the covariance matrix from a set of points. - * @param points The set of points to calculate the covariance matrix from. - * @param numPoints The number of points inside the specified set of points. - * @param mean The statistical mean will be output in this vector. - * @param C The covariance matrix values that will be written to. Since the matrix is symmetric we only output one triangle of the 3x3 matrix. - */ - void CovarianceMatrix(const AZ::Vector3 * points, uint32 numPoints, AZ::Vector3 & mean, float C[6]); - - void InitFromPointsRange(const AZ::Vector3* points, uint32 numPoints, float xDegrees, float* outMinArea, AABB* outMinBox, AZ::Transform* outMinMatrix); - }; - - // include the inline code -#include "OBB.inl" -} // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/OBB.inl b/Gems/EMotionFX/Code/MCore/Source/OBB.inl deleted file mode 100644 index e8d82dd247..0000000000 --- a/Gems/EMotionFX/Code/MCore/Source/OBB.inl +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// initialize the box -// this creates an invalid box (with negative extents) so the IsValid method will return false -MCORE_INLINE void OBB::Init() -{ - mCenter = AZ::Vector3::CreateZero(); - mExtents.Set(-FLT_MAX, -FLT_MAX, -FLT_MAX); - mRotation = AZ::Transform::CreateIdentity(); -} - - -// check if the OBB is valid -MCORE_INLINE bool OBB::CheckIfIsValid() const -{ - if (mExtents.GetX() < 0.0f) - { - return false; - } - if (mExtents.GetY() < 0.0f) - { - return false; - } - if (mExtents.GetZ() < 0.0f) - { - return false; - } - return true; -} - diff --git a/Gems/EMotionFX/Code/MCore/Source/PlaneEq.h b/Gems/EMotionFX/Code/MCore/Source/PlaneEq.h index 402de4a12c..df8738a1ee 100644 --- a/Gems/EMotionFX/Code/MCore/Source/PlaneEq.h +++ b/Gems/EMotionFX/Code/MCore/Source/PlaneEq.h @@ -54,8 +54,8 @@ namespace MCore * @param pnt A point on the plane. */ MCORE_INLINE PlaneEq(const AZ::Vector3& norm, const AZ::Vector3& pnt) - : mNormal(norm) - , mDist(-((norm.GetX() * pnt.GetX()) + (norm.GetY() * pnt.GetY()) + (norm.GetZ() * pnt.GetZ()))) {} + : m_normal(norm) + , m_dist(-((norm.GetX() * pnt.GetX()) + (norm.GetY() * pnt.GetY()) + (norm.GetZ() * pnt.GetZ()))) {} /** * Constructor when you know the normal and the value of d out of the plane equation (Ax + By + Cz + d = 0) @@ -63,8 +63,8 @@ namespace MCore * @param d The value of 'd' out of the plane equation. */ MCORE_INLINE PlaneEq(const AZ::Vector3& norm, float d) - : mNormal(norm) - , mDist(d) {} + : m_normal(norm) + , m_dist(d) {} /** * Constructor when you know 3 points on the plane (the winding matters here (clockwise vs counter-clockwise) @@ -74,8 +74,8 @@ namespace MCore * @param v3 The third point on the plane. */ MCORE_INLINE PlaneEq(const AZ::Vector3& v1, const AZ::Vector3& v2, const AZ::Vector3& v3) - : mNormal((v2 - v1).Cross(v3 - v1).GetNormalized()) - , mDist(-(mNormal.Dot(v1))) {} + : m_normal((v2 - v1).Cross(v3 - v1).GetNormalized()) + , m_dist(-(m_normal.Dot(v1))) {} /** * Calculates and returns the dominant plane. @@ -86,9 +86,9 @@ namespace MCore */ MCORE_INLINE EPlane CalcDominantPlane() const { - return (Math::Abs(mNormal.GetY()) > Math::Abs(mNormal.GetX()) - ? (Math::Abs(mNormal.GetZ()) > Math::Abs(mNormal.GetY()) - ? PLANE_XY : PLANE_XZ) : (Math::Abs(mNormal.GetZ()) > Math::Abs(mNormal.GetX()) + return (Math::Abs(m_normal.GetY()) > Math::Abs(m_normal.GetX()) + ? (Math::Abs(m_normal.GetZ()) > Math::Abs(m_normal.GetY()) + ? PLANE_XY : PLANE_XZ) : (Math::Abs(m_normal.GetZ()) > Math::Abs(m_normal.GetX()) ? PLANE_XY : PLANE_YZ)); } @@ -98,7 +98,7 @@ namespace MCore * @param v The vector representing the 3D point to use for the calculation. * @result The distance from 'v' to this plane, along the normal of this plane. */ - MCORE_INLINE float CalcDistanceTo(const AZ::Vector3& v) const { return mNormal.Dot(v) + mDist; } + MCORE_INLINE float CalcDistanceTo(const AZ::Vector3& v) const { return m_normal.Dot(v) + m_dist; } /** * Construct the plane when the normal of the plane and a point on the plane are known. @@ -107,8 +107,8 @@ namespace MCore */ MCORE_INLINE void Construct(const AZ::Vector3& normal, const AZ::Vector3& pointOnPlane) { - mNormal = normal; - mDist = -((normal.GetX() * pointOnPlane.GetX()) + (normal.GetY() * pointOnPlane.GetY()) + (normal.GetZ() * pointOnPlane.GetZ())); + m_normal = normal; + m_dist = -((normal.GetX() * pointOnPlane.GetX()) + (normal.GetY() * pointOnPlane.GetY()) + (normal.GetZ() * pointOnPlane.GetZ())); } /** @@ -118,8 +118,8 @@ namespace MCore */ MCORE_INLINE void Construct(const AZ::Vector3& normal, float d) { - mNormal = normal; - mDist = d; + m_normal = normal; + m_dist = d; } /** @@ -131,21 +131,21 @@ namespace MCore */ MCORE_INLINE void Construct(const AZ::Vector3& v1, const AZ::Vector3& v2, const AZ::Vector3& v3) { - mNormal = (v2 - v1).Cross(v3 - v1).GetNormalized(); - mDist = -(mNormal.Dot(v1)); + m_normal = (v2 - v1).Cross(v3 - v1).GetNormalized(); + m_dist = -(m_normal.Dot(v1)); } /** * Get the normal of the plane. * @result Returns the normal of the plane. */ - MCORE_INLINE const AZ::Vector3& GetNormal() const { return mNormal; } + MCORE_INLINE const AZ::Vector3& GetNormal() const { return m_normal; } /** * Get the 'd' out of the plane equation (Ax + By + Cz + d = 0). * @result Returns the 'd' from the plane equation. */ - MCORE_INLINE float GetDist() const { return mDist; } + MCORE_INLINE float GetDist() const { return m_dist; } /** * Checks if a given axis aligned bounding box (AABB) is partially above (aka in front) this plane or not. @@ -189,12 +189,12 @@ namespace MCore * @param vectorToProject The vector you wish to project onto the plane. * @result The projected vector. */ - MCORE_INLINE AZ::Vector3 Project(const AZ::Vector3& vectorToProject) { return vectorToProject - vectorToProject.Dot(mNormal) * mNormal; } + MCORE_INLINE AZ::Vector3 Project(const AZ::Vector3& vectorToProject) { return vectorToProject - vectorToProject.Dot(m_normal) * m_normal; } private: - AZ::Vector3 mNormal; /**< The normal of the plane. */ - float mDist; /**< The D in the plane equation (Ax + By + Cz + D = 0). */ + AZ::Vector3 m_normal; /**< The normal of the plane. */ + float m_dist; /**< The D in the plane equation (Ax + By + Cz + D = 0). */ }; // include the inline code diff --git a/Gems/EMotionFX/Code/MCore/Source/PlaneEq.inl b/Gems/EMotionFX/Code/MCore/Source/PlaneEq.inl index f59fcbc2ca..62ccb19551 100644 --- a/Gems/EMotionFX/Code/MCore/Source/PlaneEq.inl +++ b/Gems/EMotionFX/Code/MCore/Source/PlaneEq.inl @@ -12,11 +12,11 @@ MCORE_INLINE bool PlaneEq::PartiallyAbove(const AABB& box) const { const AZ::Vector3 minVec = box.GetMin(); const AZ::Vector3 maxVec = box.GetMax(); - const AZ::Vector3 testPoint(IsNegative(float(mNormal.GetX())) ? minVec.GetX() : maxVec.GetX(), - IsNegative(static_cast(mNormal.GetY())) ? minVec.GetY() : maxVec.GetY(), - IsNegative(static_cast(mNormal.GetZ())) ? minVec.GetZ() : maxVec.GetZ()); + const AZ::Vector3 testPoint(IsNegative(float(m_normal.GetX())) ? minVec.GetX() : maxVec.GetX(), + IsNegative(static_cast(m_normal.GetY())) ? minVec.GetY() : maxVec.GetY(), + IsNegative(static_cast(m_normal.GetZ())) ? minVec.GetZ() : maxVec.GetZ()); - return IsPositive(mNormal.Dot(testPoint) + mDist); + return IsPositive(m_normal.Dot(testPoint) + m_dist); } @@ -25,9 +25,9 @@ MCORE_INLINE bool PlaneEq::CompletelyAbove(const AABB& box) const { const AZ::Vector3 minVec = box.GetMin(); const AZ::Vector3 maxVec = box.GetMax(); - const AZ::Vector3 testPoint(IsPositive(mNormal.GetX()) ? minVec.GetX() : maxVec.GetX(), - IsPositive(mNormal.GetY()) ? minVec.GetY() : maxVec.GetY(), - IsPositive(mNormal.GetZ()) ? minVec.GetZ() : maxVec.GetZ()); + const AZ::Vector3 testPoint(IsPositive(m_normal.GetX()) ? minVec.GetX() : maxVec.GetX(), + IsPositive(m_normal.GetY()) ? minVec.GetY() : maxVec.GetY(), + IsPositive(m_normal.GetZ()) ? minVec.GetZ() : maxVec.GetZ()); - return IsPositive(mNormal.Dot(testPoint) + mDist); + return IsPositive(m_normal.Dot(testPoint) + m_dist); } diff --git a/Gems/EMotionFX/Code/MCore/Source/Random.cpp b/Gems/EMotionFX/Code/MCore/Source/Random.cpp index 393a8f36ed..2a21abc6ae 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Random.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Random.cpp @@ -24,11 +24,11 @@ namespace MCore r |= 0x3f800000; //result is in [1,2), uniformly distributed union { - float f; - unsigned int i; + float m_f; + unsigned int m_i; } u; - u.i = r; - return u.f - 1.0f; + u.m_i = r; + return u.m_f - 1.0f; } // returns a random direction vector @@ -690,15 +690,15 @@ namespace MCore HaltonSequence::HaltonSequence() { // init members - mDimensions = 0; - mNextDim = 0; - mMemory = 0; - mN = 0; - mN0 = 0; - mX = nullptr; - mRadical = nullptr; - mBase = nullptr; - mOwnBase = false; + m_dimensions = 0; + m_nextDim = 0; + m_memory = 0; + m_n = 0; + m_n0 = 0; + m_x = nullptr; + m_radical = nullptr; + m_base = nullptr; + m_ownBase = false; } @@ -706,15 +706,15 @@ namespace MCore HaltonSequence::HaltonSequence(uint32 dimensions, uint32 offset, uint32* primes) { // init members - mDimensions = 0; - mNextDim = 0; - mMemory = 0; - mN = 0; - mN0 = 0; - mX = nullptr; - mRadical = nullptr; - mBase = nullptr; - mOwnBase = false; + m_dimensions = 0; + m_nextDim = 0; + m_memory = 0; + m_n = 0; + m_n0 = 0; + m_x = nullptr; + m_radical = nullptr; + m_base = nullptr; + m_ownBase = false; // initialize Init(dimensions, offset, primes); @@ -726,33 +726,33 @@ namespace MCore { MCORE_ASSERT(dimensions > 0); - mNextDim = 0; - mDimensions = dimensions; - mX = (double*)MCore::Allocate(dimensions * sizeof(double), MCORE_MEMCATEGORY_HALTONSEQ); - mMemory = sizeof(HaltonSequence) + dimensions * sizeof(double); + m_nextDim = 0; + m_dimensions = dimensions; + m_x = (double*)MCore::Allocate(dimensions * sizeof(double), MCORE_MEMCATEGORY_HALTONSEQ); + m_memory = sizeof(HaltonSequence) + dimensions * sizeof(double); - mN = offset; - mN0 = offset; - mRadical = (double*)MCore::Allocate(dimensions * sizeof(double), MCORE_MEMCATEGORY_HALTONSEQ); + m_n = offset; + m_n0 = offset; + m_radical = (double*)MCore::Allocate(dimensions * sizeof(double), MCORE_MEMCATEGORY_HALTONSEQ); - mOwnBase = (!primes); + m_ownBase = (!primes); - if (mOwnBase) + if (m_ownBase) { - mBase = FirstPrimes((uint32)dimensions); + m_base = FirstPrimes((uint32)dimensions); } else { - mBase = primes; + m_base = primes; } for (uint32 j = 0; j < dimensions; ++j) { - mRadical[j] = 1.0 / (double)mBase[j]; - mX[j] = 0.0; + m_radical[j] = 1.0 / (double)m_base[j]; + m_x[j] = 0.0; } - SetInstance(mN0); + SetInstance(m_n0); } @@ -765,23 +765,23 @@ namespace MCore void HaltonSequence::Release() { - if (mOwnBase && mBase) + if (m_ownBase && m_base) { - MCore::Free(mBase); + MCore::Free(m_base); } - mBase = nullptr; + m_base = nullptr; - if (mRadical) + if (m_radical) { - MCore::Free(mRadical); + MCore::Free(m_radical); } - mRadical = nullptr; + m_radical = nullptr; - if (mX) + if (m_x) { - MCore::Free(mX); + MCore::Free(m_x); } - mX = nullptr; + m_x = nullptr; } @@ -791,49 +791,49 @@ namespace MCore const double one = 1.0 - 1e-10; double h, hh, remainder; - mN++; + m_n++; - if (mN & 8191) + if (m_n & 8191) { - for (uint32 j = 0; j < mDimensions; ++j) + for (uint32 j = 0; j < m_dimensions; ++j) { - remainder = one - mX[j]; + remainder = one - m_x[j]; if (remainder < 0.0) { - mX[j] = 0.0; + m_x[j] = 0.0; } else { - if (mRadical[j] < remainder) + if (m_radical[j] < remainder) { - mX[j] += mRadical[j]; + m_x[j] += m_radical[j]; } else { - h = mRadical[j]; + h = m_radical[j]; do { hh = h; - h *= mRadical[j]; + h *= m_radical[j]; } while (h >= remainder); - mX[j] += hh + h - 1.0; + m_x[j] += hh + h - 1.0; } } } } else { - if (mN >= 1073741824) // 2^30 + if (m_n >= 1073741824) // 2^30 { SetInstance(0); } else { - SetInstance(mN); + SetInstance(m_n); } } } @@ -847,16 +847,16 @@ namespace MCore uint32 b; double fac; - mN = instance; - for (uint32 j = 0; j < mDimensions; ++j) + m_n = instance; + for (uint32 j = 0; j < m_dimensions; ++j) { - mX[j] = 0.0; - fac = mRadical[j]; - b = mBase[j]; + m_x[j] = 0.0; + fac = m_radical[j]; + b = m_base[j]; - for (im = mN; im > 0; im /= b, fac *= mRadical[j]) + for (im = m_n; im > 0; im /= b, fac *= m_radical[j]) { - mX[j] += fac * (double)(im % b); + m_x[j] += fac * (double)(im % b); } } } diff --git a/Gems/EMotionFX/Code/MCore/Source/Random.h b/Gems/EMotionFX/Code/MCore/Source/Random.h index 6e1a51fbb2..55576bb958 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Random.h +++ b/Gems/EMotionFX/Code/MCore/Source/Random.h @@ -299,35 +299,35 @@ namespace MCore * Returns the number of dimensions in the sequence. * @result The number of dimensions. */ - uint32 GetNumDimensions() const { return mDimensions; } + uint32 GetNumDimensions() const { return m_dimensions; } /** * Get the memory usage in bytes by this sequence. * @result The memory usage in bytes by this sequence. */ - uint32 GetMemoryUsage() const { return mMemory; } + uint32 GetMemoryUsage() const { return m_memory; } /** * Get the current vector number. * @result The vector number. */ - uint32 GetVectorNumber() const { return (mN - mN0); } + uint32 GetVectorNumber() const { return (m_n - m_n0); } /** * Get the value of current dimension, and go to the next dimension. * @result The value of the current dimension, and step to the next dimension. */ - double GetNextDimension() { MCORE_ASSERT(mNextDim != mDimensions); return mX[mNextDim++]; } + double GetNextDimension() { MCORE_ASSERT(m_nextDim != m_dimensions); return m_x[m_nextDim++]; } /** * Reset the dimension stepping (by GetNextDimension()) and go to the first dimension again. */ - void ResetNextDimension() { mNextDim = 0; } + void ResetNextDimension() { m_nextDim = 0; } /** * Restart the sequence. */ - void Restart() { SetInstance(mN0); } + void Restart() { SetInstance(m_n0); } /** * Get the next values in the sequence. So update the dimension values. @@ -348,19 +348,19 @@ namespace MCore /** * Get a value for a given dimension. (*sequence[0]) would be the value of the first dimension and (*sequence[1]) would be the value of the second dimension, etc. */ - double operator[](uint32 j) const { MCORE_ASSERT(j < mDimensions); return mX[j]; } + double operator[](uint32 j) const { MCORE_ASSERT(j < m_dimensions); return m_x[j]; } private: - uint32 mDimensions; /**< The number of dimensions to generate random numbers for. */ - uint32 mNextDim; /**< The next dimension. */ - uint32 mMemory; /**< */ - uint32 mN; /**< */ - uint32 mN0; /**< */ - double* mX; /**< */ - double* mRadical; /**< */ - uint32* mBase; /**< Prime numbers. */ - bool mOwnBase; /**< Specifies whether we use our own primes or user specified. */ + uint32 m_dimensions; /**< The number of dimensions to generate random numbers for. */ + uint32 m_nextDim; /**< The next dimension. */ + uint32 m_memory; /**< */ + uint32 m_n; /**< */ + uint32 m_n0; /**< */ + double* m_x; /**< */ + double* m_radical; /**< */ + uint32* m_base; /**< Prime numbers. */ + bool m_ownBase; /**< Specifies whether we use our own primes or user specified. */ /** * Generates the first n number of primes. diff --git a/Gems/EMotionFX/Code/MCore/Source/Ray.cpp b/Gems/EMotionFX/Code/MCore/Source/Ray.cpp index 9498635c3f..7df1188e77 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Ray.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Ray.cpp @@ -20,23 +20,23 @@ namespace MCore // ray-boundingsphere bool Ray::Intersects(const BoundingSphere& s, AZ::Vector3* intersectA, AZ::Vector3* intersectB) const { - const AZ::Vector3 rayOrg = mOrigin - s.GetCenter(); // ray in space of the sphere + const AZ::Vector3 rayOrg = m_origin - s.GetCenter(); // ray in space of the sphere // The Intersection can be solved by finding the solutions of the quadratic equation: - // (mOrigin + t * mDirection)^2 - s.GetRadiusSquared() = 0 - // Where t is a value that makes (mOrigin + t * mDirection) intersect the sphere + // (m_origin + t * m_direction)^2 - s.GetRadiusSquared() = 0 + // Where t is a value that makes (m_origin + t * m_direction) intersect the sphere // Expanding the above equation we have to find t1 and t2: - // t1 = (-2 * mOrigin * mDirection + sqrt(delta)) / (2 * mDirection^2) - // t2 = (-2 * mOrigin * mDirection - sqrt(delta)) / (2 * mDirection^2) - // where delta = (2 * mOrigin * mDirection) ^ 2 - 4 * mDirection^2 * (mOrigin^2 - s.GetRadiusSquared()) + // t1 = (-2 * m_origin * m_direction + sqrt(delta)) / (2 * m_direction^2) + // t2 = (-2 * m_origin * m_direction - sqrt(delta)) / (2 * m_direction^2) + // where delta = (2 * m_origin * m_direction) ^ 2 - 4 * m_direction^2 * (m_origin^2 - s.GetRadiusSquared()) // The two intersection points will be: - // mOrigin + mDirection * t1 - // mOrigin + mDirection * t2 + // m_origin + m_direction * t1 + // m_origin + m_direction * t2 // If delta < 0, then there is no intersection // If delta == 0, it intersects int he same point // - const float a = mDirection.GetLengthSq(); - const float b = 2.0f * mDirection.Dot(rayOrg); + const float a = m_direction.GetLengthSq(); + const float b = 2.0f * m_direction.Dot(rayOrg); const float c = rayOrg.GetLengthSq() - s.GetRadiusSquared(); const float delta = ((b * b) - 4.0f * a * c); @@ -63,22 +63,22 @@ namespace MCore { if (intersectA) { - (*intersectA) = mOrigin + mDirection * t1; + (*intersectA) = m_origin + m_direction * t1; } if (intersectB) { - (*intersectB) = mOrigin + mDirection * t2; + (*intersectB) = m_origin + m_direction * t2; } } else { if (intersectA) { - (*intersectA) = mOrigin + mDirection * t2; + (*intersectA) = m_origin + m_direction * t2; } if (intersectB) { - (*intersectB) = mOrigin + mDirection * t1; + (*intersectB) = m_origin + m_direction * t1; } } } @@ -88,11 +88,11 @@ namespace MCore const float t = -0.5f * b / a; if (intersectA) { - (*intersectA) = mOrigin + mDirection * t; + (*intersectA) = m_origin + m_direction * t; } if (intersectB) { - (*intersectB) = mOrigin + mDirection * t; + (*intersectB) = m_origin + m_direction * t; } } @@ -104,11 +104,11 @@ namespace MCore bool Ray::Intersects(const PlaneEq& p, AZ::Vector3* intersect) const { // check if ray is parallel to plane (no intersection) or ray pointing away from plane (no intersection) - float dot1 = p.GetNormal().Dot(mDirection); + float dot1 = p.GetNormal().Dot(m_direction); //if (dot1 >= 0) return false; // backface cull // calc second dot product - float dot2 = -(p.GetNormal().Dot(mOrigin) + p.GetDist()); + float dot2 = -(p.GetNormal().Dot(m_origin) + p.GetDist()); // calc t value float t = dot2 / dot1; @@ -127,9 +127,9 @@ namespace MCore // calc intersection point if (intersect) { - intersect->SetX(mOrigin.GetX() + (mDirection.GetX() * t)); - intersect->SetY(mOrigin.GetY() + (mDirection.GetY() * t)); - intersect->SetZ(mOrigin.GetZ() + (mDirection.GetZ() * t)); + intersect->SetX(m_origin.GetX() + (m_direction.GetX() * t)); + intersect->SetY(m_origin.GetY() + (m_direction.GetY() * t)); + intersect->SetZ(m_origin.GetZ() + (m_direction.GetZ() * t)); } return true; @@ -144,7 +144,7 @@ namespace MCore const AZ::Vector3 edge2 = p3 - p1; // begin calculating determinant - also used to calculate U parameter - const AZ::Vector3 dir = mDest - mOrigin; + const AZ::Vector3 dir = m_dest - m_origin; const AZ::Vector3 pvec = dir.Cross(edge2); // if determinant is near zero, ray lies in plane of triangle @@ -155,7 +155,7 @@ namespace MCore } // calculate distance from vert0 to ray origin - const AZ::Vector3 tvec = mOrigin - p1; + const AZ::Vector3 tvec = m_origin - p1; // calculate U parameter and test bounds const float inv_det = 1.0f / det; @@ -193,7 +193,7 @@ namespace MCore } if (intersect) { - *intersect = mOrigin + t * dir; + *intersect = m_origin + t * dir; } // yes, there was an intersection @@ -212,10 +212,10 @@ namespace MCore // For all three axes, check the near and far intersection point on the two slabs for (int32 i = 0; i < 3; i++) { - if (Math::Abs(mDirection.GetElement(i)) < Math::epsilon) + if (Math::Abs(m_direction.GetElement(i)) < Math::epsilon) { // direction is parallel to this plane, check if we're somewhere between min and max - if ((mOrigin.GetElement(i) < minVec.GetElement(i)) || (mOrigin.GetElement(i) > maxVec.GetElement(i))) + if ((m_origin.GetElement(i) < minVec.GetElement(i)) || (m_origin.GetElement(i) > maxVec.GetElement(i))) { return false; } @@ -223,8 +223,8 @@ namespace MCore else { // calculate t's at the near and far slab, see if these are min or max t's - float t1 = (minVec.GetElement(i) - mOrigin.GetElement(i)) / mDirection.GetElement(i); - float t2 = (maxVec.GetElement(i) - mOrigin.GetElement(i)) / mDirection.GetElement(i); + float t1 = (minVec.GetElement(i) - m_origin.GetElement(i)) / m_direction.GetElement(i); + float t2 = (maxVec.GetElement(i) - m_origin.GetElement(i)) / m_direction.GetElement(i); if (t1 > t2) { float temp = t1; @@ -248,12 +248,12 @@ namespace MCore if (intersectA) { - *intersectA = mOrigin + mDirection * tNear; + *intersectA = m_origin + m_direction * tNear; } if (intersectB) { - *intersectB = mOrigin + mDirection * tFar; + *intersectB = m_origin + m_direction * tFar; } return true; diff --git a/Gems/EMotionFX/Code/MCore/Source/Ray.h b/Gems/EMotionFX/Code/MCore/Source/Ray.h index f5fa779bd2..1d5bec0f43 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Ray.h +++ b/Gems/EMotionFX/Code/MCore/Source/Ray.h @@ -46,9 +46,9 @@ namespace MCore * @param endPoint The end (destination) point of the ray. */ MCORE_INLINE Ray(const AZ::Vector3& org, const AZ::Vector3& endPoint) - : mOrigin(org) - , mDest(endPoint) - , mDirection((endPoint - org).GetNormalized()) {} + : m_origin(org) + , m_dest(endPoint) + , m_direction((endPoint - org).GetNormalized()) {} /** * Constructor which sets the origin, destination point and direction. @@ -57,9 +57,9 @@ namespace MCore * @param dir The normalized direction vector of the ray, which should be (endPoint - startPoint).Normalize() */ MCORE_INLINE Ray(const AZ::Vector3& org, const AZ::Vector3& endPoint, const AZ::Vector3& dir) - : mOrigin(org) - , mDest(endPoint) - , mDirection(dir) {} + : m_origin(org) + , m_dest(endPoint) + , m_direction(dir) {} /** * Set the origin and destination point (end point) of the ray. @@ -67,37 +67,37 @@ namespace MCore * @param org The origin of the ray, so the start point. * @param endPoint The destination of the ray, so the end point. */ - MCORE_INLINE void Set(const AZ::Vector3& org, const AZ::Vector3& endPoint) { mOrigin = org; mDest = endPoint; mDirection = (mDest - mOrigin).GetNormalized(); } + MCORE_INLINE void Set(const AZ::Vector3& org, const AZ::Vector3& endPoint) { m_origin = org; m_dest = endPoint; m_direction = (m_dest - m_origin).GetNormalized(); } /** * Set the origin of the ray, so the start point. The direction will automatically be updated as well. * @param org The origin. */ - MCORE_INLINE void SetOrigin(const AZ::Vector3& org) { mOrigin = org; mDirection = (mDest - mOrigin).GetNormalized(); } + MCORE_INLINE void SetOrigin(const AZ::Vector3& org) { m_origin = org; m_direction = (m_dest - m_origin).GetNormalized(); } /** * Set the destination point of the ray. * @param dest The destination of the ray. */ - MCORE_INLINE void SetDest(const AZ::Vector3& dest) { mDest = dest; mDirection = (mDest - mOrigin).GetNormalized(); } + MCORE_INLINE void SetDest(const AZ::Vector3& dest) { m_dest = dest; m_direction = (m_dest - m_origin).GetNormalized(); } /** * Get the origin of the ray. * @result The origin of the ray, so where it starts. */ - MCORE_INLINE const AZ::Vector3& GetOrigin() const { return mOrigin; } + MCORE_INLINE const AZ::Vector3& GetOrigin() const { return m_origin; } /** * Get the destination of the ray. * @result The destination point of the ray, so where it ends. */ - MCORE_INLINE const AZ::Vector3& GetDest() const { return mDest; } + MCORE_INLINE const AZ::Vector3& GetDest() const { return m_dest; } /** * Get the direction of the ray. * @result The normalized direction vector of the ray, so the direction its heading to. */ - MCORE_INLINE const AZ::Vector3& GetDirection() const { return mDirection; } + MCORE_INLINE const AZ::Vector3& GetDirection() const { return m_direction; } /** * Perform a ray/sphere intersection test. @@ -161,11 +161,11 @@ namespace MCore * Calculates the length of the ray. * @result The length of the ray. */ - MCORE_INLINE float Length() const { return SafeLength(mDest - mOrigin); } + MCORE_INLINE float Length() const { return SafeLength(m_dest - m_origin); } private: - AZ::Vector3 mOrigin; /**< The origin of the ray. */ - AZ::Vector3 mDest; /**< The destination of the ray. */ - AZ::Vector3 mDirection; /**< The normalized direction vector of the ray. */ + AZ::Vector3 m_origin; /**< The origin of the ray. */ + AZ::Vector3 m_dest; /**< The destination of the ray. */ + AZ::Vector3 m_direction; /**< The normalized direction vector of the ray. */ }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/MCore/Source/ReflectionSerializer.cpp b/Gems/EMotionFX/Code/MCore/Source/ReflectionSerializer.cpp index 7dbbfcdcd6..b13260b01f 100644 --- a/Gems/EMotionFX/Code/MCore/Source/ReflectionSerializer.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/ReflectionSerializer.cpp @@ -363,8 +363,8 @@ namespace MCore bool ReflectionSerializer::Deserialize(const AZ::TypeId& classTypeId, void* classPtr, const MCore::CommandLine& sourceCommandLine) { bool someError = false; - const uint32 numParameters = sourceCommandLine.GetNumParameters(); - for (uint32 i = 0; i < numParameters; ++i) + const size_t numParameters = sourceCommandLine.GetNumParameters(); + for (size_t i = 0; i < numParameters; ++i) { someError |= !DeserializeIntoMember(classTypeId, classPtr, sourceCommandLine.GetParameterName(i).c_str(), sourceCommandLine.GetParameterValue(i).c_str()); } diff --git a/Gems/EMotionFX/Code/MCore/Source/SmallArray.h b/Gems/EMotionFX/Code/MCore/Source/SmallArray.h index 69e3219b7f..ab94cabbfe 100644 --- a/Gems/EMotionFX/Code/MCore/Source/SmallArray.h +++ b/Gems/EMotionFX/Code/MCore/Source/SmallArray.h @@ -36,32 +36,32 @@ class SmallArray * Default constructor. * Initializes the array so it's empty and has no memory allocated. */ - MCORE_INLINE SmallArray() : mData(nullptr), mLength(0) {} + MCORE_INLINE SmallArray() : m_data(nullptr), m_length(0) {} /** * Constructor which creates a given number of elements. * @param elems The element data. * @param num The number of elements in 'elems'. */ - MCORE_INLINE explicit SmallArray(T* elems, uint32 num) : mLength(num) { mData = (T*)MCore::Allocate(mLength * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); for (uint32 i=0; i 0) { mData = (T*)MCore::Allocate(mLength * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); for (uint32 i=0; i 0) { m_data = (T*)MCore::Allocate(m_length * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); for (uint32 i=0; i& other) : mData(nullptr), mLength(0) { *this = other; } + SmallArray(const SmallArray& other) : m_data(nullptr), m_length(0) { *this = other; } /** * Move constructor. * @param other The array to move the data from. */ - SmallArray(SmallArray&& other) { mData=other.mData; mLength=other.mLength; other.mData=nullptr; other.mLength=0; } + SmallArray(SmallArray&& other) { m_data=other.m_data; m_length=other.m_length; other.m_data=nullptr; other.m_length=0; } /** * Destructor. Deletes all entry data. @@ -80,143 +80,143 @@ class SmallArray * data.Clear(); *
*/ - ~SmallArray() { for (uint32 i=0; i); return result; } + MCORE_INLINE uint32 CalcMemoryUsage(bool includeMembers=true) const { uint32 result = m_length*sizeof(T); if (includeMembers) result+=sizeof(MCore::SmallArray); return result; } /** * Set a given element to a given value. * @param pos The element number. * @param value The value to store at that element number. */ - MCORE_INLINE void SetElem(uint32 pos, const T& value) { mData[pos] = value; } + MCORE_INLINE void SetElem(uint32 pos, const T& value) { m_data[pos] = value; } /** * Add a given element to the back of the array. * @param x The element to add. */ - MCORE_INLINE void Add(const T& x) { Grow(++mLength); Construct(mLength-1, x); } + MCORE_INLINE void Add(const T& x) { Grow(++m_length); Construct(m_length-1, x); } /** * Add a given array to the back of this array. * @param a The array to add. */ - MCORE_INLINE void Add(const SmallArray& a) { uint32 l=mLength; Grow(mLength+a.mLength); for (uint32 i=0; i& a) { uint32 l=m_length; Grow(m_length+a.m_length); for (uint32 i=0; i 0) Remove((uint32)0); } + MCORE_INLINE void RemoveFirst() { if (m_length > 0) Remove((uint32)0); } /** * Remove the last array element. */ - MCORE_INLINE void RemoveLast() { if (mLength > 0) Destruct(--mLength); } + MCORE_INLINE void RemoveLast() { if (m_length > 0) Destruct(--m_length); } /** * Insert an empty element (default constructed) at a given position in the array. * @param pos The position to create the empty element. */ - MCORE_INLINE void Insert(uint32 pos) { Grow(mLength+1); MoveElements(pos+1, pos, mLength-pos-1); Construct(pos); } + MCORE_INLINE void Insert(uint32 pos) { Grow(m_length+1); MoveElements(pos+1, pos, m_length-pos-1); Construct(pos); } /** * Insert a given element at a given position in the array. * @param pos The position to insert the empty element. * @param x The element to store at this position. */ - MCORE_INLINE void Insert(uint32 pos, const T& x) { Grow(mLength+1); MoveElements(pos+1, pos, mLength-pos-1); Construct(pos, x); } + MCORE_INLINE void Insert(uint32 pos, const T& x) { Grow(m_length+1); MoveElements(pos+1, pos, m_length-pos-1); Construct(pos, x); } /** * Remove an element at a given position. * @param pos The element number to remove. */ - MCORE_INLINE void Remove(uint32 pos) { Destruct(pos); MoveElements(pos, pos+1, mLength-pos-1); mLength--; } + MCORE_INLINE void Remove(uint32 pos) { Destruct(pos); MoveElements(pos, pos+1, m_length-pos-1); m_length--; } /** * Remove a given number of elements starting at a given position in the array. * @param pos The start element, so to start removing from. * @param num The number of elements to remove from this position. */ - MCORE_INLINE void Remove(uint32 pos, uint32 num) { for (uint32 i=pos; i * ABGDEF [this is the result. G has been moved to the empty position]. */ - MCORE_INLINE void SwapRemove(uint32 pos) { Destruct(pos); if (pos != mLength-1) { Construct(pos, mData[mLength-1]); Destruct(mLength-1); } mLength--; } // remove element at and place the last element of the array in that position + MCORE_INLINE void SwapRemove(uint32 pos) { Destruct(pos); if (pos != m_length-1) { Construct(pos, m_data[m_length-1]); Destruct(m_length-1); } m_length--; } // remove element at and place the last element of the array in that position /** * Swap two elements. @@ -247,19 +247,19 @@ class SmallArray * @param clearMem If set to true (default) the allocated memory will also be released. If set to false, GetMaxLength() will still return the number of elements * which the array contained before calling the Clear() method. */ - MCORE_INLINE void Clear(bool clearMem=true) { for (uint32 i=0; i= newLength) return; uint32 oldLen=mLength; Grow(newLength); for (uint32 i=oldLen; i= newLength) return; uint32 oldLen=m_length; Grow(newLength); for (uint32 i=oldLen; i mLength) + if (newLength > m_length) { // growing array, construct empty elements at end of array - uint32 oldLen = mLength; + uint32 oldLen = m_length; GrowExact(newLength); - if (mData == nullptr) + if (m_data == nullptr) { return false; } @@ -329,10 +329,10 @@ class SmallArray else { // shrinking array, destruct elements at end of array - for (uint32 i=newLength; i 0) - MCore::MemMove(mData+destIndex, mData+sourceIndex, numElements * sizeof(T)); + MCore::MemMove(m_data+destIndex, m_data+sourceIndex, numElements * sizeof(T)); } // operators - bool operator==(const SmallArray& other) const { if (mLength != other.mLength) return false; for (uint32 i=0; i& operator= (const SmallArray& other) { if (&other != this) { Clear(); Grow(other.mLength); for (uint32 i=0; i& operator= (SmallArray&& other) { MCORE_ASSERT(&other != this); if (mData!=nullptr) MCore::Free(mData); mData=other.mData; mLength=other.mLength; other.mData=nullptr; other.mLength=0; return *this; } - //SmallArray& operator+ (const SmallArray& other) const { SmallArray newArray; newArray.Grow(mLength+other.mLength); uint32 i; for (i=0; i& other) const { if (m_length != other.m_length) return false; for (uint32 i=0; i& operator= (const SmallArray& other) { if (&other != this) { Clear(); Grow(other.m_length); for (uint32 i=0; i& operator= (SmallArray&& other) { MCORE_ASSERT(&other != this); if (m_data!=nullptr) MCore::Free(m_data); m_data=other.m_data; m_length=other.m_length; other.m_data=nullptr; other.m_length=0; return *this; } SmallArray& operator+=(const T& other) { Add(other); return *this; } SmallArray& operator+=(const SmallArray& other) { Add(other); return *this; } - MCORE_INLINE T& operator[](const uint32 index) { MCORE_ASSERT(indexFree(); return; } - if (mData) - mData = (T*)MCore::Realloc(mData, newSize * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); + if (m_data) + m_data = (T*)MCore::Realloc(m_data, newSize * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); else - mData = (T*)MCore::Allocate(newSize * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); + m_data = (T*)MCore::Allocate(newSize * sizeof(T), MCORE_MEMCATEGORY_SMALLARRAY, MEMORYBLOCK_ID, MCORE_FILE, MCORE_LINE); } - MCORE_INLINE void Free() { mLength=0; if (mData) MCore::Free(mData); mData=nullptr; } - MCORE_INLINE void Construct(uint32 index, const T& original) { ::new(mData+index) T(original); } // copy-construct an element at which is a copy of - MCORE_INLINE void Construct(uint32 index) { ::new(mData+index) T; } // construct an element at place + MCORE_INLINE void Free() { m_length=0; if (m_data) MCore::Free(m_data); m_data=nullptr; } + MCORE_INLINE void Construct(uint32 index, const T& original) { ::new(m_data+index) T(original); } // copy-construct an element at which is a copy of + MCORE_INLINE void Construct(uint32 index) { ::new(m_data+index) T; } // construct an element at place MCORE_INLINE void Destruct(uint32 index) { #if (MCORE_COMPILER == MCORE_COMPILER_MSVC) // work around a compiler bug, marking this index parameter as unused MCORE_UNUSED(index); #endif - (mData+index)->~T(); + (m_data+index)->~T(); } // destruct an element at // partition part of array (for sorting) int32 Partition(int32 left, int32 right, CmpFunc cmp) { - ::MCore::Swap(mData[left], mData[ (left+right)>>1 ]); + ::MCore::Swap(m_data[left], m_data[ (left+right)>>1 ]); - T& target = mData[right]; + T& target = m_data[right]; int32 i = left-1; int32 j = right; bool neverQuit = true; // workaround to disable a "warning C4127: conditional expression is constant" while (neverQuit) { - while (i < j) { if (cmp(mData[++i], target) >= 0) break; } - while (j > i) { if (cmp(mData[--j], target) <= 0) break; } + while (i < j) { if (cmp(m_data[++i], target) >= 0) break; } + while (j > i) { if (cmp(m_data[--j], target) <= 0) break; } if (i >= j) break; - ::MCore::Swap(mData[i], mData[j]); + ::MCore::Swap(m_data[i], m_data[j]); } - ::MCore::Swap(mData[i], mData[right]); + ::MCore::Swap(m_data[i], m_data[right]); return i; } }; diff --git a/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp b/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp index 249ba8e77d..c6b84a9e04 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp @@ -46,7 +46,7 @@ namespace MCore AzFramework::StringFunc::TrimWhiteSpace(nameWithoutLastDigits, false /* leading */, true /* trailing */); // generate the unique name - uint32 nameIndex = 0; + size_t nameIndex = 0; AZStd::string uniqueName = nameWithoutLastDigits + "0"; while (validationFunction(uniqueName) == false) { diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp index 7c934084ce..643258373b 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.cpp @@ -29,14 +29,13 @@ namespace MCore { Lock(); - const size_t numStrings = mStrings.size(); - for (size_t i = 0; i < numStrings; ++i) + for (AZStd::basic_string*& string : m_strings) { - delete mStrings[i]; + delete string; } - mStrings.clear(); + m_strings.clear(); - mStringToIndex.clear(); + m_stringToIndex.clear(); Unlock(); } @@ -44,7 +43,7 @@ namespace MCore AZ::u32 StringIdPool::GenerateIdForStringWithoutLock(const AZStd::string& objectName) { // Try to insert it, if we hit a collision, we have the element. - auto iterator = mStringToIndex.emplace(objectName, static_cast(mStrings.size())); + auto iterator = m_stringToIndex.emplace(objectName, aznumeric_caster(m_strings.size())); if (!iterator.second) { // could not insert, we have the element @@ -53,7 +52,7 @@ namespace MCore // Create the new string object and push it to the string list. AZStd::string* newString = new AZStd::string(objectName); - mStrings.push_back(newString); + m_strings.push_back(newString); // The string was already added to the hashmap return iterator.first->second; @@ -69,20 +68,11 @@ namespace MCore } - const AZStd::string& StringIdPool::GetName(uint32 id) + const AZStd::string& StringIdPool::GetName(AZ::u32 id) { Lock(); - MCORE_ASSERT(id != MCORE_INVALIDINDEX32); - const AZStd::string* stringAddress = mStrings[id]; - Unlock(); - return *stringAddress; - } - - const AZStd::string& StringIdPool::GetStringById(AZ::u32 id) - { - Lock(); - MCORE_ASSERT(id != MCORE_INVALIDINDEX32); - AZStd::string* stringAddress = mStrings[id]; + MCORE_ASSERT(id != InvalidIndex32); + const AZStd::string* stringAddress = m_strings[id]; Unlock(); return *stringAddress; } @@ -91,7 +81,7 @@ namespace MCore void StringIdPool::Reserve(size_t numStrings) { Lock(); - mStrings.reserve(numStrings); + m_strings.reserve(numStrings); Unlock(); } @@ -99,27 +89,27 @@ namespace MCore // Wait with execution until we can set the lock. void StringIdPool::Lock() { - mMutex.Lock(); + m_mutex.Lock(); } // Release the lock again. void StringIdPool::Unlock() { - mMutex.Unlock(); + m_mutex.Unlock(); } void StringIdPool::Log(bool includeEntries) { - AZ_Printf("EMotionFX", "StringIdPool: NumEntries=%d\n", mStrings.size()); + AZ_Printf("EMotionFX", "StringIdPool: NumEntries=%d\n", m_strings.size()); if (includeEntries) { - const size_t numStrings = mStrings.size(); + const size_t numStrings = m_strings.size(); for (size_t i = 0; i < numStrings; ++i) { - AZ_Printf("EMotionFX", " #%d: String='%s', Id=%d\n", i, mStrings[i]->c_str(), GenerateIdForString(mStrings[i]->c_str())); + AZ_Printf("EMotionFX", " #%d: String='%s', Id=%d\n", i, m_strings[i]->c_str(), GenerateIdForString(m_strings[i]->c_str())); } } } @@ -132,8 +122,8 @@ namespace MCore size_t Save(const void* classPtr, AZ::IO::GenericStream& stream, bool /*isDataBigEndian = false*/) { // Look up the string to save - const uint32 index = static_cast(classPtr)->m_index; - if (index == MCORE_INVALIDINDEX32) + const AZ::u32 index = static_cast(classPtr)->m_index; + if (index == InvalidIndex32) { return 0; } @@ -158,7 +148,7 @@ namespace MCore /// Convert binary data to text. size_t DataToText(AZ::IO::GenericStream& in, AZ::IO::GenericStream& out, bool /*isDataBigEndian = false*/) { - size_t dataSize = static_cast(in.GetLength()); + AZ::u64 dataSize = in.GetLength(); AZStd::string outText; outText.resize(dataSize); diff --git a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h index 30ea434331..75bbc1b010 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h +++ b/Gems/EMotionFX/Code/MCore/Source/StringIdPool.h @@ -50,14 +50,7 @@ namespace MCore * @param id The unique id to search for the name. * @return The name of the given object. */ - const AZStd::string& GetName(uint32 id); - - /** - * Return the name of the given id. - * @param id The unique id to search for the name. - * @return The name of the given object. - */ - const AZStd::string& GetStringById(AZ::u32 id); + const AZStd::string& GetName(AZ::u32 id); /** * Reserve space for a given amount of strings. @@ -73,9 +66,9 @@ namespace MCore private: - AZStd::vector mStrings; - AZStd::unordered_map mStringToIndex; /**< The string to index table, where the index maps into mNames array and is directly the ID. */ - Mutex mMutex; /**< The multithread lock. */ + AZStd::vector m_strings; + AZStd::unordered_map m_stringToIndex; /**< The string to index table, where the index maps into m_names array and is directly the ID. */ + Mutex m_mutex; /**< The multithread lock. */ StringIdPool(); ~StringIdPool(); @@ -84,17 +77,15 @@ namespace MCore /** * The StringIdPoolIndex is a helper class to aid with serialization of * class members that store indexes into the StringIdPool. Members of this - * type will serialize to a string, and deserialize to a uint32, while + * type will serialize to a string, and deserialize to a AZ::u32, while * allowing the StringIdPool to deduplicate the strings. */ struct StringIdPoolIndex { - AZ::u32 m_index; + AZ::u32 m_index{}; - StringIdPoolIndex() : m_index(0) {} - StringIdPoolIndex(uint32 index) : m_index(index) {} - operator uint32() const { return m_index; } - bool operator==(uint32 rhs) const { return m_index == rhs; } + operator AZ::u32() const { return m_index; } + bool operator==(AZ::u32 rhs) const { return m_index == rhs; } static void Reflect(AZ::ReflectContext* context); }; @@ -104,4 +95,4 @@ namespace MCore namespace AZ { AZ_TYPE_INFO_SPECIALIZE(MCore::StringIdPoolIndex, "{C374F051-8323-49DB-A1BD-C6B6CF0333C0}") -} +} // namespace AZ diff --git a/Gems/EMotionFX/Code/MCore/mcore_files.cmake b/Gems/EMotionFX/Code/MCore/mcore_files.cmake index b0d8a67ccd..47b35e004b 100644 --- a/Gems/EMotionFX/Code/MCore/mcore_files.cmake +++ b/Gems/EMotionFX/Code/MCore/mcore_files.cmake @@ -8,12 +8,10 @@ set(FILES Source/AABB.h - Source/AbstractData.h Source/Algorithms.cpp Source/Algorithms.h Source/Algorithms.inl Source/AlignedArray.h - Source/Array.h Source/Array2D.h Source/Array2D.inl Source/Attribute.cpp @@ -78,9 +76,6 @@ set(FILES Source/File.h Source/FileSystem.cpp Source/FileSystem.h - Source/HashFunctions.h - Source/HashTable.h - Source/HashTable.inl Source/IDGenerator.cpp Source/IDGenerator.h Source/LogManager.cpp @@ -101,9 +96,6 @@ set(FILES Source/MemoryTracker.cpp Source/MemoryTracker.h Source/MultiThreadManager.h - Source/OBB.cpp - Source/OBB.h - Source/OBB.inl Source/PlaneEq.cpp Source/PlaneEq.h Source/PlaneEq.inl diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp index 75d97fa065..27f83b07a3 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.cpp @@ -8,6 +8,8 @@ // include the required headers #include "DialogStack.h" +#include "AzCore/std/iterator.h" +#include "AzCore/std/limits.h" #include "MysticQtManager.h" #include #include @@ -50,45 +52,23 @@ namespace MysticQt }; - // the constructor - DialogStack::Dialog::Dialog() - { - mButton = nullptr; - mFrame = nullptr; - mWidget = nullptr; - mDialogWidget = nullptr; - mSplitter = nullptr; - mClosable = true; - } - - - // destructor - DialogStack::Dialog::~Dialog() - { - delete mDialogWidget; - } - - // the constructor DialogStack::DialogStack(QWidget* parent) : QScrollArea(parent) { - // set the memory category of the dialog array - mDialogs.SetMemoryCategory(MEMCATEGORY_MYSTICQT); - // set the object name setObjectName("DialogStack"); // create the root splitter - mRootSplitter = new DialogStackSplitter(); - mRootSplitter->setOrientation(Qt::Vertical); - mRootSplitter->setChildrenCollapsible(false); + m_rootSplitter = new DialogStackSplitter(); + m_rootSplitter->setOrientation(Qt::Vertical); + m_rootSplitter->setChildrenCollapsible(false); // set the widget resizable to have the scrollarea resizing it setWidgetResizable(true); // set the scrollarea widget - setWidget(mRootSplitter); + setWidget(m_rootSplitter); } @@ -102,7 +82,7 @@ namespace MysticQt void DialogStack::Clear() { // destroy the dialogs - mDialogs.Clear(); + m_dialogs.clear(); // update the scroll bars UpdateScrollBars(); @@ -122,11 +102,11 @@ namespace MysticQt // add the dialog widget // the splitter is hierarchical : {a, {b, c}} - QSplitter* dialogSplitter; - if (mDialogs.GetLength() == 0) + DialogStackSplitter* dialogSplitter; + if (m_dialogs.empty()) { // add the dialog widget - dialogSplitter = mRootSplitter; + dialogSplitter = m_rootSplitter; dialogSplitter->addWidget(dialogWidget); // stretch if needed @@ -138,10 +118,10 @@ namespace MysticQt else { // check if one space is free on the last splitter - if (mDialogs.GetLast().mSplitter->count() == 1) + if (m_dialogs.back().m_splitter->count() == 1) { // add the dialog widget - dialogSplitter = mDialogs.GetLast().mSplitter; + dialogSplitter = m_dialogs.back().m_splitter; dialogSplitter->addWidget(dialogWidget); // stretch if needed @@ -151,16 +131,16 @@ namespace MysticQt } // less space used by the splitter when the last dialog is closed - if (mDialogs.GetLast().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { - mDialogs.GetLast().mSplitter->handle(1)->setFixedHeight(1); - mDialogs.GetLast().mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); + m_dialogs.back().m_splitter->handle(1)->setFixedHeight(1); + m_dialogs.back().m_splitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); } // disable the splitter - if (mDialogs.GetLast().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { - mDialogs.GetLast().mSplitter->handle(1)->setDisabled(true); + m_dialogs.back().m_splitter->handle(1)->setDisabled(true); } } else // already two dialogs in the splitter @@ -171,24 +151,24 @@ namespace MysticQt dialogSplitter->setChildrenCollapsible(false); // add the current last dialog and the new dialog after - dialogSplitter->addWidget(mDialogs.GetLast().mDialogWidget); + dialogSplitter->addWidget(m_dialogs.back().m_dialogWidget); dialogSplitter->addWidget(dialogWidget); // stretch if needed - if (mDialogs.GetLast().mMaximizeSize && mDialogs.GetLast().mStretchWhenMaximize) + if (m_dialogs.back().m_maximizeSize && m_dialogs.back().m_stretchWhenMaximize) { dialogSplitter->setStretchFactor(0, 1); } // less space used by the splitter when the last dialog is closed - if (mDialogs.GetLast().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { dialogSplitter->handle(1)->setFixedHeight(1); dialogSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); } // disable the splitter - if (mDialogs.GetLast().mFrame->isHidden()) + if (m_dialogs.back().m_frame->isHidden()) { dialogSplitter->handle(1)->setDisabled(true); } @@ -200,24 +180,27 @@ namespace MysticQt } // replace the last dialog by the new splitter - mDialogs.GetLast().mSplitter->addWidget(dialogSplitter); + m_dialogs.back().m_splitter->addWidget(dialogSplitter); // disable the splitter - const uint32 lastDialogIndex = mDialogs.GetLength() - 1; - if (mDialogs[lastDialogIndex - 1].mFrame->isHidden()) + if (m_dialogs.size() > 1) { - mDialogs.GetLast().mSplitter->handle(1)->setDisabled(true); - } + const auto previousDialogIt = m_dialogs.end() - 2; + if (previousDialogIt->m_frame->isHidden()) + { + m_dialogs.back().m_splitter->handle(1)->setDisabled(true); + } - // stretch the splitter if needed - // the correct behavior is found after experimentations - if ((mDialogs.GetLast().mMaximizeSize && mDialogs.GetLast().mStretchWhenMaximize) || (mDialogs[lastDialogIndex - 1].mMaximizeSize && mDialogs[lastDialogIndex - 1].mStretchWhenMaximize == false)) - { - mDialogs.GetLast().mSplitter->setStretchFactor(1, 1); + // stretch the splitter if needed + // the correct behavior is found after experimentations + if ((m_dialogs.back().m_maximizeSize && m_dialogs.back().m_stretchWhenMaximize) || (previousDialogIt->m_maximizeSize && previousDialogIt->m_stretchWhenMaximize == false)) + { + m_dialogs.back().m_splitter->setStretchFactor(1, 1); + } } // set the new splitter of the last dialog - mDialogs.GetLast().mSplitter = dialogSplitter; + m_dialogs.back().m_splitter = dialogSplitter; } } @@ -280,17 +263,20 @@ namespace MysticQt dialogWidget->adjustSize(); // register it, so that we know which frame is linked to which header button - mDialogs.AddEmpty(); - mDialogs.GetLast().mButton = headerButton; - mDialogs.GetLast().mFrame = frame; - mDialogs.GetLast().mWidget = widget; - mDialogs.GetLast().mDialogWidget = dialogWidget; - mDialogs.GetLast().mSplitter = dialogSplitter; - mDialogs.GetLast().mClosable = closable; - mDialogs.GetLast().mMaximizeSize = maximizeSize; - mDialogs.GetLast().mStretchWhenMaximize = stretchWhenMaximize; - mDialogs.GetLast().mLayout = layout; - mDialogs.GetLast().mDialogLayout = dialogLayout; + m_dialogs.emplace_back(Dialog{ + /*.m_button =*/ headerButton, + /*.m_frame =*/ frame, + /*.m_widget =*/ widget, + /*.m_dialogWidget =*/ dialogWidget, + /*.m_splitter =*/ dialogSplitter, + /*.m_closable =*/ closable, + /*.m_maximizeSize =*/ maximizeSize, + /*.m_stretchWhenMaximize =*/ stretchWhenMaximize, + /*.m_minimumHeightBeforeClose =*/ 0, + /*.m_maximumHeightBeforeClose =*/ 0, + /*.m_layout =*/ layout, + /*.m_dialogLayout =*/ dialogLayout, + }); // check if the dialog is closed if (closed) @@ -319,32 +305,27 @@ namespace MysticQt bool DialogStack::Remove(QWidget* widget) { - const uint32 numDialogs = mDialogs.GetLength(); - for (uint32 i = 0; i < numDialogs; ++i) + const auto foundDialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [widget](const Dialog& dialog) { - QLayout* layout = mDialogs[i].mFrame->layout(); - int index = layout->indexOf(widget); + return dialog.m_frame->layout()->indexOf(widget) != -1; + }); - // if the widget is located in the current layout, remove it - // all next dialogs has to be moved to the previous splitter and delete if the last splitter is empty - if (index != -1) - { - // remove the dialog - // TODO : shift all dialogs needed as explained on the previous comment - mDialogs[i].mDialogWidget->hide(); - mDialogs[i].mDialogWidget->deleteLater(); - mDialogs.Remove(i); + if (foundDialog == end(m_dialogs)) + { + return false; + } - // update the scroll bars - UpdateScrollBars(); + // if the widget is located in the current layout, remove it + // all next dialogs has to be moved to the previous splitter and delete if the last splitter is empty + // TODO : shift all dialogs needed as explained on the previous comment + foundDialog->m_dialogWidget->hide(); + foundDialog->m_dialogWidget->deleteLater(); + m_dialogs.erase(foundDialog); - // done - return true; - } - } + // update the scroll bars + UpdateScrollBars(); - // not found - return false; + return true; } @@ -352,8 +333,8 @@ namespace MysticQt void DialogStack::OnHeaderButton() { QPushButton* button = (QPushButton*)sender(); - const uint32 dialogIndex = FindDialog(button); - if (mDialogs[dialogIndex].mFrame->isHidden()) + const size_t dialogIndex = FindDialog(button); + if (m_dialogs[dialogIndex].m_frame->isHidden()) { Open(button); } @@ -365,87 +346,85 @@ namespace MysticQt // find the dialog that goes with the given button - uint32 DialogStack::FindDialog(QPushButton* pushButton) + size_t DialogStack::FindDialog(QPushButton* pushButton) { - const uint32 numDialogs = mDialogs.GetLength(); - for (uint32 i = 0; i < numDialogs; ++i) + const auto foundDialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [pushButton](const Dialog& dialog) { - if (mDialogs[i].mButton == pushButton) - { - return i; - } - } - return MCORE_INVALIDINDEX32; + return dialog.m_button == pushButton; + }); + return foundDialog != end(m_dialogs) ? AZStd::distance(begin(m_dialogs), foundDialog) : MCore::InvalidIndex; } // open the dialog void DialogStack::Open(QPushButton* button) { - // find the dialog index - const uint32 dialogIndex = FindDialog(button); - if (dialogIndex == MCORE_INVALIDINDEX32) + const auto dialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [button](const Dialog& dialog) + { + return dialog.m_button == button; + }); + if (dialog == end(m_dialogs)) { return; } // show the widget inside the dialog - mDialogs[dialogIndex].mFrame->show(); + dialog->m_frame->show(); // set the previous minimum and maximum height before closed - mDialogs[dialogIndex].mDialogWidget->setMinimumHeight(mDialogs[dialogIndex].mMinimumHeightBeforeClose); - mDialogs[dialogIndex].mDialogWidget->setMaximumHeight(mDialogs[dialogIndex].mMaximumHeightBeforeClose); + dialog->m_dialogWidget->setMinimumHeight(dialog->m_minimumHeightBeforeClose); + dialog->m_dialogWidget->setMaximumHeight(dialog->m_maximumHeightBeforeClose); // change the stylesheet and the icon button->setStyleSheet(""); button->setIcon(GetMysticQt()->FindIcon("Images/Icons/ArrowDownGray.png")); // more space used by the splitter when the dialog is open - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialog != m_dialogs.end() - 1) { - mDialogs[dialogIndex].mSplitter->handle(1)->setFixedHeight(4); - mDialogs[dialogIndex].mSplitter->setStyleSheet("QSplitter::handle{ height: 4px; background: transparent; }"); + dialog->m_splitter->handle(1)->setFixedHeight(4); + dialog->m_splitter->setStyleSheet("QSplitter::handle{ height: 4px; background: transparent; }"); } // enable the splitter - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialog != m_dialogs.end() - 1) { - mDialogs[dialogIndex].mSplitter->handle(1)->setEnabled(true); + dialog->m_splitter->handle(1)->setEnabled(true); } // maximize the size if it's needed - if (mDialogs.GetLength() > 1) + if (m_dialogs.size() > 1) { - if (mDialogs[dialogIndex].mMaximizeSize) + if (dialog->m_maximizeSize) { // special case if it's the first dialog - if (dialogIndex == 0) + if (dialog == m_dialogs.begin()) { // if it's the first dialog and stretching is enabled, it expand to the max, all others expand to the min - if (mDialogs[dialogIndex].mStretchWhenMaximize == false && mDialogs[dialogIndex + 1].mMaximizeSize && mDialogs[dialogIndex + 1].mFrame->isHidden() == false) + if (dialog->m_stretchWhenMaximize == false && (dialog + 1)->m_maximizeSize && (dialog + 1)->m_frame->isHidden() == false) { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMin(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMin(); } else { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMax(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMax(); } } else // not the first dialog { // set the previous dialog to the min to have this dialog expanded to the top - if (mDialogs[dialogIndex - 1].mFrame->isHidden() || mDialogs[dialogIndex - 1].mMaximizeSize == false || (mDialogs[dialogIndex - 1].mMaximizeSize && mDialogs[dialogIndex - 1].mStretchWhenMaximize == false)) + if ((dialog - 1)->m_frame->isHidden() || (dialog - 1)->m_maximizeSize == false || ((dialog - 1)->m_maximizeSize && (dialog - 1)->m_stretchWhenMaximize == false)) { - static_cast(mDialogs[dialogIndex - 1].mSplitter)->MoveFirstSplitterToMin(); + static_cast((dialog - 1)->m_splitter)->MoveFirstSplitterToMin(); } // special case if it's not the last dialog - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialog != m_dialogs.end() - 1) { // if the next dialog is closed, it's needed to expand to the max too - if (mDialogs[dialogIndex + 1].mFrame->isHidden()) + if ((dialog + 1)->m_frame->isHidden()) { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMax(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMax(); } } } @@ -460,67 +439,58 @@ namespace MysticQt // close the dialog void DialogStack::Close(QPushButton* button) { - // find the dialog index - const uint32 dialogIndex = FindDialog(button); - if (dialogIndex == MCORE_INVALIDINDEX32) + const auto dialog = AZStd::find_if(begin(m_dialogs), end(m_dialogs), [button](const Dialog& dialog) + { + return dialog.m_button == button; + }); + if (dialog == end(m_dialogs)) { return; } // only closable dialog can be closed - if (mDialogs[dialogIndex].mClosable == false) + if (dialog->m_closable == false) { return; } // keep the min and max height before close - mDialogs[dialogIndex].mMinimumHeightBeforeClose = mDialogs[dialogIndex].mDialogWidget->minimumHeight(); - mDialogs[dialogIndex].mMaximumHeightBeforeClose = mDialogs[dialogIndex].mDialogWidget->maximumHeight(); + dialog->m_minimumHeightBeforeClose = dialog->m_dialogWidget->minimumHeight(); + dialog->m_maximumHeightBeforeClose = dialog->m_dialogWidget->maximumHeight(); // hide the widget inside the dialog - mDialogs[dialogIndex].mFrame->hide(); + dialog->m_frame->hide(); // set the widget to fixed size to not have it possible to resize - mDialogs[dialogIndex].mDialogWidget->setMinimumHeight(mDialogs[dialogIndex].mButton->height()); - mDialogs[dialogIndex].mDialogWidget->setMaximumHeight(mDialogs[dialogIndex].mButton->height()); + dialog->m_dialogWidget->setMinimumHeight(dialog->m_button->height()); + dialog->m_dialogWidget->setMaximumHeight(dialog->m_button->height()); // change the stylesheet and the icon button->setStyleSheet("border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; border: 1px solid rgb(40,40,40);"); // TODO: link to the real style sheets button->setIcon(GetMysticQt()->FindIcon("Images/Icons/ArrowRightGray.png")); // less space used by the splitter when the dialog is closed - if (dialogIndex < (mDialogs.GetLength() - 1)) - { - mDialogs[dialogIndex].mSplitter->handle(1)->setFixedHeight(1); - mDialogs[dialogIndex].mSplitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); - } - - // disable the splitter - if (dialogIndex < (mDialogs.GetLength() - 1)) - { - mDialogs[dialogIndex].mSplitter->handle(1)->setDisabled(true); - } - - // set the first splitter to the min if needed - if (dialogIndex < (mDialogs.GetLength() - 1)) + if (dialog < m_dialogs.end() - 1) { - static_cast(mDialogs[dialogIndex].mSplitter)->MoveFirstSplitterToMin(); + dialog->m_splitter->handle(1)->setFixedHeight(1); + dialog->m_splitter->setStyleSheet("QSplitter::handle{ height: 1px; background: transparent; }"); + dialog->m_splitter->handle(1)->setDisabled(true); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMin(); } // maximize the first needed to avoid empty space bool findPreviousMaximizedDialogNeeded = true; - const uint32 numDialogs = mDialogs.GetLength(); - for (uint32 i = dialogIndex + 1; i < numDialogs; ++i) + for (auto curDialog = dialog + 1; curDialog != m_dialogs.end(); ++curDialog) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + if (curDialog->m_maximizeSize && curDialog->m_frame->isHidden() == false) { - if (i < (numDialogs - 1) && mDialogs[i + 1].mFrame->isHidden()) + if (curDialog != (m_dialogs.end() - 1) && (curDialog + 1)->m_frame->isHidden()) { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMax(); + static_cast(curDialog->m_splitter)->MoveFirstSplitterToMax(); } else { - static_cast(mDialogs[i - 1].mSplitter)->MoveFirstSplitterToMin(); + static_cast((curDialog - 1)->m_splitter)->MoveFirstSplitterToMin(); } findPreviousMaximizedDialogNeeded = false; break; @@ -528,11 +498,11 @@ namespace MysticQt } if (findPreviousMaximizedDialogNeeded) { - for (int32 i = dialogIndex - 1; i >= 0; --i) + for (auto curDialog = AZStd::make_reverse_iterator(dialog) + 1; curDialog != m_dialogs.rend(); ++curDialog) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + if (curDialog->m_maximizeSize && curDialog->m_frame->isHidden() == false) { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMax(); + static_cast(curDialog->m_splitter)->MoveFirstSplitterToMax(); break; } } @@ -549,8 +519,8 @@ namespace MysticQt if (event->buttons() & Qt::LeftButton) { // keep the mouse pos - mPrevMouseX = event->globalX(); - mPrevMouseY = event->globalY(); + m_prevMouseX = event->globalX(); + m_prevMouseY = event->globalY(); // set the cursor if the scrollbar is visible if ((horizontalScrollBar()->maximum() > 0) || (verticalScrollBar()->maximum() > 0)) @@ -596,8 +566,8 @@ namespace MysticQt } // calculate the delta mouse movement - const int32 deltaX = event->globalX() - mPrevMouseX; - const int32 deltaY = event->globalY() - mPrevMouseY; + const int32 deltaX = event->globalX() - m_prevMouseX; + const int32 deltaY = event->globalY() - m_prevMouseY; // now apply this delta movement to the scroller int32 newX = horizontalScrollBar()->value() - deltaX; @@ -606,8 +576,8 @@ namespace MysticQt verticalScrollBar()->setSliderPosition(newY); // store the current value as previous value - mPrevMouseX = event->globalX(); - mPrevMouseY = event->globalY(); + m_prevMouseX = event->globalX(); + m_prevMouseY = event->globalY(); } @@ -636,16 +606,15 @@ namespace MysticQt QScrollArea::resizeEvent(event); // maximize the first dialog needed - const uint32 numDialogs = mDialogs.GetLength(); - const int32 lastDialogIndex = static_cast(numDialogs) - 1; - for (int32 i = lastDialogIndex; i >= 0; --i) + if (m_dialogs.empty() || m_dialogs.size() == 1) { - if (mDialogs[i].mMaximizeSize && mDialogs[i].mFrame->isHidden() == false) + return; + } + for (auto dialog = m_dialogs.rbegin() + 1; dialog != m_dialogs.rend(); ++dialog) + { + if (dialog->m_maximizeSize && dialog->m_frame->isHidden() == false) { - if (i < lastDialogIndex) - { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMax(); - } + static_cast(dialog->m_splitter)->MoveFirstSplitterToMax(); break; } } @@ -655,54 +624,54 @@ namespace MysticQt // replace an internal widget void DialogStack::ReplaceWidget(QWidget* oldWidget, QWidget* newWidget) { - for (uint32 i = 0; i < mDialogs.GetLength(); ++i) + for (auto dialog = m_dialogs.begin(); dialog != m_dialogs.end(); ++dialog) { // go next if the widget is not the same - if (mDialogs[i].mWidget != oldWidget) + if (dialog->m_widget != oldWidget) { continue; } // replace the widget - mDialogs[i].mFrame->layout()->replaceWidget(oldWidget, newWidget); - mDialogs[i].mWidget = newWidget; + dialog->m_frame->layout()->replaceWidget(oldWidget, newWidget); + dialog->m_widget = newWidget; // adjust size of the new widget newWidget->adjustSize(); // set the constraints - if (mDialogs[i].mMaximizeSize == false) + if (dialog->m_maximizeSize == false) { // get margins - const QMargins frameMargins = mDialogs[i].mLayout->contentsMargins(); - const QMargins dialogMargins = mDialogs[i].mDialogLayout->contentsMargins(); + const QMargins frameMargins = dialog->m_layout->contentsMargins(); + const QMargins dialogMargins = dialog->m_dialogLayout->contentsMargins(); const int frameMarginTopBottom = frameMargins.top() + frameMargins.bottom(); const int dialogMarginTopBottom = dialogMargins.top() + dialogMargins.bottom(); const int allMarginsTopBottom = frameMarginTopBottom + dialogMarginTopBottom; // set the frame height - mDialogs[i].mFrame->setFixedHeight(newWidget->height() + frameMarginTopBottom); + dialog->m_frame->setFixedHeight(newWidget->height() + frameMarginTopBottom); // compute the dialog height - const int dialogHeight = newWidget->height() + allMarginsTopBottom + mDialogs[i].mButton->height(); + const int dialogHeight = newWidget->height() + allMarginsTopBottom + dialog->m_button->height(); // set the maximum height in case the dialog is not closed, if it's closed update the stored height - if (mDialogs[i].mFrame->isHidden() == false) + if (dialog->m_frame->isHidden() == false) { // set the dialog height - mDialogs[i].mDialogWidget->setFixedHeight(dialogHeight); + dialog->m_dialogWidget->setFixedHeight(dialogHeight); // set the first splitter to the min if needed - if (i < (mDialogs.GetLength() - 1)) + if (dialog != m_dialogs.end() - 1) { - static_cast(mDialogs[i].mSplitter)->MoveFirstSplitterToMin(); + static_cast(dialog->m_splitter)->MoveFirstSplitterToMin(); } } else // dialog closed { // update the minimum and maximum stored height - mDialogs[i].mMinimumHeightBeforeClose = dialogHeight; - mDialogs[i].mMaximumHeightBeforeClose = dialogHeight; + dialog->m_minimumHeightBeforeClose = dialogHeight; + dialog->m_maximumHeightBeforeClose = dialogHeight; } } diff --git a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h index ddd0796a6d..bf93b5d23f 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/DialogStack.h @@ -14,7 +14,7 @@ #include "MysticQtConfig.h" #include #include -#include +#include #endif // forward declarations @@ -28,6 +28,8 @@ QT_FORWARD_DECLARE_CLASS(QSplitter) namespace MysticQt { + class DialogStackSplitter; + /** * * @@ -36,7 +38,6 @@ namespace MysticQt : public QScrollArea { Q_OBJECT - MCORE_MEMORYOBJECTCATEGORY(DialogStack, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); public: DialogStack(QWidget* parent = nullptr); @@ -61,34 +62,31 @@ namespace MysticQt private: struct Dialog { - MCORE_MEMORYOBJECTCATEGORY(DialogStack::Dialog, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); - Dialog(); - ~Dialog(); - QPushButton* mButton; - QWidget* mFrame; - QWidget* mWidget; - QWidget* mDialogWidget; - QSplitter* mSplitter; - bool mClosable; - bool mMaximizeSize; - bool mStretchWhenMaximize; - int mMinimumHeightBeforeClose; - int mMaximumHeightBeforeClose; - QLayout* mLayout; - QLayout* mDialogLayout; + QPushButton* m_button = nullptr; + QWidget* m_frame = nullptr; + QWidget* m_widget = nullptr; + QWidget* m_dialogWidget = nullptr; + DialogStackSplitter* m_splitter = nullptr; + bool m_closable = true; + bool m_maximizeSize = false; + bool m_stretchWhenMaximize = false; + int m_minimumHeightBeforeClose = 0; + int m_maximumHeightBeforeClose = 0; + QLayout* m_layout = nullptr; + QLayout* m_dialogLayout = nullptr; }; private: - uint32 FindDialog(QPushButton* pushButton); + size_t FindDialog(QPushButton* pushButton); void Open(QPushButton* button); void Close(QPushButton* button); void UpdateScrollBars(); private: - QSplitter* mRootSplitter; - MCore::Array mDialogs; - int32 mPrevMouseX; - int32 mPrevMouseY; + DialogStackSplitter* m_rootSplitter; + AZStd::vector m_dialogs; + int32 m_prevMouseX; + int32 m_prevMouseY; }; } // namespace MysticQt diff --git a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp index 8fa5850407..6b381bf9d8 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp @@ -163,7 +163,7 @@ namespace MysticQt // iterate through the groups and save all actions for them for (const AZStd::unique_ptr& group : m_groups) { - settings->beginGroup(QString::fromUtf8(group->GetName().data(), static_cast(group->GetName().size()))); + settings->beginGroup(QString::fromUtf8(group->GetName().data(), aznumeric_caster(group->GetName().size()))); // iterate through the actions and save them for (const AZStd::unique_ptr& action : group->GetActions()) diff --git a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp index 4020fd66ff..537ad6bedd 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.cpp @@ -22,7 +22,7 @@ namespace MysticQt // constructor MysticQtManager::MysticQtManager() { - mMainWindow = nullptr; + m_mainWindow = nullptr; } @@ -30,12 +30,11 @@ namespace MysticQt MysticQtManager::~MysticQtManager() { // get the number of icons and destroy them - const uint32 numIcons = mIcons.GetLength(); - for (uint32 i = 0; i < numIcons; ++i) + for (IconData* icon : m_icons) { - delete mIcons[i]; + delete icon; } - mIcons.Clear(); + m_icons.clear(); } @@ -43,34 +42,33 @@ namespace MysticQt // constructor MysticQtManager::IconData::IconData(const char* filename) { - mFileName = filename; - mIcon = new QIcon(QDir{ QString(GetMysticQt()->GetDataDir().c_str()) }.filePath(filename)); + m_fileName = filename; + m_icon = new QIcon(QDir{ QString(GetMysticQt()->GetDataDir().c_str()) }.filePath(filename)); } // destructor MysticQtManager::IconData::~IconData() { - delete mIcon; + delete m_icon; } const QIcon& MysticQtManager::FindIcon(const char* filename) { // get the number of icons and iterate through them - const uint32 numIcons = mIcons.GetLength(); - for (uint32 i = 0; i < numIcons; ++i) + for (IconData* icon : m_icons) { - if (AzFramework::StringFunc::Equal(mIcons[i]->mFileName.c_str(), filename, false /* no case */)) + if (AzFramework::StringFunc::Equal(icon->m_fileName.c_str(), filename, false /* no case */)) { - return *(mIcons[i]->mIcon); + return *(icon->m_icon); } } // we haven't found it IconData* iconData = new IconData(filename); - mIcons.Add(iconData); - return *(iconData->mIcon); + m_icons.emplace_back(iconData); + return *(iconData->m_icon); } diff --git a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h index 8f7dad06bf..9c8a73b92f 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtManager.h @@ -12,7 +12,7 @@ // include required files #if !defined(Q_MOC_RUN) #include -#include +#include #include "MysticQtConfig.h" #include #endif @@ -36,28 +36,28 @@ namespace MysticQt MCORE_MEMORYOBJECTCATEGORY(MysticQtManager, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); public: - MCORE_INLINE QWidget* GetMainWindow() const { return mMainWindow; } - MCORE_INLINE void SetMainWindow(QWidget* mainWindow) { mMainWindow = mainWindow; } + MCORE_INLINE QWidget* GetMainWindow() const { return m_mainWindow; } + MCORE_INLINE void SetMainWindow(QWidget* mainWindow) { m_mainWindow = mainWindow; } MCORE_INLINE void SetAppDir(const char* appDir) { - mAppDir = appDir; - if (mDataDir.size() == 0) + m_appDir = appDir; + if (m_dataDir.size() == 0) { - mDataDir = appDir; + m_dataDir = appDir; } } - MCORE_INLINE const AZStd::string& GetAppDir() const { return mAppDir; } + MCORE_INLINE const AZStd::string& GetAppDir() const { return m_appDir; } MCORE_INLINE void SetDataDir(const char* dataDir) { - mDataDir = dataDir; - if (mAppDir.size() == 0) + m_dataDir = dataDir; + if (m_appDir.size() == 0) { - mAppDir = dataDir; + m_appDir = dataDir; } } - MCORE_INLINE const AZStd::string& GetDataDir() const { return mDataDir; } + MCORE_INLINE const AZStd::string& GetDataDir() const { return m_dataDir; } const QIcon& FindIcon(const char* filename); @@ -69,14 +69,14 @@ namespace MysticQt IconData(const char* filename); ~IconData(); - QIcon* mIcon; - AZStd::string mFileName; + QIcon* m_icon; + AZStd::string m_fileName; }; - QWidget* mMainWindow; - MCore::Array mIcons; - AZStd::string mAppDir; - AZStd::string mDataDir; + QWidget* m_mainWindow; + AZStd::vector m_icons; + AZStd::string m_appDir; + AZStd::string m_dataDir; MysticQtManager(); ~MysticQtManager(); diff --git a/Gems/EMotionFX/Code/MysticQt/Source/RecentFiles.cpp b/Gems/EMotionFX/Code/MysticQt/Source/RecentFiles.cpp index 78490a3b13..b5dfd2ead1 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/RecentFiles.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/RecentFiles.cpp @@ -27,7 +27,7 @@ namespace MysticQt ToolTipMenu(const QString title, QWidget* parent) : QMenu(title, parent) { - mParent = parent; + m_parent = parent; } bool event(QEvent* e) override @@ -40,7 +40,7 @@ namespace MysticQt QAction* action = activeAction(); if (action) { - QToolTip::showText(helpEvent->globalPos(), action->toolTip(), mParent); + QToolTip::showText(helpEvent->globalPos(), action->toolTip(), m_parent); } } else @@ -52,7 +52,7 @@ namespace MysticQt } private: - QWidget* mParent; + QWidget* m_parent; }; diff --git a/Gems/EMotionFX/Code/Platform/Common/FileOffsetType/MCore/Source/DiskFile_FileOffsetType.cpp b/Gems/EMotionFX/Code/Platform/Common/FileOffsetType/MCore/Source/DiskFile_FileOffsetType.cpp index e041afb417..1603f6326e 100644 --- a/Gems/EMotionFX/Code/Platform/Common/FileOffsetType/MCore/Source/DiskFile_FileOffsetType.cpp +++ b/Gems/EMotionFX/Code/Platform/Common/FileOffsetType/MCore/Source/DiskFile_FileOffsetType.cpp @@ -14,18 +14,18 @@ namespace MCore // returns the position (offset) in the file in bytes size_t DiskFile::GetPos() const { - MCORE_ASSERT(mFile); + MCORE_ASSERT(m_file); - return ftello(mFile); + return ftello(m_file); } // seek a given number of bytes ahead from it's current position bool DiskFile::Forward(size_t numBytes) { - MCORE_ASSERT(mFile); + MCORE_ASSERT(m_file); - if (fseeko(mFile, numBytes, SEEK_CUR) != 0) + if (fseeko(m_file, numBytes, SEEK_CUR) != 0) { return false; } @@ -36,9 +36,9 @@ namespace MCore // seek to an absolute position in the file (offset in bytes) bool DiskFile::Seek(size_t offset) { - MCORE_ASSERT(mFile); + MCORE_ASSERT(m_file); - if (fseeko(mFile, offset, SEEK_SET) != 0) + if (fseeko(m_file, offset, SEEK_SET) != 0) { return false; } @@ -49,8 +49,8 @@ namespace MCore // returns the filesize in bytes size_t DiskFile::GetFileSize() const { - MCORE_ASSERT(mFile); - if (mFile == nullptr) + MCORE_ASSERT(m_file); + if (m_file == nullptr) { return 0; } @@ -59,13 +59,13 @@ namespace MCore size_t curPos = GetPos(); // seek to the end of the file - fseeko(mFile, 0, SEEK_END); + fseeko(m_file, 0, SEEK_END); // get the position, whis is the size of the file size_t fileSize = GetPos(); // seek back to the original position - fseeko(mFile, curPos, SEEK_SET); + fseeko(m_file, curPos, SEEK_SET); // return the size of the file return fileSize; diff --git a/Gems/EMotionFX/Code/Platform/Common/WinAPI/MCore/Source/DiskFile_WinAPI.cpp b/Gems/EMotionFX/Code/Platform/Common/WinAPI/MCore/Source/DiskFile_WinAPI.cpp index 14a73bf3f5..6cafebeff5 100644 --- a/Gems/EMotionFX/Code/Platform/Common/WinAPI/MCore/Source/DiskFile_WinAPI.cpp +++ b/Gems/EMotionFX/Code/Platform/Common/WinAPI/MCore/Source/DiskFile_WinAPI.cpp @@ -14,18 +14,18 @@ namespace MCore // returns the position (offset) in the file in bytes size_t DiskFile::GetPos() const { - MCORE_ASSERT(mFile); + MCORE_ASSERT(m_file); - return _ftelli64(mFile); + return _ftelli64(m_file); } // seek a given number of bytes ahead from it's current position bool DiskFile::Forward(size_t numBytes) { - MCORE_ASSERT(mFile); + MCORE_ASSERT(m_file); - if (_fseeki64(mFile, numBytes, SEEK_CUR) != 0) + if (_fseeki64(m_file, numBytes, SEEK_CUR) != 0) { return false; } @@ -36,9 +36,9 @@ namespace MCore // seek to an absolute position in the file (offset in bytes) bool DiskFile::Seek(size_t offset) { - MCORE_ASSERT(mFile); + MCORE_ASSERT(m_file); - if (_fseeki64(mFile, offset, SEEK_SET) != 0) + if (_fseeki64(m_file, offset, SEEK_SET) != 0) { return false; } @@ -49,8 +49,8 @@ namespace MCore // returns the filesize in bytes size_t DiskFile::GetFileSize() const { - MCORE_ASSERT(mFile); - if (mFile == nullptr) + MCORE_ASSERT(m_file); + if (m_file == nullptr) { return 0; } @@ -59,13 +59,13 @@ namespace MCore size_t curPos = GetPos(); // seek to the end of the file - _fseeki64(mFile, 0, SEEK_END); + _fseeki64(m_file, 0, SEEK_END); // get the position, whis is the size of the file size_t fileSize = GetPos(); // seek back to the original position - _fseeki64(mFile, curPos, SEEK_SET); + _fseeki64(m_file, curPos, SEEK_SET); // return the size of the file return fileSize; diff --git a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp index fb359eb671..41253a513e 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.cpp @@ -64,7 +64,6 @@ namespace EMStudio m_previouslySelectedJoints = m_selectedJoints; m_jointSelectionWindow = new NodeSelectionWindow(this, m_singleJointSelection); - connect(m_jointSelectionWindow->GetNodeHierarchyWidget(), qOverload>(&NodeHierarchyWidget::OnSelectionDone), this, &ActorJointBrowseEdit::OnSelectionDoneMCoreArray); connect(m_jointSelectionWindow, &NodeSelectionWindow::rejected, this, &ActorJointBrowseEdit::OnSelectionRejected); connect(m_jointSelectionWindow->GetNodeHierarchyWidget()->GetTreeWidget(), &QTreeWidget::itemSelectionChanged, this, &ActorJointBrowseEdit::OnSelectionChanged); @@ -118,12 +117,6 @@ namespace EMStudio emit SelectionDone(selectedJoints); } - void ActorJointBrowseEdit::OnSelectionDoneMCoreArray(const MCore::Array& selectedJoints) - { - AZStd::vector convertedSelection = FromMCoreArray(selectedJoints); - OnSelectionDone(convertedSelection); - } - void ActorJointBrowseEdit::OnSelectionChanged() { if (m_jointSelectionWindow) @@ -161,8 +154,8 @@ namespace EMStudio EMotionFX::Actor* actor = selectionList.GetSingleActor(); if (actor) { - const uint32 numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); - for (uint32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = EMotionFX::GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { EMotionFX::ActorInstance* actorInstance2 = EMotionFX::GetActorManager().GetActorInstance(i); if (actorInstance2->GetActor() == actor) @@ -175,15 +168,4 @@ namespace EMStudio return nullptr; } - AZStd::vector ActorJointBrowseEdit::FromMCoreArray(const MCore::Array& in) const - { - const AZ::u32 numItems = in.GetLength(); - AZStd::vector result(static_cast(numItems)); - for (AZ::u32 i = 0; i < numItems; ++i) - { - result[static_cast(i)] = in[i]; - } - - return result; - } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.h b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.h index 770c000b1b..adae07dfc2 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.h +++ b/Gems/EMotionFX/Code/Source/Editor/ActorJointBrowseEdit.h @@ -51,7 +51,6 @@ namespace EMStudio private slots: void OnBrowseButtonClicked(); void OnSelectionDone(const AZStd::vector& selectedJoints); - void OnSelectionDoneMCoreArray(const MCore::Array& selectedJoints); void OnSelectionChanged(); void OnSelectionRejected(); void OnTextEdited(const QString& text); @@ -59,8 +58,6 @@ namespace EMStudio private: void UpdatePlaceholderText(); - AZStd::vector FromMCoreArray(const MCore::Array& in) const; - AZStd::vector m_previouslySelectedJoints; /// Selected joints before selection window opened. AZStd::vector m_selectedJoints; NodeSelectionWindow* m_jointSelectionWindow = nullptr; diff --git a/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp b/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp index d62e82f438..fea4f23c6a 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/ColliderContainerWidget.cpp @@ -553,7 +553,7 @@ namespace EMotionFX for (size_t i = numColliders; i < numAvailableColliderWidgets; ++i) { m_colliderWidgets[i]->hide(); - m_colliderWidgets[i]->Update(nullptr, nullptr, MCORE_INVALIDINDEX32, PhysicsSetup::ColliderConfigType::Unknown, AzPhysics::ShapeColliderPair()); + m_colliderWidgets[i]->Update(nullptr, nullptr, InvalidIndex, PhysicsSetup::ColliderConfigType::Unknown, AzPhysics::ShapeColliderPair()); } } @@ -616,13 +616,13 @@ namespace EMotionFX EMStudio::EMStudioPlugin::RenderInfo* renderInfo, const MCore::RGBAColor& colliderColor) { - const AZ::u32 nodeIndex = node->GetNodeIndex(); - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + const size_t nodeIndex = node->GetNodeIndex(); + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; for (const auto& collider : colliders) { #ifndef EMFX_SCALE_DISABLED - const AZ::Vector3& worldScale = actorInstance->GetTransformData()->GetCurrentPose()->GetModelSpaceTransform(nodeIndex).mScale; + const AZ::Vector3& worldScale = actorInstance->GetTransformData()->GetCurrentPose()->GetModelSpaceTransform(nodeIndex).m_scale; #else const AZ::Vector3 worldScale = AZ::Vector3::CreateOne(); #endif @@ -677,15 +677,15 @@ namespace EMotionFX return; } - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; const bool oldLightingEnabled = renderUtil->GetLightingEnabled(); renderUtil->EnableLighting(false); - const AZStd::unordered_set& selectedJointIndices = EMStudio::GetManager()->GetSelectedJointIndices(); + const AZStd::unordered_set& selectedJointIndices = EMStudio::GetManager()->GetSelectedJointIndices(); const ActorManager* actorManager = GetEMotionFX().GetActorManager(); - const AZ::u32 actorInstanceCount = actorManager->GetNumActorInstances(); - for (AZ::u32 i = 0; i < actorInstanceCount; ++i) + const size_t actorInstanceCount = actorManager->GetNumActorInstances(); + for (size_t i = 0; i < actorInstanceCount; ++i) { const ActorInstance* actorInstance = actorManager->GetActorInstance(i); const Actor* actor = actorInstance->GetActor(); diff --git a/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.cpp b/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.cpp index b8cf69f2cb..b5db607c50 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.cpp @@ -13,7 +13,7 @@ namespace EMotionFX { - const int ObjectEditor::m_propertyLabelWidth = 160; + const int ObjectEditor::s_propertyLabelWidth = 160; ObjectEditor::ObjectEditor(AZ::SerializeContext* serializeContext, QWidget* parent) : ObjectEditor(serializeContext, nullptr, parent) @@ -30,7 +30,7 @@ namespace EMotionFX m_propertyEditor = aznew AzToolsFramework::ReflectedPropertyEditor(this); m_propertyEditor->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Maximum); m_propertyEditor->setObjectName("PropertyEditor"); - m_propertyEditor->Setup(serializeContext, notify, false/*enableScrollbars*/, m_propertyLabelWidth); + m_propertyEditor->Setup(serializeContext, notify, false/*enableScrollbars*/, s_propertyLabelWidth); QVBoxLayout* mainLayout = new QVBoxLayout(this); mainLayout->setSizeConstraint(QLayout::SetMinimumSize); diff --git a/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.h b/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.h index a726170b98..c76dc3b88f 100644 --- a/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.h +++ b/Gems/EMotionFX/Code/Source/Editor/ObjectEditor.h @@ -47,6 +47,6 @@ namespace EMotionFX private: void* m_object; AzToolsFramework::ReflectedPropertyEditor* m_propertyEditor; - static const int m_propertyLabelWidth; + static const int s_propertyLabelWidth; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.cpp index 0b806ebc00..861100b073 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/Cloth/ClothJointInspectorPlugin.cpp @@ -65,13 +65,13 @@ namespace EMotionFX scrollArea->setWidget(m_jointWidget); scrollArea->setWidgetResizable(true); - mDock->setWidget(scrollArea); + m_dock->setWidget(scrollArea); EMotionFX::SkeletonOutlinerNotificationBus::Handler::BusConnect(); } else { - mDock->setWidget(CreateErrorContentWidget("Cloth collider editor depends on the NVIDIA Cloth gem. Please enable it in the project configurator.")); + m_dock->setWidget(CreateErrorContentWidget("Cloth collider editor depends on the NVIDIA Cloth gem. Please enable it in the project configurator.")); } return true; diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/HitDetection/HitDetectionJointInspectorPlugin.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/HitDetection/HitDetectionJointInspectorPlugin.cpp index d0578306ab..c69fdd9393 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/HitDetection/HitDetectionJointInspectorPlugin.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/HitDetection/HitDetectionJointInspectorPlugin.cpp @@ -51,13 +51,13 @@ namespace EMotionFX scrollArea->setWidget(m_nodeWidget); scrollArea->setWidgetResizable(true); - mDock->setWidget(scrollArea); + m_dock->setWidget(scrollArea); EMotionFX::SkeletonOutlinerNotificationBus::Handler::BusConnect(); } else { - mDock->setWidget(CreateErrorContentWidget("Hit detection collider editor depends on the PhysX gem. Please enable it in the project configurator.")); + m_dock->setWidget(CreateErrorContentWidget("Hit detection collider editor depends on the PhysX gem. Please enable it in the project configurator.")); } return true; diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp index bda6e68449..5324950c82 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.cpp @@ -80,13 +80,13 @@ namespace EMotionFX scrollArea->setWidget(m_nodeWidget); scrollArea->setWidgetResizable(true); - mDock->setWidget(scrollArea); + m_dock->setWidget(scrollArea); EMotionFX::SkeletonOutlinerNotificationBus::Handler::BusConnect(); } else { - mDock->setWidget(CreateErrorContentWidget("Ragdoll editor depends on the PhysX gem. Please enable it in the project configurator.")); + m_dock->setWidget(CreateErrorContentWidget("Ragdoll editor depends on the PhysX gem. Please enable it in the project configurator.")); } return true; @@ -432,12 +432,12 @@ namespace EMotionFX return; } - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; const bool oldLightingEnabled = renderUtil->GetLightingEnabled(); renderUtil->EnableLighting(false); - const AZ::u32 actorInstanceCount = GetActorManager().GetNumActorInstances(); - for (AZ::u32 i = 0; i < actorInstanceCount; ++i) + const size_t actorInstanceCount = GetActorManager().GetNumActorInstances(); + for (size_t i = 0; i < actorInstanceCount; ++i) { ActorInstance* actorInstance = GetActorManager().GetActorInstance(i); RenderRagdoll(actorInstance, renderColliders, renderJointLimits, renderPlugin, renderInfo); @@ -451,7 +451,7 @@ namespace EMotionFX { const Actor* actor = actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); - const AZ::u32 numNodes = skeleton->GetNumNodes(); + const size_t numNodes = skeleton->GetNumNodes(); const AZStd::shared_ptr& physicsSetup = actor->GetPhysicsSetup(); const Physics::RagdollConfiguration& ragdollConfig = physicsSetup->GetRagdollConfig(); const AZStd::vector& ragdollNodes = ragdollConfig.m_nodes; @@ -462,12 +462,12 @@ namespace EMotionFX const MCore::RGBAColor defaultColor = renderOptions->GetRagdollColliderColor(); const MCore::RGBAColor selectedColor = renderOptions->GetSelectedRagdollColliderColor(); - const AZStd::unordered_set& selectedJointIndices = EMStudio::GetManager()->GetSelectedJointIndices(); + const AZStd::unordered_set& selectedJointIndices = EMStudio::GetManager()->GetSelectedJointIndices(); - for (AZ::u32 nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) + for (size_t nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) { const Node* joint = skeleton->GetNode(nodeIndex); - const AZ::u32 jointIndex = joint->GetNodeIndex(); + const size_t jointIndex = joint->GetNodeIndex(); AZ::Outcome ragdollNodeIndex = AZ::Failure(); if (ragdollInstance) @@ -535,12 +535,12 @@ namespace EMotionFX { const EMStudio::RenderOptions* renderOptions = renderPlugin->GetRenderOptions(); const MCore::RGBAColor violatedColor = renderOptions->GetViolatedJointLimitColor(); - const AZ::u32 nodeIndex = node->GetNodeIndex(); - const AZ::u32 parentNodeIndex = parentNode->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); + const size_t parentNodeIndex = parentNode->GetNodeIndex(); const Transform& actorInstanceWorldTransform = actorInstance->GetWorldSpaceTransform(); const Pose* currentPose = actorInstance->GetTransformData()->GetCurrentPose(); - const AZ::Quaternion& parentOrientation = currentPose->GetModelSpaceTransform(parentNodeIndex).mRotation; - const AZ::Quaternion& childOrientation = currentPose->GetModelSpaceTransform(nodeIndex).mRotation; + const AZ::Quaternion& parentOrientation = currentPose->GetModelSpaceTransform(parentNodeIndex).m_rotation; + const AZ::Quaternion& childOrientation = currentPose->GetModelSpaceTransform(nodeIndex).m_rotation; m_vertexBuffer.clear(); m_indexBuffer.clear(); @@ -554,10 +554,10 @@ namespace EMotionFX } Transform jointModelSpaceTransform = currentPose->GetModelSpaceTransform(parentNodeIndex); - jointModelSpaceTransform.mPosition = currentPose->GetModelSpaceTransform(nodeIndex).mPosition; + jointModelSpaceTransform.m_position = currentPose->GetModelSpaceTransform(nodeIndex).m_position; const Transform jointGlobalTransformNoScale = jointModelSpaceTransform * actorInstanceWorldTransform; - MCommon::RenderUtil* renderUtil = renderInfo->mRenderUtil; + MCommon::RenderUtil* renderUtil = renderInfo->m_renderUtil; const size_t numLineBufferEntries = m_lineBuffer.size(); if (m_lineValidityBuffer.size() * 2 != numLineBufferEntries) { @@ -588,6 +588,6 @@ namespace EMotionFX const Transform childModelSpaceTransform = childJointLocalSpaceTransform * currentPose->GetModelSpaceTransform(node->GetNodeIndex()); const Transform jointChildWorldSpaceTransformNoScale = (childModelSpaceTransform * actorInstanceWorldSpaceTransform); - renderInfo->mRenderUtil->RenderArrow(0.1f, jointChildWorldSpaceTransformNoScale.mPosition, MCore::GetRight(jointChildWorldSpaceTransformNoScale.ToAZTransform()), color); + renderInfo->m_renderUtil->RenderArrow(0.1f, jointChildWorldSpaceTransformNoScale.m_position, MCore::GetRight(jointChildWorldSpaceTransformNoScale.ToAZTransform()), color); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.cpp index 978ee0a298..681008d979 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.cpp @@ -26,11 +26,11 @@ namespace EMStudio { setWindowTitle("SimulatedObject Selection Window"); - m_OKButton = new QPushButton("OK"); + m_okButton = new QPushButton("OK"); m_cancelButton = new QPushButton("Cancel"); QHBoxLayout* buttonLayout = new QHBoxLayout(); - buttonLayout->addWidget(m_OKButton); + buttonLayout->addWidget(m_okButton); buttonLayout->addWidget(m_cancelButton); QVBoxLayout* layout = new QVBoxLayout(this); @@ -38,7 +38,7 @@ namespace EMStudio layout->addWidget(m_simulatedObjectSelectionWidget); layout->addLayout(buttonLayout); - connect(m_OKButton, &QPushButton::clicked, this, &SimulatedObjectSelectionWindow::accept); + connect(m_okButton, &QPushButton::clicked, this, &SimulatedObjectSelectionWindow::accept); connect(m_cancelButton, &QPushButton::clicked, this, &SimulatedObjectSelectionWindow::reject); connect(m_simulatedObjectSelectionWidget, &SimulatedObjectSelectionWidget::OnDoubleClicked, this, &SimulatedObjectSelectionWindow::accept); } diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.h b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.h index 6411be5c98..d5bebb7abd 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.h +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectSelectionWindow.h @@ -33,7 +33,7 @@ namespace EMStudio private: SimulatedObjectSelectionWidget* m_simulatedObjectSelectionWidget = nullptr; - QPushButton* m_OKButton = nullptr; + QPushButton* m_okButton = nullptr; QPushButton* m_cancelButton = nullptr; bool m_accepted = false; }; diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp index aa222c0405..a2b23e3268 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/SimulatedObject/SimulatedObjectWidget.cpp @@ -84,7 +84,7 @@ namespace EMotionFX } else { - AZStd::unordered_set selectedJointIndices; + AZStd::unordered_set selectedJointIndices; for (const QModelIndex& index : selectedIndices) { const SimulatedJoint* joint = index.data(SimulatedObjectModel::ROLE_JOINT_PTR).value(); @@ -113,7 +113,7 @@ namespace EMotionFX connect(m_addSimulatedObjectButton, &QPushButton::clicked, this, [this]() { - m_actionManager->OnAddNewObjectAndAddJoints(m_actor, /*selectedJoints=*/{}, /*addChildJoints=*/false, mDock); + m_actionManager->OnAddNewObjectAndAddJoints(m_actor, /*selectedJoints=*/{}, /*addChildJoints=*/false, m_dock); }); AZ::SerializeContext* serializeContext; @@ -130,9 +130,9 @@ namespace EMotionFX mainLayout->addWidget(m_selectionWidget, /*stretch=*/1); mainLayout->addStretch(); - mDock->setWidget(m_mainWidget); + m_dock->setWidget(m_mainWidget); - m_simulatedObjectInspectorDock = new AzQtComponents::StyledDockWidget("Simulated Object Inspector", mDock); + m_simulatedObjectInspectorDock = new AzQtComponents::StyledDockWidget("Simulated Object Inspector", m_dock); m_simulatedObjectInspectorDock->setFeatures(QDockWidget::DockWidgetFloatable | QDockWidget::DockWidgetMovable); m_simulatedObjectInspectorDock->setObjectName("EMFX.SimulatedObjectWidget.SimulatedObjectInspectorDock"); m_simulatedJointWidget = new SimulatedJointWidget(this); @@ -361,7 +361,7 @@ namespace EMotionFX connect(addToSimulatedObjectMenu->addAction("New simulated object..."), &QAction::triggered, this, [this, selectedRowIndices]() { const bool addChildren = (QMessageBox::question(this->GetDockWidget(), "Add children of joints?", "Add all children of selected joints to the simulated object?") == QMessageBox::Yes); - m_actionManager->OnAddNewObjectAndAddJoints(m_actor, selectedRowIndices, addChildren, mDock); + m_actionManager->OnAddNewObjectAndAddJoints(m_actor, selectedRowIndices, addChildren, m_dock); }); menu->addSeparator(); @@ -451,7 +451,7 @@ namespace EMotionFX { CommandAddSimulatedJoints* addSimulatedJointsCommand = static_cast(command); const size_t objectIndex = addSimulatedJointsCommand->GetObjectIndex(); - const AZStd::vector& jointIndices = addSimulatedJointsCommand->GetJointIndices(); + const AZStd::vector& jointIndices = addSimulatedJointsCommand->GetJointIndices(); SimulatedObjectWidget* simulatedObjectPlugin = static_cast(EMStudio::GetPluginManager()->FindActivePlugin(SimulatedObjectWidget::CLASS_ID)); if (simulatedObjectPlugin) @@ -491,13 +491,13 @@ namespace EMotionFX } const bool renderSimulatedJoints = activeViewWidget->GetRenderFlag(EMStudio::RenderViewWidget::RENDER_SIMULATEJOINTS); - const AZStd::unordered_set& selectedJointIndices = EMStudio::GetManager()->GetSelectedJointIndices(); + const AZStd::unordered_set& selectedJointIndices = EMStudio::GetManager()->GetSelectedJointIndices(); if (renderSimulatedJoints && !selectedJointIndices.empty()) { // Render the joint radius. const MCore::RGBAColor defaultColor = renderPlugin->GetRenderOptions()->GetSelectedSimulatedObjectColliderColor(); - const AZ::u32 actorInstanceCount = GetActorManager().GetNumActorInstances(); - for (AZ::u32 actorInstanceIndex = 0; actorInstanceIndex < actorInstanceCount; ++actorInstanceIndex) + const size_t actorInstanceCount = GetActorManager().GetNumActorInstances(); + for (size_t actorInstanceIndex = 0; actorInstanceIndex < actorInstanceCount; ++actorInstanceIndex) { ActorInstance* actorInstance = GetActorManager().GetActorInstance(actorInstanceIndex); const Actor* actor = actorInstance->GetActor(); @@ -511,7 +511,7 @@ namespace EMotionFX for (size_t simulatedJointIndex = 0; simulatedJointIndex < simulatedJointCount; ++simulatedJointIndex) { const SimulatedJoint* simulatedJoint = object->GetSimulatedJoint(simulatedJointIndex); - const AZ::u32 skeletonJointIndex = simulatedJoint->GetSkeletonJointIndex(); + const size_t skeletonJointIndex = simulatedJoint->GetSkeletonJointIndex(); if (selectedJointIndices.find(skeletonJointIndex) != selectedJointIndices.end()) { RenderJointRadius(simulatedJoint, actorInstance, AZ::Color(1.0f, 0.0f, 1.0f, 1.0f)); @@ -536,7 +536,7 @@ namespace EMotionFX void SimulatedObjectWidget::RenderJointRadius(const SimulatedJoint* joint, ActorInstance* actorInstance, const AZ::Color& color) { #ifndef EMFX_SCALE_DISABLED - const float scale = actorInstance->GetWorldSpaceTransform().mScale.GetX(); + const float scale = actorInstance->GetWorldSpaceTransform().m_scale.GetX(); #else const float scale = 1.0f; #endif @@ -547,13 +547,13 @@ namespace EMotionFX return; } - AZ_Assert(joint->GetSkeletonJointIndex() != MCORE_INVALIDINDEX32, "Expected skeletal joint index to be valid."); + AZ_Assert(joint->GetSkeletonJointIndex() != InvalidIndex, "Expected skeletal joint index to be valid."); const EMotionFX::Transform jointTransform = actorInstance->GetTransformData()->GetCurrentPose()->GetWorldSpaceTransform(joint->GetSkeletonJointIndex()); DebugDraw& debugDraw = GetDebugDraw(); DebugDraw::ActorInstanceData* drawData = debugDraw.GetActorInstanceData(actorInstance); drawData->Lock(); - drawData->DrawWireframeSphere(jointTransform.mPosition, radius, color, jointTransform.mRotation, 12, 12); + drawData->DrawWireframeSphere(jointTransform.m_position, radius, color, jointTransform.m_rotation, 12, 12); drawData->Unlock(); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Editor/Plugins/SkeletonOutliner/SkeletonOutlinerPlugin.cpp b/Gems/EMotionFX/Code/Source/Editor/Plugins/SkeletonOutliner/SkeletonOutlinerPlugin.cpp index 949325f101..f8ca291d55 100644 --- a/Gems/EMotionFX/Code/Source/Editor/Plugins/SkeletonOutliner/SkeletonOutlinerPlugin.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/Plugins/SkeletonOutliner/SkeletonOutlinerPlugin.cpp @@ -42,7 +42,7 @@ namespace EMotionFX bool SkeletonOutlinerPlugin::Init() { - m_mainWidget = new QWidget(mDock); + m_mainWidget = new QWidget(m_dock); QVBoxLayout* mainLayout = new QVBoxLayout(); m_mainWidget->setLayout(mainLayout); @@ -112,7 +112,7 @@ namespace EMotionFX connect(m_searchWidget, &AzQtComponents::FilteredSearchWidget::TypeFilterChanged, this, &SkeletonOutlinerPlugin::OnTypeFilterChanged); mainLayout->addWidget(m_treeView); - mDock->setWidget(m_mainWidget); + m_dock->setWidget(m_mainWidget); EMotionFX::SkeletonOutlinerRequestBus::Handler::BusConnect(); Reinit(); diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp index a05fbc9fa3..9883b06e23 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/ActorGoalNodeHandler.cpp @@ -103,13 +103,13 @@ namespace EMotionFX } - MCore::Array actorInstanceIDs; + AZStd::vector actorInstanceIDs; // Add the current actor instance and all the ones it is attached to EMotionFX::ActorInstance* currentInstance = actorInstance; while (currentInstance) { - actorInstanceIDs.Add(currentInstance->GetID()); + actorInstanceIDs.emplace_back(currentInstance->GetID()); EMotionFX::Attachment* attachment = currentInstance->GetSelfAttachment(); if (attachment) { @@ -131,12 +131,12 @@ namespace EMotionFX if (newSelection.size() == 1) { AZStd::string selectedNodeName = newSelection[0].GetNodeName(); - AZ::u32 selectedActorInstanceId = newSelection[0].mActorInstanceID; + AZ::u32 selectedActorInstanceId = newSelection[0].m_actorInstanceId; - uint32 parentDepth = actorInstanceIDs.Find(selectedActorInstanceId); - AZ_Assert(parentDepth != MCORE_INVALIDINDEX32, "Cannot get parent depth. The selected actor instance was not shown in the selection window."); + const auto parentDepth = AZStd::find(begin(actorInstanceIDs), end(actorInstanceIDs), selectedActorInstanceId); + AZ_Assert(parentDepth != end(actorInstanceIDs), "Cannot get parent depth. The selected actor instance was not shown in the selection window."); - m_goalNode = AZStd::make_pair(selectedNodeName, parentDepth); + m_goalNode = {AZStd::move(selectedNodeName), static_cast(AZStd::distance(begin(actorInstanceIDs), parentDepth))}; UpdateInterface(); emit SelectionChanged(); diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphNodeHandler.cpp b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphNodeHandler.cpp index 06542e5fef..81c15d2f98 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphNodeHandler.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/AnimGraphNodeHandler.cpp @@ -113,7 +113,7 @@ namespace EMotionFX const AZStd::vector& selectedNodes = dialog.GetAnimGraphHierarchyWidget().GetSelectedItems(); if (!selectedNodes.empty()) { - AnimGraphNode* selectedNode = m_animGraph->RecursiveFindNodeByName(selectedNodes[0].mNodeName.c_str()); + AnimGraphNode* selectedNode = m_animGraph->RecursiveFindNodeByName(selectedNodes[0].m_nodeName.c_str()); if (selectedNode) { m_nodeId = selectedNode->GetId(); diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/BlendNParamWeightsHandler.cpp b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/BlendNParamWeightsHandler.cpp index 62b1af5250..7b615c22ce 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/BlendNParamWeightsHandler.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/BlendNParamWeightsHandler.cpp @@ -238,11 +238,11 @@ namespace EMotionFX const char* sourceNodeName = ""; for (const AnimGraphNode::Port& port : inputPorts) { - if (port.mConnection) + if (port.m_connection) { - if (port.mPortID == paramWeights[i].GetPortId()) + if (port.m_portId == paramWeights[i].GetPortId()) { - sourceNodeName = port.mConnection->GetSourceNode()->GetName(); + sourceNodeName = port.m_connection->GetSourceNode()->GetName(); } } } diff --git a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/LODSceneGraphWidget.h b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/LODSceneGraphWidget.h index 1ed9a8f67d..4905f8612d 100644 --- a/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/LODSceneGraphWidget.h +++ b/Gems/EMotionFX/Code/Source/Editor/PropertyWidgets/LODSceneGraphWidget.h @@ -40,7 +40,7 @@ namespace EMotionFX private: bool m_hideUncheckableItem; - Data::LodNodeSelectionList m_LODSelectionList; + Data::LodNodeSelectionList m_lodSelectionList; }; } } diff --git a/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectHelpers.cpp b/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectHelpers.cpp index 75a32444e2..2d87d6b603 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectHelpers.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectHelpers.cpp @@ -45,7 +45,7 @@ namespace EMotionFX } const Actor* actor = modelIndices[0].data(SkeletonModel::ROLE_ACTOR_POINTER).value(); - AZStd::vector jointIndices; + AZStd::vector jointIndices; for (const QModelIndex& selectedIndex : modelIndices) { @@ -68,7 +68,7 @@ namespace EMotionFX void SimulatedObjectHelpers::RemoveSimulatedJoints(const QModelIndexList& modelIndices, bool removeChildren) { - AZStd::unordered_map>> objectToSkeletonJointIndices; + AZStd::unordered_map>> objectToSkeletonJointIndices; for (const QModelIndex& index : modelIndices) { @@ -80,7 +80,7 @@ namespace EMotionFX } const Actor* actor = index.data(SimulatedObjectModel::ROLE_ACTOR_PTR).value(); const size_t objectIndex = static_cast(index.data(SimulatedObjectModel::ROLE_OBJECT_INDEX).toInt()); - const AZ::u32 jointIndex = index.data(SimulatedObjectModel::ROLE_JOINT_PTR).value()->GetSkeletonJointIndex(); + const size_t jointIndex = index.data(SimulatedObjectModel::ROLE_JOINT_PTR).value()->GetSkeletonJointIndex(); objectToSkeletonJointIndices[objectIndex].first = actor; objectToSkeletonJointIndices[objectIndex].second.emplace_back(jointIndex); } @@ -92,7 +92,7 @@ namespace EMotionFX { const size_t objectIndex = objectIndexAndJointIndices.first; const Actor* actor = objectIndexAndJointIndices.second.first; - const AZStd::vector jointIndices = objectIndexAndJointIndices.second.second; + const AZStd::vector jointIndices = objectIndexAndJointIndices.second.second; CommandSimulatedObjectHelpers::RemoveSimulatedJoints(actor->GetID(), jointIndices, objectIndex, removeChildren, &commandGroup); } diff --git a/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.cpp b/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.cpp index 452ba2798a..f04ca3fede 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.cpp @@ -171,7 +171,7 @@ namespace EMotionFX SimulatedJoint* parentJoint = childJoint->FindParentSimulatedJoint(); if (parentJoint) { - return createIndex(parentJoint->CalculateChildIndex(), 0, parentJoint); + return createIndex(aznumeric_caster(parentJoint->CalculateChildIndex()), 0, parentJoint); } else { @@ -377,7 +377,7 @@ namespace EMotionFX return QModelIndex(); } - void SimulatedObjectModel::AddJointsToSelection(QItemSelection& selection, size_t objectIndex, const AZStd::vector& jointIndices) + void SimulatedObjectModel::AddJointsToSelection(QItemSelection& selection, size_t objectIndex, const AZStd::vector& jointIndices) { if (!m_actor || !m_actor->GetSimulatedObjectSetup()) { @@ -392,12 +392,12 @@ namespace EMotionFX return; } - for (AZ::u32 jointIndex : jointIndices) + for (const size_t jointIndex : jointIndices) { SimulatedJoint* joint = object->FindSimulatedJointBySkeletonJointIndex(jointIndex); if (!joint) { - AZ_Warning("EMotionFX", false, "Simulated joint with joint index %d does not exist", jointIndex); + AZ_Warning("EMotionFX", false, "Simulated joint with joint index %zu does not exist", jointIndex); continue; } int row = static_cast(joint->CalculateChildIndex()); diff --git a/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.h b/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.h index 0873086850..46b9b811b3 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.h +++ b/Gems/EMotionFX/Code/Source/Editor/SimulatedObjectModel.h @@ -75,7 +75,7 @@ namespace EMotionFX QModelIndex GetModelIndexByObjectIndex(size_t objectIndex); QModelIndex FindModelIndex(SimulatedObject* object); - void AddJointsToSelection(QItemSelection& selection, size_t objectIndex, const AZStd::vector& jointIndices); + void AddJointsToSelection(QItemSelection& selection, size_t objectIndex, const AZStd::vector& jointIndices); private: // Command callbacks. diff --git a/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp index d71e0e1acf..49f68bcbc5 100644 --- a/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp +++ b/Gems/EMotionFX/Code/Source/Editor/SkeletonModel.cpp @@ -123,7 +123,7 @@ namespace EMotionFX return QModelIndex(); } - const AZ::u32 childNodeIndex = parentNode->GetChildIndex(row); + const size_t childNodeIndex = parentNode->GetChildIndex(row); Node* childNode = m_skeleton->GetNode(childNodeIndex); return createIndex(row, column, childNode); } @@ -135,7 +135,7 @@ namespace EMotionFX return QModelIndex(); } - const AZ::u32 rootNodeIndex = m_skeleton->GetRootNodeIndex(row); + const size_t rootNodeIndex = m_skeleton->GetRootNodeIndex(row); Node* rootNode = m_skeleton->GetNode(rootNodeIndex); return createIndex(row, column, rootNode); } @@ -157,8 +157,8 @@ namespace EMotionFX Node* grandParentNode = parentNode->GetParentNode(); if (grandParentNode) { - const AZ::u32 numChildNodes = grandParentNode->GetNumChildNodes(); - for (AZ::u32 i = 0; i < numChildNodes; ++i) + const int numChildNodes = aznumeric_caster(grandParentNode->GetNumChildNodes()); + for (int i = 0; i < numChildNodes; ++i) { const Node* grandParentChildNode = m_skeleton->GetNode(grandParentNode->GetChildIndex(i)); if (grandParentChildNode == parentNode) @@ -169,8 +169,8 @@ namespace EMotionFX } else { - const AZ::u32 numRootNodes = m_skeleton->GetNumRootNodes(); - for (AZ::u32 i = 0; i < numRootNodes; ++i) + const int numRootNodes = aznumeric_caster(m_skeleton->GetNumRootNodes()); + for (int i = 0; i < numRootNodes; ++i) { const Node* rootNode = m_skeleton->GetNode(m_skeleton->GetRootNodeIndex(i)); if (rootNode == parentNode) @@ -234,7 +234,7 @@ namespace EMotionFX Node* node = static_cast(index.internalPointer()); AZ_Assert(node, "Expected valid node pointer."); - const AZ::u32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); const NodeInfo& nodeInfo = m_nodeInfos[nodeIndex]; switch (role) @@ -389,7 +389,7 @@ namespace EMotionFX break; } case ROLE_NODE_INDEX: - return nodeIndex; + return qulonglong(nodeIndex); case ROLE_POINTER: return QVariant::fromValue(node); case ROLE_ACTOR_POINTER: @@ -474,7 +474,7 @@ namespace EMotionFX Node* node = static_cast(index.internalPointer()); AZ_Assert(node, "Expected valid node pointer."); - const AZ::u32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); const NodeInfo& nodeInfo = m_nodeInfos[nodeIndex]; if (nodeInfo.m_checkable) @@ -496,7 +496,7 @@ namespace EMotionFX const Node* node = static_cast(index.internalPointer()); AZ_Assert(node, "Expected valid node pointer."); - const AZ::u32 nodeIndex = node->GetNodeIndex(); + const size_t nodeIndex = node->GetNodeIndex(); NodeInfo& nodeInfo = m_nodeInfos[nodeIndex]; switch (role) @@ -525,8 +525,8 @@ namespace EMotionFX Node* parentNode = node->GetParentNode(); if (parentNode) { - const AZ::u32 numChildNodes = parentNode->GetNumChildNodes(); - for (AZ::u32 i = 0; i < numChildNodes; ++i) + const int numChildNodes = aznumeric_caster(parentNode->GetNumChildNodes()); + for (int i = 0; i < numChildNodes; ++i) { const Node* childNode = m_skeleton->GetNode(parentNode->GetChildIndex(i)); if (childNode == node) @@ -536,8 +536,8 @@ namespace EMotionFX } } - const AZ::u32 numRootNodes = m_skeleton->GetNumRootNodes(); - for (AZ::u32 i = 0; i < numRootNodes; ++i) + const int numRootNodes = aznumeric_caster(m_skeleton->GetNumRootNodes()); + for (int i = 0; i < numRootNodes; ++i) { const Node* rootNode = m_skeleton->GetNode(m_skeleton->GetRootNodeIndex(i)); if (rootNode == node) @@ -552,8 +552,8 @@ namespace EMotionFX QModelIndexList SkeletonModel::GetModelIndicesForFullSkeleton() const { QModelIndexList result; - const AZ::u32 jointCount = m_skeleton->GetNumNodes(); - for (AZ::u32 i = 0; i < jointCount; ++i) + const size_t jointCount = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < jointCount; ++i) { Node* joint = m_skeleton->GetNode(i); result.push_back(GetModelIndex(joint)); @@ -585,8 +585,8 @@ namespace EMotionFX void SkeletonModel::ForEach(const AZStd::function& func) { QModelIndex modelIndex; - const AZ::u32 jointCount = m_skeleton->GetNumNodes(); - for (AZ::u32 i = 0; i < jointCount; ++i) + const size_t jointCount = m_skeleton->GetNumNodes(); + for (size_t i = 0; i < jointCount; ++i) { Node* joint = m_skeleton->GetNode(i); modelIndex = GetModelIndex(joint); @@ -615,36 +615,31 @@ namespace EMotionFX return; } - const AZ::u32 numLodLevels = actor->GetNumLODLevels(); + const size_t numLodLevels = actor->GetNumLODLevels(); const Skeleton* skeleton = actor->GetSkeleton(); - const AZ::u32 numNodes = skeleton->GetNumNodes(); + const size_t numNodes = skeleton->GetNumNodes(); m_nodeInfos.resize(numNodes); - AZStd::vector > boneListPerLodLevel; + AZStd::vector > boneListPerLodLevel; boneListPerLodLevel.resize(numLodLevels); - for (AZ::u32 lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) + for (size_t lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) { actor->ExtractBoneList(lodLevel, &boneListPerLodLevel[lodLevel]); } - for (AZ::u32 nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) + for (size_t nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) { NodeInfo& nodeInfo = m_nodeInfos[nodeIndex]; // Is bone? - nodeInfo.m_isBone = false; - for (AZ::u32 lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) + nodeInfo.m_isBone = AZStd::any_of(begin(boneListPerLodLevel), end(boneListPerLodLevel), [nodeIndex](const AZStd::vector& lodLevel) { - if (boneListPerLodLevel[lodLevel].Find(nodeIndex) != MCORE_INVALIDINDEX32) - { - nodeInfo.m_isBone = true; - break; - } - } + return AZStd::find(begin(lodLevel), end(lodLevel), nodeIndex) != end(lodLevel); + }); // Has mesh? nodeInfo.m_hasMesh = false; - for (AZ::u32 lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) + for (size_t lodLevel = 0; lodLevel < numLodLevels; ++lodLevel) { if (actor->GetMesh(lodLevel, nodeIndex)) { diff --git a/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp b/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp index bfee6b582c..5082d4b739 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Assets/ActorAsset.cpp @@ -55,7 +55,7 @@ namespace EMotionFX Importer::ActorSettings actorSettings; if (GetEMotionFX().GetEnableServerOptimization()) { - actorSettings.mOptimizeForServer = true; + actorSettings.m_optimizeForServer = true; } assetData->m_emfxActor = EMotionFX::GetImporter().LoadActor( diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index 74133997e4..303a7e118b 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -58,27 +58,32 @@ namespace EMotionFX }; ////////////////////////////////////////////////////////////////////////// - void ActorComponent::BoundingBoxConfiguration::Set(ActorInstance* actor) const + void ActorComponent::BoundingBoxConfiguration::Set(ActorInstance* actorInstance) const { + actorInstance->SetExpandBoundsBy(m_expandBy * 0.01f); // Normalize percentage for internal use. (1% == 0.01f) + if (m_autoUpdateBounds) { - actor->SetupAutoBoundsUpdate(m_updateTimeFrequency, m_boundsType, m_updateItemFrequency); + actorInstance->SetupAutoBoundsUpdate(m_updateTimeFrequency, m_boundsType, m_updateItemFrequency); } else { - actor->SetBoundsUpdateType(m_boundsType); - actor->SetBoundsUpdateEnabled(false); + actorInstance->SetBoundsUpdateType(m_boundsType); + actorInstance->SetBoundsUpdateEnabled(false); } } - void ActorComponent::BoundingBoxConfiguration::SetAndUpdate(ActorInstance* actor) const + void ActorComponent::BoundingBoxConfiguration::SetAndUpdate(ActorInstance* actorInstance) const { - Set(actor); - const AZ::u32 freq = actor->GetBoundsUpdateEnabled() ? actor->GetBoundsUpdateItemFrequency() : 1; - actor->UpdateBounds(0, actor->GetBoundsUpdateType(), freq); + Set(actorInstance); + + const AZ::u32 updateFrequency = actorInstance->GetBoundsUpdateEnabled() ? actorInstance->GetBoundsUpdateItemFrequency() : 1; + const ActorInstance::EBoundsType boundUpdateType = actorInstance->GetBoundsUpdateType(); + + actorInstance->UpdateBounds(actorInstance->GetLODLevel(), boundUpdateType, updateFrequency); } - void ActorComponent::BoundingBoxConfiguration::Reflect(AZ::ReflectContext * context) + void ActorComponent::BoundingBoxConfiguration::Reflect(AZ::ReflectContext* context) { if (auto* serializeContext = azrtti_cast(context)) { @@ -105,10 +110,26 @@ namespace EMotionFX ->Field("m_autoUpdateBounds", &BoundingBoxConfiguration::m_autoUpdateBounds) ->Field("m_updateTimeFrequency", &BoundingBoxConfiguration::m_updateTimeFrequency) ->Field("m_updateItemFrequency", &BoundingBoxConfiguration::m_updateItemFrequency) + ->Field("expandBy", &BoundingBoxConfiguration::m_expandBy) ; } } + AZ::Crc32 ActorComponent::BoundingBoxConfiguration::GetVisibilityAutoUpdate() const + { + return m_boundsType != EMotionFX::ActorInstance::BOUNDS_STATIC_BASED ? AZ::Edit::PropertyVisibility::Show : AZ::Edit::PropertyVisibility::Hide; + } + + AZ::Crc32 ActorComponent::BoundingBoxConfiguration::GetVisibilityAutoUpdateSettings() const + { + if (m_boundsType == EMotionFX::ActorInstance::BOUNDS_STATIC_BASED || m_autoUpdateBounds == false) + { + return AZ::Edit::PropertyVisibility::Hide; + } + + return AZ::Edit::PropertyVisibility::Show; + } + ////////////////////////////////////////////////////////////////////////// void ActorComponent::Configuration::Reflect(AZ::ReflectContext* context) { @@ -505,14 +526,14 @@ namespace EMotionFX if (m_actorInstance) { const Transform localTransform = m_actorInstance->GetParentWorldSpaceTransform().Inversed() * Transform(world); - m_actorInstance->SetLocalSpacePosition(localTransform.mPosition); - m_actorInstance->SetLocalSpaceRotation(localTransform.mRotation); + m_actorInstance->SetLocalSpacePosition(localTransform.m_position); + m_actorInstance->SetLocalSpaceRotation(localTransform.m_rotation); // Disable updating the scale to prevent feedback from adding up. // We need to find a better way to handle this or to prevent this feedback loop. EMFX_SCALECODE ( - m_actorInstance->SetLocalSpaceScale(localTransform.mScale); + m_actorInstance->SetLocalSpaceScale(localTransform.m_scale); ) } } @@ -642,8 +663,8 @@ namespace EMotionFX if (emfxNode) { const Transform& nodeTransform = emfxPose->GetModelSpaceTransform(emfxNode->GetNodeIndex()); - physicsPose[nodeIndex].m_position = nodeTransform.mPosition; - physicsPose[nodeIndex].m_orientation = nodeTransform.mRotation; + physicsPose[nodeIndex].m_position = nodeTransform.m_position; + physicsPose[nodeIndex].m_orientation = nodeTransform.m_rotation; } } @@ -701,10 +722,10 @@ namespace EMotionFX { AZ_Assert(m_actorInstance, "The actor instance needs to be valid."); - const AZ::u32 index = static_cast(jointIndex); - const AZ::u32 numNodes = m_actorInstance->GetActor()->GetNumNodes(); + const size_t index = jointIndex; + const size_t numNodes = m_actorInstance->GetActor()->GetNumNodes(); - AZ_Error("EMotionFX", index < numNodes, "GetJointTransform: The joint index %d is out of bounds [0;%d]. Entity: %s", + AZ_Error("EMotionFX", index < numNodes, "GetJointTransform: The joint index %zu is out of bounds [0;%zu]. Entity: %s", index, numNodes, GetEntity()->GetName().c_str()); if (index >= numNodes) @@ -741,10 +762,10 @@ namespace EMotionFX { AZ_Assert(m_actorInstance, "The actor instance needs to be valid."); - const AZ::u32 index = static_cast(jointIndex); - const AZ::u32 numNodes = m_actorInstance->GetActor()->GetNumNodes(); + const size_t index = jointIndex; + const size_t numNodes = m_actorInstance->GetActor()->GetNumNodes(); - AZ_Error("EMotionFX", index < numNodes, "GetJointTransformComponents: The joint index %d is out of bounds [0;%d]. Entity: %s", + AZ_Error("EMotionFX", index < numNodes, "GetJointTransformComponents: The joint index %zu is out of bounds [0;%zu]. Entity: %s", index, numNodes, GetEntity()->GetName().c_str()); if (index >= numNodes) @@ -759,11 +780,11 @@ namespace EMotionFX case Space::LocalSpace: { const Transform& localTransform = currentPose->GetLocalSpaceTransform(index); - outPosition = localTransform.mPosition; - outRotation = localTransform.mRotation; + outPosition = localTransform.m_position; + outRotation = localTransform.m_rotation; EMFX_SCALECODE ( - outScale = localTransform.mScale; + outScale = localTransform.m_scale; ) return; } @@ -771,11 +792,11 @@ namespace EMotionFX case Space::ModelSpace: { const Transform& modelTransform = currentPose->GetModelSpaceTransform(index); - outPosition = modelTransform.mPosition; - outRotation = modelTransform.mRotation; + outPosition = modelTransform.m_position; + outRotation = modelTransform.m_rotation; EMFX_SCALECODE ( - outScale = modelTransform.mScale; + outScale = modelTransform.m_scale; ) return; } @@ -783,11 +804,11 @@ namespace EMotionFX case Space::WorldSpace: { const Transform worldTransform = currentPose->GetWorldSpaceTransform(index); - outPosition = worldTransform.mPosition; - outRotation = worldTransform.mRotation; + outPosition = worldTransform.m_position; + outRotation = worldTransform.m_rotation; EMFX_SCALECODE ( - outScale = worldTransform.mScale; + outScale = worldTransform.m_scale; ) return; } @@ -849,7 +870,7 @@ namespace EMotionFX Node* node = jointName ? m_actorInstance->GetActor()->GetSkeleton()->FindNodeByName(jointName) : m_actorInstance->GetActor()->GetSkeleton()->GetNode(0); if (node) { - const AZ::u32 jointIndex = node->GetNodeIndex(); + const size_t jointIndex = node->GetNodeIndex(); Attachment* attachment = AttachmentNode::Create(m_actorInstance.get(), jointIndex, targetActorInstance, true /* Managed externally, by this component. */); m_actorInstance->AddAttachment(attachment); } diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 0f36846a50..f834456e45 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -45,24 +45,29 @@ namespace EMotionFX AZ_COMPONENT(ActorComponent, "{BDC97E7F-A054-448B-A26F-EA2B5D78E377}"); friend class EditorActorComponent; - struct BoundingBoxConfiguration + class BoundingBoxConfiguration { + public: AZ_TYPE_INFO(BoundingBoxConfiguration, "{EBCFF975-00A5-4578-85C7-59909F52067C}"); BoundingBoxConfiguration() = default; - EMotionFX::ActorInstance::EBoundsType m_boundsType = EMotionFX::ActorInstance::BOUNDS_STATIC_BASED; - bool m_autoUpdateBounds = true; - float m_updateTimeFrequency = 0.f; - AZ::u32 m_updateItemFrequency = 1; + EMotionFX::ActorInstance::EBoundsType m_boundsType = EMotionFX::ActorInstance::BOUNDS_STATIC_BASED; + float m_expandBy = 25.0f; ///< Expand the bounding volume by the given percentage. + bool m_autoUpdateBounds = true; + float m_updateTimeFrequency = 0.0f; + AZ::u32 m_updateItemFrequency = 1; - // Set the bounding box configuration of the given actor instance to the parameters given by `this'. The actor instance must not be null (this is not checked). - void Set(ActorInstance* inst) const; + // Set the bounding box configuration of the given actor instance to the parameters given by 'this'. The actor instance must not be null (this is not checked). + void Set(ActorInstance* actorInstance) const; // Set the bounding box configuration, then update the bounds of the actor instance - void SetAndUpdate(ActorInstance* inst) const; + void SetAndUpdate(ActorInstance* actorInstance) const; static void Reflect(AZ::ReflectContext* context); + + AZ::Crc32 GetVisibilityAutoUpdate() const; + AZ::Crc32 GetVisibilityAutoUpdateSettings() const; }; /** @@ -75,13 +80,13 @@ namespace EMotionFX AZ::Data::Asset m_actorAsset{AZ::Data::AssetLoadBehavior::NoLoad}; ///< Selected actor asset. ActorAsset::MaterialList m_materialPerLOD{}; ///< Material assignment per LOD. AZ::EntityId m_attachmentTarget{}; ///< Target entity this actor should attach to. - AZ::u32 m_attachmentJointIndex = MCORE_INVALIDINDEX32; ///< Index of joint on target skeleton for actor attachments. + size_t m_attachmentJointIndex = InvalidIndex; ///< Index of joint on target skeleton for actor attachments. AttachmentType m_attachmentType = AttachmentType::None; ///< Type of attachment. bool m_renderSkeleton = false; ///< Toggles debug rendering of the skeleton. bool m_renderCharacter = true; ///< Toggles rendering of the character. bool m_renderBounds = false; ///< Toggles rendering of the character bounds used for visibility testing. SkinningMethod m_skinningMethod = SkinningMethod::DualQuat; ///< The skinning method for this actor - AZ::u32 m_lodLevel = 0; + size_t m_lodLevel = 0; // Force updating the joints when it is out of camera view. By // default, joints level update (beside the root joint) on diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.cpp index 10046728ab..704b746e3f 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.cpp @@ -43,32 +43,32 @@ namespace EMotionFX Call(FN_OnAnimGraphInstanceDestroyed, animGraphInstance); } - void OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, AZ::u32 parameterIndex, float beforeValue, float afterValue) override + void OnAnimGraphFloatParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, size_t parameterIndex, float beforeValue, float afterValue) override { Call(FN_OnAnimGraphFloatParameterChanged, animGraphInstance, parameterIndex, beforeValue, afterValue); } - void OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, AZ::u32 parameterIndex, bool beforeValue, bool afterValue) override + void OnAnimGraphBoolParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, size_t parameterIndex, bool beforeValue, bool afterValue) override { Call(FN_OnAnimGraphBoolParameterChanged, animGraphInstance, parameterIndex, beforeValue, afterValue); } - void OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, AZ::u32 parameterIndex, const char* beforeValue, const char* afterValue) override + void OnAnimGraphStringParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, size_t parameterIndex, const char* beforeValue, const char* afterValue) override { Call(FN_OnAnimGraphStringParameterChanged, animGraphInstance, parameterIndex, beforeValue, afterValue); } - void OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, AZ::u32 parameterIndex, const AZ::Vector2& beforeValue, const AZ::Vector2& afterValue) override + void OnAnimGraphVector2ParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, size_t parameterIndex, const AZ::Vector2& beforeValue, const AZ::Vector2& afterValue) override { Call(FN_OnAnimGraphVector2ParameterChanged, animGraphInstance, parameterIndex, beforeValue, afterValue); } - void OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, AZ::u32 parameterIndex, const AZ::Vector3& beforeValue, const AZ::Vector3& afterValue) override + void OnAnimGraphVector3ParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, size_t parameterIndex, const AZ::Vector3& beforeValue, const AZ::Vector3& afterValue) override { Call(FN_OnAnimGraphVector3ParameterChanged, animGraphInstance, parameterIndex, beforeValue, afterValue); } - void OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, AZ::u32 parameterIndex, const AZ::Quaternion& beforeValue, const AZ::Quaternion& afterValue) override + void OnAnimGraphRotationParameterChanged(EMotionFX::AnimGraphInstance* animGraphInstance, size_t parameterIndex, const AZ::Quaternion& beforeValue, const AZ::Quaternion& afterValue) override { Call(FN_OnAnimGraphVector3ParameterChanged, animGraphInstance, parameterIndex, beforeValue, afterValue); } @@ -138,7 +138,7 @@ namespace EMotionFX auto* behaviorContext = azrtti_cast(context); if (behaviorContext) { - behaviorContext->Constant("InvalidParameterIndex", BehaviorConstant(static_cast(MCORE_INVALIDINDEX32))); + behaviorContext->Constant("InvalidParameterIndex", BehaviorConstant(InvalidIndex)); behaviorContext->EBus("AnimGraphComponentRequestBus") // General API @@ -546,24 +546,24 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - AZ::u32 AnimGraphComponent::FindParameterIndex(const char* parameterName) + size_t AnimGraphComponent::FindParameterIndex(const char* parameterName) { if (m_animGraphInstance) { const AZ::Outcome parameterIndex = m_animGraphInstance->FindParameterIndex(parameterName); if (parameterIndex.IsSuccess()) { - return static_cast(parameterIndex.GetValue()); + return parameterIndex.GetValue(); } } - return MCORE_INVALIDINDEX32; + return InvalidIndex; } ////////////////////////////////////////////////////////////////////////// - const char* AnimGraphComponent::FindParameterName(AZ::u32 parameterIndex) + const char* AnimGraphComponent::FindParameterName(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32 || !m_animGraphInstance || !m_animGraphInstance->GetAnimGraph()) + if (parameterIndex == InvalidIndex || !m_animGraphInstance || !m_animGraphInstance->GetAnimGraph()) { return ""; } @@ -572,11 +572,11 @@ namespace EMotionFX ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterFloat(AZ::u32 parameterIndex, float value) + void AnimGraphComponent::SetParameterFloat(size_t parameterIndex, float value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -610,7 +610,7 @@ namespace EMotionFX } default: { - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u can not be set as float, is of type: %s", parameterIndex, param->GetTypeString()); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu can not be set as float, is of type: %s", parameterIndex, param->GetTypeString()); return; } } @@ -627,11 +627,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterBool(AZ::u32 parameterIndex, bool value) + void AnimGraphComponent::SetParameterBool(size_t parameterIndex, bool value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -665,7 +665,7 @@ namespace EMotionFX } default: { - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u can not be set as bool, is of type: %s", parameterIndex, param->GetTypeString()); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu can not be set as bool, is of type: %s", parameterIndex, param->GetTypeString()); return; } } @@ -682,11 +682,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterString(AZ::u32 parameterIndex, const char* value) + void AnimGraphComponent::SetParameterString(size_t parameterIndex, const char* value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -713,17 +713,17 @@ namespace EMotionFX } else { - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u is not a string", parameterIndex); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu is not a string", parameterIndex); } } } ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterVector2(AZ::u32 parameterIndex, const AZ::Vector2& value) + void AnimGraphComponent::SetParameterVector2(size_t parameterIndex, const AZ::Vector2& value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -746,17 +746,17 @@ namespace EMotionFX } else { - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u is not a vector2", parameterIndex); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu is not a vector2", parameterIndex); } } } ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterVector3(AZ::u32 parameterIndex, const AZ::Vector3& value) + void AnimGraphComponent::SetParameterVector3(size_t parameterIndex, const AZ::Vector3& value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -779,17 +779,17 @@ namespace EMotionFX } else { - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u is not a vector3", parameterIndex); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu is not a vector3", parameterIndex); } } } ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterRotationEuler(AZ::u32 parameterIndex, const AZ::Vector3& value) + void AnimGraphComponent::SetParameterRotationEuler(size_t parameterIndex, const AZ::Vector3& value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -808,7 +808,7 @@ namespace EMotionFX break; } default: - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u can not be set as rotation euler, is of type: %s", parameterIndex, param->GetTypeString()); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu can not be set as rotation euler, is of type: %s", parameterIndex, param->GetTypeString()); return; } @@ -824,11 +824,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - void AnimGraphComponent::SetParameterRotation(AZ::u32 parameterIndex, const AZ::Quaternion& value) + void AnimGraphComponent::SetParameterRotation(size_t parameterIndex, const AZ::Quaternion& value) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return; } @@ -847,7 +847,7 @@ namespace EMotionFX break; } default: - AZ_Warning("EMotionFX", false, "Anim graph parameter index: %u can not be set as rotation, is of type: %s", parameterIndex, param->GetTypeString()); + AZ_Warning("EMotionFX", false, "Anim graph parameter index: %zu can not be set as rotation, is of type: %s", parameterIndex, param->GetTypeString()); return; } @@ -986,11 +986,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - float AnimGraphComponent::GetParameterFloat(AZ::u32 parameterIndex) + float AnimGraphComponent::GetParameterFloat(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return 0.f; } @@ -1003,11 +1003,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - bool AnimGraphComponent::GetParameterBool(AZ::u32 parameterIndex) + bool AnimGraphComponent::GetParameterBool(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return false; } @@ -1020,11 +1020,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - AZStd::string AnimGraphComponent::GetParameterString(AZ::u32 parameterIndex) + AZStd::string AnimGraphComponent::GetParameterString(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return AZStd::string(); } @@ -1040,11 +1040,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - AZ::Vector2 AnimGraphComponent::GetParameterVector2(AZ::u32 parameterIndex) + AZ::Vector2 AnimGraphComponent::GetParameterVector2(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return AZ::Vector2::CreateZero(); } @@ -1058,11 +1058,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - AZ::Vector3 AnimGraphComponent::GetParameterVector3(AZ::u32 parameterIndex) + AZ::Vector3 AnimGraphComponent::GetParameterVector3(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return AZ::Vector3::CreateZero(); } @@ -1076,11 +1076,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - AZ::Vector3 AnimGraphComponent::GetParameterRotationEuler(AZ::u32 parameterIndex) + AZ::Vector3 AnimGraphComponent::GetParameterRotationEuler(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return AZ::Vector3::CreateZero(); } @@ -1094,11 +1094,11 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - AZ::Quaternion AnimGraphComponent::GetParameterRotation(AZ::u32 parameterIndex) + AZ::Quaternion AnimGraphComponent::GetParameterRotation(size_t parameterIndex) { - if (parameterIndex == MCORE_INVALIDINDEX32) + if (parameterIndex == InvalidIndex) { - AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %u", parameterIndex); + AZ_Warning("EMotionFX", false, "Invalid anim graph parameter index: %zu", parameterIndex); return AZ::Quaternion::CreateZero(); } diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.h index 52b57ce76e..474d0cb6c5 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/AnimGraphComponent.h @@ -104,15 +104,15 @@ namespace EMotionFX ////////////////////////////////////////////////////////////////////////// // AnimGraphComponentRequestBus::Handler EMotionFX::AnimGraphInstance* GetAnimGraphInstance() override; - AZ::u32 FindParameterIndex(const char* parameterName) override; - const char* FindParameterName(AZ::u32 parameterIndex) override; - void SetParameterFloat(AZ::u32 parameterIndex, float value) override; - void SetParameterBool(AZ::u32 parameterIndex, bool value) override; - void SetParameterString(AZ::u32 parameterIndex, const char* value) override; - void SetParameterVector2(AZ::u32 parameterIndex, const AZ::Vector2& value) override; - void SetParameterVector3(AZ::u32 parameterIndex, const AZ::Vector3& value) override; - void SetParameterRotationEuler(AZ::u32 parameterIndex, const AZ::Vector3& value) override; - void SetParameterRotation(AZ::u32 parameterIndex, const AZ::Quaternion& value) override; + size_t FindParameterIndex(const char* parameterName) override; + const char* FindParameterName(size_t parameterIndex) override; + void SetParameterFloat(size_t parameterIndex, float value) override; + void SetParameterBool(size_t parameterIndex, bool value) override; + void SetParameterString(size_t parameterIndex, const char* value) override; + void SetParameterVector2(size_t parameterIndex, const AZ::Vector2& value) override; + void SetParameterVector3(size_t parameterIndex, const AZ::Vector3& value) override; + void SetParameterRotationEuler(size_t parameterIndex, const AZ::Vector3& value) override; + void SetParameterRotation(size_t parameterIndex, const AZ::Quaternion& value) override; void SetNamedParameterFloat(const char* parameterName, float value) override; void SetNamedParameterBool(const char* parameterName, bool value) override; void SetNamedParameterString(const char* parameterName, const char* value) override; @@ -121,13 +121,13 @@ namespace EMotionFX void SetNamedParameterRotationEuler(const char* parameterName, const AZ::Vector3& value) override; void SetNamedParameterRotation(const char* parameterName, const AZ::Quaternion& value) override; void SetVisualizeEnabled(bool enabled) override; - float GetParameterFloat(AZ::u32 parameterIndex) override; - bool GetParameterBool(AZ::u32 parameterIndex) override; - AZStd::string GetParameterString(AZ::u32 parameterIndex) override; - AZ::Vector2 GetParameterVector2(AZ::u32 parameterIndex) override; - AZ::Vector3 GetParameterVector3(AZ::u32 parameterIndex) override; - AZ::Vector3 GetParameterRotationEuler(AZ::u32 parameterIndex) override; - AZ::Quaternion GetParameterRotation(AZ::u32 parameterIndex) override; + float GetParameterFloat(size_t parameterIndex) override; + bool GetParameterBool(size_t parameterIndex) override; + AZStd::string GetParameterString(size_t parameterIndex) override; + AZ::Vector2 GetParameterVector2(size_t parameterIndex) override; + AZ::Vector3 GetParameterVector3(size_t parameterIndex) override; + AZ::Vector3 GetParameterRotationEuler(size_t parameterIndex) override; + AZ::Quaternion GetParameterRotation(size_t parameterIndex) override; float GetNamedParameterFloat(const char* parameterName) override; bool GetNamedParameterBool(const char* parameterName) override; AZStd::string GetNamedParameterString(const char* parameterName) override; diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.cpp index 356f5f934a..5db0fae842 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.cpp @@ -71,13 +71,13 @@ namespace EMotionFX m_lodDistances.clear(); } - void SimpleLODComponent::Configuration::GenerateDefaultValue(AZ::u32 numLODs) + void SimpleLODComponent::Configuration::GenerateDefaultValue(size_t numLODs) { if (numLODs != m_lodDistances.size()) { // Generate the default LOD (max) distance to 10, 20, 30.... m_lodDistances.resize(numLODs); - for (AZ::u32 i = 0; i < numLODs; ++i) + for (size_t i = 0; i < numLODs; ++i) { m_lodDistances[i] = i * 10.0f + 10.0f; } @@ -86,12 +86,9 @@ namespace EMotionFX if (numLODs != m_lodSampleRates.size()) { // Generate the default LOD Sample Rate to 140, 60, 45, 25, 15, 10 - const float defaultSampleRate[] = {140.0f, 60.0f, 45.0f, 25.0f, 15.0f, 10.0f}; + constexpr AZStd::array defaultSampleRate {140.0f, 60.0f, 45.0f, 25.0f, 15.0f, 10.0f}; m_lodSampleRates.resize(numLODs); - for (AZ::u32 i = 0; i < numLODs; ++i) - { - m_lodSampleRates[i] = defaultSampleRate[i]; - } + AZStd::copy(begin(defaultSampleRate), end(defaultSampleRate), begin(m_lodSampleRates)); } } @@ -171,7 +168,7 @@ namespace EMotionFX UpdateLodLevelByDistance(m_actorInstance, m_configuration, GetEntityId()); } - AZ::u32 SimpleLODComponent::GetLodByDistance(const AZStd::vector& distances, float distance) + size_t SimpleLODComponent::GetLodByDistance(const AZStd::vector& distances, float distance) { const size_t max = distances.size(); for (size_t i = 0; i < max; ++i) @@ -179,11 +176,11 @@ namespace EMotionFX const float rDistance = distances[i]; if (distance < rDistance) { - return static_cast(i); + return i; } } - return static_cast(max - 1); + return max - 1; } void SimpleLODComponent::UpdateLodLevelByDistance(EMotionFX::ActorInstance * actorInstance, const Configuration& configuration, AZ::EntityId entityId) @@ -204,7 +201,7 @@ namespace EMotionFX AZ::RPI::ViewportContextPtr defaultViewportContext = viewportContextManager->GetViewportContextByName(viewportContextManager->GetDefaultViewportContextName()); const float distance = worldPos.GetDistance(defaultViewportContext->GetCameraTransform().GetTranslation()); - const AZ::u32 lodByDistance = GetLodByDistance(configuration.m_lodDistances, distance); + const size_t lodByDistance = GetLodByDistance(configuration.m_lodDistances, distance); actorInstance->SetLODLevel(lodByDistance); if (configuration.m_enableLodSampling) diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.h index d8ccb9cd06..96bebdc660 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleLODComponent.h @@ -44,7 +44,7 @@ namespace EMotionFX void Reset(); // Generate the default value based on LOD level. - void GenerateDefaultValue(AZ::u32 numLODs); + void GenerateDefaultValue(size_t numLODs); bool GetEnableLodSampling(); static void Reflect(AZ::ReflectContext* context); @@ -88,7 +88,7 @@ namespace EMotionFX // AZ::TickBus::Handler void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - static AZ::u32 GetLodByDistance(const AZStd::vector& distances, float distance); + static size_t GetLodByDistance(const AZStd::vector& distances, float distance); static void UpdateLodLevelByDistance(EMotionFX::ActorInstance* actorInstance, const Configuration& configuration, AZ::EntityId entityId); Configuration m_configuration; // Component configuration. diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.cpp index fa7ea7f2a7..dd7fdeea50 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/SimpleMotionComponent.cpp @@ -444,18 +444,18 @@ namespace EMotionFX } //init the PlaybackInfo based on our config EMotionFX::PlayBackInfo info; - info.mNumLoops = cfg.m_loop ? EMFX_LOOPFOREVER : 1; - info.mRetarget = cfg.m_retarget; - info.mPlayMode = cfg.m_reverse ? EMotionFX::EPlayMode::PLAYMODE_BACKWARD : EMotionFX::EPlayMode::PLAYMODE_FORWARD; - info.mFreezeAtLastFrame = info.mNumLoops == 1; - info.mMirrorMotion = cfg.m_mirror; - info.mPlaySpeed = cfg.m_playspeed; - info.mPlayNow = true; - info.mDeleteOnZeroWeight = deleteOnZeroWeight; - info.mCanOverwrite = false; - info.mBlendInTime = cfg.m_blendInTime; - info.mBlendOutTime = cfg.m_blendOutTime; - info.mInPlace = cfg.m_inPlace; + info.m_numLoops = cfg.m_loop ? EMFX_LOOPFOREVER : 1; + info.m_retarget = cfg.m_retarget; + info.m_playMode = cfg.m_reverse ? EMotionFX::EPlayMode::PLAYMODE_BACKWARD : EMotionFX::EPlayMode::PLAYMODE_FORWARD; + info.m_freezeAtLastFrame = info.m_numLoops == 1; + info.m_mirrorMotion = cfg.m_mirror; + info.m_playSpeed = cfg.m_playspeed; + info.m_playNow = true; + info.m_deleteOnZeroWeight = deleteOnZeroWeight; + info.m_canOverwrite = false; + info.m_blendInTime = cfg.m_blendInTime; + info.m_blendOutTime = cfg.m_blendOutTime; + info.m_inPlace = cfg.m_inPlace; return actorInstance->GetMotionSystem()->PlayMotion(motionAsset->m_emfxMotion.get(), &info); } diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index efc5cbd9a2..485b56c077 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -62,39 +62,40 @@ namespace EMotionFX { editContext->Class("Actor Bounding Box Config", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &ActorComponent::BoundingBoxConfiguration::m_boundsType, "Bounds type", - "The method used to compute the Actor bounding box. NOTE: ordered by least expensive to compute to most expensive to compute." - ) - ->EnumAttribute(ActorInstance::BOUNDS_STATIC_BASED, "Static bounds (source-asset bounds)") - ->EnumAttribute(ActorInstance::BOUNDS_NODE_BASED, "Bone position-based") - ->EnumAttribute(ActorInstance::BOUNDS_NODEOBB_BASED, "Bone local bounding box-based") - ->EnumAttribute(ActorInstance::BOUNDS_MESH_BASED, "Render mesh vertex position-based (VERY EXPENSIVE)") - - ->DataElement(0, &ActorComponent::BoundingBoxConfiguration::m_autoUpdateBounds, + "The method used to compute the Actor bounding box. NOTE: ordered by least expensive to compute to most expensive to compute.") + ->EnumAttribute(ActorInstance::BOUNDS_STATIC_BASED, "Static (Recommended)") + ->EnumAttribute(ActorInstance::BOUNDS_NODE_BASED, "Bone position-based") + ->EnumAttribute(ActorInstance::BOUNDS_MESH_BASED, "Mesh vertex-based (VERY EXPENSIVE)") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) + ->DataElement(AZ::Edit::UIHandlers::Default, &ActorComponent::BoundingBoxConfiguration::m_expandBy, + "Expand by", + "Percentage that the calculated bounding box should be automatically expanded with. " + "This can be used to add a tolerance area to the calculated bounding box to avoid clipping the character too early. " + "A static bounding box together with the expansion is the recommended way for maximum performance. (Default = 25%)") + ->Attribute(AZ::Edit::Attributes::Suffix, " %") + ->Attribute(AZ::Edit::Attributes::Min, -100.0f + AZ::Constants::Tolerance) + ->DataElement(AZ::Edit::UIHandlers::Default, &ActorComponent::BoundingBoxConfiguration::m_autoUpdateBounds, "Automatically update bounds?", - "If true, bounds are automatically updated based on some frequency. Otherwise bounds are computed only at creation or when triggered manually" - ) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) - - ->DataElement(0, &ActorComponent::BoundingBoxConfiguration::m_updateTimeFrequency, + "If true, bounds are automatically updated based on some frequency. Otherwise bounds are computed only at creation or when triggered manually") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::EntireTree) + ->Attribute(AZ::Edit::Attributes::Visibility, &ActorComponent::BoundingBoxConfiguration::GetVisibilityAutoUpdate) + ->DataElement(AZ::Edit::UIHandlers::Default, &ActorComponent::BoundingBoxConfiguration::m_updateTimeFrequency, "Update frequency", - "How often to update bounds automatically" - ) - ->Attribute(AZ::Edit::Attributes::Suffix, " Hz") - ->Attribute(AZ::Edit::Attributes::Min, 0.f) - ->Attribute(AZ::Edit::Attributes::Step, 0.001f) - ->Attribute(AZ::Edit::Attributes::Visibility, &ActorComponent::BoundingBoxConfiguration::m_autoUpdateBounds) - - ->DataElement(0, &ActorComponent::BoundingBoxConfiguration::m_updateItemFrequency, + "How often to update bounds automatically") + ->Attribute(AZ::Edit::Attributes::Suffix, " Hz") + ->Attribute(AZ::Edit::Attributes::Min, 0.0f) + ->Attribute(AZ::Edit::Attributes::Max, FLT_MAX) + ->Attribute(AZ::Edit::Attributes::Step, 0.1f) + ->Attribute(AZ::Edit::Attributes::Visibility, &ActorComponent::BoundingBoxConfiguration::GetVisibilityAutoUpdateSettings) + ->DataElement(AZ::Edit::UIHandlers::Default, &ActorComponent::BoundingBoxConfiguration::m_updateItemFrequency, "Update item skip factor", "How many items (bones or vertices) to skip when automatically updating bounds." - "
i.e. =1 uses every single item, =2 uses every 2nd item, =3 uses every 3rd item... " - ) - ->Attribute(AZ::Edit::Attributes::Suffix, " items") - ->Attribute(AZ::Edit::Attributes::Min, (AZ::u32)1) - ->Attribute(AZ::Edit::Attributes::Visibility, &ActorComponent::BoundingBoxConfiguration::m_autoUpdateBounds) + "
i.e. =1 uses every single item, =2 uses every 2nd item, =3 uses every 3rd item...") + ->Attribute(AZ::Edit::Attributes::Suffix, " items") + ->Attribute(AZ::Edit::Attributes::Min, (AZ::u32)1) + ->Attribute(AZ::Edit::Attributes::Visibility, &ActorComponent::BoundingBoxConfiguration::GetVisibilityAutoUpdateSettings) ; editContext->Class("Actor", "The Actor component manages an instance of an Actor") @@ -679,11 +680,11 @@ namespace EMotionFX bool isHit = false; // Iterate through the meshes in the actor, looking for the closest hit - const AZ::u32 lodLevel = m_actorInstance->GetLODLevel(); + const size_t lodLevel = m_actorInstance->GetLODLevel(); Actor* actor = m_actorAsset.Get()->GetActor(); - const uint32 numNodes = actor->GetNumNodes(); - const uint32 numLods = actor->GetNumLODLevels(); - for (uint32 nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) + const size_t numNodes = actor->GetNumNodes(); + const size_t numLods = actor->GetNumLODLevels(); + for (size_t nodeIndex = 0; nodeIndex < numNodes; ++nodeIndex) { Mesh* mesh = actor->GetMesh(lodLevel, nodeIndex); if (!mesh || mesh->GetIsCollisionMesh()) @@ -802,7 +803,7 @@ namespace EMotionFX Node* node = jointName ? targetActorInstance->GetActor()->GetSkeleton()->FindNodeByName(jointName) : targetActorInstance->GetActor()->GetSkeleton()->GetNode(0); if (node) { - const AZ::u32 jointIndex = node->GetNodeIndex(); + const size_t jointIndex = node->GetNodeIndex(); Attachment* attachment = AttachmentNode::Create(targetActorInstance, jointIndex, m_actorInstance.get(), true /* Managed externally, by this component. */); targetActorInstance->AddAttachment(attachment); } diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h index 26df2b6e47..10c75860cf 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.h @@ -158,8 +158,8 @@ namespace EMotionFX AttachmentType m_attachmentType; ///< Attachment type. AZ::EntityId m_attachmentTarget; ///< Target entity to attach to, if any. AZStd::string m_attachmentJointName; ///< Joint name on target to which to attach (if ActorAttachment). - AZ::u32 m_attachmentJointIndex; - AZ::u32 m_lodLevel; + size_t m_attachmentJointIndex; + size_t m_lodLevel; ActorComponent::BoundingBoxConfiguration m_bboxConfig; bool m_forceUpdateJointsOOV = false; // \todo attachmentTarget node nr diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorSimpleLODComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorSimpleLODComponent.cpp index 030ca42ca1..384caf074b 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorSimpleLODComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorSimpleLODComponent.cpp @@ -88,7 +88,7 @@ namespace EMotionFX if (actorInstance) { m_actorInstance = actorInstance.get(); - const AZ::u32 numLODs = m_actorInstance->GetActor()->GetNumLODLevels(); + const size_t numLODs = m_actorInstance->GetActor()->GetNumLODLevels(); m_configuration.GenerateDefaultValue(numLODs); } else @@ -111,7 +111,7 @@ namespace EMotionFX if (m_actorInstance != actorInstance) { m_actorInstance = actorInstance; - const AZ::u32 numLODs = m_actorInstance->GetActor()->GetNumLODLevels(); + const size_t numLODs = m_actorInstance->GetActor()->GetNumLODLevels(); m_configuration.GenerateDefaultValue(numLODs); } } diff --git a/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.cpp index 6536241465..8946a435b6 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.cpp @@ -21,14 +21,14 @@ namespace EMotionFX AZ::EnvironmentVariable PipelineComponent::s_eMotionFXAllocatorInitializer = nullptr; PipelineComponent::PipelineComponent() - : m_EMotionFXInited(false) + : m_eMotionFxInited(false) { } void PipelineComponent::Activate() { - if (!m_EMotionFXInited) + if (!m_eMotionFxInited) { // Start EMotionFX allocator or increase the reference counting s_eMotionFXAllocatorInitializer = AZ::Environment::CreateVariable(EMotionFXAllocatorInitializer::EMotionFXAllocatorInitializerTag); @@ -42,7 +42,7 @@ namespace EMotionFX // Initialize EMotion FX runtime. EMotionFX::Initializer::InitSettings emfxSettings; - emfxSettings.mUnitType = MCore::Distance::UNITTYPE_METERS; + emfxSettings.m_unitType = MCore::Distance::UNITTYPE_METERS; if (!EMotionFX::Initializer::Init(&emfxSettings)) { @@ -52,15 +52,15 @@ namespace EMotionFX // Initialize the EMotionFX command system. m_commandManager = AZStd::make_unique(); - m_EMotionFXInited = true; + m_eMotionFxInited = true; } } void PipelineComponent::Deactivate() { - if (m_EMotionFXInited) + if (m_eMotionFxInited) { - m_EMotionFXInited = false; + m_eMotionFxInited = false; m_commandManager.reset(); EMotionFX::Initializer::Shutdown(); MCore::Initializer::Shutdown(); diff --git a/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.h b/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.h index d89d1a33a0..392af36fd5 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/System/PipelineComponent.h @@ -33,7 +33,7 @@ namespace EMotionFX static void Reflect(AZ::ReflectContext* context); private: - bool m_EMotionFXInited; + bool m_eMotionFxInited; AZStd::unique_ptr m_commandManager; // Creates a static shared pointer using the AZ EnvironmentVariable system. diff --git a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp index c1b7be1239..b5a252e293 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp @@ -132,7 +132,7 @@ namespace EMotionFX /// Dispatch motion events to listeners via ActorNotificationBus::OnMotionEvent. void OnEvent(const EMotionFX::EventInfo& emfxInfo) override { - const ActorInstance* actorInstance = emfxInfo.mActorInstance; + const ActorInstance* actorInstance = emfxInfo.m_actorInstance; if (actorInstance) { const AZ::EntityId owningEntityId = actorInstance->GetEntityId(); @@ -140,11 +140,11 @@ namespace EMotionFX // Fill engine-compatible structure to dispatch to game code. MotionEvent motionEvent; motionEvent.m_entityId = owningEntityId; - motionEvent.m_actorInstance = emfxInfo.mActorInstance; - motionEvent.m_motionInstance = emfxInfo.mMotionInstance; - motionEvent.m_time = emfxInfo.mTimeValue; + motionEvent.m_actorInstance = emfxInfo.m_actorInstance; + motionEvent.m_motionInstance = emfxInfo.m_motionInstance; + motionEvent.m_time = emfxInfo.m_timeValue; // TODO - for (const auto& eventData : emfxInfo.mEvent->GetEventDatas()) + for (const auto& eventData : emfxInfo.m_event->GetEventDatas()) { if (const EMotionFX::TwoStringEventData* twoStringEventData = azrtti_cast(eventData.get())) { @@ -153,8 +153,8 @@ namespace EMotionFX break; } } - motionEvent.m_globalWeight = emfxInfo.mGlobalWeight; - motionEvent.m_localWeight = emfxInfo.mLocalWeight; + motionEvent.m_globalWeight = emfxInfo.m_globalWeight; + motionEvent.m_localWeight = emfxInfo.m_localWeight; motionEvent.m_isEventStart = emfxInfo.IsEventStart(); // Queue the event to flush on the main thread. @@ -469,9 +469,9 @@ namespace EMotionFX // Initialize MCore, which is EMotionFX's standard library of containers and systems. MCore::Initializer::InitSettings coreSettings; - coreSettings.mMemAllocFunction = &EMotionFXAlloc; - coreSettings.mMemReallocFunction = &EMotionFXRealloc; - coreSettings.mMemFreeFunction = &EMotionFXFree; + coreSettings.m_memAllocFunction = &EMotionFXAlloc; + coreSettings.m_memReallocFunction = &EMotionFXRealloc; + coreSettings.m_memFreeFunction = &EMotionFXFree; if (!MCore::Initializer::Init(&coreSettings)) { AZ_Error("EMotion FX Animation", false, "Failed to initialize EMotion FX SDK Core"); @@ -480,7 +480,7 @@ namespace EMotionFX // Initialize EMotionFX runtime. EMotionFX::Initializer::InitSettings emfxSettings; - emfxSettings.mUnitType = MCore::Distance::UNITTYPE_METERS; + emfxSettings.m_unitType = MCore::Distance::UNITTYPE_METERS; if (!EMotionFX::Initializer::Init(&emfxSettings)) { @@ -619,8 +619,8 @@ namespace EMotionFX } // Process the plugins. - const AZ::u32 numPlugins = pluginManager->GetNumActivePlugins(); - for (AZ::u32 i = 0; i < numPlugins; ++i) + const size_t numPlugins = pluginManager->GetNumActivePlugins(); + for (size_t i = 0; i < numPlugins; ++i) { EMStudio::EMStudioPlugin* plugin = pluginManager->GetActivePlugin(i); plugin->ProcessFrame(delta); @@ -677,8 +677,8 @@ namespace EMotionFX const float timeDelta = delta; const ActorManager* actorManager = GetEMotionFX().GetActorManager(); - const AZ::u32 numActorInstances = actorManager->GetNumActorInstances(); - for (AZ::u32 i = 0; i < numActorInstances; ++i) + const size_t numActorInstances = actorManager->GetNumActorInstances(); + for (size_t i = 0; i < numActorInstances; ++i) { const ActorInstance* actorInstance = actorManager->GetActorInstance(i); @@ -709,7 +709,7 @@ namespace EMotionFX AZ::Transform currentTransform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(currentTransform, entityId, &AZ::TransformBus::Events::GetWorldTM); - const AZ::Vector3 actorInstancePosition = actorInstance->GetWorldSpaceTransform().mPosition; + const AZ::Vector3 actorInstancePosition = actorInstance->GetWorldSpaceTransform().m_position; const AZ::Vector3 positionDelta = actorInstancePosition - currentTransform.GetTranslation(); if (hasPhysicsController) @@ -724,7 +724,7 @@ namespace EMotionFX } // Update the entity rotation. - const AZ::Quaternion actorInstanceRotation = actorInstance->GetWorldSpaceTransform().mRotation; + const AZ::Quaternion actorInstanceRotation = actorInstance->GetWorldSpaceTransform().m_rotation; const AZ::Quaternion currentRotation = currentTransform.GetRotation(); if (!currentRotation.IsClose(actorInstanceRotation, AZ::Constants::FloatEpsilon)) { diff --git a/Gems/EMotionFX/Code/Tests/AdditiveMotionSamplingTests.cpp b/Gems/EMotionFX/Code/Tests/AdditiveMotionSamplingTests.cpp index ae8b42441a..4171598801 100644 --- a/Gems/EMotionFX/Code/Tests/AdditiveMotionSamplingTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AdditiveMotionSamplingTests.cpp @@ -27,10 +27,10 @@ namespace EMotionFX void CreateSubMotionLikeBindPose(const std::string& name) { const Skeleton* skeleton = m_actor->GetSkeleton(); - AZ::u32 jointIndex = InvalidIndex32; + size_t jointIndex = InvalidIndex; const Node* node = skeleton->FindNodeAndIndexByName(name.c_str(), jointIndex); ASSERT_NE(node, nullptr); - ASSERT_NE(jointIndex, InvalidIndex32); + ASSERT_NE(jointIndex, InvalidIndex); const Pose* bindPose = m_actorInstance->GetTransformData()->GetBindPose(); const Transform& transform = bindPose->GetLocalSpaceTransform(jointIndex); @@ -41,7 +41,7 @@ namespace EMotionFX { // Find and store the joint index. const Skeleton* skeleton = m_actor->GetSkeleton(); - AZ::u32 jointIndex = InvalidIndex32; + size_t jointIndex = InvalidIndex; const Node* node = skeleton->FindNodeAndIndexByName(name.c_str(), jointIndex); ASSERT_NE(node, nullptr); ASSERT_NE(jointIndex, InvalidIndex32); @@ -91,9 +91,9 @@ namespace EMotionFX protected: Motion* m_motion = nullptr; MotionInstance* m_motionInstance = nullptr; // Automatically deleted internally when deleting the actor instance. - std::vector m_jointIndices; + std::vector m_jointIndices; std::vector m_jointNames { "l_upLeg", "l_loLeg", "l_ankle" }; - AZ::u32 m_footIndex = InvalidIndex32; + size_t m_footIndex = InvalidIndex; }; TEST_F(MotionSamplingFixture, SampleAdditiveJoint) @@ -102,7 +102,7 @@ namespace EMotionFX // Sample the joints that exist in our actor skeleton as well as inside the motion data. const Pose* bindPose = m_actorInstance->GetTransformData()->GetBindPose(); - for (AZ::u32 jointIndex : m_jointIndices) + for (size_t jointIndex : m_jointIndices) { // Sample the motion. Transform transform = Transform::CreateZero(); // Set all to Zero, not identity as this methods might return identity and we want to verify that. @@ -140,7 +140,7 @@ namespace EMotionFX // Test if the joints that exist in both motion and actor have the expected transforms. const Pose* bindPose = m_actorInstance->GetTransformData()->GetBindPose(); - for (AZ::u32 jointIndex : m_jointIndices) + for (size_t jointIndex : m_jointIndices) { const Transform& transform = pose.GetLocalSpaceTransform(jointIndex); const Transform& bindTransform = bindPose->GetLocalSpaceTransform(jointIndex); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphComponentBusTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphComponentBusTests.cpp index 35d63c3c53..b40088e01f 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphComponentBusTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphComponentBusTests.cpp @@ -52,12 +52,12 @@ namespace EMotionFX MOCK_METHOD1(OnAnimGraphInstanceCreated, void(EMotionFX::AnimGraphInstance*)); MOCK_METHOD1(OnAnimGraphInstanceDestroyed, void(EMotionFX::AnimGraphInstance*)); - MOCK_METHOD4(OnAnimGraphFloatParameterChanged, void(EMotionFX::AnimGraphInstance*, AZ::u32, float, float)); - MOCK_METHOD4(OnAnimGraphBoolParameterChanged, void(EMotionFX::AnimGraphInstance*, AZ::u32, bool, bool)); - MOCK_METHOD4(OnAnimGraphStringParameterChanged, void(EMotionFX::AnimGraphInstance*, AZ::u32, const char*, const char*)); - MOCK_METHOD4(OnAnimGraphVector2ParameterChanged, void(EMotionFX::AnimGraphInstance*, AZ::u32, const AZ::Vector2&, const AZ::Vector2&)); - MOCK_METHOD4(OnAnimGraphVector3ParameterChanged, void(EMotionFX::AnimGraphInstance*, AZ::u32, const AZ::Vector3&, const AZ::Vector3&)); - MOCK_METHOD4(OnAnimGraphRotationParameterChanged, void(EMotionFX::AnimGraphInstance*, AZ::u32, const AZ::Quaternion&, const AZ::Quaternion&)); + MOCK_METHOD4(OnAnimGraphFloatParameterChanged, void(EMotionFX::AnimGraphInstance*, size_t, float, float)); + MOCK_METHOD4(OnAnimGraphBoolParameterChanged, void(EMotionFX::AnimGraphInstance*, size_t, bool, bool)); + MOCK_METHOD4(OnAnimGraphStringParameterChanged, void(EMotionFX::AnimGraphInstance*, size_t, const char*, const char*)); + MOCK_METHOD4(OnAnimGraphVector2ParameterChanged, void(EMotionFX::AnimGraphInstance*, size_t, const AZ::Vector2&, const AZ::Vector2&)); + MOCK_METHOD4(OnAnimGraphVector3ParameterChanged, void(EMotionFX::AnimGraphInstance*, size_t, const AZ::Vector3&, const AZ::Vector3&)); + MOCK_METHOD4(OnAnimGraphRotationParameterChanged, void(EMotionFX::AnimGraphInstance*, size_t, const AZ::Quaternion&, const AZ::Quaternion&)); }; class AnimGraphComponentBusTests @@ -143,7 +143,7 @@ namespace EMotionFX Integration::ActorComponent* m_actorComponent = nullptr; Integration::AnimGraphComponent* m_animGraphComponent = nullptr; AnimGraphInstance* m_animGraphInstance = nullptr; - AZ::u32 m_parameterIndex = InvalidIndex32; + size_t m_parameterIndex = InvalidIndex; std::string m_parameterName; }; @@ -164,7 +164,11 @@ namespace EMotionFX PrepareParameterTest(aznew FloatSliderParameter()); - EXPECT_CALL(testBus, OnAnimGraphFloatParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, 3.0f)); + { + testing::InSequence parameterChangedCallSequence; + EXPECT_CALL(testBus, OnAnimGraphFloatParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, 3.0f)); + EXPECT_CALL(testBus, OnAnimGraphFloatParameterChanged(m_animGraphInstance, m_parameterIndex, 3.0f, 4.0f)); + } // SetParameterFloat/GetParameterFloat() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterFloat, m_parameterIndex, 3.0f); @@ -172,8 +176,6 @@ namespace EMotionFX Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterFloat, m_parameterIndex); EXPECT_EQ(newValue, 3.0f) << "Expected a parameter value of 3.0."; - EXPECT_CALL(testBus, OnAnimGraphFloatParameterChanged(m_animGraphInstance, m_parameterIndex, 3.0f, 4.0f)); - // SetNamedParameterFloat/GetNamedParameterFloat() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterFloat, m_parameterName.c_str(), 4.0f); Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetNamedParameterFloat, m_parameterName.c_str()); @@ -187,7 +189,12 @@ namespace EMotionFX PrepareParameterTest(aznew BoolParameter()); - EXPECT_CALL(testBus, OnAnimGraphBoolParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, true)); + { + testing::InSequence parameterChangedCallSequence; + EXPECT_CALL(testBus, OnAnimGraphBoolParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, true)); + EXPECT_CALL(testBus, OnAnimGraphBoolParameterChanged(m_animGraphInstance, m_parameterIndex, true, false)); + } + // SetParameterBool/GetParameterBool() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterBool, m_parameterIndex, true); @@ -195,8 +202,6 @@ namespace EMotionFX Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterBool, m_parameterIndex); EXPECT_EQ(newValue, true) << "Expected true as parameter value."; - EXPECT_CALL(testBus, OnAnimGraphBoolParameterChanged(m_animGraphInstance, m_parameterIndex, true, false)); - // SetNamedParameterBool/GetNamedParameterBool() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterBool, m_parameterName.c_str(), false); Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetNamedParameterBool, m_parameterName.c_str()); @@ -210,7 +215,8 @@ namespace EMotionFX PrepareParameterTest(aznew StringParameter()); - EXPECT_CALL(testBus, OnAnimGraphStringParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, testing::_)); + EXPECT_CALL(testBus, OnAnimGraphStringParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, testing::_)) + .Times(2); // SetParameterString/GetParameterString() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterString, m_parameterIndex, "Test String"); @@ -218,8 +224,6 @@ namespace EMotionFX Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterString, m_parameterIndex); EXPECT_STREQ(newValue.c_str(), "Test String") << "Expected the test string parameter."; - EXPECT_CALL(testBus, OnAnimGraphStringParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, testing::_)); - // SetNamedParameterString/GetNamedParameterString() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterString, m_parameterName.c_str(), "Yet Another String"); Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetNamedParameterString, m_parameterName.c_str()); @@ -233,7 +237,11 @@ namespace EMotionFX PrepareParameterTest(aznew Vector2Parameter()); - EXPECT_CALL(testBus, OnAnimGraphVector2ParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, AZ::Vector2(1.0f, 2.0f))); + { + testing::InSequence parameterChangedCallSequence; + EXPECT_CALL(testBus, OnAnimGraphVector2ParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, AZ::Vector2(1.0f, 2.0f))); + EXPECT_CALL(testBus, OnAnimGraphVector2ParameterChanged(m_animGraphInstance, m_parameterIndex, AZ::Vector2(1.0f, 2.0f), AZ::Vector2(3.0f, 4.0f))); + } // SetParameterVector2/GetParameterVector2() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterVector2, m_parameterIndex, AZ::Vector2(1.0f, 2.0f)); @@ -241,8 +249,6 @@ namespace EMotionFX Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterVector2, m_parameterIndex); EXPECT_EQ(newValue, AZ::Vector2(1.0f, 2.0f)); - EXPECT_CALL(testBus, OnAnimGraphVector2ParameterChanged(m_animGraphInstance, m_parameterIndex, AZ::Vector2(1.0f, 2.0f), AZ::Vector2(3.0f, 4.0f))); - // SetNamedParameterVector2/GetNamedParameterVector2() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterVector2, m_parameterName.c_str(), AZ::Vector2(3.0f, 4.0f)); Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetNamedParameterVector2, m_parameterName.c_str()); @@ -256,7 +262,11 @@ namespace EMotionFX PrepareParameterTest(aznew Vector3Parameter()); - EXPECT_CALL(testBus, OnAnimGraphVector3ParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, AZ::Vector3(1.0f, 2.0f, 3.0f))); + { + testing::InSequence parameterChangedCallSequence; + EXPECT_CALL(testBus, OnAnimGraphVector3ParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, AZ::Vector3(1.0f, 2.0f, 3.0f))); + EXPECT_CALL(testBus, OnAnimGraphVector3ParameterChanged(m_animGraphInstance, m_parameterIndex, AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Vector3(4.0f, 5.0f, 6.0f))); + } // SetParameterVector3/GetParameterVector3() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterVector3, m_parameterIndex, AZ::Vector3(1.0f, 2.0f, 3.0f)); @@ -264,8 +274,6 @@ namespace EMotionFX Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterVector3, m_parameterIndex); EXPECT_EQ(newValue, AZ::Vector3(1.0f, 2.0f, 3.0f)); - EXPECT_CALL(testBus, OnAnimGraphVector3ParameterChanged(m_animGraphInstance, m_parameterIndex, AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Vector3(4.0f, 5.0f, 6.0f))); - // SetNamedParameterVector3/GetNamedParameterVector3() test Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterVector3, m_parameterName.c_str(), AZ::Vector3(4.0f, 5.0f, 6.0f)); Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetNamedParameterVector3, m_parameterName.c_str()); @@ -279,7 +287,8 @@ namespace EMotionFX PrepareParameterTest(aznew RotationParameter()); - EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, testing::_)); + EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, testing::_)) + .Times(2); // SetParameterRotationEuler/GetParameterRotationEuler() test AZ::Vector3 expectedEuler(AZ::DegToRad(30.0f), AZ::DegToRad(20.0f), 0.0f); @@ -288,8 +297,6 @@ namespace EMotionFX Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterRotationEuler, m_parameterIndex); EXPECT_TRUE(newValue.IsClose(expectedEuler, 0.001f)); - EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, testing::_)); - // SetNamedParameterRotationEuler/GetNamedParameterRotationEuler() test expectedEuler = AZ::Vector3(AZ::DegToRad(45.0f), 0.0f, AZ::DegToRad(30.0f)); Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterRotationEuler, m_parameterName.c_str(), expectedEuler); @@ -299,30 +306,33 @@ namespace EMotionFX TEST_F(AnimGraphComponentBusTests, RotationParameter) { - AZ::Vector3 expected(AZ::DegToRad(30.0f), AZ::DegToRad(20.0f), 0.0f); - AZ::Quaternion expectedQuat = MCore::AzEulerAnglesToAzQuat(expected); + const AZ::Vector3 firstExpected(AZ::DegToRad(30.0f), AZ::DegToRad(20.0f), 0.0f); + const AZ::Quaternion firstExpectedQuat = MCore::AzEulerAnglesToAzQuat(firstExpected); + const AZ::Vector3 secondExpected = AZ::Vector3(AZ::DegToRad(45.0f), 0.0f, AZ::DegToRad(30.0f)); + const AZ::Quaternion secondExpectedQuat = MCore::AzEulerAnglesToAzQuat(secondExpected); + AnimGraphComponentNotificationTestBus testBus(m_entityId); EXPECT_CALL(testBus, OnAnimGraphInstanceCreated(testing::_)); PrepareParameterTest(aznew RotationParameter()); - EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, expectedQuat)); + { + testing::InSequence parameterChangedCallSequence; + EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, firstExpectedQuat)); + EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, secondExpectedQuat)); + } // SetParameterRotation/GetParameterRotation() test - Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterRotation, m_parameterIndex, expectedQuat); + Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetParameterRotation, m_parameterIndex, firstExpectedQuat); AZ::Quaternion newValue; Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetParameterRotation, m_parameterIndex); - EXPECT_TRUE(newValue.IsClose(expectedQuat, 0.001f)); - - expected = AZ::Vector3(AZ::DegToRad(45.0f), 0.0f, AZ::DegToRad(30.0f)); - expectedQuat = MCore::AzEulerAnglesToAzQuat(expected); - EXPECT_CALL(testBus, OnAnimGraphRotationParameterChanged(m_animGraphInstance, m_parameterIndex, testing::_, expectedQuat)); + EXPECT_TRUE(newValue.IsClose(firstExpectedQuat, 0.001f)); // SetNamedParameterRotation/GetNamedParameterRotation() test - Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterRotation, m_parameterName.c_str(), expectedQuat); + Integration::AnimGraphComponentRequestBus::Event(m_entityId, &Integration::AnimGraphComponentRequestBus::Events::SetNamedParameterRotation, m_parameterName.c_str(), secondExpectedQuat); Integration::AnimGraphComponentRequestBus::EventResult(newValue, m_entityId, &Integration::AnimGraphComponentRequestBus::Events::GetNamedParameterRotation, m_parameterName.c_str()); - EXPECT_TRUE(newValue.IsClose(expectedQuat, 0.001f)); + EXPECT_TRUE(newValue.IsClose(secondExpectedQuat, 0.001f)); } TEST_F(AnimGraphComponentBusTests, OnAnimGraphInstanceDestroyed) diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp index e05e5f3245..aa1bde295a 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphDeferredInitTests.cpp @@ -36,7 +36,7 @@ namespace EMotionFX m_blendTree->AddChildNode(paramNode); paramNode->InitAfterLoading(m_animGraph.get()); paramNode->InvalidateUniqueData(m_animGraphInstance); - m_blend2Node->AddConnection(paramNode, paramNode->FindOutputPortByName("weightParam")->mPortID, BlendTreeBlend2Node::PORTID_INPUT_WEIGHT); + m_blend2Node->AddConnection(paramNode, paramNode->FindOutputPortByName("weightParam")->m_portId, BlendTreeBlend2Node::PORTID_INPUT_WEIGHT); } void ConstructGraph() diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphEventTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphEventTests.cpp index 8479bda94c..1b88092917 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphEventTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphEventTests.cpp @@ -63,8 +63,8 @@ namespace EMotionFX MotionSet::MotionEntry* motionEntry = AddMotionEntry("testMotion", 1.0); // Assign a motion to all our motion nodes - const AZ::u32 numStates = m_rootStateMachine->GetNumChildNodes(); - for (AZ::u32 i = 0; i < numStates; ++i) + const size_t numStates = m_rootStateMachine->GetNumChildNodes(); + for (size_t i = 0; i < numStates; ++i) { AnimGraphMotionNode* motionNode = azdynamic_cast(m_rootStateMachine->GetChildNode(i)); if (motionNode) diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphFixture.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphFixture.cpp index 31c5455571..ab9d91046b 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphFixture.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphFixture.cpp @@ -45,7 +45,7 @@ namespace EMotionFX ConstructActor(); ASSERT_TRUE(m_actor) << "Construct actor did not build a valid actor."; m_actor->ResizeTransformData(); - m_actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/ false, /*generateOBBs=*/ false, /*convertUnitType=*/ false); + m_actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/ false, /*convertUnitType=*/ false); } { m_motionSet = aznew MotionSet("testMotionSet"); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp index 6fa1d962ab..121f438d82 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphMotionNodeTests.cpp @@ -118,16 +118,16 @@ namespace EMotionFX } protected: - AZ::u32 m_l_handIndex = InvalidIndex32; - AZ::u32 m_l_loArmIndex = InvalidIndex32; - AZ::u32 m_l_loLegIndex = InvalidIndex32; - AZ::u32 m_l_ankleIndex = InvalidIndex32; - AZ::u32 m_r_handIndex = InvalidIndex32; - AZ::u32 m_r_loArmIndex = InvalidIndex32; - AZ::u32 m_r_loLegIndex = InvalidIndex32; - AZ::u32 m_r_ankleIndex = InvalidIndex32; - AZ::u32 m_jack_rootIndex = InvalidIndex32; - AZ::u32 m_bip01__pelvisIndex = InvalidIndex32; + size_t m_lHandIndex = InvalidIndex; + size_t m_lLoArmIndex = InvalidIndex; + size_t m_lLoLegIndex = InvalidIndex; + size_t m_lAnkleIndex = InvalidIndex; + size_t m_rHandIndex = InvalidIndex; + size_t m_rLoArmIndex = InvalidIndex; + size_t m_rLoLegIndex = InvalidIndex; + size_t m_rAnkleIndex = InvalidIndex; + size_t m_jackRootIndex = InvalidIndex; + size_t m_bip01PelvisIndex = InvalidIndex; AnimGraphMotionNode* m_motionNode = nullptr; BlendTree* m_blendTree = nullptr; BlendTreeFloatConstantNode* m_fltConstNode = nullptr; @@ -147,16 +147,16 @@ namespace EMotionFX void SetupIndices() { - Node* rootNode = m_jackSkeleton->FindNodeAndIndexByName("jack_root", m_jack_rootIndex); - Node* pelvisNode = m_jackSkeleton->FindNodeAndIndexByName("Bip01__pelvis", m_bip01__pelvisIndex); - Node* lHandNode = m_jackSkeleton->FindNodeAndIndexByName("l_hand", m_l_handIndex); - Node* lLoArmNode = m_jackSkeleton->FindNodeAndIndexByName("l_loArm", m_l_loArmIndex); - Node* lLoLegNode = m_jackSkeleton->FindNodeAndIndexByName("l_loLeg", m_l_loLegIndex); - Node* lAnkleNode = m_jackSkeleton->FindNodeAndIndexByName("l_ankle", m_l_ankleIndex); - Node* rHandNode = m_jackSkeleton->FindNodeAndIndexByName("r_hand", m_r_handIndex); - Node* rLoArmNode = m_jackSkeleton->FindNodeAndIndexByName("r_loArm", m_r_loArmIndex); - Node* rLoLegNode = m_jackSkeleton->FindNodeAndIndexByName("r_loLeg", m_r_loLegIndex); - Node* rAnkleNode = m_jackSkeleton->FindNodeAndIndexByName("r_ankle", m_r_ankleIndex); + Node* rootNode = m_jackSkeleton->FindNodeAndIndexByName("jack_root", m_jackRootIndex); + Node* pelvisNode = m_jackSkeleton->FindNodeAndIndexByName("Bip01__pelvis", m_bip01PelvisIndex); + Node* lHandNode = m_jackSkeleton->FindNodeAndIndexByName("l_hand", m_lHandIndex); + Node* lLoArmNode = m_jackSkeleton->FindNodeAndIndexByName("l_loArm", m_lLoArmIndex); + Node* lLoLegNode = m_jackSkeleton->FindNodeAndIndexByName("l_loLeg", m_lLoLegIndex); + Node* lAnkleNode = m_jackSkeleton->FindNodeAndIndexByName("l_ankle", m_lAnkleIndex); + Node* rHandNode = m_jackSkeleton->FindNodeAndIndexByName("r_hand", m_rHandIndex); + Node* rLoArmNode = m_jackSkeleton->FindNodeAndIndexByName("r_loArm", m_rLoArmIndex); + Node* rLoLegNode = m_jackSkeleton->FindNodeAndIndexByName("r_loLeg", m_rLoLegIndex); + Node* rAnkleNode = m_jackSkeleton->FindNodeAndIndexByName("r_ankle", m_rAnkleIndex); // Make sure all nodes exist. ASSERT_TRUE(rootNode && pelvisNode && lHandNode && lLoArmNode && lLoLegNode && lAnkleNode && @@ -166,14 +166,14 @@ namespace EMotionFX void SetupMirrorNodes() { m_actor->AllocateNodeMirrorInfos(); - m_actor->GetNodeMirrorInfo(m_l_handIndex).mSourceNode = static_cast(m_r_handIndex); - m_actor->GetNodeMirrorInfo(m_r_handIndex).mSourceNode = static_cast(m_l_handIndex); - m_actor->GetNodeMirrorInfo(m_l_loArmIndex).mSourceNode = static_cast(m_r_loArmIndex); - m_actor->GetNodeMirrorInfo(m_r_loArmIndex).mSourceNode = static_cast(m_l_loArmIndex); - m_actor->GetNodeMirrorInfo(m_l_loLegIndex).mSourceNode = static_cast(m_r_loLegIndex); - m_actor->GetNodeMirrorInfo(m_r_loLegIndex).mSourceNode = static_cast(m_l_loLegIndex); - m_actor->GetNodeMirrorInfo(m_l_ankleIndex).mSourceNode = static_cast(m_r_ankleIndex); - m_actor->GetNodeMirrorInfo(m_r_ankleIndex).mSourceNode = static_cast(m_l_ankleIndex); + m_actor->GetNodeMirrorInfo(m_lHandIndex).m_sourceNode = static_cast(m_rHandIndex); + m_actor->GetNodeMirrorInfo(m_rHandIndex).m_sourceNode = static_cast(m_lHandIndex); + m_actor->GetNodeMirrorInfo(m_lLoArmIndex).m_sourceNode = static_cast(m_rLoArmIndex); + m_actor->GetNodeMirrorInfo(m_rLoArmIndex).m_sourceNode = static_cast(m_lLoArmIndex); + m_actor->GetNodeMirrorInfo(m_lLoLegIndex).m_sourceNode = static_cast(m_rLoLegIndex); + m_actor->GetNodeMirrorInfo(m_rLoLegIndex).m_sourceNode = static_cast(m_lLoLegIndex); + m_actor->GetNodeMirrorInfo(m_lAnkleIndex).m_sourceNode = static_cast(m_rAnkleIndex); + m_actor->GetNodeMirrorInfo(m_rAnkleIndex).m_sourceNode = static_cast(m_lAnkleIndex); m_actor->AutoDetectMirrorAxes(); } }; @@ -186,11 +186,11 @@ namespace EMotionFX // Follow-through during the duration(~1.06666672 seconds) of the motion. for (float i = 0.1f; i < 1.2f; i += 0.1f) { - const AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - const AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + const AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + const AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; GetEMotionFX().Update(1.0f / 10.0f); - const AZ::Vector3 rootUpdatedPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - const AZ::Vector3 pelvisUpdatedPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + const AZ::Vector3 rootUpdatedPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + const AZ::Vector3 pelvisUpdatedPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; const float rootDifference = rootUpdatedPos.GetY() - rootCurrentPos.GetY(); const float pelvisDifference = pelvisUpdatedPos.GetY() - pelvisCurrentPos.GetY(); @@ -203,7 +203,7 @@ namespace EMotionFX TEST_F(AnimGraphMotionNodeFixture, NoInputAndLoopOutputsCorrectMotionAndPose) { AnimGraphMotionNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_motionNode)); - uniqueData->mReload = true; + uniqueData->m_reload = true; m_motionNode->SetLoop(true); m_motionNode->InvalidateUniqueData(m_animGraphInstance); m_actorInstance->SetMotionExtractionEnabled(false); @@ -211,14 +211,14 @@ namespace EMotionFX GetEMotionFX().Update(0.0f); // Needed to trigger a refresh of motion node internals. // Update to half the motion's duration. - AZ::Vector3 rootStartPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - AZ::Vector3 pelvisStartPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + AZ::Vector3 rootStartPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + AZ::Vector3 pelvisStartPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; const float duration = m_motionNode->GetDuration(m_animGraphInstance); const float offset = duration * 0.5f; GetEMotionFX().Update(offset); EXPECT_FLOAT_EQ(uniqueData->GetCurrentPlayTime(), offset); - AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; EXPECT_TRUE(rootCurrentPos.GetY() > rootStartPos.GetY()) << "Y-axis position of root should increase."; EXPECT_TRUE(pelvisCurrentPos.GetY() > pelvisStartPos.GetY()) << "Y-axis position of pelvis should increase."; @@ -227,8 +227,8 @@ namespace EMotionFX pelvisStartPos = pelvisCurrentPos; GetEMotionFX().Update(duration * 0.6f); EXPECT_FLOAT_EQ(uniqueData->GetCurrentPlayTime(), duration * 0.1f); - rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; EXPECT_TRUE(rootCurrentPos.GetY() < rootStartPos.GetY()) << "Y-axis position of root should increase."; EXPECT_TRUE(pelvisCurrentPos.GetY() < pelvisStartPos.GetY()) << "Y-axis position of pelvis should increase."; }; @@ -237,7 +237,7 @@ namespace EMotionFX { m_motionNode->SetReverse(true); AnimGraphMotionNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_motionNode)); - uniqueData->mReload = true; + uniqueData->m_reload = true; GetEMotionFX().Update(1.1f); EXPECT_TRUE(m_motionNode->GetIsReversed()) << "Reverse effect should be on."; @@ -246,11 +246,11 @@ namespace EMotionFX // Follow-through during the duration(~1.06666672 seconds) of the motion. for (float i = 0.1f; i < 1.2f; i += 0.1f) { - const AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - const AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + const AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + const AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; GetEMotionFX().Update(1.0f / 10.0f); - const AZ::Vector3 rootUpdatedPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - const AZ::Vector3 pelvisUpdatedPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; + const AZ::Vector3 rootUpdatedPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + const AZ::Vector3 pelvisUpdatedPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; const float rootDifference = rootCurrentPos.GetY() - rootUpdatedPos.GetY(); const float pelvisDifference = pelvisCurrentPos.GetY() - pelvisUpdatedPos.GetY(); @@ -263,33 +263,33 @@ namespace EMotionFX TEST_F(AnimGraphMotionNodeFixture, DISABLED_NoInputAndMirrorMotionOutputsCorrectMotionAndPose) { AnimGraphMotionNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_motionNode)); - uniqueData->mReload = true; + uniqueData->m_reload = true; GetEMotionFX().Update(1.0f); // Get positions before mirroring to compare with mirrored positions later. - const AZ::Vector3 l_handCurrentPos = m_jackPose->GetModelSpaceTransform(m_l_handIndex).mPosition; - const AZ::Vector3 l_loArmCurrentPos = m_jackPose->GetModelSpaceTransform(m_l_loArmIndex).mPosition; - const AZ::Vector3 l_loLegCurrentPos = m_jackPose->GetModelSpaceTransform(m_l_loLegIndex).mPosition; - const AZ::Vector3 l_ankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_l_ankleIndex).mPosition; - const AZ::Vector3 r_handCurrentPos = m_jackPose->GetModelSpaceTransform(m_r_handIndex).mPosition; - const AZ::Vector3 r_loArmCurrentPos = m_jackPose->GetModelSpaceTransform(m_r_loArmIndex).mPosition; - const AZ::Vector3 r_loLegCurrentPos = m_jackPose->GetModelSpaceTransform(m_r_loLegIndex).mPosition; - const AZ::Vector3 r_ankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_r_ankleIndex).mPosition; + const AZ::Vector3 l_handCurrentPos = m_jackPose->GetModelSpaceTransform(m_lHandIndex).m_position; + const AZ::Vector3 l_loArmCurrentPos = m_jackPose->GetModelSpaceTransform(m_lLoArmIndex).m_position; + const AZ::Vector3 l_loLegCurrentPos = m_jackPose->GetModelSpaceTransform(m_lLoLegIndex).m_position; + const AZ::Vector3 l_ankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_lAnkleIndex).m_position; + const AZ::Vector3 r_handCurrentPos = m_jackPose->GetModelSpaceTransform(m_rHandIndex).m_position; + const AZ::Vector3 r_loArmCurrentPos = m_jackPose->GetModelSpaceTransform(m_rLoArmIndex).m_position; + const AZ::Vector3 r_loLegCurrentPos = m_jackPose->GetModelSpaceTransform(m_rLoLegIndex).m_position; + const AZ::Vector3 r_ankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_rAnkleIndex).m_position; m_motionNode->SetMirrorMotion(true); - uniqueData->mReload = true; + uniqueData->m_reload = true; GetEMotionFX().Update(0.0001f); EXPECT_TRUE(m_motionNode->GetMirrorMotion()) << "Mirror motion effect should be on."; - const AZ::Vector3 l_handMirroredPos = m_jackPose->GetModelSpaceTransform(m_l_handIndex).mPosition; - const AZ::Vector3 l_loArmMirroredPos = m_jackPose->GetModelSpaceTransform(m_l_loArmIndex).mPosition; - const AZ::Vector3 l_loLegMirroredPos = m_jackPose->GetModelSpaceTransform(m_l_loLegIndex).mPosition; - const AZ::Vector3 l_ankleMirroredPos = m_jackPose->GetModelSpaceTransform(m_l_ankleIndex).mPosition; - const AZ::Vector3 r_handMirroredPos = m_jackPose->GetModelSpaceTransform(m_r_handIndex).mPosition; - const AZ::Vector3 r_loArmMirroredPos = m_jackPose->GetModelSpaceTransform(m_r_loArmIndex).mPosition; - const AZ::Vector3 r_loLegMirroredPos = m_jackPose->GetModelSpaceTransform(m_r_loLegIndex).mPosition; - const AZ::Vector3 r_ankleMirroredPos = m_jackPose->GetModelSpaceTransform(m_r_ankleIndex).mPosition; + const AZ::Vector3 l_handMirroredPos = m_jackPose->GetModelSpaceTransform(m_lHandIndex).m_position; + const AZ::Vector3 l_loArmMirroredPos = m_jackPose->GetModelSpaceTransform(m_lLoArmIndex).m_position; + const AZ::Vector3 l_loLegMirroredPos = m_jackPose->GetModelSpaceTransform(m_lLoLegIndex).m_position; + const AZ::Vector3 l_ankleMirroredPos = m_jackPose->GetModelSpaceTransform(m_lAnkleIndex).m_position; + const AZ::Vector3 r_handMirroredPos = m_jackPose->GetModelSpaceTransform(m_rHandIndex).m_position; + const AZ::Vector3 r_loArmMirroredPos = m_jackPose->GetModelSpaceTransform(m_rLoArmIndex).m_position; + const AZ::Vector3 r_loLegMirroredPos = m_jackPose->GetModelSpaceTransform(m_rLoLegIndex).m_position; + const AZ::Vector3 r_ankleMirroredPos = m_jackPose->GetModelSpaceTransform(m_rAnkleIndex).m_position; EXPECT_TRUE(PositionsAreMirrored(l_handCurrentPos, r_handMirroredPos, 0.001f)) << "Actor's left hand should be mirrored to right hand."; EXPECT_TRUE(PositionsAreMirrored(l_handMirroredPos, r_handCurrentPos, 0.001f)) << "Actor's right hand should be mirrored to left hand."; @@ -303,7 +303,7 @@ namespace EMotionFX TEST_F(AnimGraphMotionNodeFixture, InPlaceInputAndNoEffectOutputsCorrectMotionAndPose) { - m_motionNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("InPlace")->mPortID, AnimGraphMotionNode::INPUTPORT_INPLACE); + m_motionNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("InPlace")->m_portId, AnimGraphMotionNode::INPUTPORT_INPLACE); ParamSetValue("InPlace", true); m_animGraphInstance->FindOrCreateUniqueNodeData(m_motionNode); @@ -315,15 +315,15 @@ namespace EMotionFX // Follow-through during the duration(~1.06666672 seconds) of the motion. for (float i = 0.1f; i < 1.2f; i += 0.1f) { - const AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - const AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; - const AZ::Vector3 lankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_l_ankleIndex).mPosition; - const AZ::Vector3 rankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_r_ankleIndex).mPosition; + const AZ::Vector3 rootCurrentPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + const AZ::Vector3 pelvisCurrentPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; + const AZ::Vector3 lankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_lAnkleIndex).m_position; + const AZ::Vector3 rankleCurrentPos = m_jackPose->GetModelSpaceTransform(m_rAnkleIndex).m_position; GetEMotionFX().Update(1.0f / 10.0f); - const AZ::Vector3 rootUpdatedPos = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - const AZ::Vector3 pelvisUpdatedPos = m_jackPose->GetModelSpaceTransform(m_bip01__pelvisIndex).mPosition; - const AZ::Vector3 lankleUpdatedPos = m_jackPose->GetModelSpaceTransform(m_l_ankleIndex).mPosition; - const AZ::Vector3 rankleUpdatedPos = m_jackPose->GetModelSpaceTransform(m_r_ankleIndex).mPosition; + const AZ::Vector3 rootUpdatedPos = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + const AZ::Vector3 pelvisUpdatedPos = m_jackPose->GetModelSpaceTransform(m_bip01PelvisIndex).m_position; + const AZ::Vector3 lankleUpdatedPos = m_jackPose->GetModelSpaceTransform(m_lAnkleIndex).m_position; + const AZ::Vector3 rankleUpdatedPos = m_jackPose->GetModelSpaceTransform(m_rAnkleIndex).m_position; EXPECT_TRUE(m_motionNode->GetIsInPlace(m_animGraphInstance)) << "InPlace flag of the motion node should be true."; EXPECT_TRUE(rootUpdatedPos.IsClose(rootCurrentPos, 0.0f)) << "Position of root should not change."; EXPECT_TRUE(pelvisCurrentPos != pelvisUpdatedPos) << "Position of pelvis should change."; @@ -343,26 +343,26 @@ namespace EMotionFX GetEMotionFX().Update(1.0f / 60.0f); // Root node's initial position under the first speed factor. - AZ::Vector3 rootInitialPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - uniqueData->mReload = true; + AZ::Vector3 rootInitialPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + uniqueData->m_reload = true; GetEMotionFX().Update(1.1f); // Root node's final position under the first speed factor. - AZ::Vector3 rootFinalPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; + AZ::Vector3 rootFinalPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; std::vector speedFactors = { 2.0f, 3.0f, 10.0f, 100.0f }; std::vector playTimes = { 0.6f, 0.4f, 0.11f, 0.011f }; - for (AZ::u32 i = 0; i < 4; i++) + for (size_t i = 0; i < 4; i++) { m_motionNode->Rewind(m_animGraphInstance); m_fltConstNode->SetValue(speedFactors[i]); GetEMotionFX().Update(1.0f / 60.0f); - uniqueData->mReload = true; - const AZ::Vector3 rootInitialPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; + uniqueData->m_reload = true; + const AZ::Vector3 rootInitialPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; // Faster play speed requires less play time to reach its final pose. GetEMotionFX().Update(playTimes[i]); - const AZ::Vector3 rootFinalPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; + const AZ::Vector3 rootFinalPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; EXPECT_TRUE(rootInitialPosUnderSpeed1.IsClose(rootInitialPosUnderSpeed2, 0.0f)) << "Root initial position should be same in different motion speeds."; EXPECT_TRUE(rootFinalPosUnderSpeed1.IsClose(rootFinalPosUnderSpeed2, 0.0f)) << "Root final position should be same in different motion speeds."; @@ -379,23 +379,23 @@ namespace EMotionFX m_motionNode->SetMotionPlaySpeed(1.0f); GetEMotionFX().Update(1.0f / 60.0f); - rootInitialPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; - uniqueData->mReload = true; + rootInitialPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; + uniqueData->m_reload = true; GetEMotionFX().Update(1.1f); - rootFinalPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; + rootFinalPosUnderSpeed1 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; // Similar test to using the InPlace input port. - for (AZ::u32 i = 0; i < 4; i++) + for (size_t i = 0; i < 4; i++) { m_motionNode->Rewind(m_animGraphInstance); m_motionNode->SetMotionPlaySpeed(speedFactors[i]); GetEMotionFX().Update(1.0f / 60.0f); - uniqueData->mReload = true; - const AZ::Vector3 rootInitialPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; + uniqueData->m_reload = true; + const AZ::Vector3 rootInitialPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; GetEMotionFX().Update(playTimes[i]); - const AZ::Vector3 rootFinalPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jack_rootIndex).mPosition; + const AZ::Vector3 rootFinalPosUnderSpeed2 = m_jackPose->GetModelSpaceTransform(m_jackRootIndex).m_position; EXPECT_TRUE(rootInitialPosUnderSpeed1.IsClose(rootInitialPosUnderSpeed2, 0.0f)); EXPECT_TRUE(rootFinalPosUnderSpeed1.IsClose(rootFinalPosUnderSpeed2, 0.0f)); @@ -412,7 +412,7 @@ namespace EMotionFX AddMotionData(TestMotionAssets::GetJackDie(), "jack_death_fall_back_zup"); m_motionNode->AddMotionId("jack_death_fall_back_zup"); AnimGraphMotionNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_motionNode)); - uniqueData->mReload = true; + uniqueData->m_reload = true; m_motionNode->Reinit(); m_motionNode->SetIndexMode(AnimGraphMotionNode::INDEXMODE_RANDOMIZE); @@ -426,14 +426,14 @@ namespace EMotionFX // In randomized index mode, all motions should at least appear once over 10 loops. bool motion1Displayed = false; bool motion2Displayed = false; - for (AZ::u32 i = 0; i < 20; i++) + for (size_t i = 0; i < 20; i++) { // Run the test loop multiple times to make sure all the motion index is picked. - uniqueData->mReload = true; + uniqueData->m_reload = true; m_motionNode->Reinit(); GetEMotionFX().Update(2.0f); - const uint32 motionIndex = uniqueData->mActiveMotionIndex; + const uint32 motionIndex = uniqueData->m_activeMotionIndex; if (motionIndex == 0) { motion1Displayed = true; @@ -457,18 +457,18 @@ namespace EMotionFX uniqueData->Reset(); m_motionNode->Reinit(); uniqueData->Update(); - uint32 currentMotionIndex = uniqueData->mActiveMotionIndex; + uint32 currentMotionIndex = uniqueData->m_activeMotionIndex; // In randomized no repeat index mode, motions should change in each loop. - for (AZ::u32 i = 0; i < 10; i++) + for (size_t i = 0; i < 10; i++) { - uniqueData->mReload = true; + uniqueData->m_reload = true; m_motionNode->Reinit(); // As we keep and use the cached version of the unique data, we need to manually update it. uniqueData->Update(); - const AZ::u32 updatedMotionIndex = uniqueData->mActiveMotionIndex; + const AZ::u32 updatedMotionIndex = uniqueData->m_activeMotionIndex; EXPECT_TRUE(updatedMotionIndex != currentMotionIndex) << "Updated motion index should be different from its previous motion index."; currentMotionIndex = updatedMotionIndex; } @@ -476,13 +476,13 @@ namespace EMotionFX m_motionNode->SetIndexMode(AnimGraphMotionNode::INDEXMODE_SEQUENTIAL); // In sequential index mode, motions should increase its index each time and wrap around. Basically iterating over the list of motions. - for (AZ::u32 i = 0; i < 10; i++) + for (size_t i = 0; i < 10; i++) { - uniqueData->mReload = true; + uniqueData->m_reload = true; m_motionNode->Reinit(); uniqueData->Update(); - EXPECT_NE(currentMotionIndex, uniqueData->mActiveMotionIndex) << "Updated motion index should match the expected motion index."; - currentMotionIndex = uniqueData->mActiveMotionIndex; + EXPECT_NE(currentMotionIndex, uniqueData->m_activeMotionIndex) << "Updated motion index should match the expected motion index."; + currentMotionIndex = uniqueData->m_activeMotionIndex; } }; } // end namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp index 67f6fa860e..7509f03ede 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphNodeEventFilterTests.cpp @@ -26,12 +26,12 @@ namespace EMotionFX { struct EventFilteringTestParam { - AnimGraphObject::EEventMode eventMode; - float motionTime; - float testDuration; // Maximum of time this test will be run. - AZStd::pair eventTimeRange; - float blendWeight; - int eventTriggerTimes; + AnimGraphObject::EEventMode m_eventMode; + float m_motionTime; + float m_testDuration; // Maximum of time this test will be run. + AZStd::pair m_eventTimeRange; + float m_blendWeight; + int m_eventTriggerTimes; }; // Use this event handler to test if the on event is called. @@ -86,7 +86,7 @@ namespace EMotionFX AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); motionNode->SetName(AZStd::string::format("MotionNode%zu", i).c_str()); m_blendTree->AddChildNode(motionNode); - m_blend2Node->AddConnection(motionNode, AnimGraphMotionNode::PORTID_OUTPUT_POSE, static_cast(i)); + m_blend2Node->AddConnection(motionNode, AnimGraphMotionNode::PORTID_OUTPUT_POSE, aznumeric_caster(i)); m_motionNodes.push_back(motionNode); } @@ -111,7 +111,7 @@ namespace EMotionFX const AZStd::string motionId = AZStd::string::format("Motion%zu", i); Motion* motion = aznew Motion(motionId.c_str()); motion->SetMotionData(aznew NonUniformMotionData()); - motion->GetMotionData()->SetDuration(param.motionTime); + motion->GetMotionData()->SetDuration(param.m_motionTime); m_motions.emplace_back(motion); MotionSet::MotionEntry* motionEntry = aznew MotionSet::MotionEntry(motion->GetName(), motion->GetName(), motion); m_motionSet->AddMotionEntry(motionEntry); @@ -124,7 +124,7 @@ namespace EMotionFX motion->GetEventTable()->AutoCreateSyncTrack(motion); AnimGraphSyncTrack* syncTrack = motion->GetEventTable()->GetSyncTrack(); AZStd::shared_ptr data = GetEMotionFX().GetEventManager()->FindOrCreateEventData(motionId.c_str(), "params"); - syncTrack->AddEvent(param.eventTimeRange.first, param.eventTimeRange.second, data); + syncTrack->AddEvent(param.m_eventTimeRange.first, param.m_eventTimeRange.second, data); } m_eventHandler = aznew EventFilteringEventHandler(); @@ -151,20 +151,20 @@ namespace EMotionFX TEST_P(AnimGraphNodeEventFilterTestFixture, EventFilterTests) { const EventFilteringTestParam& param = GetParam(); - m_floatNode->SetValue(param.blendWeight); - m_blend2Node->SetEventMode(param.eventMode); + m_floatNode->SetValue(param.m_blendWeight); + m_blend2Node->SetEventMode(param.m_eventMode); // Calling update first to make sure unique data is created. GetEMotionFX().Update(0.0f); // Expect the event handler will call different number of times based on the filtering mode, motion event range and test duration. EXPECT_CALL(*m_eventHandler, OnEvent(testing::_)) - .Times(param.eventTriggerTimes); + .Times(param.m_eventTriggerTimes); // Update emfx to trigger the event firing. float totalTime = 0.0f; const float deltaTime = 0.1f; - while (totalTime <= param.testDuration) + while (totalTime <= param.m_testDuration) { GetEMotionFX().Update(deltaTime); totalTime += deltaTime; diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphNodeProcessingTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphNodeProcessingTests.cpp index 4a85d452a3..32b82ab5b8 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphNodeProcessingTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphNodeProcessingTests.cpp @@ -69,7 +69,7 @@ namespace EMotionFX AnimGraphMotionNode* motionNode = aznew AnimGraphMotionNode(); motionNode->SetName(AZStd::string::format("MotionNode%zu", i).c_str()); m_blendTree->AddChildNode(motionNode); - m_blendNNode->AddConnection(motionNode, AnimGraphMotionNode::PORTID_OUTPUT_POSE, static_cast(i)); + m_blendNNode->AddConnection(motionNode, AnimGraphMotionNode::PORTID_OUTPUT_POSE, aznumeric_caster(i)); m_motionNodes.push_back(motionNode); } m_blendNNode->UpdateParamWeights(); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphParameterActionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphParameterActionTests.cpp index d49cc5568e..8d51069782 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphParameterActionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphParameterActionTests.cpp @@ -110,7 +110,7 @@ namespace EMotionFX { AZStd::unique_ptr newParameter(EMotionFX::ParameterFactory::Create(azrtti_typeid())); newParameter->SetName("Parameter1"); - CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), MCORE_INVALIDINDEX32); + CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), InvalidIndex); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); } @@ -119,7 +119,7 @@ namespace EMotionFX { AZStd::unique_ptr newParameter(EMotionFX::ParameterFactory::Create(azrtti_typeid())); newParameter->SetName(parameterName); - CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), MCORE_INVALIDINDEX32); + CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), InvalidIndex); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); } @@ -127,7 +127,8 @@ namespace EMotionFX action->Reinit(); AZ::Outcome parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 1) << "Parameter2 should be at the 2nd position."; + ASSERT_TRUE(parameterIndex.IsSuccess()); + EXPECT_EQ(parameterIndex.GetValue(), 1) << "Parameter2 should be at the 2nd position."; // 1. Move Parameter2 from the 2nd place to the 1st place. commandString = AZStd::string::format("AnimGraphMoveParameter -animGraphID %d -name \"%s\" -index %d ", @@ -136,19 +137,19 @@ namespace EMotionFX 0); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "Parameter2 should now be at the 1st position."; + ASSERT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "Parameter2 should now be at the 1st position."; EXPECT_EQ(parameterIndex.GetValue(), action->GetParameterIndex().GetValue()) << "The action should now refer to the 1st parameter in the anim graph."; // 2. Undo. EXPECT_TRUE(commandManager.Undo(result)) << result.c_str(); parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 1) << "Parameter2 should now be back at the 2nd position."; + ASSERT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 1) << "Parameter2 should now be back at the 2nd position."; EXPECT_EQ(parameterIndex.GetValue(), action->GetParameterIndex().GetValue()) << "The action should now refer to the 2nd parameter in the anim graph."; // 3. Redo. EXPECT_TRUE(commandManager.Redo(result)) << result.c_str(); parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "Parameter2 should now be back at the 1st position."; + ASSERT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "Parameter2 should now be back at the 1st position."; EXPECT_EQ(parameterIndex.GetValue(), action->GetParameterIndex().GetValue()) << "The action should now refer to the 1st parameter in the anim graph."; } } diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphParameterCommandsTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphParameterCommandsTests.cpp index 9dd6e61b3c..2f5a661850 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphParameterCommandsTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphParameterCommandsTests.cpp @@ -62,7 +62,6 @@ namespace AnimGraphParameterCommandsTests using ::MCore::GetStringIdPool; using ::MCore::ReflectionSerializer; using ::MCore::LogWarning; - using ::MCore::Array; } // namespace MCore namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionCommandTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionCommandTests.cpp index d8dd1c7343..0d420b6881 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionCommandTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphParameterConditionCommandTests.cpp @@ -47,7 +47,7 @@ namespace EMotionFX newParameter->SetName(parameterName); CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), - MCORE_INVALIDINDEX32); + InvalidIndex); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); } diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphRefCountTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphRefCountTests.cpp index 28e2536989..8b51f5b814 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphRefCountTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphRefCountTests.cpp @@ -39,8 +39,8 @@ namespace EMotionFX const uint32 threadIndex = this->m_actorInstance->GetThreadIndex(); // Check if data and pose ref counts are back to 0 for all nodes. - const uint32 numNodes = this->m_animGraph->GetNumNodes(); - for (uint32 i = 0; i < numNodes; ++i) + const size_t numNodes = this->m_animGraph->GetNumNodes(); + for (size_t i = 0; i < numNodes; ++i) { const AnimGraphNode* node = this->m_animGraph->GetNode(i); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp index 38acdd68ee..1f700129c0 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineInterruptionTests.cpp @@ -21,34 +21,34 @@ namespace EMotionFX struct AnimGraphStateMachine_InterruptionTestData { // Graph construction data. - float transitionLeftBlendTime; - float transitionLeftCountDownTime; - float transitionMiddleBlendTime; - float transitionMiddleCountDownTime; - float transitionRightBlendTime; - float transitionRightCountDownTime; + float m_transitionLeftBlendTime; + float m_transitionLeftCountDownTime; + float m_transitionMiddleBlendTime; + float m_transitionMiddleCountDownTime; + float m_transitionRightBlendTime; + float m_transitionRightCountDownTime; // Per frame checks. struct ActiveObjectsAtFrame { - AZ::u32 frameNr; - - bool stateA; - bool stateB; - bool stateC; - bool transitionLeft; - bool transitionMiddle; - bool transitionRight; - - AZ::u32 numStatesEntering; - AZ::u32 numStatesEntered; - AZ::u32 numStatesExited; - AZ::u32 numStatesEnded; - AZ::u32 numTransitionsStarted; - AZ::u32 numTransitionsEnded; + AZ::u32 m_frameNr; + + bool m_stateA; + bool m_stateB; + bool m_stateC; + bool m_transitionLeft; + bool m_transitionMiddle; + bool m_transitionRight; + + AZ::u32 m_numStatesEntering; + AZ::u32 m_numStatesEntered; + AZ::u32 m_numStatesExited; + AZ::u32 m_numStatesEnded; + AZ::u32 m_numTransitionsStarted; + AZ::u32 m_numTransitionsEnded; }; - std::vector activeObjectsAtFrame; + std::vector m_activeObjectsAtFrame; }; class AnimGraphStateMachine_InterruptionFixture @@ -86,21 +86,21 @@ namespace EMotionFX AnimGraphStateTransition* transitionLeft = AddTransitionWithTimeCondition(stateStart, stateA, - param.transitionLeftBlendTime/*blendTime*/, - param.transitionLeftCountDownTime)/*countDownTime*/; + param.m_transitionLeftBlendTime/*blendTime*/, + param.m_transitionLeftCountDownTime)/*countDownTime*/; transitionLeft->SetCanBeInterrupted(true); AnimGraphStateTransition* transitionMiddle = AddTransitionWithTimeCondition(stateStart, stateB, - param.transitionMiddleBlendTime, - param.transitionMiddleCountDownTime); + param.m_transitionMiddleBlendTime, + param.m_transitionMiddleCountDownTime); transitionMiddle->SetCanBeInterrupted(true); transitionMiddle->SetCanInterruptOtherTransitions(true); AnimGraphStateTransition* transitionRight = AddTransitionWithTimeCondition(stateStart, stateC, - param.transitionRightBlendTime, - param.transitionRightCountDownTime); + param.m_transitionRightBlendTime, + param.m_transitionRightCountDownTime); transitionRight->SetCanInterruptOtherTransitions(true); m_motionNodeAnimGraph->InitAfterLoading(); @@ -142,58 +142,58 @@ namespace EMotionFX /*preUpdateCallback*/[this](AnimGraphInstance*, float, float, int) {}, /*postUpdateCallback*/[this](AnimGraphInstance* animGraphInstance, [[maybe_unused]] float time, [[maybe_unused]] float timeDelta, int frame) { - const std::vector& activeObjectsAtFrame = GetParam().activeObjectsAtFrame; + const std::vector& activeObjectsAtFrame = GetParam().m_activeObjectsAtFrame; const AnimGraphStateMachine* stateMachine = this->m_rootStateMachine; const AZStd::vector& activeStates = stateMachine->GetActiveStates(animGraphInstance); const AZStd::vector& activeTransitions = stateMachine->GetActiveTransitions(animGraphInstance); AnimGraphStateMachine_InterruptionTestData::ActiveObjectsAtFrame compareAgainst; - compareAgainst.stateA = AZStd::find_if(activeStates.begin(), activeStates.end(), + compareAgainst.m_stateA = AZStd::find_if(activeStates.begin(), activeStates.end(), [](AnimGraphNode* element) -> bool { return element->GetNameString() == "A"; }) != activeStates.end(); - compareAgainst.stateB = AZStd::find_if(activeStates.begin(), activeStates.end(), + compareAgainst.m_stateB = AZStd::find_if(activeStates.begin(), activeStates.end(), [](AnimGraphNode* element) -> bool { return element->GetNameString() == "B"; }) != activeStates.end(); - compareAgainst.stateC = AZStd::find_if(activeStates.begin(), activeStates.end(), + compareAgainst.m_stateC = AZStd::find_if(activeStates.begin(), activeStates.end(), [](AnimGraphNode* element) -> bool { return element->GetNameString() == "C"; }) != activeStates.end(); - compareAgainst.transitionLeft = AZStd::find_if(activeTransitions.begin(), activeTransitions.end(), + compareAgainst.m_transitionLeft = AZStd::find_if(activeTransitions.begin(), activeTransitions.end(), [](AnimGraphStateTransition* element) -> bool { return element->GetTargetNode()->GetNameString() == "A"; }) != activeTransitions.end(); - compareAgainst.transitionMiddle = AZStd::find_if(activeTransitions.begin(), activeTransitions.end(), + compareAgainst.m_transitionMiddle = AZStd::find_if(activeTransitions.begin(), activeTransitions.end(), [](AnimGraphStateTransition* element) -> bool { return element->GetTargetNode()->GetNameString() == "B"; }) != activeTransitions.end(); - compareAgainst.transitionRight = AZStd::find_if(activeTransitions.begin(), activeTransitions.end(), + compareAgainst.m_transitionRight = AZStd::find_if(activeTransitions.begin(), activeTransitions.end(), [](AnimGraphStateTransition* element) -> bool { return element->GetTargetNode()->GetNameString() == "C"; }) != activeTransitions.end(); for (const auto& activeObjects : activeObjectsAtFrame) { - if (activeObjects.frameNr == frame) + if (activeObjects.m_frameNr == frame) { // Check which states and transitions are active and compare it to the expected ones. - EXPECT_EQ(activeObjects.stateA, compareAgainst.stateA) - << "State A expected to be " << (activeObjects.stateA ? "active." : "inactive."); - EXPECT_EQ(activeObjects.stateB, compareAgainst.stateB) - << "State B expected to be " << (activeObjects.stateB ? "active." : "inactive."); - EXPECT_EQ(activeObjects.stateC, compareAgainst.stateC) - << "State C expected to be " << (activeObjects.stateB ? "active." : "inactive."); - EXPECT_EQ(activeObjects.transitionLeft, compareAgainst.transitionLeft) - << "Transition Start->A expected to be " << (activeObjects.transitionLeft ? "active." : "inactive."); - EXPECT_EQ(activeObjects.transitionMiddle, compareAgainst.transitionMiddle) - << "Transition Start->B expected to be " << (activeObjects.transitionMiddle ? "active." : "inactive."); - EXPECT_EQ(activeObjects.transitionRight, compareAgainst.transitionRight) - << "Transition Start->C expected to be " << (activeObjects.transitionRight ? "active." : "inactive."); + EXPECT_EQ(activeObjects.m_stateA, compareAgainst.m_stateA) + << "State A expected to be " << (activeObjects.m_stateA ? "active." : "inactive."); + EXPECT_EQ(activeObjects.m_stateB, compareAgainst.m_stateB) + << "State B expected to be " << (activeObjects.m_stateB ? "active." : "inactive."); + EXPECT_EQ(activeObjects.m_stateC, compareAgainst.m_stateC) + << "State C expected to be " << (activeObjects.m_stateB ? "active." : "inactive."); + EXPECT_EQ(activeObjects.m_transitionLeft, compareAgainst.m_transitionLeft) + << "Transition Start->A expected to be " << (activeObjects.m_transitionLeft ? "active." : "inactive."); + EXPECT_EQ(activeObjects.m_transitionMiddle, compareAgainst.m_transitionMiddle) + << "Transition Start->B expected to be " << (activeObjects.m_transitionMiddle ? "active." : "inactive."); + EXPECT_EQ(activeObjects.m_transitionRight, compareAgainst.m_transitionRight) + << "Transition Start->C expected to be " << (activeObjects.m_transitionRight ? "active." : "inactive."); // Check anim graph events. - EXPECT_EQ(this->m_eventHandler->m_numStatesEntering, activeObjects.numStatesEntering) - << this->m_eventHandler->m_numStatesEntering << " states entering while " << activeObjects.numStatesEntering << " are expected."; - EXPECT_EQ(this->m_eventHandler->m_numStatesEntered, activeObjects.numStatesEntered) - << this->m_eventHandler->m_numStatesEntered << " states entered while " << activeObjects.numStatesEntered << " are expected."; - EXPECT_EQ(this->m_eventHandler->m_numStatesExited, activeObjects.numStatesExited) - << this->m_eventHandler->m_numStatesExited << " states exited while " << activeObjects.numStatesExited << " are expected."; - EXPECT_EQ(this->m_eventHandler->m_numStatesEnded, activeObjects.numStatesEnded) - << this->m_eventHandler->m_numStatesEnded << " states ended while " << activeObjects.numStatesEnded << " are expected."; - EXPECT_EQ(this->m_eventHandler->m_numTransitionsStarted, activeObjects.numTransitionsStarted) - << this->m_eventHandler->m_numTransitionsStarted << " transitions started while " << activeObjects.numTransitionsStarted << " are expected."; - EXPECT_EQ(this->m_eventHandler->m_numTransitionsEnded, activeObjects.numTransitionsEnded) - << this->m_eventHandler->m_numTransitionsEnded << " transitions ended while " << activeObjects.numTransitionsEnded << " are expected."; + EXPECT_EQ(this->m_eventHandler->m_numStatesEntering, activeObjects.m_numStatesEntering) + << this->m_eventHandler->m_numStatesEntering << " states entering while " << activeObjects.m_numStatesEntering << " are expected."; + EXPECT_EQ(this->m_eventHandler->m_numStatesEntered, activeObjects.m_numStatesEntered) + << this->m_eventHandler->m_numStatesEntered << " states entered while " << activeObjects.m_numStatesEntered << " are expected."; + EXPECT_EQ(this->m_eventHandler->m_numStatesExited, activeObjects.m_numStatesExited) + << this->m_eventHandler->m_numStatesExited << " states exited while " << activeObjects.m_numStatesExited << " are expected."; + EXPECT_EQ(this->m_eventHandler->m_numStatesEnded, activeObjects.m_numStatesEnded) + << this->m_eventHandler->m_numStatesEnded << " states ended while " << activeObjects.m_numStatesEnded << " are expected."; + EXPECT_EQ(this->m_eventHandler->m_numTransitionsStarted, activeObjects.m_numTransitionsStarted) + << this->m_eventHandler->m_numTransitionsStarted << " transitions started while " << activeObjects.m_numTransitionsStarted << " are expected."; + EXPECT_EQ(this->m_eventHandler->m_numTransitionsEnded, activeObjects.m_numTransitionsEnded) + << this->m_eventHandler->m_numTransitionsEnded << " transitions ended while " << activeObjects.m_numTransitionsEnded << " are expected."; } } } @@ -381,13 +381,13 @@ namespace EMotionFX struct AnimGraphStateMachine_InterruptionPropertiesTestData { - float transitionLeftBlendTime; - float transitionLeftCountDownTime; - float transitionRightBlendTime; - float transitionRightCountDownTime; - AnimGraphStateTransition::EInterruptionMode interruptionMode; - float maxBlendWeight; - AnimGraphStateTransition::EInterruptionBlendBehavior interruptionBlendBehavior; + float m_transitionLeftBlendTime; + float m_transitionLeftCountDownTime; + float m_transitionRightBlendTime; + float m_transitionRightCountDownTime; + AnimGraphStateTransition::EInterruptionMode m_interruptionMode; + float m_maxBlendWeight; + AnimGraphStateTransition::EInterruptionBlendBehavior m_interruptionBlendBehavior; }; class AnimGraphStateMachine_InterruptionPropertiesFixture @@ -422,18 +422,18 @@ namespace EMotionFX // Start->A (can be interrupted) m_transitionLeft = AddTransitionWithTimeCondition(stateStart, stateA, - param.transitionLeftBlendTime, - param.transitionLeftCountDownTime); + param.m_transitionLeftBlendTime, + param.m_transitionLeftCountDownTime); m_transitionLeft->SetCanBeInterrupted(true); - m_transitionLeft->SetInterruptionMode(param.interruptionMode); - m_transitionLeft->SetMaxInterruptionBlendWeight(param.maxBlendWeight); - m_transitionLeft->SetInterruptionBlendBehavior(param.interruptionBlendBehavior); + m_transitionLeft->SetInterruptionMode(param.m_interruptionMode); + m_transitionLeft->SetMaxInterruptionBlendWeight(param.m_maxBlendWeight); + m_transitionLeft->SetInterruptionBlendBehavior(param.m_interruptionBlendBehavior); // Start->B (interrupting transition) m_transitionRight = AddTransitionWithTimeCondition(stateStart, stateB, - param.transitionRightBlendTime, - param.transitionRightCountDownTime); + param.m_transitionRightBlendTime, + param.m_transitionRightCountDownTime); m_transitionRight->SetCanInterruptOtherTransitions(true); m_motionNodeAnimGraph->InitAfterLoading(); diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineSyncTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineSyncTests.cpp index 1d341dd753..37996abbd8 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineSyncTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphStateMachineSyncTests.cpp @@ -20,11 +20,11 @@ namespace EMotionFX { struct AnimGraphStateMachineSyncParam { - float playSpeedA; - float durationA; - float playSpeedB; - float durationB; - bool syncEnabled; + float m_playSpeedA; + float m_durationA; + float m_playSpeedB; + float m_durationB; + bool m_syncEnabled; }; class AnimGraphStateMachineSyncFixture @@ -51,7 +51,7 @@ namespace EMotionFX 1.0f/*blendTime*/, 0.0f/*countDownTime*/); - if (param.syncEnabled) + if (param.m_syncEnabled) { m_transition->SetSyncMode(AnimGraphObject::SYNCMODE_CLIPBASED); } @@ -85,8 +85,8 @@ namespace EMotionFX m_animGraphInstance->Destroy(); m_animGraphInstance = m_motionNodeAnimGraph->GetAnimGraphInstance(m_actorInstance, m_motionSet); - SetUpMotionNode("testMotionA", param.playSpeedA, param.durationA, m_stateA); - SetUpMotionNode("testMotionB", param.playSpeedB, param.durationB, m_stateB); + SetUpMotionNode("testMotionA", param.m_playSpeedA, param.m_durationA, m_stateA); + SetUpMotionNode("testMotionB", param.m_playSpeedB, param.m_durationB, m_stateB); GetEMotionFX().Update(0.0f); } diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp index fedd77bb24..bb0c4e47b8 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphSyncTrackTests.cpp @@ -19,27 +19,27 @@ namespace EMotionFX { struct FindEventIndicesParams { - void (*eventFactory)(MotionEventTrack* track); - float timeValue; - size_t expectedLeft; - size_t expectedRight; + void (*m_eventFactory)(MotionEventTrack* track); + float m_timeValue; + size_t m_expectedLeft; + size_t m_expectedRight; }; void PrintTo(FindEventIndicesParams const object, ::std::ostream* os) { - if (object.eventFactory == &MakeNoEvents) + if (object.m_eventFactory == &MakeNoEvents) { *os << "Events: 0"; } - else if (object.eventFactory == &MakeOneEvent) + else if (object.m_eventFactory == &MakeOneEvent) { *os << "Events: 1"; } - else if (object.eventFactory == &MakeTwoEvents) + else if (object.m_eventFactory == &MakeTwoEvents) { *os << "Events: 2"; } - else if (object.eventFactory == &MakeThreeEvents) + else if (object.m_eventFactory == &MakeThreeEvents) { *os << "Events: 3"; } @@ -47,9 +47,9 @@ namespace EMotionFX { *os << "Events: Unknown"; } - *os << " Time value: " << object.timeValue - << " Expected left: " << object.expectedLeft - << " Expected right: " << object.expectedRight + *os << " Time value: " << object.m_timeValue + << " Expected left: " << object.m_expectedLeft + << " Expected right: " << object.m_expectedRight ; } @@ -67,7 +67,7 @@ namespace EMotionFX m_syncTrack = m_motion->GetEventTable()->GetSyncTrack(); const FindEventIndicesParams& params = GetParam(); - params.eventFactory(m_syncTrack); + params.m_eventFactory(m_syncTrack); } void TearDown() override @@ -85,9 +85,9 @@ namespace EMotionFX { const FindEventIndicesParams& params = GetParam(); size_t indexLeft, indexRight; - m_syncTrack->FindEventIndices(params.timeValue, &indexLeft, &indexRight); - EXPECT_EQ(indexLeft, params.expectedLeft); - EXPECT_EQ(indexRight, params.expectedRight); + m_syncTrack->FindEventIndices(params.m_timeValue, &indexLeft, &indexRight); + EXPECT_EQ(indexLeft, params.m_expectedLeft); + EXPECT_EQ(indexRight, params.m_expectedRight); } INSTANTIATE_TEST_CASE_P(TestFindEventIndices, TestFindEventIndicesFixture, @@ -95,8 +95,8 @@ namespace EMotionFX { MakeNoEvents, 0.5f, - MCORE_INVALIDINDEX32, - MCORE_INVALIDINDEX32 + InvalidIndex, + InvalidIndex }, { MakeOneEvent, @@ -167,28 +167,28 @@ namespace EMotionFX struct FindMatchingEventsParams { - void (*eventFactory)(MotionEventTrack* track); - size_t startingIndex; - size_t inEventAIndex; - size_t inEventBIndex; - size_t expectedEventA; - size_t expectedEventB; - bool mirrorInput; - bool mirrorOutput; - bool forward; + void (*m_eventFactory)(MotionEventTrack* track); + size_t m_startingIndex; + size_t m_inEventAIndex; + size_t m_inEventBIndex; + size_t m_expectedEventA; + size_t m_expectedEventB; + bool m_mirrorInput; + bool m_mirrorOutput; + bool m_forward; }; void PrintTo(FindMatchingEventsParams const object, ::std::ostream* os) { - if (object.eventFactory == &MakeNoEvents) + if (object.m_eventFactory == &MakeNoEvents) { *os << "Events: 0"; } - else if (object.eventFactory == &MakeOneEvent) + else if (object.m_eventFactory == &MakeOneEvent) { *os << "Events: 1"; } - else if (object.eventFactory == &MakeTwoLeftRightEvents) + else if (object.m_eventFactory == &MakeTwoLeftRightEvents) { *os << "Events: LRLR"; } @@ -196,14 +196,14 @@ namespace EMotionFX { *os << "Events: Unknown"; } - *os << " Start index: " << object.startingIndex - << " In Event A: " << object.inEventAIndex - << " In Event B: " << object.inEventBIndex - << " Expected Event A: " << object.expectedEventA - << " Expected Event B: " << object.expectedEventB - << " Mirror Input: " << object.mirrorInput - << " Mirror Output: " << object.mirrorOutput - << " Play direction: " << (object.forward ? "Forward" : "Backward") + *os << " Start index: " << object.m_startingIndex + << " In Event A: " << object.m_inEventAIndex + << " In Event B: " << object.m_inEventBIndex + << " Expected Event A: " << object.m_expectedEventA + << " Expected Event B: " << object.m_expectedEventB + << " Mirror Input: " << object.m_mirrorInput + << " Mirror Output: " << object.m_mirrorOutput + << " Play direction: " << (object.m_forward ? "Forward" : "Backward") ; } @@ -221,7 +221,7 @@ namespace EMotionFX m_syncTrack = m_motion->GetEventTable()->GetSyncTrack(); const FindMatchingEventsParams& params = GetParam(); - params.eventFactory(m_syncTrack); + params.m_eventFactory(m_syncTrack); } void TearDown() override @@ -241,21 +241,21 @@ namespace EMotionFX // Make sure we have an event to get the id of const size_t eventCount = m_syncTrack->GetNumEvents(); - const size_t eventAID = eventCount ? m_syncTrack->GetEvent(params.inEventAIndex).HashForSyncing(params.mirrorInput) : 0; - const size_t eventBID = eventCount ? m_syncTrack->GetEvent(params.inEventBIndex).HashForSyncing(params.mirrorInput) : 0; + const size_t eventAID = eventCount ? m_syncTrack->GetEvent(params.m_inEventAIndex).HashForSyncing(params.m_mirrorInput) : 0; + const size_t eventBID = eventCount ? m_syncTrack->GetEvent(params.m_inEventBIndex).HashForSyncing(params.m_mirrorInput) : 0; size_t outLeft, outRight; m_syncTrack->FindMatchingEvents( - params.startingIndex, + params.m_startingIndex, eventAID, eventBID, &outLeft, &outRight, - params.forward, - params.mirrorOutput + params.m_forward, + params.m_mirrorOutput ); - EXPECT_EQ(outLeft, params.expectedEventA); - EXPECT_EQ(outRight, params.expectedEventB); + EXPECT_EQ(outLeft, params.m_expectedEventA); + EXPECT_EQ(outRight, params.m_expectedEventB); } INSTANTIATE_TEST_CASE_P(TestFindMatchingEvents, TestFindMatchingEventsFixture, @@ -267,8 +267,8 @@ namespace EMotionFX 0, // startingIndex 0, // inEventAIndex 1, // inEventBIndex - MCORE_INVALIDINDEX32, // expectedEventA - MCORE_INVALIDINDEX32, // expectedEventB + InvalidIndex, // expectedEventA + InvalidIndex, // expectedEventB false, // mirrorInput false, // mirrorOutput true // forward diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphTagConditionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphTagConditionTests.cpp index 6d085894f5..8312912f47 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphTagConditionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphTagConditionTests.cpp @@ -38,7 +38,7 @@ namespace EMotionFX { const AZStd::string& parameterName = parameterNames[i]; AZ::Outcome parameterIndex = animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess()) << "Parameter " << parameterName.c_str() << " does not exist in the anim graph."; + ASSERT_TRUE(parameterIndex.IsSuccess()) << "Parameter " << parameterName.c_str() << " does not exist in the anim graph."; EXPECT_EQ(parameterIndex.GetValue(), parameterIndices[i]) << "Index for parameter " << parameterName.c_str() << "out of date."; } } @@ -115,7 +115,8 @@ namespace EMotionFX { const AZStd::string parameterName = "Tag3"; AZ::Outcome parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 2) << "Tag3 should be at the 3rd position after removing Tag1."; + ASSERT_TRUE(parameterIndex.IsSuccess()); + EXPECT_EQ(parameterIndex.GetValue(), 2) << "Tag3 should be at the 3rd position after removing Tag1."; // Move Tag3 from the 3rd place to the 1st place. commandString = AZStd::string::format("AnimGraphMoveParameter -animGraphID %d -name \"%s\" -index %d", diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphTransitionConditionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphTransitionConditionTests.cpp index 67f7421509..8e72ea1e8a 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphTransitionConditionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphTransitionConditionTests.cpp @@ -72,7 +72,7 @@ namespace EMotionFX const ConditionSetUpFunc& func, const ActiveNodesMap& activeNodesMap, const FrameCallback& frameCallback = [] (AnimGraphInstance*, int) {} - ) : m_setUpFunction(func), activeNodes(activeNodesMap), callback(frameCallback) + ) : m_setUpFunction(func), m_activeNodes(activeNodesMap), m_callback(frameCallback) { } @@ -80,9 +80,9 @@ namespace EMotionFX const ConditionSetUpFunc m_setUpFunction; // List of nodes that are active on each frame - const ActiveNodesMap activeNodes; + const ActiveNodesMap m_activeNodes; - const FrameCallback callback; + const FrameCallback m_callback; }; template @@ -90,14 +90,14 @@ namespace EMotionFX public ::testing::WithParamInterface> { public: - const float fps; - const float updateInterval; - const int numUpdates; + const float m_fps; + const float m_updateInterval; + const int m_numUpdates; TransitionConditionFixtureP() - : fps(60.0f) - , updateInterval(1.0f / fps) - , numUpdates(static_cast(3.0f * fps)) + : m_fps(60.0f) + , m_updateInterval(1.0f / m_fps) + , m_numUpdates(static_cast(3.0f * m_fps)) { } @@ -130,14 +130,14 @@ namespace EMotionFX protected: void RunEMotionFXUpdateLoop() { - const ActiveNodesMap& activeNodes = this->GetParam().activeNodes; - const FrameCallback& callback = this->GetParam().callback; + const ActiveNodesMap& activeNodes = this->GetParam().m_activeNodes; + const FrameCallback& callback = this->GetParam().m_callback; // Allow tests to set starting values for parameters callback(m_animGraphInstance, -1); // Run the EMotionFX update loop for 3 seconds at 60 fps - for (int frameNum = 0; frameNum < numUpdates; ++frameNum) + for (int frameNum = 0; frameNum < m_numUpdates; ++frameNum) { // Allow for test-data defined updates to the graph state callback(m_animGraphInstance, frameNum); @@ -154,7 +154,7 @@ namespace EMotionFX } else { - GetEMotionFX().Update(updateInterval); + GetEMotionFX().Update(m_updateInterval); } // Check the state for the current frame @@ -168,7 +168,7 @@ namespace EMotionFX const AZStd::vector& gotActiveNodes = m_stateMachine->GetActiveStates(m_animGraphInstance); - EXPECT_EQ(gotActiveNodes, expectedActiveNodes) << "on frame " << frameNum << ", time " << frameNum * updateInterval; + EXPECT_EQ(gotActiveNodes, expectedActiveNodes) << "on frame " << frameNum << ", time " << frameNum * m_updateInterval; } } { @@ -237,28 +237,28 @@ namespace EMotionFX motionToExitTransition->SetBlendTime(0.0f); motionToExitTransition->AddCondition(motionToExitCondition); - mChildState = aznew AnimGraphStateMachine(); - mChildState->SetName("ChildStateMachine"); - mChildState->AddChildNode(childMotionNode); - mChildState->AddChildNode(childExitNode); - mChildState->SetEntryState(childMotionNode); - mChildState->AddTransition(motionToExitTransition); + m_childState = aznew AnimGraphStateMachine(); + m_childState->SetName("ChildStateMachine"); + m_childState->AddChildNode(childMotionNode); + m_childState->AddChildNode(childExitNode); + m_childState->SetEntryState(childMotionNode); + m_childState->AddTransition(motionToExitTransition); AnimGraphTimeCondition* motion0ToChildStateCondition = aznew AnimGraphTimeCondition(); motion0ToChildStateCondition->SetCountDownTime(0.5f); AnimGraphStateTransition* motion0ToChildStateTransition = aznew AnimGraphStateTransition(); motion0ToChildStateTransition->SetSourceNode(m_motionNodeA); - motion0ToChildStateTransition->SetTargetNode(mChildState); + motion0ToChildStateTransition->SetTargetNode(m_childState); motion0ToChildStateTransition->SetBlendTime(0.5f); motion0ToChildStateTransition->AddCondition(motion0ToChildStateCondition); AnimGraphStateTransition* childStateToMotion1Transition = aznew AnimGraphStateTransition(); - childStateToMotion1Transition->SetSourceNode(mChildState); + childStateToMotion1Transition->SetSourceNode(m_childState); childStateToMotion1Transition->SetTargetNode(m_motionNodeB); childStateToMotion1Transition->SetBlendTime(0.5f); - m_stateMachine->AddChildNode(mChildState); + m_stateMachine->AddChildNode(m_childState); m_stateMachine->AddTransition(motion0ToChildStateTransition); m_stateMachine->AddTransition(childStateToMotion1Transition); @@ -272,7 +272,7 @@ namespace EMotionFX } protected: - AnimGraphStateMachine* mChildState; + AnimGraphStateMachine* m_childState; }; class RangedMotionEventConditionFixture diff --git a/Gems/EMotionFX/Code/Tests/AnimGraphVector2ConditionTests.cpp b/Gems/EMotionFX/Code/Tests/AnimGraphVector2ConditionTests.cpp index 7e85700a33..5e850b7cf0 100644 --- a/Gems/EMotionFX/Code/Tests/AnimGraphVector2ConditionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/AnimGraphVector2ConditionTests.cpp @@ -45,7 +45,7 @@ namespace EMotionFX { AZStd::unique_ptr newParameter(EMotionFX::ParameterFactory::Create(azrtti_typeid())); newParameter->SetName("Float Slider Parameter"); - CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), MCORE_INVALIDINDEX32); + CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), InvalidIndex); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); } @@ -54,7 +54,7 @@ namespace EMotionFX { AZStd::unique_ptr newParameter(EMotionFX::ParameterFactory::Create(azrtti_typeid())); newParameter->SetName(parameterName); - CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), MCORE_INVALIDINDEX32); + CommandSystem::ConstructCreateParameterCommand(commandString, m_animGraph.get(), newParameter.get(), InvalidIndex); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); } @@ -62,7 +62,8 @@ namespace EMotionFX condition->Reinit(); AZ::Outcome parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 1) << "The Vector2 parameter should be at the 2nd position."; + ASSERT_TRUE(parameterIndex.IsSuccess()); + EXPECT_EQ(parameterIndex.GetValue(), 1) << "The Vector2 parameter should be at the 2nd position."; // 1. Move the Vector2 parameter from the 2nd place to the 1st place. commandString = AZStd::string::format("AnimGraphMoveParameter -animGraphID %d -name \"%s\" -index %d ", @@ -71,19 +72,19 @@ namespace EMotionFX 0); EXPECT_TRUE(commandManager.ExecuteCommand(commandString, result)) << result.c_str(); parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "The Vector2 parameter should now be at the 1st position."; + ASSERT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "The Vector2 parameter should now be at the 1st position."; EXPECT_EQ(parameterIndex.GetValue(), condition->GetParameterIndex().GetValue()) << "The Vector2 condition should now refer to the 1st parameter in the anim graph."; // 2. Undo. EXPECT_TRUE(commandManager.Undo(result)) << result.c_str(); parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 1) << "The Vector2 parameter should now be back at the 2nd position."; + ASSERT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 1) << "The Vector2 parameter should now be back at the 2nd position."; EXPECT_EQ(parameterIndex.GetValue(), condition->GetParameterIndex().GetValue()) << "The Vector2 condition should now refer to the 2nd parameter in the anim graph."; // 3. Redo. EXPECT_TRUE(commandManager.Redo(result)) << result.c_str(); parameterIndex = m_animGraph->FindValueParameterIndexByName(parameterName); - EXPECT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "The Vector2 parameter should now be back at the 1st position."; + ASSERT_TRUE(parameterIndex.IsSuccess() && parameterIndex.GetValue() == 0) << "The Vector2 parameter should now be back at the 1st position."; EXPECT_EQ(parameterIndex.GetValue(), condition->GetParameterIndex().GetValue()) << "The Vector2 condition should now refer to the 1st parameter in the anim graph."; } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp index 522cbf194e..3ece046845 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeFloatMath1NodeTests.cpp @@ -98,7 +98,7 @@ namespace EMotionFX void TestInput(const AZStd::string& paramName, std::vector xInputs) { BlendTreeConnection* connection = m_floatMath1Node->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName(paramName)->mPortID, BlendTreeFloatMath1Node::PORTID_INPUT_X); + m_paramNode->FindOutputPortByName(paramName)->m_portId, BlendTreeFloatMath1Node::PORTID_INPUT_X); for (inputType i : xInputs) { diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp index 5fddb5a94b..2f62365dd8 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeFootIKNodeTests.cpp @@ -136,14 +136,14 @@ namespace EMotionFX void ValidateFootHeight(BlendTreeFootIKNode::LegId legId, const char* jointName, float height, float tolerance) { // Check the left foot height. - AZ::u32 footIndex; + size_t footIndex = InvalidIndex; Skeleton* skeleton = m_actor->GetSkeleton(); skeleton->FindNodeAndIndexByName(jointName, footIndex); - ASSERT_NE(footIndex, MCORE_INVALIDINDEX32); + ASSERT_NE(footIndex, InvalidIndex); EMotionFX::Transform transform = m_actorInstance->GetTransformData()->GetCurrentPose()->GetWorldSpaceTransform(footIndex); const BlendTreeFootIKNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_ikNode)); - const float correction = (m_actorInstance->GetWorldSpaceTransform().mRotation.TransformVector(AZ::Vector3(0.0f, 0.0f, uniqueData->m_legs[legId].m_footHeight))).GetZ(); - const float pos = transform.mPosition.GetZ() - correction; + const float correction = (m_actorInstance->GetWorldSpaceTransform().m_rotation.TransformVector(AZ::Vector3(0.0f, 0.0f, uniqueData->m_legs[legId].m_footHeight))).GetZ(); + const float pos = transform.m_position.GetZ() - correction; EXPECT_NEAR(pos, height, tolerance); } @@ -209,15 +209,15 @@ namespace EMotionFX BlendTreeFootIKNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_ikNode)); ASSERT_TRUE(uniqueData != nullptr); ASSERT_TRUE(!uniqueData->GetHasError()); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::UpperLeg], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::Knee], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::Foot], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::Toe], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::UpperLeg], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::Knee], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::Foot], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::Toe], MCORE_INVALIDINDEX32); - ASSERT_NE(uniqueData->m_hipJointIndex, MCORE_INVALIDINDEX32); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::UpperLeg], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::Knee], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::Foot], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_jointIndices[BlendTreeFootIKNode::LegJointId::Toe], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::UpperLeg], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::Knee], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::Foot], InvalidIndex); + ASSERT_NE(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Right].m_jointIndices[BlendTreeFootIKNode::LegJointId::Toe], InvalidIndex); + ASSERT_NE(uniqueData->m_hipJointIndex, InvalidIndex); // Make sure the weights are fully active. ASSERT_FLOAT_EQ(uniqueData->m_legs[BlendTreeFootIKNode::LegId::Left].m_weight, 1.0f); @@ -325,7 +325,7 @@ namespace EMotionFX // Rotate the actor instance 180 degrees over the X axis as well. EMotionFX::Transform transform; transform.Identity(); - transform.mRotation = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3(1.0f, 0.0f, 0.0f), MCore::Math::pi); + transform.m_rotation = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3(1.0f, 0.0f, 0.0f), MCore::Math::pi); m_actorInstance->SetLocalSpaceTransform(transform); // Tests where the leg can reach the target position just fine, make sure the hip adjustment doesn't break it. diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp index 29c6269639..b86041c7aa 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMaskNodeTests.cpp @@ -68,11 +68,11 @@ namespace EMotionFX Pose& outputPose = outputAnimGraphPose->GetPose(); // Output the assigned value of the node for each joint so that we can identify from which input each joint is coming from. - const AZ::u32 numJoints = outputPose.GetNumTransforms(); - for (AZ::u32 i = 0; i < numJoints; ++i) + const size_t numJoints = outputPose.GetNumTransforms(); + for (size_t i = 0; i < numJoints; ++i) { Transform transform = outputPose.GetLocalSpaceTransform(i); - transform.mPosition = AZ::Vector3(m_identificationValue, m_identificationValue, m_identificationValue); + transform.m_position = AZ::Vector3(m_identificationValue, m_identificationValue, m_identificationValue); outputPose.SetLocalSpaceTransform(i, transform); } } @@ -113,7 +113,7 @@ namespace EMotionFX return result; } - AZ::Outcome FindMaskIndexForJoint(AZ::u32 jointIndex) const + AZ::Outcome FindMaskIndexForJoint(size_t jointIndex) const { const MaskNodeTestParam& param = GetParam(); Skeleton* skeleton = m_actor->GetSkeleton(); @@ -216,12 +216,12 @@ namespace EMotionFX GetEMotionFX().Update(0.0f); Skeleton* skeleton = m_actor->GetSkeleton(); - const AZ::u32 numJoints = skeleton->GetNumNodes(); + const size_t numJoints = skeleton->GetNumNodes(); TransformData* transformData = m_actorInstance->GetTransformData(); Pose* pose = transformData->GetCurrentPose(); // Iterate through the joints and make sure their transforms originate according to the mask setup. - for (AZ::u32 jointIndex = 0; jointIndex < numJoints; jointIndex++) + for (size_t jointIndex = 0; jointIndex < numJoints; jointIndex++) { const Node* joint = skeleton->GetNode(jointIndex); const char* jointName = joint->GetName(); @@ -230,7 +230,7 @@ namespace EMotionFX // The components of the position embed the origin. // If the compareValue equals m_basePosePosValue, it originates from the base pose input. // In case the joint is part of any of the masks and got overwriten by them, the compareValue represents the mask index. - const size_t compareValue = static_cast(transform.mPosition.GetX()); + const size_t compareValue = static_cast(transform.m_position.GetX()); AZ::Outcome maskIndex = FindMaskIndexForJoint(jointIndex); if (maskIndex.IsSuccess()) diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp index 53e0e7de77..ee61e25370 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMirrorPoseNodeTests.cpp @@ -32,8 +32,8 @@ namespace EMotionFX public: void SetupMirrorNodes(const Node* leftNode, const Node* rightNode) { - m_actor->GetNodeMirrorInfo(leftNode->GetNodeIndex()).mSourceNode = static_cast(rightNode->GetNodeIndex()); - m_actor->GetNodeMirrorInfo(rightNode->GetNodeIndex()).mSourceNode = static_cast(leftNode->GetNodeIndex()); + m_actor->GetNodeMirrorInfo(leftNode->GetNodeIndex()).m_sourceNode = static_cast(rightNode->GetNodeIndex()); + m_actor->GetNodeMirrorInfo(rightNode->GetNodeIndex()).m_sourceNode = static_cast(leftNode->GetNodeIndex()); } void ConstructGraph() override @@ -111,12 +111,12 @@ namespace EMotionFX TEST_F(BlendTreeMirrorPoseNodeFixture, OutputsCorrectPose) { GetEMotionFX().Update(1.0f / 60.0f); - AZ::u32 l_upArmIndex; - AZ::u32 r_upArmIndex; - AZ::u32 l_loArmIndex; - AZ::u32 r_loArmIndex; - AZ::u32 l_handIndex; - AZ::u32 r_handIndex; + size_t l_upArmIndex; + size_t r_upArmIndex; + size_t l_loArmIndex; + size_t r_loArmIndex; + size_t l_handIndex; + size_t r_handIndex; m_jackSkeleton->FindNodeAndIndexByName("l_upArm", l_upArmIndex); m_jackSkeleton->FindNodeAndIndexByName("r_upArm", r_upArmIndex); m_jackSkeleton->FindNodeAndIndexByName("l_loArm", l_loArmIndex); @@ -129,13 +129,13 @@ namespace EMotionFX // Remember the original position for comparison later Pose * jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - const AZ::Vector3 l_upArmOriginalPos = jackPose->GetModelSpaceTransform(l_upArmIndex).mPosition; - const AZ::Vector3 r_upArmOriginalPos = jackPose->GetModelSpaceTransform(r_upArmIndex).mPosition; + const AZ::Vector3 l_upArmOriginalPos = jackPose->GetModelSpaceTransform(l_upArmIndex).m_position; + const AZ::Vector3 r_upArmOriginalPos = jackPose->GetModelSpaceTransform(r_upArmIndex).m_position; GetEMotionFX().Update(1.0f / 60.0f); // Remember mirrored position - const AZ::Vector3 l_upArmMirroredPos = jackPose->GetModelSpaceTransform(l_upArmIndex).mPosition; - const AZ::Vector3 r_upArmMirroredPos = jackPose->GetModelSpaceTransform(r_upArmIndex).mPosition; + const AZ::Vector3 l_upArmMirroredPos = jackPose->GetModelSpaceTransform(l_upArmIndex).m_position; + const AZ::Vector3 r_upArmMirroredPos = jackPose->GetModelSpaceTransform(r_upArmIndex).m_position; // Expect poses to be at the same position because mirror pose node is off EXPECT_FALSE(m_mirrorPoseNode->GetIsMirroringEnabled(m_animGraphInstance)); @@ -144,19 +144,19 @@ namespace EMotionFX // Mirror Pose Node enabled m_floatConstantNode->SetValue(1.0f); - const AZ::Vector3 l_upArmPos = jackPose->GetModelSpaceTransform(l_upArmIndex).mPosition; - const AZ::Vector3 r_upArmPos = jackPose->GetModelSpaceTransform(r_upArmIndex).mPosition; - const AZ::Vector3 l_loArmPos = jackPose->GetModelSpaceTransform(l_loArmIndex).mPosition; - const AZ::Vector3 r_loArmPos = jackPose->GetModelSpaceTransform(r_loArmIndex).mPosition; - const AZ::Vector3 l_handPos = jackPose->GetModelSpaceTransform(l_handIndex).mPosition; - const AZ::Vector3 r_handPos = jackPose->GetModelSpaceTransform(r_handIndex).mPosition; + const AZ::Vector3 l_upArmPos = jackPose->GetModelSpaceTransform(l_upArmIndex).m_position; + const AZ::Vector3 r_upArmPos = jackPose->GetModelSpaceTransform(r_upArmIndex).m_position; + const AZ::Vector3 l_loArmPos = jackPose->GetModelSpaceTransform(l_loArmIndex).m_position; + const AZ::Vector3 r_loArmPos = jackPose->GetModelSpaceTransform(r_loArmIndex).m_position; + const AZ::Vector3 l_handPos = jackPose->GetModelSpaceTransform(l_handIndex).m_position; + const AZ::Vector3 r_handPos = jackPose->GetModelSpaceTransform(r_handIndex).m_position; GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 mirroredl_upArmPos = jackPose->GetModelSpaceTransform(l_upArmIndex).mPosition; - const AZ::Vector3 mirroredr_upArmPos = jackPose->GetModelSpaceTransform(r_upArmIndex).mPosition; - const AZ::Vector3 mirroredl_loArmPos = jackPose->GetModelSpaceTransform(l_loArmIndex).mPosition; - const AZ::Vector3 mirroredr_loArmPos = jackPose->GetModelSpaceTransform(r_loArmIndex).mPosition; - const AZ::Vector3 mirroredl_handPos = jackPose->GetModelSpaceTransform(l_handIndex).mPosition; - const AZ::Vector3 mirroredr_handPos = jackPose->GetModelSpaceTransform(r_handIndex).mPosition; + const AZ::Vector3 mirroredl_upArmPos = jackPose->GetModelSpaceTransform(l_upArmIndex).m_position; + const AZ::Vector3 mirroredr_upArmPos = jackPose->GetModelSpaceTransform(r_upArmIndex).m_position; + const AZ::Vector3 mirroredl_loArmPos = jackPose->GetModelSpaceTransform(l_loArmIndex).m_position; + const AZ::Vector3 mirroredr_loArmPos = jackPose->GetModelSpaceTransform(r_loArmIndex).m_position; + const AZ::Vector3 mirroredl_handPos = jackPose->GetModelSpaceTransform(l_handIndex).m_position; + const AZ::Vector3 mirroredr_handPos = jackPose->GetModelSpaceTransform(r_handIndex).m_position; EXPECT_TRUE(m_mirrorPoseNode->GetIsMirroringEnabled(m_animGraphInstance)); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeMotionFrameNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeMotionFrameNodeTests.cpp index 49938c121e..947b10f16e 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeMotionFrameNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeMotionFrameNodeTests.cpp @@ -73,7 +73,7 @@ namespace EMotionFX void SetAndTestTimeValue(BlendTreeMotionFrameNode::UniqueData* uniqueData, float newNormalizedTime, bool rewind = false) { - const float prevNewTime = uniqueData->mNewTime; + const float prevNewTime = uniqueData->m_newTime; m_motionFrameNode->SetNormalizedTimeValue(newNormalizedTime); if (rewind) @@ -96,9 +96,9 @@ namespace EMotionFX expectedOldTime = newNormalizedTime * m_motionDuration; } } - EXPECT_EQ(uniqueData->mOldTime, expectedOldTime); + EXPECT_EQ(uniqueData->m_oldTime, expectedOldTime); - EXPECT_EQ(uniqueData->mNewTime, newNormalizedTime * m_motionDuration); + EXPECT_EQ(uniqueData->m_newTime, newNormalizedTime * m_motionDuration); } public: diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeRagdollNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeRagdollNodeTests.cpp index 8fedda5577..85504675db 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeRagdollNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeRagdollNodeTests.cpp @@ -127,7 +127,7 @@ namespace EMotionFX m_actorInstance->SetRagdoll(&testRagdoll); RagdollInstance* ragdollInstance = m_actorInstance->GetRagdollInstance(); const AZ::Outcome rootNodeIndex = ragdollInstance->GetRootRagdollNodeIndex(); - EXPECT_TRUE(rootNodeIndex.IsSuccess()) << "No root node for the ragdoll found."; + ASSERT_TRUE(rootNodeIndex.IsSuccess()) << "No root node for the ragdoll found."; EXPECT_EQ(ragdollInstance->GetRagdollRootNode()->GetNameString(), ragdollRootNodeName) << "Wrong ragdoll root node."; // Create an anim graph with a ragdoll node. diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeRotationLimitNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeRotationLimitNodeTests.cpp index 31e0d696d0..b6d5e0b04d 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeRotationLimitNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeRotationLimitNodeTests.cpp @@ -101,10 +101,10 @@ namespace EMotionFX Transform expected = Transform::CreateIdentity(); expected.Set(AZ::Vector3::CreateZero(), expectedRotation); - bool success = AZ::IsClose(expected.mRotation.GetW(), outputRoot.mRotation.GetW(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetX(), outputRoot.mRotation.GetX(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetY(), outputRoot.mRotation.GetY(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetZ(), outputRoot.mRotation.GetZ(), 0.0001f); + bool success = AZ::IsClose(expected.m_rotation.GetW(), outputRoot.m_rotation.GetW(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetX(), outputRoot.m_rotation.GetX(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetY(), outputRoot.m_rotation.GetY(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetZ(), outputRoot.m_rotation.GetZ(), 0.0001f); ASSERT_TRUE(success); } diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeRotationMath2NodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeRotationMath2NodeTests.cpp index a59d91fa8c..ef0a2aa959 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeRotationMath2NodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeRotationMath2NodeTests.cpp @@ -87,10 +87,10 @@ namespace EMotionFX Transform outputRoot = GetOutputTransform(); Transform expected = Transform::CreateIdentity(); expected.Set(AZ::Vector3::CreateZero(), expectedRotation); - bool success = AZ::IsClose(expected.mRotation.GetW(), outputRoot.mRotation.GetW(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetX(), outputRoot.mRotation.GetX(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetY(), outputRoot.mRotation.GetY(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetZ(), outputRoot.mRotation.GetZ(), 0.0001f); + bool success = AZ::IsClose(expected.m_rotation.GetW(), outputRoot.m_rotation.GetW(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetX(), outputRoot.m_rotation.GetX(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetY(), outputRoot.m_rotation.GetY(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetZ(), outputRoot.m_rotation.GetZ(), 0.0001f); m_rotationMathNode->SetMathFunction(EMotionFX::BlendTreeRotationMath2Node::MATHFUNCTION_INVERSE_MULTIPLY); @@ -99,10 +99,10 @@ namespace EMotionFX outputRoot = GetOutputTransform(); expected.Identity(); expected.Set(AZ::Vector3::CreateZero(), expectedRotation); - success = success && AZ::IsClose(expected.mRotation.GetW(), outputRoot.mRotation.GetW(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetX(), outputRoot.mRotation.GetX(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetY(), outputRoot.mRotation.GetY(), 0.0001f); - success = success && AZ::IsClose(expected.mRotation.GetZ(), outputRoot.mRotation.GetZ(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetW(), outputRoot.m_rotation.GetW(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetX(), outputRoot.m_rotation.GetX(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetY(), outputRoot.m_rotation.GetY(), 0.0001f); + success = success && AZ::IsClose(expected.m_rotation.GetZ(), outputRoot.m_rotation.GetZ(), 0.0001f); ASSERT_TRUE(success); diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp index a53a3d7e0b..a4ec05746a 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeSimulatedObjectNodeTests.cpp @@ -47,7 +47,7 @@ namespace EMotionFX ASSERT_EQ(jointNames.size(), 3); for (size_t i= 0; i < 3; ++i) { - AZ::u32 jointIndex = InvalidIndex32; + size_t jointIndex = InvalidIndex; const Node* node = skeleton->FindNodeAndIndexByName(jointNames[i].c_str(), jointIndex); ASSERT_NE(node, nullptr); m_jointIndices[i] = jointIndex; @@ -116,7 +116,7 @@ namespace EMotionFX FloatSliderParameter* m_weightParameter = nullptr; BlendTreeSimulatedObjectNode* m_simNode = nullptr; BlendTreeParameterNode* m_parameterNode = nullptr; - AZ::u32 m_jointIndices[3] { InvalidIndex32, InvalidIndex32, InvalidIndex32 }; + size_t m_jointIndices[3] { InvalidIndex, InvalidIndex, InvalidIndex }; }; TEST_F(BlendTreeSimulatedObjectNodeFixture, TransformsCheck) @@ -135,10 +135,10 @@ namespace EMotionFX for (size_t joint = 0; joint < 3; ++joint) { - const AZ::Vector3& jointPos = currentPose.GetWorldSpaceTransform(m_jointIndices[joint]).mPosition; - const AZ::Vector3& jointBindPos = bindPose.GetWorldSpaceTransform(m_jointIndices[joint]).mPosition; + const AZ::Vector3& jointPos = currentPose.GetWorldSpaceTransform(m_jointIndices[joint]).m_position; + const AZ::Vector3& jointBindPos = bindPose.GetWorldSpaceTransform(m_jointIndices[joint]).m_position; ASSERT_TRUE((jointPos - jointBindPos).GetLength() <= 0.01f); // Make sure we didn't move too far from the bind pose. - ASSERT_TRUE(AZ::IsClose(currentPose.GetWorldSpaceTransform(m_jointIndices[joint]).mRotation.GetLength(), 1.0f, 0.001f)); // Make sure we have a unit quaternion. + ASSERT_TRUE(AZ::IsClose(currentPose.GetWorldSpaceTransform(m_jointIndices[joint]).m_rotation.GetLength(), 1.0f, 0.001f)); // Make sure we have a unit quaternion. } } } diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeTransformNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeTransformNodeTests.cpp index 13baa72d09..80e6c81bb3 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeTransformNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeTransformNodeTests.cpp @@ -89,13 +89,13 @@ namespace EMotionFX translate_amount->SetValue(0.5f); Evaluate(); - expected.mPosition = AZ::Vector3(5.0f, 0.0f, 0.0f); + expected.m_position = AZ::Vector3(5.0f, 0.0f, 0.0f); outputRoot = GetOutputTransform(); ASSERT_EQ(expected, outputRoot); translate_amount->SetValue(1.0f); Evaluate(); - expected.mPosition = AZ::Vector3(10.0f, 0.0f, 0.0f); + expected.m_position = AZ::Vector3(10.0f, 0.0f, 0.0f); outputRoot = GetOutputTransform(); ASSERT_EQ(expected, outputRoot); } diff --git a/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp index 91b7687a02..d68bf9db83 100644 --- a/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BlendTreeTwoLinkIKNodeTests.cpp @@ -28,13 +28,13 @@ namespace EMotionFX { struct BlendTreeTwoLinkIKNodeTestsData { - AZStd::string testJointName; - std::vector linkedJointNames; - std::vector> reachablePositions; - std::vector> unreachablePositions; - std::vector> rotations; - std::vector bendDirPosition; - std::vector alignToNodeNames; + AZStd::string m_testJointName; + std::vector m_linkedJointNames; + std::vector> m_reachablePositions; + std::vector> m_unreachablePositions; + std::vector> m_rotations; + std::vector m_bendDirPosition; + std::vector m_alignToNodeNames; }; class BlendTreeTwoLinkIKNodeFixture @@ -70,7 +70,7 @@ namespace EMotionFX m_paramNode = aznew BlendTreeParameterNode(); m_twoLinkIKNode = aznew BlendTreeTwoLinkIKNode(); - m_twoLinkIKNode->SetEndNodeName(m_param.testJointName); + m_twoLinkIKNode->SetEndNodeName(m_param.m_testJointName); m_blendTree = aznew BlendTree(); m_blendTree->AddChildNode(bindPoseNode); @@ -137,9 +137,9 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, ReachablePositionsOutputCorrectPose) { // Set values for vector3 and twoLinkIKNode weight parameter - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); + m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); GetEMotionFX().Update(1.0f / 60.0f); const float weight = testing::get<0>(GetParam()); @@ -147,11 +147,11 @@ namespace EMotionFX // Remeber specific joint's original position to compare with its new position later const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + size_t testJointIndex; + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_testJointName, testJointIndex); + const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).m_position; - for (std::vector goalPosXYZ : m_param.reachablePositions) + for (std::vector goalPosXYZ : m_param.m_reachablePositions) { const float goalX = goalPosXYZ[0]; const float goalY = goalPosXYZ[1]; @@ -159,7 +159,7 @@ namespace EMotionFX ParamSetValue("GoalPosParam", AZ::Vector3(goalX, goalY, goalZ)); GetEMotionFX().Update(5.0f / 60.0f); - const AZ::Vector3& testJointNewPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + const AZ::Vector3& testJointNewPos = jackPose->GetModelSpaceTransform(testJointIndex).m_position; // Based on weight, check if position of node changes to reachable goal position if (weight) @@ -179,7 +179,7 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, ReachableAlignToNodeOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->mPortID, + m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); GetEMotionFX().Update(1.0f / 60.0f); @@ -187,27 +187,27 @@ namespace EMotionFX ParamSetValue("WeightParam", weight); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + size_t testJointIndex; + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_testJointName, testJointIndex); + const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).m_position; - for (AZStd::string& nodeName : m_param.alignToNodeNames) + for (AZStd::string& nodeName : m_param.m_alignToNodeNames) { NodeAlignmentData alignToNode; alignToNode.first = nodeName; alignToNode.second = 0; m_twoLinkIKNode->SetAlignToNode(alignToNode); - // Update will set uniqueData->mMustUpdate to false for efficiency purposes - // Unique data only updates once unless reset mMustUpdate to true again + // Update will set uniqueData->m_mustUpdate to false for efficiency purposes + // Unique data only updates once unless reset m_mustUpdate to true again BlendTreeTwoLinkIKNode::UniqueData* uniqueData = static_cast(m_animGraphInstance->FindOrCreateUniqueNodeData(m_twoLinkIKNode)); uniqueData->Invalidate(); - AZ::u32 alignToNodeIndex; + size_t alignToNodeIndex; m_jackSkeleton->FindNodeAndIndexByName(nodeName, alignToNodeIndex); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3& alignToNodePos = jackPose->GetModelSpaceTransform(alignToNodeIndex).mPosition; - const AZ::Vector3& testJointNewPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + const AZ::Vector3& alignToNodePos = jackPose->GetModelSpaceTransform(alignToNodeIndex).m_position; + const AZ::Vector3& testJointNewPos = jackPose->GetModelSpaceTransform(testJointIndex).m_position; // Based on weight, check if position of node changes to alignToNode position if (weight) @@ -224,25 +224,25 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, UnreachablePositionsOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->mPortID, + m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); GetEMotionFX().Update(1.0f / 60.0f); const float weight = testing::get<0>(GetParam()); ParamSetValue("WeightParam", weight); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - AZ::u32 linkedJoint0Index; - AZ::u32 linkedJoint1Index; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - m_jackSkeleton->FindNodeAndIndexByName(m_param.linkedJointNames[0], linkedJoint0Index); - m_jackSkeleton->FindNodeAndIndexByName(m_param.linkedJointNames[1], linkedJoint1Index); - const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; + size_t testJointIndex; + size_t linkedJoint0Index; + size_t linkedJoint1Index; + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_testJointName, testJointIndex); + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_linkedJointNames[0], linkedJoint0Index); + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_linkedJointNames[1], linkedJoint1Index); + const AZ::Vector3& testJointPos = jackPose->GetModelSpaceTransform(testJointIndex).m_position; - for (std::vector goalPosXYZ : m_param.unreachablePositions) + for (std::vector goalPosXYZ : m_param.m_unreachablePositions) { const float goalX = goalPosXYZ[0]; const float goalY = goalPosXYZ[1]; @@ -250,9 +250,9 @@ namespace EMotionFX ParamSetValue("GoalPosParam", AZ::Vector3(goalX, goalY, goalZ)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3& testJointNewPos = jackPose->GetModelSpaceTransform(testJointIndex).mPosition; - const AZ::Vector3& linkedJoint0Pos = jackPose->GetModelSpaceTransform(linkedJoint0Index).mPosition; - const AZ::Vector3& linkedJoint1Pos = jackPose->GetModelSpaceTransform(linkedJoint1Index).mPosition; + const AZ::Vector3& testJointNewPos = jackPose->GetModelSpaceTransform(testJointIndex).m_position; + const AZ::Vector3& linkedJoint0Pos = jackPose->GetModelSpaceTransform(linkedJoint0Index).m_position; + const AZ::Vector3& linkedJoint1Pos = jackPose->GetModelSpaceTransform(linkedJoint1Index).m_position; // Based on weight, check if position of the test node // And its linked nodes are pointing towards the unreachable position @@ -272,12 +272,12 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, RotatedPositionsOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->mPortID, + m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("RotationParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); + m_paramNode->FindOutputPortByName("RotationParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); m_twoLinkIKNode->SetRotationEnabled(true); GetEMotionFX().Update(1.0f / 60.0f); @@ -287,11 +287,11 @@ namespace EMotionFX ParamSetValue("GoalPosParam", AZ::Vector3(0.0f, 1.0f, 1.0f)); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); - const AZ::Quaternion testJointRotation = jackPose->GetModelSpaceTransform(testJointIndex).mRotation; + size_t testJointIndex; + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_testJointName, testJointIndex); + const AZ::Quaternion testJointRotation = jackPose->GetModelSpaceTransform(testJointIndex).m_rotation; - for (std::vector rotateXYZ : m_param.rotations) + for (std::vector rotateXYZ : m_param.m_rotations) { const float rotateX = rotateXYZ[0]; const float rotateY = rotateXYZ[1]; @@ -299,7 +299,7 @@ namespace EMotionFX ParamSetValue("RotationParam", AZ::Quaternion(rotateX, rotateY, rotateZ, 1.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Quaternion testJointNewRotation = jackPose->GetModelSpaceTransform(testJointIndex).mRotation; + const AZ::Quaternion testJointNewRotation = jackPose->GetModelSpaceTransform(testJointIndex).m_rotation; if (weight) { @@ -315,49 +315,49 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, BendDirectionOutputCorrectPose) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->mPortID, + m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("BendDirParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); + m_paramNode->FindOutputPortByName("BendDirParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); m_twoLinkIKNode->SetRelativeBendDir(true); GetEMotionFX().Update(1.0f / 60.0f); // Set up Jack's arm to specific position for testing const float weight = testing::get<0>(GetParam()); - const float x = m_param.bendDirPosition[0]; - const float y = m_param.bendDirPosition[1]; - const float z = m_param.bendDirPosition[2]; + const float x = m_param.m_bendDirPosition[0]; + const float y = m_param.m_bendDirPosition[1]; + const float z = m_param.m_bendDirPosition[2]; ParamSetValue("WeightParam", weight); ParamSetValue("GoalPosParam", AZ::Vector3(x, y, z)); GetEMotionFX().Update(1.0f / 60.0f); Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testBendJointIndex; - AZ::u32 testJointIndex; - AZStd::string& bendLoArm = m_param.linkedJointNames[0]; + size_t testBendJointIndex; + size_t testJointIndex; + AZStd::string& bendLoArm = m_param.m_linkedJointNames[0]; m_jackSkeleton->FindNodeAndIndexByName(bendLoArm, testBendJointIndex); - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_testJointName, testJointIndex); - const AZ::Vector3 testJointBendPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; // Bend the test joint to opposite positions and check positions are opposite ParamSetValue("BendDirParam", AZ::Vector3(1.0f, 0.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendRightPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendRightPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(-1.0f, 0.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendLeftPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendLeftPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(0.0f, 1.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendDownPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendDownPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(0.0f, -1.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendUpPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendUpPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; if (weight) { @@ -382,63 +382,63 @@ namespace EMotionFX TEST_P(BlendTreeTwoLinkIKNodeFixture, CombinedFunctionsOutputCorrectPose) { // Two Link IK Node should not break when using all of its functions at the same time - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->mPortID, + m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortByName("WeightParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_WEIGHT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("GoalPosParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); + m_paramNode->FindOutputPortByName("GoalPosParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALPOS); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("RotationParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); + m_paramNode->FindOutputPortByName("RotationParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_GOALROT); m_twoLinkIKNode->AddConnection(m_paramNode, - m_paramNode->FindOutputPortByName("BendDirParam")->mPortID, BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); + m_paramNode->FindOutputPortByName("BendDirParam")->m_portId, BlendTreeTwoLinkIKNode::INPUTPORT_BENDDIR); m_twoLinkIKNode->SetRotationEnabled(true); m_twoLinkIKNode->SetRelativeBendDir(true); GetEMotionFX().Update(1.0f / 60.0f); const Pose* jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); - AZ::u32 testJointIndex; - AZ::u32 testBendJointIndex; - AZStd::string& bendLoArm = m_param.linkedJointNames[0]; - m_jackSkeleton->FindNodeAndIndexByName(m_param.testJointName, testJointIndex); + size_t testJointIndex; + size_t testBendJointIndex; + AZStd::string& bendLoArm = m_param.m_linkedJointNames[0]; + m_jackSkeleton->FindNodeAndIndexByName(m_param.m_testJointName, testJointIndex); m_jackSkeleton->FindNodeAndIndexByName(bendLoArm, testBendJointIndex); // Adding weight and goal position const float weight = testing::get<0>(GetParam()); - const float posX = m_param.bendDirPosition[0]; - const float posY = m_param.bendDirPosition[1]; - const float posZ = m_param.bendDirPosition[2]; + const float posX = m_param.m_bendDirPosition[0]; + const float posY = m_param.m_bendDirPosition[1]; + const float posZ = m_param.m_bendDirPosition[2]; ParamSetValue("WeightParam", weight); ParamSetValue("GoalPosParam", AZ::Vector3(posX, posY, posZ)); GetEMotionFX().Update(1.0f / 60.0f); // Add bend direction - const AZ::Vector3 testJointBendPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(1.0f, 0.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendRightPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendRightPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(-1.0f, 0.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendLeftPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendLeftPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(0.0f, 1.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendDownPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendDownPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; ParamSetValue("BendDirParam", AZ::Vector3(0.0f, -1.0f, 0.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Vector3 testJointBendUpPos = jackPose->GetModelSpaceTransform(testBendJointIndex).mPosition; + const AZ::Vector3 testJointBendUpPos = jackPose->GetModelSpaceTransform(testBendJointIndex).m_position; // Rotations with bent joint - const AZ::Quaternion testJointOriginalRotation = jackPose->GetModelSpaceTransform(testJointIndex).mRotation; - for (std::vector rotateXYZ : m_param.rotations) + const AZ::Quaternion testJointOriginalRotation = jackPose->GetModelSpaceTransform(testJointIndex).m_rotation; + for (std::vector rotateXYZ : m_param.m_rotations) { const float rotateX = rotateXYZ[0]; const float rotateY = rotateXYZ[1]; const float rotateZ = rotateXYZ[2]; ParamSetValue("RotationParam", AZ::Quaternion(rotateX, rotateY, rotateZ, 1.0f)); GetEMotionFX().Update(1.0f / 60.0f); - const AZ::Quaternion testJointNewRotation = jackPose->GetModelSpaceTransform(testJointIndex).mRotation; + const AZ::Quaternion testJointNewRotation = jackPose->GetModelSpaceTransform(testJointIndex).m_rotation; if (weight) { diff --git a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp index b64c2a212f..6214005a71 100644 --- a/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/BoolLogicNodeTests.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include namespace EMotionFX { @@ -168,15 +168,15 @@ namespace EMotionFX const AZStd::vector& parameterNodeOutputPorts = parameterNode->GetOutputPorts(); for (const EMotionFX::AnimGraphNode::Port& port : parameterNodeOutputPorts) { - uint32 paramIndex = parameterNode->GetParameterIndex(port.mPortID); + uint32 paramIndex = parameterNode->GetParameterIndex(port.m_portId); if (paramIndex == boolXParamIndexOutcome.GetValue()) { - boolXOutputPortIndex = port.mPortID; + boolXOutputPortIndex = port.m_portId; portIndicesFound++; } else if (paramIndex == boolYParamIndexOutcome.GetValue()) { - boolYOutputPortIndex = port.mPortID; + boolYOutputPortIndex = port.m_portId; portIndicesFound++; } } diff --git a/Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp b/Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp index 9da4f0fdb8..88ca19b277 100644 --- a/Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp +++ b/Gems/EMotionFX/Code/Tests/Bugs/CanUndoParameterDeletionAndRestoreBlendTreeConnections.cpp @@ -142,7 +142,7 @@ namespace EMotionFX for (const AnimGraphNode::Port& outputPort : outputPorts) { - ASSERT_TRUE(outputPort.mConnection) << "Expected a valid connection at the output port."; + ASSERT_TRUE(outputPort.m_connection) << "Expected a valid connection at the output port."; } } @@ -173,7 +173,7 @@ namespace EMotionFX for (const AnimGraphNode::Port& outputPort : outputPorts) { - ASSERT_TRUE(outputPort.mConnection) << "Expected a valid connection at the output port."; + ASSERT_TRUE(outputPort.m_connection) << "Expected a valid connection at the output port."; } } } diff --git a/Gems/EMotionFX/Code/Tests/EmotionFXMathLibTests.cpp b/Gems/EMotionFX/Code/Tests/EmotionFXMathLibTests.cpp index 041cc9e862..e4d532928c 100644 --- a/Gems/EMotionFX/Code/Tests/EmotionFXMathLibTests.cpp +++ b/Gems/EMotionFX/Code/Tests/EmotionFXMathLibTests.cpp @@ -22,9 +22,9 @@ protected: void SetUp() override { - m_azNormalizedVector3_a = AZ::Vector3(s_x1, s_y1, s_z1); - m_azNormalizedVector3_a.Normalize(); - m_azQuaternion_a = AZ::Quaternion::CreateFromAxisAngle(m_azNormalizedVector3_a, s_angle_a); + m_azNormalizedVector3A = AZ::Vector3(s_x1, s_y1, s_z1); + m_azNormalizedVector3A.Normalize(); + m_azQuaternionA = AZ::Quaternion::CreateFromAxisAngle(m_azNormalizedVector3A, s_angle_a); } void TearDown() override @@ -117,8 +117,8 @@ protected: static const float s_y1; static const float s_z1; static const float s_angle_a; - AZ::Vector3 m_azNormalizedVector3_a; - AZ::Quaternion m_azQuaternion_a; + AZ::Vector3 m_azNormalizedVector3A; + AZ::Quaternion m_azQuaternionA; }; const float EmotionFXMathLibTests::s_toleranceHigh = 0.00001f; diff --git a/Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp b/Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp index 3c529c93dd..9b18ca5862 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp +++ b/Gems/EMotionFX/Code/Tests/Integration/CanAddActor.cpp @@ -40,7 +40,7 @@ namespace EMotionFX } // Ensure the Actor is correct - ASSERT_TRUE(GetActorManager().FindActorByName("rinactor")); + ASSERT_TRUE(GetActorManager().FindActorByName("rinActor")); EXPECT_EQ(GetActorManager().GetNumActors(), 1); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/Integration/CanAddSimpleMotionComponent.cpp b/Gems/EMotionFX/Code/Tests/Integration/CanAddSimpleMotionComponent.cpp index 74aea6ea50..09542a9761 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/CanAddSimpleMotionComponent.cpp +++ b/Gems/EMotionFX/Code/Tests/Integration/CanAddSimpleMotionComponent.cpp @@ -66,7 +66,7 @@ namespace EMotionFX entity->GetId(), AZ::ComponentTypeList{azrtti_typeid()} ); - EXPECT_TRUE(componentOutcome.IsSuccess()) << componentOutcome.GetError().c_str(); + ASSERT_TRUE(componentOutcome.IsSuccess()) << componentOutcome.GetError().c_str(); bool hasComponent = false; AzToolsFramework::EditorComponentAPIBus::BroadcastResult( diff --git a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h index 16d9fb2389..d354153f9b 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h +++ b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonFixture.h @@ -18,12 +18,12 @@ namespace EMotionFX struct PoseComparisonFixtureParams { - const char* actorFile = nullptr; - const char* animGraphFile = nullptr; - const char* motionSetFile = nullptr; - const char* recordingFile = nullptr; + const char* m_actorFile = nullptr; + const char* m_animGraphFile = nullptr; + const char* m_motionSetFile = nullptr; + const char* m_recordingFile = nullptr; PoseComparisonFixtureParams(const char* actorFile, const char* animGraphFile, const char* motionSetFile, const char* recordingFile) - : actorFile(actorFile), animGraphFile(animGraphFile), motionSetFile(motionSetFile), recordingFile(recordingFile) + : m_actorFile(actorFile), m_animGraphFile(animGraphFile), m_motionSetFile(motionSetFile), m_recordingFile(recordingFile) {} }; diff --git a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp index dff4f4162c..cccf744cfc 100644 --- a/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp +++ b/Gems/EMotionFX/Code/Tests/Integration/PoseComparisonTests.cpp @@ -23,7 +23,7 @@ namespace EMotionFX { void PrintTo(const Recorder::ActorInstanceData& actorInstanceData, ::std::ostream* os) { - *os << actorInstanceData.mActorInstance->GetActor()->GetName(); + *os << actorInstanceData.m_actorInstance->GetActor()->GetName(); } template @@ -42,8 +42,8 @@ namespace EMotionFX void PrintTo(const Recorder::TransformTracks& tracks, ::std::ostream* os) { - PrintTo(tracks.mPositions, os); - PrintTo(tracks.mRotations, os); + PrintTo(tracks.m_positions, os); + PrintTo(tracks.m_rotations, os); } AZ_PUSH_DISABLE_WARNING(4100, "-Wmissing-declarations") // 'result_listener': unreferenced formal parameter @@ -90,11 +90,11 @@ namespace EMotionFX bool MatchAndExplain(const KeyTrackLinearDynamic& got, ::testing::MatchResultListener* result_listener) const override { - const uint32 gotSize = got.GetNumKeys(); - const uint32 expectedSize = m_expected.GetNumKeys(); - const uint32 commonSize = AZStd::min(gotSize, expectedSize); + const size_t gotSize = got.GetNumKeys(); + const size_t expectedSize = m_expected.GetNumKeys(); + const size_t commonSize = AZStd::min(gotSize, expectedSize); - for (uint32 i = 0; i != commonSize; ++i) + for (size_t i = 0; i != commonSize; ++i) { const KeyFrame* gotKey = got.GetKey(i); const KeyFrame* expectedKey = m_expected.GetKey(i); @@ -104,9 +104,9 @@ namespace EMotionFX *result_listener << "where the value pair at index #" << i << " don't match\n"; const uint32 numContextLines = 2; - const uint32 beginContextLines = i > numContextLines ? i - numContextLines : 0; - const uint32 endContextLines = i > commonSize - numContextLines - 1 ? commonSize : i + numContextLines + 1; - for (uint32 contextIndex = beginContextLines; contextIndex < endContextLines; ++contextIndex) + const size_t beginContextLines = i > numContextLines ? i - numContextLines : 0; + const size_t endContextLines = i > commonSize - numContextLines - 1 ? commonSize : i + numContextLines + 1; + for (size_t contextIndex = beginContextLines; contextIndex < endContextLines; ++contextIndex) { const bool contextLineMatches = ::testing::Matches(innerMatcher)(::testing::make_tuple(got.GetKey(contextIndex), m_expected.GetKey(contextIndex))); if (!contextLineMatches) @@ -178,15 +178,15 @@ namespace EMotionFX void INTEG_PoseComparisonFixture::LoadAssets() { - const AZStd::string actorPath = ResolvePath(GetParam().actorFile); + const AZStd::string actorPath = ResolvePath(GetParam().m_actorFile); m_actor = EMotionFX::GetImporter().LoadActor(actorPath); ASSERT_TRUE(m_actor) << "Failed to load actor"; - const AZStd::string animGraphPath = ResolvePath(GetParam().animGraphFile); + const AZStd::string animGraphPath = ResolvePath(GetParam().m_animGraphFile); m_animGraph = EMotionFX::GetImporter().LoadAnimGraph(animGraphPath); ASSERT_TRUE(m_animGraph) << "Failed to load anim graph"; - const AZStd::string motionSetPath = ResolvePath(GetParam().motionSetFile); + const AZStd::string motionSetPath = ResolvePath(GetParam().m_motionSetFile); m_motionSet = EMotionFX::GetImporter().LoadMotionSet(motionSetPath); ASSERT_TRUE(m_motionSet) << "Failed to load motion set"; m_motionSet->Preload(); @@ -197,7 +197,7 @@ namespace EMotionFX TEST_P(INTEG_PoseComparisonFixture, Integ_TestPoses) { - const AZStd::string recordingPath = ResolvePath(GetParam().recordingFile); + const AZStd::string recordingPath = ResolvePath(GetParam().m_recordingFile); Recorder* recording = EMotionFX::Recorder::LoadFromFile(recordingPath.c_str()); const EMotionFX::Recorder::ActorInstanceData& expectedActorInstanceData = recording->GetActorInstanceData(0); @@ -222,10 +222,10 @@ namespace EMotionFX { const Recorder::TransformTracks& gotTrack = gotTracks[trackNum]; const Recorder::TransformTracks& expectedTrack = expectedTracks[trackNum]; - const char* nodeName = gotActorInstanceData.mActorInstance->GetActor()->GetSkeleton()->GetNode(static_cast(trackNum))->GetName(); + const char* nodeName = gotActorInstanceData.m_actorInstance->GetActor()->GetSkeleton()->GetNode(trackNum)->GetName(); - EXPECT_THAT(gotTrack.mPositions, MatchesKeyTrack(expectedTrack.mPositions, nodeName)); - EXPECT_THAT(gotTrack.mRotations, MatchesKeyTrack(expectedTrack.mRotations, nodeName)); + EXPECT_THAT(gotTrack.m_positions, MatchesKeyTrack(expectedTrack.m_positions, nodeName)); + EXPECT_THAT(gotTrack.m_rotations, MatchesKeyTrack(expectedTrack.m_rotations, nodeName)); } recording->Destroy(); @@ -235,14 +235,14 @@ namespace EMotionFX { // Make one recording, 10 seconds at 60 fps Recorder::RecordSettings settings; - settings.mFPS = 1000000; - settings.mRecordTransforms = true; - settings.mRecordAnimGraphStates = false; - settings.mRecordNodeHistory = false; - settings.mRecordScale = false; - settings.mInitialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb - settings.mHistoryStatesOnly = false; - settings.mRecordEvents = false; + settings.m_fps = 1000000; + settings.m_recordTransforms = true; + settings.m_recordAnimGraphStates = false; + settings.m_recordNodeHistory = false; + settings.m_recordScale = false; + settings.m_initialAnimGraphAnimBytes = 4 * 1024 * 1024; // 4 mb + settings.m_historyStatesOnly = false; + settings.m_recordEvents = false; EMotionFX::GetRecorder().StartRecording(settings); @@ -285,10 +285,10 @@ namespace EMotionFX { const Recorder::TransformTracks& gotTrack = gotTracks[trackNum]; const Recorder::TransformTracks& expectedTrack = expectedTracks[trackNum]; - const char* nodeName = gotActorInstanceData.mActorInstance->GetActor()->GetSkeleton()->GetNode(static_cast(trackNum))->GetName(); + const char* nodeName = gotActorInstanceData.m_actorInstance->GetActor()->GetSkeleton()->GetNode(trackNum)->GetName(); - EXPECT_THAT(gotTrack.mPositions, MatchesKeyTrack(expectedTrack.mPositions, nodeName)); - EXPECT_THAT(gotTrack.mRotations, MatchesKeyTrack(expectedTrack.mRotations, nodeName)); + EXPECT_THAT(gotTrack.m_positions, MatchesKeyTrack(expectedTrack.m_positions, nodeName)); + EXPECT_THAT(gotTrack.m_rotations, MatchesKeyTrack(expectedTrack.m_rotations, nodeName)); } recording->Destroy(); diff --git a/Gems/EMotionFX/Code/Tests/KeyTrackLinearTests.cpp b/Gems/EMotionFX/Code/Tests/KeyTrackLinearTests.cpp index bf7eee3afc..ae6150734e 100644 --- a/Gems/EMotionFX/Code/Tests/KeyTrackLinearTests.cpp +++ b/Gems/EMotionFX/Code/Tests/KeyTrackLinearTests.cpp @@ -32,9 +32,9 @@ namespace EMotionFX void LogFloatTrack(KeyTrackLinearDynamic& track) { AZ_Printf("EMotionFX", "----------\n"); - for (AZ::u32 i=0; i < track.GetNumKeys(); ++i) + for (size_t i=0; i < track.GetNumKeys(); ++i) { - AZ_Printf("EMotionFX", "#%d = time:%f value:%f\n", i, track.GetKey(i)->GetTime(), track.GetKey(i)->GetValue()); + AZ_Printf("EMotionFX", "#%zu = time:%f value:%f\n", i, track.GetKey(i)->GetTime(), track.GetKey(i)->GetValue()); } } @@ -185,16 +185,16 @@ namespace EMotionFX EMotionFX::KeyTrackLinearDynamic track; FillFloatTrackZeroToThree(track); - ASSERT_EQ(track.FindKeyNumber(-1.0f), MCORE_INVALIDINDEX32); + ASSERT_EQ(track.FindKeyNumber(-1.0f), InvalidIndex); ASSERT_EQ(track.FindKeyNumber(0.0f), 0); ASSERT_EQ(track.FindKeyNumber(1.0f), 1); ASSERT_EQ(track.FindKeyNumber(2.0f), 2); ASSERT_EQ(track.FindKeyNumber(2.4f), 2); ASSERT_EQ(track.FindKeyNumber(2.8f), 2); ASSERT_EQ(track.FindKeyNumber(2.999f), 2); - ASSERT_EQ(track.FindKeyNumber(3.0f), MCORE_INVALIDINDEX32); - ASSERT_EQ(track.FindKeyNumber(3.001f), MCORE_INVALIDINDEX32); - ASSERT_EQ(track.FindKeyNumber(4.0f), MCORE_INVALIDINDEX32); + ASSERT_EQ(track.FindKeyNumber(3.0f), InvalidIndex); + ASSERT_EQ(track.FindKeyNumber(3.001f), InvalidIndex); + ASSERT_EQ(track.FindKeyNumber(4.0f), InvalidIndex); } TEST_F(KeyTrackLinearDynamicFixture, KeyTrackSetNumKeys) @@ -231,7 +231,7 @@ namespace EMotionFX track.AddKey(2.01f, 1.0001f); track.AddKey(3.0f, 3.0f); track.Init(); - const uint32 numKeysRemoved = track.Optimize(0.001f); + const size_t numKeysRemoved = track.Optimize(0.001f); ASSERT_EQ(numKeysRemoved, 1); ASSERT_EQ(track.GetNumKeys(), 4); ASSERT_FLOAT_EQ(track.GetKey(0)->GetTime(), 0.0f); @@ -252,7 +252,7 @@ namespace EMotionFX ASSERT_FLOAT_EQ(track.GetValueAtTime(4.0f), 3.0f); uint8 cacheHit = 0; - uint32 cached = 0; + size_t cached = 0; ASSERT_FLOAT_EQ(track.GetValueAtTime(0.0f, &cached, &cacheHit), 0.0f); ASSERT_EQ(cached, 0); ASSERT_EQ(cacheHit, 1); diff --git a/Gems/EMotionFX/Code/Tests/Matchers.h b/Gems/EMotionFX/Code/Tests/Matchers.h index ad3c204f72..9f7b9017ba 100644 --- a/Gems/EMotionFX/Code/Tests/Matchers.h +++ b/Gems/EMotionFX/Code/Tests/Matchers.h @@ -81,12 +81,12 @@ template<> inline bool IsCloseMatcherP::gmock_Impl::MatchAndExplain(const EMotionFX::Transform& arg, ::testing::MatchResultListener* result_listener) const { #ifndef EMFX_SCALE_DISABLED - return ::testing::ExplainMatchResult(IsClose(expected.mPosition), arg.mPosition, result_listener) - && ::testing::ExplainMatchResult(IsClose(expected.mRotation), arg.mRotation, result_listener) - && ::testing::ExplainMatchResult(IsClose(expected.mScale), arg.mScale, result_listener); + return ::testing::ExplainMatchResult(IsClose(expected.m_position), arg.m_position, result_listener) + && ::testing::ExplainMatchResult(IsClose(expected.m_rotation), arg.m_rotation, result_listener) + && ::testing::ExplainMatchResult(IsClose(expected.m_scale), arg.m_scale, result_listener); #else - return ::testing::ExplainMatchResult(IsClose(expected.mPosition), arg.mPosition, result_listener) - && ::testing::ExplainMatchResult(IsClose(expected.mRotation), arg.mRotation, result_listener); + return ::testing::ExplainMatchResult(IsClose(expected.m_position), arg.m_position, result_listener) + && ::testing::ExplainMatchResult(IsClose(expected.m_rotation), arg.m_rotation, result_listener); #endif } @@ -96,20 +96,20 @@ inline bool IsCloseMatcherP::gmock_Impl::Ma { using ::testing::FloatEq; using ::testing::ExplainMatchResult; - return ExplainMatchResult(FloatEq(expected.m16[0]), arg.m16[0], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[1]), arg.m16[1], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[2]), arg.m16[2], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[3]), arg.m16[3], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[4]), arg.m16[4], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[5]), arg.m16[5], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[6]), arg.m16[6], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[7]), arg.m16[7], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[8]), arg.m16[8], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[9]), arg.m16[9], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[10]), arg.m16[10], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[11]), arg.m16[11], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[12]), arg.m16[12], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[13]), arg.m16[13], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[14]), arg.m16[14], result_listener) - && ExplainMatchResult(FloatEq(expected.m16[15]), arg.m16[15], result_listener); + return ExplainMatchResult(FloatEq(expected.m_m16[0]), arg.m_m16[0], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[1]), arg.m_m16[1], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[2]), arg.m_m16[2], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[3]), arg.m_m16[3], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[4]), arg.m_m16[4], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[5]), arg.m_m16[5], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[6]), arg.m_m16[6], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[7]), arg.m_m16[7], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[8]), arg.m_m16[8], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[9]), arg.m_m16[9], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[10]), arg.m_m16[10], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[11]), arg.m_m16[11], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[12]), arg.m_m16[12], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[13]), arg.m_m16[13], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[14]), arg.m_m16[14], result_listener) + && ExplainMatchResult(FloatEq(expected.m_m16[15]), arg.m_m16[15], result_listener); } diff --git a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h index d3225759a1..00eca16f44 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraph.h @@ -24,13 +24,13 @@ namespace EMotionFX MOCK_CONST_METHOD1(RecursiveFindNodeById, AnimGraphNode*(AnimGraphNodeId)); MOCK_CONST_METHOD1(RecursiveFindTransitionById, AnimGraphStateTransition*(AnimGraphConnectionId)); MOCK_CONST_METHOD2(RecursiveCollectNodesOfType, void(const AZ::TypeId& nodeType, AZStd::vector* outNodes)); - MOCK_CONST_METHOD2(RecursiveCollectTransitionConditionsOfType, void(const AZ::TypeId& conditionType, MCore::Array* outConditions)); + MOCK_CONST_METHOD2(RecursiveCollectTransitionConditionsOfType, void(const AZ::TypeId& conditionType, AZStd::vector* outConditions)); MOCK_METHOD2(RecursiveCollectObjectsOfType, void(const AZ::TypeId& objectType, AZStd::vector& outObjects)); MOCK_METHOD2(RecursiveCollectObjectsAffectedBy, void(AnimGraph* animGraph, AZStd::vector& outObjects)); //uint32 RecursiveCalcNumNodes() const; //void RecursiveCalcStatistics(Statistics& outStatistics) const; //uint32 RecursiveCalcNumNodeConnections() const; - //void DecreaseInternalAttributeIndices(uint32 decreaseEverythingHigherThan); + //void DecreaseInternalAttributeIndices(size_t decreaseEverythingHigherThan); //AZStd::string GenerateNodeName(const AZStd::unordered_set& nameReserveList, const char* prefix = "Node") const; MOCK_CONST_METHOD0(GetNumParameters, size_t()); MOCK_CONST_METHOD0(GetNumValueParameters, size_t()); diff --git a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h index 705bef9602..e04f19fa95 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphInstance.h @@ -27,27 +27,27 @@ namespace EMotionFX //bool GetVector3ParameterValue(const char* paramName, AZ::Vector3* outValue); //bool GetVector4ParameterValue(const char* paramName, AZ::Vector4* outValue); //bool GetRotationParameterValue(const char* paramName, MCore::Quaternion* outRotation); - //bool GetParameterValueAsFloat(uint32 paramIndex, float* outValue); - //bool GetParameterValueAsBool(uint32 paramIndex, bool* outValue); - //bool GetParameterValueAsInt(uint32 paramIndex, int32* outValue); - //bool GetVector2ParameterValue(uint32 paramIndex, AZ::Vector2* outValue); - //bool GetVector3ParameterValue(uint32 paramIndex, AZ::Vector3* outValue); - //bool GetVector4ParameterValue(uint32 paramIndex, AZ::Vector4* outValue); - //bool GetRotationParameterValue(uint32 paramIndex, MCore::Quaternion* outRotation); + //bool GetParameterValueAsFloat(size_t paramIndex, float* outValue); + //bool GetParameterValueAsBool(size_t paramIndex, bool* outValue); + //bool GetParameterValueAsInt(size_t paramIndex, int32* outValue); + //bool GetVector2ParameterValue(size_t paramIndex, AZ::Vector2* outValue); + //bool GetVector3ParameterValue(size_t paramIndex, AZ::Vector3* outValue); + //bool GetVector4ParameterValue(size_t paramIndex, AZ::Vector4* outValue); + //bool GetRotationParameterValue(size_t paramIndex, MCore::Quaternion* outRotation); //void SetMotionSet(MotionSet* motionSet); //void CreateParameterValues(); MOCK_METHOD0(AddMissingParameterValues, void()); - MOCK_METHOD1(ReInitParameterValue, void(uint32 index)); + MOCK_METHOD1(ReInitParameterValue, void(size_t index)); MOCK_METHOD0(ReInitParameterValues, void()); - MOCK_METHOD2(RemoveParameterValueImpl, void(uint32 index, bool delFromMem)); - virtual void RemoveParameterValue(uint32 index, bool delFromMem = true) { RemoveParameterValueImpl(index, delFromMem); } + MOCK_METHOD2(RemoveParameterValueImpl, void(size_t index, bool delFromMem)); + virtual void RemoveParameterValue(size_t index, bool delFromMem = true) { RemoveParameterValueImpl(index, delFromMem); } //void AddParameterValue(); - MOCK_METHOD2(MoveParameterValue, void(uint32 oldIndex, uint32 newIndex)); - MOCK_METHOD1(InsertParameterValue, void(uint32 index)); + MOCK_METHOD2(MoveParameterValue, void(size_t oldIndex, size_t newIndex)); + MOCK_METHOD1(InsertParameterValue, void(size_t index)); //void RemoveAllParameters(bool delFromMem); //template - //T* GetParameterValueChecked(uint32 index) const; - //MCore::Attribute* GetParameterValue(uint32 index) const; + //T* GetParameterValueChecked(size_t index) const; + //MCore::Attribute* GetParameterValue(size_t index) const; //MCore::Attribute* FindParameter(const AZStd::string& name) const; //AZ::Outcome FindParameterIndex(const AZStd::string& name) const; //bool SwitchToState(const char* stateName); @@ -99,7 +99,7 @@ namespace EMotionFX //void OnStateEnd(AnimGraphNode* state); //void OnStartTransition(AnimGraphStateTransition* transition); //void OnEndTransition(AnimGraphStateTransition* transition); - //void CollectActiveAnimGraphNodes(MCore::Array* outNodes, const AZ::TypeId& nodeType = AZ::TypeId::CreateNull()); + //void CollectActiveAnimGraphNodes(AZStd::vector* outNodes, const AZ::TypeId& nodeType = AZ::TypeId::CreateNull()); //void CollectActiveNetTimeSyncNodes(AZStd::vector* outNodes); //uint32 GetObjectFlags(uint32 objectIndex) const; //void SetObjectFlags(uint32 objectIndex, uint32 flags); diff --git a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphNode.h b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphNode.h index 85b80b2e60..9c73694d2a 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphNode.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/AnimGraphNode.h @@ -15,8 +15,8 @@ namespace EMotionFX AZ_RTTI(AnimGraphNode, "{7F1C0E1D-4D32-4A6D-963C-20193EA28F95}", AnimGraphObject) MOCK_CONST_METHOD1(CollectOutgoingConnections, void(AZStd::vector>& outConnections)); - MOCK_CONST_METHOD2(CollectOutgoingConnections, void(AZStd::vector>& outConnections, const uint32 portIndex)); + MOCK_CONST_METHOD2(CollectOutgoingConnections, void(AZStd::vector>& outConnections, const size_t portIndex)); - MOCK_CONST_METHOD1(FindOutputPortIndex, uint32(const AZStd::string& name)); + MOCK_CONST_METHOD1(FindOutputPortIndex, size_t(const AZStd::string& name)); }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/Mocks/CommandManagerCallback.h b/Gems/EMotionFX/Code/Tests/Mocks/CommandManagerCallback.h index 7f9a8d6530..0e805b72e1 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/CommandManagerCallback.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/CommandManagerCallback.h @@ -21,8 +21,8 @@ namespace MCore MOCK_METHOD2(OnPreExecuteCommandGroup, void(MCore::CommandGroup*, bool)); MOCK_METHOD2(OnPostExecuteCommandGroup, void(MCore::CommandGroup*, bool)); - MOCK_METHOD4(OnAddCommandToHistory, void(uint32, MCore::CommandGroup*, MCore::Command*, const MCore::CommandLine&)); - MOCK_METHOD1(OnRemoveCommand, void(uint32)); - MOCK_METHOD1(OnSetCurrentCommand, void(uint32)); + MOCK_METHOD4(OnAddCommandToHistory, void(size_t, MCore::CommandGroup*, MCore::Command*, const MCore::CommandLine&)); + MOCK_METHOD1(OnRemoveCommand, void(size_t)); + MOCK_METHOD1(OnSetCurrentCommand, void(size_t)); }; } // namespace MCore diff --git a/Gems/EMotionFX/Code/Tests/Mocks/EventHandler.h b/Gems/EMotionFX/Code/Tests/Mocks/EventHandler.h index 80e4a6ff21..1208082e67 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/EventHandler.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/EventHandler.h @@ -58,7 +58,7 @@ namespace EMotionFX MOCK_METHOD2(OnStartTransition, void(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition)); MOCK_METHOD2(OnEndTransition, void(AnimGraphInstance* animGraphInstance, AnimGraphStateTransition* transition)); - MOCK_METHOD3(OnSetVisualManipulatorOffset, void(AnimGraphInstance* animGraphInstance, uint32 paramIndex, const AZ::Vector3& offset)); + MOCK_METHOD3(OnSetVisualManipulatorOffset, void(AnimGraphInstance* animGraphInstance, size_t paramIndex, const AZ::Vector3& offset)); MOCK_METHOD4(OnInputPortsChanged, void(AnimGraphNode* node, const AZStd::vector& newInputPorts, const AZStd::string& memberName, const AZStd::vector& memberValue)); MOCK_METHOD4(OnOutputPortsChanged, void(AnimGraphNode* node, const AZStd::vector& newOutputPorts, const AZStd::string& memberName, const AZStd::vector& memberValue)); MOCK_METHOD3(OnRenamedNode, void(AnimGraph* animGraph, AnimGraphNode* node, const AZStd::string& oldName)); diff --git a/Gems/EMotionFX/Code/Tests/Mocks/Node.h b/Gems/EMotionFX/Code/Tests/Mocks/Node.h index 712eb257d5..6c46cc95bb 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/Node.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/Node.h @@ -25,10 +25,10 @@ namespace EMotionFX static Node* Create(const char* name, Skeleton* skeleton); static Node* Create(uint32 nameID, Skeleton* skeleton); MOCK_CONST_METHOD1(Clone, Node*(Skeleton* skeleton)); - MOCK_METHOD1(SetParentIndex, void(uint32 parentNodeIndex)); - MOCK_CONST_METHOD0(GetParentIndex, uint32()); + MOCK_METHOD1(SetParentIndex, void(size_t parentNodeIndex)); + MOCK_CONST_METHOD0(GetParentIndex, size_t()); MOCK_CONST_METHOD0(GetParentNode, Node*()); - MOCK_CONST_METHOD2(RecursiveCollectParents, void(MCore::Array& parents, bool clearParentsArray)); + MOCK_CONST_METHOD2(RecursiveCollectParents, void(AZStd::vector& parents, bool clearParentsArray)); MOCK_METHOD1(SetName, void(const char* name)); MOCK_CONST_METHOD0(GetName, const char*()); MOCK_CONST_METHOD0(GetNameString, const AZStd::string&()); @@ -37,33 +37,33 @@ namespace EMotionFX MOCK_CONST_METHOD0(GetSemanticNameString, const AZStd::string&()); MOCK_CONST_METHOD0(GetID, uint32()); MOCK_CONST_METHOD0(GetSemanticID, uint32()); - MOCK_CONST_METHOD0(GetNumChildNodes, uint32()); - MOCK_CONST_METHOD0(GetNumChildNodesRecursive, uint32()); - MOCK_CONST_METHOD1(GetChildIndex, uint32(uint32 nr)); - MOCK_CONST_METHOD1(CheckIfIsChildNode, bool(uint32 nodeIndex)); - MOCK_METHOD1(AddChild, void(uint32 nodeIndex)); - MOCK_METHOD2(SetChild, void(uint32 childNr, uint32 childNodeIndex)); - MOCK_METHOD1(SetNumChildNodes, void(uint32 numChildNodes)); - MOCK_METHOD1(PreAllocNumChildNodes, void(uint32 numChildNodes)); - MOCK_METHOD1(RemoveChild, void(uint32 nodeIndex)); + MOCK_CONST_METHOD0(GetNumChildNodes, size_t()); + MOCK_CONST_METHOD0(GetNumChildNodesRecursive, size_t()); + MOCK_CONST_METHOD1(GetChildIndex, size_t(size_t nr)); + MOCK_CONST_METHOD1(CheckIfIsChildNode, bool(size_t nodeIndex)); + MOCK_METHOD1(AddChild, void(size_t nodeIndex)); + MOCK_METHOD2(SetChild, void(size_t childNr, size_t childNodeIndex)); + MOCK_METHOD1(SetNumChildNodes, void(size_t numChildNodes)); + MOCK_METHOD1(PreAllocNumChildNodes, void(size_t numChildNodes)); + MOCK_METHOD1(RemoveChild, void(size_t nodeIndex)); MOCK_METHOD0(RemoveAllChildNodes, void()); MOCK_CONST_METHOD0(GetIsRootNode, bool()); MOCK_CONST_METHOD0(GetHasChildNodes, bool()); MOCK_CONST_METHOD0(FindRoot, Node*()); MOCK_METHOD1(AddAttribute, void(NodeAttribute* attribute)); - MOCK_CONST_METHOD0(GetNumAttributes, uint32()); - MOCK_METHOD1(GetAttribute, NodeAttribute*(uint32 attributeNr)); + MOCK_CONST_METHOD0(GetNumAttributes, size_t()); + MOCK_METHOD1(GetAttribute, NodeAttribute*(size_t attributeNr)); MOCK_METHOD1(GetAttributeByType, NodeAttribute*(uint32 attributeType)); - MOCK_CONST_METHOD1(FindAttributeNumber, uint32(uint32 attributeTypeID)); + MOCK_CONST_METHOD1(FindAttributeNumber, size_t(uint32 attributeTypeID)); MOCK_METHOD0(RemoveAllAttributes, void()); - MOCK_METHOD1(RemoveAttribute, void(uint32 index)); - MOCK_METHOD2(RemoveAttributeByType, void(uint32 attributeTypeID, uint32 occurrence)); - MOCK_METHOD1(RemoveAllAttributesByType, uint32(uint32 attributeTypeID)); - MOCK_METHOD1(SetNodeIndex, void(uint32 index)); - MOCK_CONST_METHOD0(GetNodeIndex, uint32()); + MOCK_METHOD1(RemoveAttribute, void(size_t index)); + MOCK_METHOD2(RemoveAttributeByType, void(uint32 attributeTypeID, size_t occurrence)); + MOCK_METHOD1(RemoveAllAttributesByType, size_t(uint32 attributeTypeID)); + MOCK_METHOD1(SetNodeIndex, void(size_t index)); + MOCK_CONST_METHOD0(GetNodeIndex, size_t()); MOCK_METHOD1(SetSkeletalLODLevelBits, void(uint32 bitValues)); - MOCK_METHOD2(SetSkeletalLODStatus, void(uint32 lodLevel, bool enabled)); - MOCK_CONST_METHOD1(GetSkeletalLODStatus, bool(uint32 lodLevel)); + MOCK_METHOD2(SetSkeletalLODStatus, void(size_t lodLevel, bool enabled)); + MOCK_CONST_METHOD1(GetSkeletalLODStatus, bool(size_t lodLevel)); MOCK_CONST_METHOD0(GetIncludeInBoundsCalc, bool()); MOCK_METHOD1(SetIncludeInBoundsCalc, void(bool includeThisNode)); MOCK_CONST_METHOD0(GetIsAttachmentNode, bool()); diff --git a/Gems/EMotionFX/Code/Tests/Mocks/SimulatedJoint.h b/Gems/EMotionFX/Code/Tests/Mocks/SimulatedJoint.h index bb1b8aef68..5f2f78cf25 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/SimulatedJoint.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/SimulatedJoint.h @@ -26,7 +26,7 @@ namespace EMotionFX SimulatedJoint([[maybe_unused]] const SimulatedJoint& simulatedJoint) {} MOCK_METHOD1(SetSimulatedObject, void (SimulatedObject* object)); - MOCK_METHOD1(SetSkeletonJointIndex, void (AZ::u32 jointIndex)); + MOCK_METHOD1(SetSkeletonJointIndex, void (size_t jointIndex)); MOCK_METHOD1(SetConeAngleLimit, void (float degrees)); MOCK_METHOD1(SetMass, void (float mass)); MOCK_METHOD1(SetStiffness, void (float stiffness)); @@ -36,7 +36,7 @@ namespace EMotionFX MOCK_METHOD1(SetPinned, void (bool pinned)); MOCK_METHOD1(InitAfterLoading, bool (SimulatedObject* object)); - MOCK_CONST_METHOD0(GetSkeletonJointIndex, AZ::u32()); + MOCK_CONST_METHOD0(GetSkeletonJointIndex, size_t()); MOCK_CONST_METHOD0(GetConeAngleLimit, float()); MOCK_CONST_METHOD0(GetMass, float()); MOCK_CONST_METHOD0(GetStiffness, float()); diff --git a/Gems/EMotionFX/Code/Tests/Mocks/SimulatedObject.h b/Gems/EMotionFX/Code/Tests/Mocks/SimulatedObject.h index a9d69ea8af..320871ed7f 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/SimulatedObject.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/SimulatedObject.h @@ -18,14 +18,14 @@ namespace EMotionFX { public: AZ_TYPE_INFO(SimulatedObject, "{8CF0F474-69DC-4DE3-AF19-002F19DA27DB}"); - MOCK_CONST_METHOD1(FindSimulatedJointBySkeletonJointIndex, SimulatedJoint*(AZ::u32)); + MOCK_CONST_METHOD1(FindSimulatedJointBySkeletonJointIndex, SimulatedJoint*(size_t)); - MOCK_METHOD1(AddSimulatedJointAndChildren, void(AZ::u32)); - MOCK_METHOD1(AddSimulatedJoint, SimulatedJoint*(AZ::u32)); - MOCK_METHOD1(AddSimulatedJoints, void(AZStd::vector joints)); + MOCK_METHOD1(AddSimulatedJointAndChildren, void(size_t)); + MOCK_METHOD1(AddSimulatedJoint, SimulatedJoint*(size_t)); + MOCK_METHOD1(AddSimulatedJoints, void(AZStd::vector joints)); - MOCK_METHOD2(RemoveSimulatedJoint, void(AZ::u32, bool)); - MOCK_METHOD1(RemoveSimulatedJoint, void(AZ::u32)); + MOCK_METHOD2(RemoveSimulatedJoint, void(size_t, bool)); + MOCK_METHOD1(RemoveSimulatedJoint, void(size_t)); MOCK_CONST_METHOD0(GetNumSimulatedJoints, size_t()); MOCK_CONST_METHOD1(SetSimulatedJoints, void(const AZStd::vector& joints)); diff --git a/Gems/EMotionFX/Code/Tests/Mocks/Skeleton.h b/Gems/EMotionFX/Code/Tests/Mocks/Skeleton.h index b6aa4309f8..987718a157 100644 --- a/Gems/EMotionFX/Code/Tests/Mocks/Skeleton.h +++ b/Gems/EMotionFX/Code/Tests/Mocks/Skeleton.h @@ -11,8 +11,8 @@ namespace EMotionFX class Skeleton { public: - MOCK_CONST_METHOD1(GetNode, Node*(uint32 index)); + MOCK_CONST_METHOD1(GetNode, Node*(size_t index)); MOCK_CONST_METHOD1(FindNodeByName, Node*(const char* name)); - MOCK_CONST_METHOD0(GetNumNodes, uint32()); + MOCK_CONST_METHOD0(GetNumNodes, size_t()); }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/MorphTargetPipelineTests.cpp b/Gems/EMotionFX/Code/Tests/MorphTargetPipelineTests.cpp index c8aabc636a..0df39af8c5 100644 --- a/Gems/EMotionFX/Code/Tests/MorphTargetPipelineTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MorphTargetPipelineTests.cpp @@ -151,8 +151,8 @@ namespace EMotionFX Skeleton* skeleton = actor->GetSkeleton(); EMotionFX::Mesh* mesh = nullptr; - const uint32 numNodes = skeleton->GetNumNodes(); - for (uint32 nodeNum = 0; nodeNum < numNodes; ++nodeNum) + const size_t numNodes = skeleton->GetNumNodes(); + for (size_t nodeNum = 0; nodeNum < numNodes; ++nodeNum) { if (mesh) { @@ -223,8 +223,8 @@ namespace EMotionFX return; } - const uint32 numMorphTargets = morphSetup->GetNumMorphTargets(); - for (uint32 morphTargetIndex = 0; morphTargetIndex < numMorphTargets; ++morphTargetIndex) + const size_t numMorphTargets = morphSetup->GetNumMorphTargets(); + for (size_t morphTargetIndex = 0; morphTargetIndex < numMorphTargets; ++morphTargetIndex) { const MorphTarget* morphTarget = morphSetup->GetMorphTarget(morphTargetIndex); EXPECT_STREQ(morphTarget->GetName(), selectedMorphTargets[morphTargetIndex].c_str()) << "Morph target's name is incorrect"; diff --git a/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp index 0f022b72ef..02c17702a2 100644 --- a/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MorphTargetRuntimeTests.cpp @@ -82,9 +82,9 @@ namespace EMotionFX m_morphSetup->AddMorphTarget(morphTarget); // Without this call, the bind pose does not know about newly added - // morph target (mMorphWeights.GetLength() == 0) + // morph target (m_morphWeights.size() == 0) m_actor->ResizeTransformData(); - m_actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*generateOBBs=*/false, /*convertUnitType=*/false); + m_actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*convertUnitType=*/false); m_animGraph = AZStd::make_unique(); @@ -116,7 +116,7 @@ namespace EMotionFX // InitAfterLoading() is called morphTargetNode->AddConnection( parameterNode, - parameterNode->FindOutputPortIndex("FloatParam"), + aznumeric_caster(parameterNode->FindOutputPortIndex("FloatParam")), BlendTreeMorphTargetNode::PORTID_INPUT_WEIGHT ); finalNode->AddConnection( diff --git a/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp b/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp index c1fa8f3be4..30ab36e35a 100644 --- a/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MotionEventTrackTests.cpp @@ -27,11 +27,11 @@ namespace EMotionFX { struct ExtractEventsParams { - void (*eventFactory)(MotionEventTrack* track); - float startTime; - float endTime; - EPlayMode playMode; - std::vector expectedEvents; + void (*m_eventFactory)(MotionEventTrack* track); + float m_startTime; + float m_endTime; + EPlayMode m_playMode; + std::vector m_expectedEvents; }; void PrintTo(const EMotionFX::EventInfo::EventState& state, ::std::ostream* os) @@ -52,7 +52,7 @@ namespace EMotionFX void PrintTo(const EMotionFX::EventInfo& event, ::std::ostream* os) { - *os << "Time: " << event.mTimeValue + *os << "Time: " << event.m_timeValue << " State: " ; PrintTo(event.m_eventState, os); @@ -60,23 +60,23 @@ namespace EMotionFX void PrintTo(const ExtractEventsParams& object, ::std::ostream* os) { - if (object.eventFactory == &MakeNoEvents) + if (object.m_eventFactory == &MakeNoEvents) { *os << "Events: 0"; } - else if (object.eventFactory == &MakeOneEvent) + else if (object.m_eventFactory == &MakeOneEvent) { *os << "Events: 1"; } - else if (object.eventFactory == &MakeTwoEvents) + else if (object.m_eventFactory == &MakeTwoEvents) { *os << "Events: 2"; } - else if (object.eventFactory == &MakeThreeEvents) + else if (object.m_eventFactory == &MakeThreeEvents) { *os << "Events: 3"; } - else if (object.eventFactory == &MakeThreeRangedEvents) + else if (object.m_eventFactory == &MakeThreeRangedEvents) { *os << "Events: 3 (ranged)"; } @@ -84,15 +84,15 @@ namespace EMotionFX { *os << "Events: Unknown"; } - *os << " Start time: " << object.startTime - << " End time: " << object.endTime - << " Play mode: " << ((object.playMode == EPlayMode::PLAYMODE_FORWARD) ? "Forward" : "Backward") + *os << " Start time: " << object.m_startTime + << " End time: " << object.m_endTime + << " Play mode: " << ((object.m_playMode == EPlayMode::PLAYMODE_FORWARD) ? "Forward" : "Backward") << " Expected events: [" ; - for (const auto& entry : object.expectedEvents) + for (const auto& entry : object.m_expectedEvents) { PrintTo(entry, os); - if (&entry != &(*(object.expectedEvents.end() - 1))) + if (&entry != &(*(object.m_expectedEvents.end() - 1))) { *os << ", "; } @@ -148,7 +148,7 @@ namespace EMotionFX m_motion->GetEventTable()->AutoCreateSyncTrack(m_motion); m_track = m_motion->GetEventTable()->GetSyncTrack(); - GetParam().eventFactory(m_track); + GetParam().m_eventFactory(m_track); m_actor = ActorFactory::CreateAndInit(5); @@ -178,11 +178,11 @@ namespace EMotionFX const ExtractEventsParams& params = GetParam(); // Call the function being tested - func(params.startTime, params.endTime, params.playMode, m_motionInstance); + func(params.m_startTime, params.m_endTime, params.m_playMode, m_motionInstance); // ProcessEvents filters out the ACTIVE events, remove those from our expected results AZStd::vector expectedEvents; - for (const EventInfo& event : params.expectedEvents) + for (const EventInfo& event : params.m_expectedEvents) { if (event.m_eventState != EventInfo::ACTIVE || m_shouldContainActiveEvents) { @@ -191,11 +191,11 @@ namespace EMotionFX } EXPECT_EQ(m_buffer->GetNumEvents(), expectedEvents.size()) << "Number of events is incorrect"; - for (uint32 i = 0; i < AZStd::min(m_buffer->GetNumEvents(), static_cast(expectedEvents.size())); ++i) + for (size_t i = 0; i < AZStd::min(m_buffer->GetNumEvents(), expectedEvents.size()); ++i) { const EventInfo& gotEvent = m_buffer->GetEvent(i); const EventInfo& expectedEvent = expectedEvents[i]; - EXPECT_EQ(gotEvent.mTimeValue, expectedEvent.mTimeValue); + EXPECT_EQ(gotEvent.m_timeValue, expectedEvent.m_timeValue); EXPECT_EQ(gotEvent.m_eventState, expectedEvent.m_eventState); } } diff --git a/Gems/EMotionFX/Code/Tests/MotionExtractionBusTests.cpp b/Gems/EMotionFX/Code/Tests/MotionExtractionBusTests.cpp index 5c823c153f..d8b8a2a430 100644 --- a/Gems/EMotionFX/Code/Tests/MotionExtractionBusTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MotionExtractionBusTests.cpp @@ -137,7 +137,7 @@ namespace EMotionFX AZ::Transform currentTransform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(currentTransform, m_entityId, &AZ::TransformBus::Events::GetWorldTM); - const AZ::Vector3 actorInstancePosition = actorInstance->GetWorldSpaceTransform().mPosition; + const AZ::Vector3 actorInstancePosition = actorInstance->GetWorldSpaceTransform().m_position; const AZ::Vector3 positionDelta = actorInstancePosition - currentTransform.GetTranslation(); EXPECT_CALL(testBus, ExtractMotion(testing::_, testing::_)); diff --git a/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp b/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp index e1839d8d9f..35f1b96cce 100644 --- a/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MotionExtractionTests.cpp @@ -36,8 +36,8 @@ namespace EMotionFX { struct MotionExtractionTestsData { - std::vector durationMultipliers; - std::vector numOfLoops; + std::vector m_durationMultipliers; + std::vector m_numOfLoops; }; std::vector motionExtractionTestData @@ -59,8 +59,8 @@ namespace EMotionFX m_actorInstance->SetMotionExtractionEnabled(true); m_actor->AutoSetMotionExtractionNode(); - rootNode = m_jackSkeleton->FindNodeAndIndexByName("jack_root", m_jack_rootIndex); - hipNode = m_jackSkeleton->FindNodeAndIndexByName("Bip01__pelvis", m_jack_hipIndex); + m_rootNode = m_jackSkeleton->FindNodeAndIndexByName("jack_root", m_jackRootIndex); + m_hipNode = m_jackSkeleton->FindNodeAndIndexByName("Bip01__pelvis", m_jackHipIndex); m_jackPose = m_actorInstance->GetTransformData()->GetCurrentPose(); AddMotionEntry(TestMotionAssets::GetJackWalkForward(), "jack_walk_forward_aim_zup"); @@ -119,13 +119,13 @@ namespace EMotionFX } protected: - AZ::u32 m_jack_rootIndex = MCORE_INVALIDINDEX32; - AZ::u32 m_jack_hipIndex = MCORE_INVALIDINDEX32; + size_t m_jackRootIndex = InvalidIndex; + size_t m_jackHipIndex = InvalidIndex; AnimGraphMotionNode* m_motionNode = nullptr; BlendTree* m_blendTree = nullptr; Motion* m_motion = nullptr; - Node* rootNode = nullptr; - Node* hipNode = nullptr; + Node* m_rootNode = nullptr; + Node* m_hipNode = nullptr; Pose* m_jackPose = nullptr; Skeleton* m_jackSkeleton = nullptr; }; @@ -227,7 +227,7 @@ namespace EMotionFX // Make sure we also really end where we expect. // Motion extraction will introduce some small inaccuracies, so we can't use AZ::g_fltEps here, but need a slightly larger value in our AZ::IsClose(). - const float yPos = m_actorInstance->GetWorldSpaceTransform().mPosition.GetY(); + const float yPos = m_actorInstance->GetWorldSpaceTransform().m_position.GetY(); EXPECT_TRUE(AZ::IsClose(yPos, expectedY, 0.01f)); } #endif @@ -243,16 +243,16 @@ namespace EMotionFX // The expected delta used is the distance of the jack walk forward motion will move in 1 complete duration const float expectedDelta = ExtractLastFramePos().GetY(); - for (AZ::u32 paramIndex = 0; paramIndex < m_param.durationMultipliers.size(); paramIndex++) + for (size_t paramIndex = 0; paramIndex < m_param.m_durationMultipliers.size(); paramIndex++) { // Test motion extraction under different durations/time deltas - const float motionDuration = 1.066f * m_param.durationMultipliers[paramIndex]; - const float originalPositionY = m_actorInstance->GetWorldSpaceTransform().mPosition.GetY(); - for (AZ::u32 i = 0; i < m_param.numOfLoops[paramIndex]; i++) + const float motionDuration = 1.066f * m_param.m_durationMultipliers[paramIndex]; + const float originalPositionY = m_actorInstance->GetWorldSpaceTransform().m_position.GetY(); + for (AZ::u32 i = 0; i < m_param.m_numOfLoops[paramIndex]; i++) { GetEMotionFX().Update(motionDuration); } - const float updatedPositionY = m_actorInstance->GetWorldSpaceTransform().mPosition.GetY(); + const float updatedPositionY = m_actorInstance->GetWorldSpaceTransform().m_position.GetY(); const float actualDeltaY = AZ::GetAbs(updatedPositionY - originalPositionY); EXPECT_TRUE(AZ::GetAbs(actualDeltaY - expectedDelta) < 0.002f) << "The absolute difference between actual delta and expected delta of Y-axis should be less than 0.002f."; @@ -262,15 +262,15 @@ namespace EMotionFX const AZ::Quaternion actorRotation(0.0f, 0.0f, -1.0f, 1.0f); m_actorInstance->SetLocalSpaceRotation(actorRotation.GetNormalized()); GetEMotionFX().Update(0.0f); - for (AZ::u32 paramIndex = 0; paramIndex < m_param.durationMultipliers.size(); paramIndex++) + for (size_t paramIndex = 0; paramIndex < m_param.m_durationMultipliers.size(); paramIndex++) { - const float motionDuration = 1.066f * m_param.durationMultipliers[paramIndex]; - const float originalPositionX = m_actorInstance->GetWorldSpaceTransform().mPosition.GetX(); - for (AZ::u32 i = 0; i < m_param.numOfLoops[paramIndex]; i++) + const float motionDuration = 1.066f * m_param.m_durationMultipliers[paramIndex]; + const float originalPositionX = m_actorInstance->GetWorldSpaceTransform().m_position.GetX(); + for (AZ::u32 i = 0; i < m_param.m_numOfLoops[paramIndex]; i++) { GetEMotionFX().Update(motionDuration); } - const float updatedPositionX = m_actorInstance->GetWorldSpaceTransform().mPosition.GetX(); + const float updatedPositionX = m_actorInstance->GetWorldSpaceTransform().m_position.GetX(); const float actualDeltaX = AZ::GetAbs(updatedPositionX - originalPositionX); EXPECT_TRUE(AZ::GetAbs(actualDeltaX - expectedDelta) < 0.002f) << "The absolute difference between actual delta and expected delta of X-axis should be less than 0.002f."; @@ -290,17 +290,17 @@ namespace EMotionFX const AZ::Quaternion diagonalRotation = m_reverse ? AZ::Quaternion(0.0f, 0.0f, 0.5f, 1.0f) : AZ::Quaternion(0.0f, 0.0f, -0.5f, 1.0f); m_actorInstance->SetLocalSpaceRotation(diagonalRotation.GetNormalized()); GetEMotionFX().Update(0.0f); - for (AZ::u32 paramIndex = 0; paramIndex < m_param.durationMultipliers.size(); paramIndex++) + for (size_t paramIndex = 0; paramIndex < m_param.m_durationMultipliers.size(); paramIndex++) { - const float originalPositionX = m_actorInstance->GetWorldSpaceTransform().mPosition.GetX(); - const float originalPositionY = m_actorInstance->GetWorldSpaceTransform().mPosition.GetY(); - const float motionDuration = 1.066f * m_param.durationMultipliers[paramIndex]; - for (AZ::u32 i = 0; i < m_param.numOfLoops[paramIndex]; i++) + const float originalPositionX = m_actorInstance->GetWorldSpaceTransform().m_position.GetX(); + const float originalPositionY = m_actorInstance->GetWorldSpaceTransform().m_position.GetY(); + const float motionDuration = 1.066f * m_param.m_durationMultipliers[paramIndex]; + for (AZ::u32 i = 0; i < m_param.m_numOfLoops[paramIndex]; i++) { GetEMotionFX().Update(motionDuration); } - const float updatedPositionX = m_actorInstance->GetWorldSpaceTransform().mPosition.GetX(); - const float updatedPositionY = m_actorInstance->GetWorldSpaceTransform().mPosition.GetY(); + const float updatedPositionX = m_actorInstance->GetWorldSpaceTransform().m_position.GetX(); + const float updatedPositionY = m_actorInstance->GetWorldSpaceTransform().m_position.GetY(); const float actualDeltaX = AZ::GetAbs(updatedPositionX - originalPositionX); const float actualDeltaY = AZ::GetAbs(updatedPositionY - originalPositionY); EXPECT_NEAR(actualDeltaX, expectedDeltaX, 0.001f) @@ -327,14 +327,14 @@ namespace EMotionFX // This is because the presync time value of the second motion node is from the unsynced playback. // When we improve our syncing system we can handle this differently and we won't expect a zero trajectory delta anymore. GetEMotionFX().Update(0.15f); - EXPECT_FLOAT_EQ(m_actorInstance->GetTrajectoryDeltaTransform().mPosition.GetLength(), 0.0f); + EXPECT_FLOAT_EQ(m_actorInstance->GetTrajectoryDeltaTransform().m_position.GetLength(), 0.0f); EXPECT_FLOAT_EQ(m_motionNode1->GetCurrentPlayTime(m_animGraphInstance), m_motionNode2->GetCurrentPlayTime(m_animGraphInstance)); EXPECT_EQ(m_animGraphInstance->GetEventBuffer().GetNumEvents(), 0); // The second frame should be as normal. GetEMotionFX().Update(0.15f); - EXPECT_GT(m_actorInstance->GetTrajectoryDeltaTransform().mPosition.GetLength(), 0.0f); - EXPECT_LE(m_actorInstance->GetTrajectoryDeltaTransform().mPosition.GetLength(), 0.3f); + EXPECT_GT(m_actorInstance->GetTrajectoryDeltaTransform().m_position.GetLength(), 0.0f); + EXPECT_LE(m_actorInstance->GetTrajectoryDeltaTransform().m_position.GetLength(), 0.3f); EXPECT_FLOAT_EQ(m_motionNode1->GetCurrentPlayTime(m_animGraphInstance), m_motionNode2->GetCurrentPlayTime(m_animGraphInstance)); EXPECT_EQ(m_animGraphInstance->GetEventBuffer().GetNumEvents(), 0); } diff --git a/Gems/EMotionFX/Code/Tests/MotionLayerSystemTests.cpp b/Gems/EMotionFX/Code/Tests/MotionLayerSystemTests.cpp index dd3661a366..de0c37f5b2 100644 --- a/Gems/EMotionFX/Code/Tests/MotionLayerSystemTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MotionLayerSystemTests.cpp @@ -35,11 +35,11 @@ namespace EMotionFX MotionSystem* motionSystem = actorInstance->GetMotionSystem(); PlayBackInfo playBackInfo; - playBackInfo.mBlendInTime = 1.0f; - playBackInfo.mBlendOutTime = 1.0f; - playBackInfo.mNumLoops = 1; - playBackInfo.mPlayNow = false; - playBackInfo.mFreezeAtLastFrame = false; + playBackInfo.m_blendInTime = 1.0f; + playBackInfo.m_blendOutTime = 1.0f; + playBackInfo.m_numLoops = 1; + playBackInfo.m_playNow = false; + playBackInfo.m_freezeAtLastFrame = false; // Add 2 motions to the queue const MotionInstance* motionInstance1 = motionSystem->PlayMotion(motion1, &playBackInfo); @@ -106,10 +106,10 @@ namespace EMotionFX MotionSystem* motionSystem = actorInstance->GetMotionSystem(); PlayBackInfo playBackInfo; - playBackInfo.mBlendInTime = 1.0f; - playBackInfo.mBlendOutTime = 1.0f; - playBackInfo.mNumLoops = EMFX_LOOPFOREVER; - playBackInfo.mPlayNow = true; + playBackInfo.m_blendInTime = 1.0f; + playBackInfo.m_blendOutTime = 1.0f; + playBackInfo.m_numLoops = EMFX_LOOPFOREVER; + playBackInfo.m_playNow = true; const MotionInstance* walkInstance = motionSystem->PlayMotion(walk, &playBackInfo); @@ -163,11 +163,11 @@ namespace EMotionFX MotionSystem* motionSystem = actorInstance->GetMotionSystem(); PlayBackInfo playBackInfo; - playBackInfo.mBlendInTime = 1.0f; - playBackInfo.mBlendOutTime = 1.0f; - playBackInfo.mNumLoops = 1; - playBackInfo.mPlayNow = false; - playBackInfo.mFreezeAtLastFrame = false; + playBackInfo.m_blendInTime = 1.0f; + playBackInfo.m_blendOutTime = 1.0f; + playBackInfo.m_numLoops = 1; + playBackInfo.m_playNow = false; + playBackInfo.m_freezeAtLastFrame = false; // Add 2 motions to the queue const MotionInstance* motionInstance1 = motionSystem->PlayMotion(motion1, &playBackInfo); diff --git a/Gems/EMotionFX/Code/Tests/MultiThreadSchedulerTests.cpp b/Gems/EMotionFX/Code/Tests/MultiThreadSchedulerTests.cpp index f3d6d44e1d..180da46746 100644 --- a/Gems/EMotionFX/Code/Tests/MultiThreadSchedulerTests.cpp +++ b/Gems/EMotionFX/Code/Tests/MultiThreadSchedulerTests.cpp @@ -31,14 +31,14 @@ namespace EMotionFX // Create an actor instance and make sure it is in the scheduler. ActorInstance* actorInstance = ActorInstance::Create(actor.get()); EXPECT_EQ(scheduler->GetNumScheduleSteps(), 1) << "The actor instance should be part of the scheduler."; - EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances.size(), 1) << "The step should hold exactly one actor instance."; - EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances[0], actorInstance) << "The actor instance should be part of the step."; + EXPECT_EQ(scheduler->GetScheduleStep(0).m_actorInstances.size(), 1) << "The step should hold exactly one actor instance."; + EXPECT_EQ(scheduler->GetScheduleStep(0).m_actorInstances[0], actorInstance) << "The actor instance should be part of the step."; // Insert the actor instance manually again and make sure there is no duplicate. scheduler->RecursiveInsertActorInstance(actorInstance); EXPECT_EQ(scheduler->GetNumScheduleSteps(), 1) << "The actor instance should be part of the scheduler."; - EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances.size(), 1) << "The step should hold exactly one actor instance."; - EXPECT_EQ(scheduler->GetScheduleStep(0).mActorInstances[0], actorInstance) << "The actor instance should be part of the step."; + EXPECT_EQ(scheduler->GetScheduleStep(0).m_actorInstances.size(), 1) << "The step should hold exactly one actor instance."; + EXPECT_EQ(scheduler->GetScheduleStep(0).m_actorInstances[0], actorInstance) << "The actor instance should be part of the step."; actorInstance->Destroy(); } diff --git a/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp b/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp index 7498eed311..09a4e46b84 100644 --- a/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp +++ b/Gems/EMotionFX/Code/Tests/NonUniformMotionDataTests.cpp @@ -185,15 +185,15 @@ namespace EMotionFX EXPECT_FALSE(motionData.FindJointIndexByName("Blah").IsSuccess()); EXPECT_FALSE(motionData.FindMorphIndexByName("Blah").IsSuccess()); EXPECT_FALSE(motionData.FindFloatIndexByName("Blah").IsSuccess()); - EXPECT_TRUE(motionData.FindJointIndexByName("Joint1").IsSuccess()); - EXPECT_TRUE(motionData.FindJointIndexByName("Joint2").IsSuccess()); - EXPECT_TRUE(motionData.FindJointIndexByName("Joint3").IsSuccess()); - EXPECT_TRUE(motionData.FindMorphIndexByName("Morph1").IsSuccess()); - EXPECT_TRUE(motionData.FindMorphIndexByName("Morph2").IsSuccess()); - EXPECT_TRUE(motionData.FindMorphIndexByName("Morph3").IsSuccess()); - EXPECT_TRUE(motionData.FindFloatIndexByName("Float1").IsSuccess()); - EXPECT_TRUE(motionData.FindFloatIndexByName("Float2").IsSuccess()); - EXPECT_TRUE(motionData.FindFloatIndexByName("Float3").IsSuccess()); + ASSERT_TRUE(motionData.FindJointIndexByName("Joint1").IsSuccess()); + ASSERT_TRUE(motionData.FindJointIndexByName("Joint2").IsSuccess()); + ASSERT_TRUE(motionData.FindJointIndexByName("Joint3").IsSuccess()); + ASSERT_TRUE(motionData.FindMorphIndexByName("Morph1").IsSuccess()); + ASSERT_TRUE(motionData.FindMorphIndexByName("Morph2").IsSuccess()); + ASSERT_TRUE(motionData.FindMorphIndexByName("Morph3").IsSuccess()); + ASSERT_TRUE(motionData.FindFloatIndexByName("Float1").IsSuccess()); + ASSERT_TRUE(motionData.FindFloatIndexByName("Float2").IsSuccess()); + ASSERT_TRUE(motionData.FindFloatIndexByName("Float3").IsSuccess()); EXPECT_EQ(motionData.FindJointIndexByName("Joint1").GetValue(), 0); EXPECT_EQ(motionData.FindJointIndexByName("Joint2").GetValue(), 1); EXPECT_EQ(motionData.FindJointIndexByName("Joint3").GetValue(), 2); @@ -663,7 +663,7 @@ namespace EMotionFX // Test morph sampling. AZ::Outcome index = motionData.FindMorphIndexByName("Morph1"); - EXPECT_TRUE(index.IsSuccess()); + ASSERT_TRUE(index.IsSuccess()); if (index.IsSuccess()) { float result = -1.0f; @@ -693,7 +693,7 @@ namespace EMotionFX // Test float sampling. index = motionData.FindFloatIndexByName("Float1"); - EXPECT_TRUE(index.IsSuccess()); + ASSERT_TRUE(index.IsSuccess()); if (index.IsSuccess()) { float result = -1.0f; @@ -745,15 +745,15 @@ namespace EMotionFX EXPECT_FALSE(motionData.IsJointAnimated(3)); EXPECT_STREQ(motionData.GetJointName(3).c_str(), "Joint4"); - EXPECT_THAT(motionData.GetJointPoseTransform(3).mPosition, IsClose(poseTransform.mPosition)); - EXPECT_THAT(motionData.GetJointPoseTransform(3).mRotation, IsClose(poseTransform.mRotation)); + EXPECT_THAT(motionData.GetJointPoseTransform(3).m_position, IsClose(poseTransform.m_position)); + EXPECT_THAT(motionData.GetJointPoseTransform(3).m_rotation, IsClose(poseTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(motionData.GetJointPoseTransform(3).mScale, IsClose(poseTransform.mScale)); + EXPECT_THAT(motionData.GetJointPoseTransform(3).m_scale, IsClose(poseTransform.m_scale)); #endif - EXPECT_THAT(motionData.GetJointBindPoseTransform(3).mPosition, IsClose(bindTransform.mPosition)); - EXPECT_THAT(motionData.GetJointBindPoseTransform(3).mRotation, IsClose(bindTransform.mRotation)); + EXPECT_THAT(motionData.GetJointBindPoseTransform(3).m_position, IsClose(bindTransform.m_position)); + EXPECT_THAT(motionData.GetJointBindPoseTransform(3).m_rotation, IsClose(bindTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(motionData.GetJointBindPoseTransform(3).mScale, IsClose(bindTransform.mScale)); + EXPECT_THAT(motionData.GetJointBindPoseTransform(3).m_scale, IsClose(bindTransform.m_scale)); #endif // Test adding a morph. @@ -888,19 +888,19 @@ namespace EMotionFX sampleSettings.m_actorInstance = m_actorInstance; sampleSettings.m_sampleTime = expectation.first; const Transform sampledResult = motionData.SampleJointTransform(sampleSettings, 0); - EXPECT_THAT(sampledResult.mPosition, IsClose(expectation.second.mPosition)); - EXPECT_THAT(sampledResult.mRotation, IsClose(expectation.second.mRotation)); + EXPECT_THAT(sampledResult.m_position, IsClose(expectation.second.m_position)); + EXPECT_THAT(sampledResult.m_rotation, IsClose(expectation.second.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(sampledResult.mScale, IsClose(expectation.second.mScale)); + EXPECT_THAT(sampledResult.m_scale, IsClose(expectation.second.m_scale)); #endif // Fourth joint has no motion data to apply to our actor, so expect a bind pose. // It has motion data, but there is no joint in the skeleton that matches its name, so it is like motion data for a joint that doesn't exist in our actor. const Transform fourthJointTransform = motionData.SampleJointTransform(sampleSettings, 3); - EXPECT_THAT(fourthJointTransform.mPosition, IsClose(expectedBindTransform.mPosition)); - EXPECT_THAT(fourthJointTransform.mRotation, IsClose(expectedBindTransform.mRotation)); + EXPECT_THAT(fourthJointTransform.m_position, IsClose(expectedBindTransform.m_position)); + EXPECT_THAT(fourthJointTransform.m_rotation, IsClose(expectedBindTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(fourthJointTransform.mScale, IsClose(expectedBindTransform.mScale)); + EXPECT_THAT(fourthJointTransform.m_scale, IsClose(expectedBindTransform.m_scale)); #endif } @@ -917,19 +917,19 @@ namespace EMotionFX // We only verify the first joint, to see if it interpolated fine. const Transform sampledResult = pose.GetLocalSpaceTransform(0); - EXPECT_THAT(sampledResult.mPosition, IsClose(expectation.second.mPosition)); - EXPECT_THAT(sampledResult.mRotation, IsClose(expectation.second.mRotation)); + EXPECT_THAT(sampledResult.m_position, IsClose(expectation.second.m_position)); + EXPECT_THAT(sampledResult.m_rotation, IsClose(expectation.second.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(sampledResult.mScale, IsClose(expectation.second.mScale)); + EXPECT_THAT(sampledResult.m_scale, IsClose(expectation.second.m_scale)); #endif // Fourth joint has no motion data to apply to our actor, so expect a bind pose. // It has motion data, but there is no joint in the skeleton that matches its name, so it is like motion data for a joint that doesn't exist in our actor. const Transform fourthJointTransform = pose.GetLocalSpaceTransform(3); - EXPECT_THAT(fourthJointTransform.mPosition, IsClose(expectedBindTransform.mPosition)); - EXPECT_THAT(fourthJointTransform.mRotation, IsClose(expectedBindTransform.mRotation)); + EXPECT_THAT(fourthJointTransform.m_position, IsClose(expectedBindTransform.m_position)); + EXPECT_THAT(fourthJointTransform.m_rotation, IsClose(expectedBindTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(fourthJointTransform.mScale, IsClose(expectedBindTransform.mScale)); + EXPECT_THAT(fourthJointTransform.m_scale, IsClose(expectedBindTransform.m_scale)); #endif } } diff --git a/Gems/EMotionFX/Code/Tests/PoseTests.cpp b/Gems/EMotionFX/Code/Tests/PoseTests.cpp index 0957176813..ed14da5354 100644 --- a/Gems/EMotionFX/Code/Tests/PoseTests.cpp +++ b/Gems/EMotionFX/Code/Tests/PoseTests.cpp @@ -74,8 +74,8 @@ namespace EMotionFX void CompareFlags(const Pose& pose, uint8 expectedFlags) { - const AZ::u32 numTransforms = pose.GetNumTransforms(); - for (AZ::u32 i = 0; i < numTransforms; ++i) + const size_t numTransforms = pose.GetNumTransforms(); + for (size_t i = 0; i < numTransforms; ++i) { EXPECT_EQ(pose.GetFlags(i), expectedFlags); } @@ -83,10 +83,10 @@ namespace EMotionFX void CompareFlags(const Pose& poseA, const Pose& poseB) { - const AZ::u32 numTransforms = poseA.GetNumTransforms(); + const size_t numTransforms = poseA.GetNumTransforms(); EXPECT_EQ(numTransforms, poseB.GetNumTransforms()); - for (AZ::u32 i = 0; i < numTransforms; ++i) + for (size_t i = 0; i < numTransforms; ++i) { EXPECT_EQ(poseA.GetFlags(i), poseB.GetFlags(i)); } @@ -94,10 +94,10 @@ namespace EMotionFX void CompareMorphTargets(const Pose& poseA, const Pose& poseB) { - const AZ::u32 numMorphWeights = poseA.GetNumMorphWeights(); + const size_t numMorphWeights = poseA.GetNumMorphWeights(); EXPECT_EQ(numMorphWeights, poseB.GetNumMorphWeights()); - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + for (size_t i = 0; i < numMorphWeights; ++i) { EXPECT_EQ(poseA.GetMorphWeight(i), poseB.GetMorphWeight(i)); } @@ -113,10 +113,10 @@ namespace EMotionFX void ComparePoseTransforms(const Pose& poseA, const Pose& poseB) { - const AZ::u32 numTransforms = poseA.GetNumTransforms(); + const size_t numTransforms = poseA.GetNumTransforms(); EXPECT_EQ(numTransforms, poseB.GetNumTransforms()); - for (AZ::u32 i = 0; i < numTransforms; ++i) + for (size_t i = 0; i < numTransforms; ++i) { const Transform& localA = poseA.GetLocalSpaceTransform(i); const Transform& localB = poseB.GetLocalSpaceTransform(i); @@ -140,7 +140,7 @@ namespace EMotionFX public: AZStd::unique_ptr m_actor; ActorInstance* m_actorInstance = nullptr; - const AZ::u32 m_numMorphTargets = 5; + const size_t m_numMorphTargets = 5; const float m_testOffset = 10.0f; }; @@ -184,8 +184,8 @@ namespace EMotionFX Pose pose; pose.LinkToActor(m_actor.get()); - const AZ::u32 numTransforms = pose.GetNumTransforms(); - for (AZ::u32 i = 0; i < numTransforms; ++i) + const size_t numTransforms = pose.GetNumTransforms(); + for (size_t i = 0; i < numTransforms; ++i) { pose.SetFlags(i, Pose::FLAG_LOCALTRANSFORMREADY); EXPECT_EQ(pose.GetFlags(i), Pose::FLAG_LOCALTRANSFORMREADY); @@ -270,7 +270,7 @@ namespace EMotionFX AZ::SimpleLcgRandom random; random.SetSeed(875960); - for (AZ::u32 i = 0; i < m_numMorphTargets; ++i) + for (size_t i = 0; i < m_numMorphTargets; ++i) { // Zero all weights on the morph instance. morphInstance->GetMorphTarget(i)->SetWeight(0.0f); @@ -284,7 +284,7 @@ namespace EMotionFX pose.ApplyMorphWeightsToActorInstance(); // Check if all weights got correctly forwarded from the pose to the actor instance. - for (AZ::u32 i = 0; i < m_numMorphTargets; ++i) + for (size_t i = 0; i < m_numMorphTargets; ++i) { EXPECT_EQ(pose.GetMorphWeight(i), morphInstance->GetMorphTarget(i)->GetWeight()); } @@ -297,7 +297,7 @@ namespace EMotionFX EXPECT_EQ(pose.GetNumMorphWeights(), m_numMorphTargets); // Set and get tests. - for (AZ::u32 i = 0; i < m_numMorphTargets; ++i) + for (size_t i = 0; i < m_numMorphTargets; ++i) { const float newWeight = static_cast(i); pose.SetMorphWeight(i, newWeight); @@ -306,7 +306,7 @@ namespace EMotionFX // Zero weights test. pose.ZeroMorphWeights(); - for (AZ::u32 i = 0; i < m_numMorphTargets; ++i) + for (size_t i = 0; i < m_numMorphTargets; ++i) { EXPECT_EQ(pose.GetMorphWeight(i), 0.0f); } @@ -326,7 +326,7 @@ namespace EMotionFX { Pose pose; pose.LinkToActor(m_actor.get()); - const AZ::u32 jointIndex = 0; + const size_t jointIndex = 0; // Set the new transform. Transform newTransform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); @@ -337,7 +337,7 @@ namespace EMotionFX // All model space transforms should be invalidated. // The model space transform of the node doesn't get automatically updated and // all child node model transforms are invalidated along with the joint. - for (AZ::u32 i = jointIndex; i < m_actor->GetNumNodes(); ++i) + for (size_t i = jointIndex; i < m_actor->GetNumNodes(); ++i) { EXPECT_FALSE(pose.GetFlags(i) & Pose::FLAG_MODELTRANSFORMREADY); } @@ -355,7 +355,7 @@ namespace EMotionFX { Pose pose; pose.LinkToActor(m_actor.get()); - const AZ::u32 jointIndex = 0; + const size_t jointIndex = 0; Transform newTransform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); pose.SetLocalSpaceTransformDirect(jointIndex, newTransform); @@ -367,7 +367,7 @@ namespace EMotionFX { Pose pose; pose.LinkToActor(m_actor.get()); - const AZ::u32 jointIndex = 0; + const size_t jointIndex = 0; // Set the new transform. Transform newTransform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); @@ -381,7 +381,7 @@ namespace EMotionFX EXPECT_TRUE(pose.GetFlags(jointIndex) & Pose::FLAG_LOCALTRANSFORMREADY); // All child model space transforms should be invalidated as they haven't been updated yet. - for (AZ::u32 i = jointIndex + 1; i < m_actor->GetNumNodes(); ++i) + for (size_t i = jointIndex + 1; i < m_actor->GetNumNodes(); ++i) { EXPECT_FALSE(pose.GetFlags(i) & Pose::FLAG_MODELTRANSFORMREADY); } @@ -398,7 +398,7 @@ namespace EMotionFX { Pose pose; pose.LinkToActor(m_actor.get()); - const AZ::u32 jointIndex = 0; + const size_t jointIndex = 0; Transform newTransform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); pose.SetModelSpaceTransformDirect(jointIndex, newTransform); @@ -415,7 +415,7 @@ namespace EMotionFX const Transform newTransform(AZ::Vector3(1.0f, 1.0f, 1.0f), AZ::Quaternion::CreateIdentity()); // Iterate through the joints, adjust their local space transforms and check if the model space transform adjusts automatically, accordingly. - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { pose.SetLocalSpaceTransform(i, newTransform); EXPECT_EQ(pose.GetLocalSpaceTransform(i), newTransform); @@ -433,7 +433,7 @@ namespace EMotionFX const Transform newTransform(AZ::Vector3(1.0f, 1.0f, 1.0f), AZ::Quaternion::CreateIdentity()); // Same as the previous test, but this time we use the direct call which does not automatically invalidate the model space transform. - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform oldModelSpaceTransform = pose.GetModelSpaceTransform(i); @@ -458,7 +458,7 @@ namespace EMotionFX pose.InitFromBindPose(m_actor.get()); // Similar to previous test, model space and local space operations are switched. - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform oldLocalSpaceTransform = pose.GetLocalSpaceTransform(i); const Transform newTransform(Transform(AZ::Vector3(0.0f, 0.0f, static_cast((i + 1) * m_testOffset)), AZ::Quaternion::CreateIdentity())); @@ -482,7 +482,7 @@ namespace EMotionFX pose.LinkToActor(m_actor.get()); pose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform oldLocalSpaceTransform = pose.GetLocalSpaceTransform(i); const Transform newTransform(Transform(AZ::Vector3(0.0f, 0.0f, static_cast((i + 1) * m_testOffset)), AZ::Quaternion::CreateIdentity())); @@ -503,13 +503,13 @@ namespace EMotionFX } else { - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { pose.UpdateLocalSpaceTransform(i); } } - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { // Get the local space transform without auto-updating them, to see if update call worked. EXPECT_EQ(pose.GetLocalSpaceTransformDirect(i), Transform(AZ::Vector3(0.0f, 0.0f, m_testOffset), AZ::Quaternion::CreateIdentity())); @@ -522,7 +522,7 @@ namespace EMotionFX pose.LinkToActor(m_actor.get()); pose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform oldLocalSpaceTransform = pose.GetLocalSpaceTransform(i); const Transform newTransform(AZ::Vector3(0.0f, 0.0f, static_cast((i + 1) * m_testOffset)), AZ::Quaternion::CreateIdentity()); @@ -536,7 +536,7 @@ namespace EMotionFX // Update all local space transforms regardless of the invalidate flag. pose.ForceUpdateFullLocalSpacePose(); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { // Get the local space transform without auto-updating them, to see if update call worked. EXPECT_EQ(pose.GetLocalSpaceTransformDirect(i), Transform(AZ::Vector3(0.0f, 0.0f, m_testOffset), AZ::Quaternion::CreateIdentity())); @@ -549,7 +549,7 @@ namespace EMotionFX pose.LinkToActor(m_actor.get()); pose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform oldModelSpaceTransform = pose.GetModelSpaceTransform(i); const Transform newTransform(AZ::Vector3(0.0f, 0.0f, m_testOffset), AZ::Quaternion::CreateIdentity()); @@ -567,13 +567,13 @@ namespace EMotionFX } else { - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { pose.UpdateModelSpaceTransform(i); } } - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { // Get the model space transform without auto-updating them, to see if the update call worked. EXPECT_EQ(pose.GetModelSpaceTransformDirect(i), @@ -587,7 +587,7 @@ namespace EMotionFX pose.LinkToActor(m_actor.get()); pose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform oldModelSpaceTransform = pose.GetModelSpaceTransform(i); const Transform newTransform(AZ::Vector3(0.0f, 0.0f, m_testOffset), AZ::Quaternion::CreateIdentity()); @@ -601,7 +601,7 @@ namespace EMotionFX // Update all model space transforms regardless of the invalidate flag. pose.ForceUpdateFullModelSpacePose(); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { // Get the model space transform without auto-updating them, to see if the ForceUpdateFullModelSpacePose() worked. EXPECT_EQ(pose.GetModelSpaceTransformDirect(i), Transform(AZ::Vector3(0.0f, 0.0f, static_cast((i + 1) * m_testOffset)), AZ::Quaternion::CreateIdentity())); @@ -618,7 +618,7 @@ namespace EMotionFX m_actorInstance->SetLocalSpaceTransform(offsetTransform); m_actorInstance->UpdateWorldTransform(); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { pose.SetLocalSpaceTransform(i, offsetTransform); @@ -638,8 +638,8 @@ namespace EMotionFX TEST_F(PoseTests, GetMeshNodeWorldSpaceTransform) { - const AZ::u32 lodLevel = 0; - const AZ::u32 jointIndex = 0; + const size_t lodLevel = 0; + const size_t jointIndex = 0; Pose pose; // If there is no actor instance linked, expect the identity transform. @@ -677,8 +677,8 @@ namespace EMotionFX TEST_P(PoseTestsBoolParam, CompensateForMotionExtraction) { - const AZ::u32 motionExtractionJointIndex = m_actor->GetMotionExtractionNodeIndex(); - ASSERT_NE(motionExtractionJointIndex, MCORE_INVALIDINDEX32) + const size_t motionExtractionJointIndex = m_actor->GetMotionExtractionNodeIndex(); + ASSERT_NE(motionExtractionJointIndex, InvalidIndex) << "Motion extraction joint not set for the test actor."; Pose pose; @@ -715,8 +715,8 @@ namespace EMotionFX TEST_F(PoseTests, CalcTrajectoryTransform) { - const AZ::u32 motionExtractionJointIndex = m_actor->GetMotionExtractionNodeIndex(); - ASSERT_NE(motionExtractionJointIndex, MCORE_INVALIDINDEX32) + const size_t motionExtractionJointIndex = m_actor->GetMotionExtractionNodeIndex(); + ASSERT_NE(motionExtractionJointIndex, InvalidIndex) << "Motion extraction joint not set for the test actor."; Pose pose; @@ -729,7 +729,7 @@ namespace EMotionFX const Transform transformResult = pose.CalcTrajectoryTransform(); const Transform expectedResult = pose.GetWorldSpaceTransform(motionExtractionJointIndex).ProjectedToGroundPlane(); EXPECT_THAT(transformResult, IsClose(expectedResult)); - EXPECT_EQ(transformResult.mPosition, AZ::Vector3(1.0f, 1.0f, 0.0f)); + EXPECT_EQ(transformResult.m_position, AZ::Vector3(1.0f, 1.0f, 0.0f)); } /////////////////////////////////////////////////////////////////////////// @@ -742,21 +742,21 @@ namespace EMotionFX pose.LinkToActorInstance(m_actorInstance); pose.InitFromBindPose(m_actor.get()); - AZ::u32 jointIndex = InvalidIndex32; + size_t jointIndex = InvalidIndex; Node* joint = m_actor->GetSkeleton()->FindNodeAndIndexByName("joint4", jointIndex); ASSERT_NE(joint, nullptr) << "Can't find the joint named 'joint4'."; const Transform jointTransform = pose.GetWorldSpaceTransform(jointIndex); - EXPECT_THAT(jointTransform.mScale, IsClose(AZ::Vector3::CreateOne())); + EXPECT_THAT(jointTransform.m_scale, IsClose(AZ::Vector3::CreateOne())); AZ::Vector3 scale(2.0f); m_actorInstance->SetLocalSpaceScale(scale); m_actorInstance->UpdateWorldTransform(); const Transform jointTransform2 = pose.GetWorldSpaceTransform(jointIndex); - EXPECT_THAT(jointTransform2.mScale, IsClose(scale)); + EXPECT_THAT(jointTransform2.m_scale, IsClose(scale)); - const float distToOrigin = jointTransform.mPosition.GetLength(); - const float distToOrigin2= jointTransform2.mPosition.GetLength(); + const float distToOrigin = jointTransform.m_position.GetLength(); + const float distToOrigin2= jointTransform2.m_position.GetLength(); EXPECT_FLOAT_EQ(distToOrigin2 / distToOrigin, 2.0f) << "Expecting the scaled joint to be twice as far from the origin as the unscaled joint."; ) } @@ -779,14 +779,14 @@ namespace EMotionFX Pose destPose; destPose.LinkToActorInstance(m_actorInstance); destPose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); Transform transform(AZ::Vector3(0.0f, 0.0f, -floatI), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3(0.0f, 1.0f, 0.0f), floatI)); EMFX_SCALECODE ( - transform.mScale = AZ::Vector3(floatI, floatI, floatI); + transform.m_scale = AZ::Vector3(floatI, floatI, floatI); ) destPose.SetLocalSpaceTransform(i, transform); } @@ -798,7 +798,7 @@ namespace EMotionFX blendedPose.Blend(&destPose, blendWeight); // Check the blended result. - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform& sourceTransform = sourcePose->GetLocalSpaceTransform(i); const Transform& destTransform = destPose.GetLocalSpaceTransform(i); @@ -807,7 +807,7 @@ namespace EMotionFX Transform expectedResult = sourceTransform; expectedResult.Blend(destTransform, blendWeight); EXPECT_THAT(transformResult, IsClose(expectedResult)); - CheckIfRotationIsNormalized(destTransform.mRotation); + CheckIfRotationIsNormalized(destTransform.m_rotation); } } @@ -820,14 +820,14 @@ namespace EMotionFX Pose sourcePose; sourcePose.LinkToActorInstance(m_actorInstance); sourcePose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); Transform transform(AZ::Vector3(floatI, 0.0f, 0.0f), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3(0.0f, 1.0f, 0.0f), floatI)); EMFX_SCALECODE ( - transform.mScale = AZ::Vector3(floatI, floatI, floatI); + transform.m_scale = AZ::Vector3(floatI, floatI, floatI); ) sourcePose.SetLocalSpaceTransform(i, transform); @@ -837,14 +837,14 @@ namespace EMotionFX Pose destPose; destPose.LinkToActorInstance(m_actorInstance); destPose.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); Transform transform(AZ::Vector3(0.0f, 0.0f, -floatI), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3(1.0f, 0.0f, 0.0f), floatI)); EMFX_SCALECODE ( - transform.mScale = AZ::Vector3(floatI, floatI, floatI); + transform.m_scale = AZ::Vector3(floatI, floatI, floatI); ) destPose.SetLocalSpaceTransform(i, transform); @@ -856,7 +856,7 @@ namespace EMotionFX blendedPose.InitFromPose(&sourcePose); blendedPose.BlendAdditiveUsingBindPose(&destPose, blendWeight); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform& bindPoseTransform = bindPose->GetLocalSpaceTransform(i); const Transform& sourceTransform = sourcePose.GetLocalSpaceTransform(i); @@ -866,7 +866,7 @@ namespace EMotionFX Transform expectedResult = sourceTransform; expectedResult.BlendAdditive(destTransform, bindPoseTransform, blendWeight); EXPECT_THAT(transformResult, IsClose(expectedResult)); - CheckIfRotationIsNormalized(destTransform.mRotation); + CheckIfRotationIsNormalized(destTransform.m_rotation); } } @@ -897,7 +897,7 @@ namespace EMotionFX poseB.LinkToActorInstance(m_actorInstance); poseB.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); const Transform transformA(AZ::Vector3(floatI, 0.0f, 0.0f), @@ -920,7 +920,7 @@ namespace EMotionFX default: { ASSERT_TRUE(false) << "Case not handled."; } } - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform& transformA = poseA.GetLocalSpaceTransform(i); const Transform& transformB = poseB.GetLocalSpaceTransform(i); @@ -960,7 +960,7 @@ namespace EMotionFX poseB.LinkToActorInstance(m_actorInstance); poseB.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); const Transform transformA(AZ::Vector3(floatI, 0.0f, 0.0f), AZ::Quaternion::CreateIdentity()); @@ -969,8 +969,8 @@ namespace EMotionFX poseB.SetLocalSpaceTransform(i, transformB); } - const AZ::u32 numMorphWeights = poseA.GetNumMorphWeights(); - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + const size_t numMorphWeights = poseA.GetNumMorphWeights(); + for (size_t i = 0; i < numMorphWeights; ++i) { const float floatI = static_cast(i); poseA.SetMorphWeight(i, floatI); @@ -982,7 +982,7 @@ namespace EMotionFX poseSum.InitFromPose(&poseA); poseSum.Sum(&poseB, weight); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform& transformA = poseA.GetLocalSpaceTransform(i); const Transform& transformB = poseB.GetLocalSpaceTransform(i); @@ -993,7 +993,7 @@ namespace EMotionFX EXPECT_THAT(transformResult, IsClose(expectedResult)); } - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + for (size_t i = 0; i < numMorphWeights; ++i) { EXPECT_FLOAT_EQ(poseSum.GetMorphWeight(i), poseA.GetMorphWeight(i) + poseB.GetMorphWeight(i) * weight); @@ -1012,7 +1012,7 @@ namespace EMotionFX poseB.LinkToActorInstance(m_actorInstance); poseB.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); const Transform transformA(AZ::Vector3(floatI, floatI, floatI), AZ::Quaternion::CreateIdentity()); @@ -1026,11 +1026,11 @@ namespace EMotionFX poseRel.InitFromPose(&poseA); poseRel.MakeRelativeTo(poseB); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform& transformRel = poseRel.GetLocalSpaceTransform(i); - const AZ::Vector3& result = transformRel.mPosition; + const AZ::Vector3& result = transformRel.m_position; EXPECT_TRUE(result.IsClose(AZ::Vector3::CreateOne())); } } @@ -1095,7 +1095,7 @@ namespace EMotionFX } poseB.InitFromBindPose(m_actor.get()); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const float floatI = static_cast(i); const Transform transformA(AZ::Vector3(floatI, 0.0f, 0.0f), @@ -1106,8 +1106,8 @@ namespace EMotionFX poseB.SetLocalSpaceTransform(i, transformB); } - const AZ::u32 numMorphWeights = poseA.GetNumMorphWeights(); - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + const size_t numMorphWeights = poseA.GetNumMorphWeights(); + for (size_t i = 0; i < numMorphWeights; ++i) { const float floatI = static_cast(i); poseA.SetMorphWeight(i, floatI); @@ -1133,7 +1133,7 @@ namespace EMotionFX default: { ASSERT_TRUE(false) << "Case not handled."; } } - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { const Transform& transformA = poseA.GetLocalSpaceTransform(i); const Transform& transformB = poseB.GetLocalSpaceTransform(i); @@ -1142,22 +1142,22 @@ namespace EMotionFX Transform expectedResult = Transform::CreateIdentity(); if (additiveFunction == MakeAdditive) { - expectedResult.mPosition = transformA.mPosition - transformB.mPosition; - expectedResult.mRotation = transformB.mRotation.GetConjugate() * transformA.mRotation; + expectedResult.m_position = transformA.m_position - transformB.m_position; + expectedResult.m_rotation = transformB.m_rotation.GetConjugate() * transformA.m_rotation; EMFX_SCALECODE ( - expectedResult.mScale = transformA.mScale * transformB.mScale; + expectedResult.m_scale = transformA.m_scale * transformB.m_scale; ) } else if (additiveFunction == ApplyAdditive || weight > 1.0f - MCore::Math::epsilon) { - expectedResult.mPosition = transformA.mPosition + transformB.mPosition; - expectedResult.mRotation = transformA.mRotation * transformB.mRotation; - expectedResult.mRotation.Normalize(); + expectedResult.m_position = transformA.m_position + transformB.m_position; + expectedResult.m_rotation = transformA.m_rotation * transformB.m_rotation; + expectedResult.m_rotation.Normalize(); EMFX_SCALECODE ( - expectedResult.mScale = transformA.mScale * transformB.mScale; + expectedResult.m_scale = transformA.m_scale * transformB.m_scale; ) } else if (weight < MCore::Math::epsilon ) @@ -1166,13 +1166,13 @@ namespace EMotionFX } else { - expectedResult.mPosition = transformA.mPosition + transformB.mPosition * weight; - expectedResult.mRotation = transformA.mRotation.NLerp(transformB.mRotation * transformA.mRotation, weight); - expectedResult.mRotation.Normalize(); + expectedResult.m_position = transformA.m_position + transformB.m_position * weight; + expectedResult.m_rotation = transformA.m_rotation.NLerp(transformB.m_rotation * transformA.m_rotation, weight); + expectedResult.m_rotation.Normalize(); EMFX_SCALECODE ( - expectedResult.mScale = transformA.mScale * AZ::Vector3::CreateOne().Lerp(transformB.mScale, weight); + expectedResult.m_scale = transformA.m_scale * AZ::Vector3::CreateOne().Lerp(transformB.m_scale, weight); ) } @@ -1183,7 +1183,7 @@ namespace EMotionFX { case 0: { - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + for (size_t i = 0; i < numMorphWeights; ++i) { EXPECT_FLOAT_EQ(poseResult.GetMorphWeight(i), poseA.GetMorphWeight(i) - poseB.GetMorphWeight(i)); @@ -1192,7 +1192,7 @@ namespace EMotionFX } case 1: { - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + for (size_t i = 0; i < numMorphWeights; ++i) { EXPECT_FLOAT_EQ(poseResult.GetMorphWeight(i), poseA.GetMorphWeight(i) + poseB.GetMorphWeight(i)); @@ -1201,7 +1201,7 @@ namespace EMotionFX } case 2: { - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + for (size_t i = 0; i < numMorphWeights; ++i) { EXPECT_FLOAT_EQ(poseResult.GetMorphWeight(i), poseA.GetMorphWeight(i) + poseB.GetMorphWeight(i) * weight); @@ -1222,14 +1222,14 @@ namespace EMotionFX pose.Zero(); // Check if local space transforms are correctly zeroed. - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { EXPECT_EQ(pose.GetLocalSpaceTransform(i), Transform::CreateZero()); } // Check if morph target weights are all zero. - const AZ::u32 numMorphWeights = pose.GetNumMorphWeights(); - for (AZ::u32 i = 0; i < numMorphWeights; ++i) + const size_t numMorphWeights = pose.GetNumMorphWeights(); + for (size_t i = 0; i < numMorphWeights; ++i) { EXPECT_EQ(pose.GetMorphWeight(i), 0.0f); } @@ -1244,7 +1244,7 @@ namespace EMotionFX AZ::SimpleLcgRandom random; random.SetSeed(875960); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { Transform transformRandomRot(AZ::Vector3::CreateZero(), CreateRandomUnnormalizedQuaternion(random)); @@ -1255,9 +1255,9 @@ namespace EMotionFX pose.NormalizeQuaternions(); - for (AZ::u32 i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) + for (size_t i = 0; i < m_actor->GetSkeleton()->GetNumNodes(); ++i) { - CheckIfRotationIsNormalized(pose.GetLocalSpaceTransform(i).mRotation); + CheckIfRotationIsNormalized(pose.GetLocalSpaceTransform(i).m_rotation); } } diff --git a/Gems/EMotionFX/Code/Tests/Prefabs/LeftArmSkeleton.h b/Gems/EMotionFX/Code/Tests/Prefabs/LeftArmSkeleton.h index 7cbcf24322..2af9da3306 100644 --- a/Gems/EMotionFX/Code/Tests/Prefabs/LeftArmSkeleton.h +++ b/Gems/EMotionFX/Code/Tests/Prefabs/LeftArmSkeleton.h @@ -30,7 +30,7 @@ namespace EMotionFX leftPinky2Index = 11, leftPinky3Index = 12, numJoints = 13, - INVALID = MCORE_INVALIDINDEX32 + INVALID = InvalidIndex }; PrefabLeftArmSkeleton() diff --git a/Gems/EMotionFX/Code/Tests/Printers.cpp b/Gems/EMotionFX/Code/Tests/Printers.cpp index ebf5167508..eb909a7aca 100644 --- a/Gems/EMotionFX/Code/Tests/Printers.cpp +++ b/Gems/EMotionFX/Code/Tests/Printers.cpp @@ -39,12 +39,12 @@ namespace EMotionFX void PrintTo(const Transform& transform, ::std::ostream* os) { *os << "(pos: "; - PrintTo(transform.mPosition, os); + PrintTo(transform.m_position, os); *os << ", rot: "; - PrintTo(transform.mRotation, os); + PrintTo(transform.m_rotation, os); #if !defined(EMFX_SCALE_DISABLED) *os << ", scale: "; - PrintTo(transform.mScale, os); + PrintTo(transform.m_scale, os); #endif *os << ")"; } diff --git a/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanEditAnimGraphNode.cpp b/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanEditAnimGraphNode.cpp index 08b702abb4..fe1204dd3b 100644 --- a/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanEditAnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanEditAnimGraphNode.cpp @@ -75,7 +75,7 @@ namespace EMotionFX ASSERT_TRUE(activeAnimGraph) << "An anim graph was not created with command: " << createAnimGraphCommand.c_str(); // Create a new AnimGraph Node - const AZ::u32 nodeCount = activeAnimGraph->GetNumNodes(); + const size_t nodeCount = activeAnimGraph->GetNumNodes(); EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommand(createNodeCommand, result)) << result.c_str(); EXPECT_EQ(activeAnimGraph->GetNumNodes(), nodeCount + 1) << "Expected one more anim graph node after running command: " << createNodeCommand.c_str(); } diff --git a/Gems/EMotionFX/Code/Tests/QuaternionParameterTests.cpp b/Gems/EMotionFX/Code/Tests/QuaternionParameterTests.cpp index db45a4a35f..a60a8eb3c8 100644 --- a/Gems/EMotionFX/Code/Tests/QuaternionParameterTests.cpp +++ b/Gems/EMotionFX/Code/Tests/QuaternionParameterTests.cpp @@ -97,7 +97,7 @@ namespace EMotionFX TEST_P(QuaternionParameterFixture, ParameterOutputsCorrectQuaternion) { // Parameter node needs to connect to another node, otherwise it will not update. - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortIndex("quaternionTest"), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALROT); + m_twoLinkIKNode->AddConnection(m_paramNode, aznumeric_caster(m_paramNode->FindOutputPortIndex("quaternionTest")), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALROT); GetEMotionFX().Update(1.0f / 60.0f); // Check correct output for quaternion parameter. @@ -112,7 +112,7 @@ namespace EMotionFX TEST_P(QuaternionParameterFixture, QuaternionSetValueOutputsCorrectQuaternion) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortIndex("quaternionTest"), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALROT); + m_twoLinkIKNode->AddConnection(m_paramNode, aznumeric_caster(m_paramNode->FindOutputPortIndex("quaternionTest")), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALROT); GetEMotionFX().Update(1.0f / 60.0f); // Shuffle the Quaternion parameter values to check changing quaternion values will be processed correctly. diff --git a/Gems/EMotionFX/Code/Tests/RandomMotionSelectionTests.cpp b/Gems/EMotionFX/Code/Tests/RandomMotionSelectionTests.cpp index 3a0b7f4959..556166e240 100644 --- a/Gems/EMotionFX/Code/Tests/RandomMotionSelectionTests.cpp +++ b/Gems/EMotionFX/Code/Tests/RandomMotionSelectionTests.cpp @@ -73,14 +73,14 @@ namespace EMotionFX for (int i = 0; i < iterationCount; ++i) { m_motionNode->PickNewActiveMotion(m_animGraphInstance, nodeUniqueData); - auto mapIterator = m_selectedMotionCount->find(nodeUniqueData->mActiveMotionIndex); + auto mapIterator = m_selectedMotionCount->find(nodeUniqueData->m_activeMotionIndex); if (mapIterator != m_selectedMotionCount->end()) { mapIterator->second++; } else { - m_selectedMotionCount->emplace(nodeUniqueData->mActiveMotionIndex, 1); + m_selectedMotionCount->emplace(nodeUniqueData->m_activeMotionIndex, 1); } } diff --git a/Gems/EMotionFX/Code/Tests/SimulatedObjectCommandTests.cpp b/Gems/EMotionFX/Code/Tests/SimulatedObjectCommandTests.cpp index 7337160d3f..4bac70c13d 100644 --- a/Gems/EMotionFX/Code/Tests/SimulatedObjectCommandTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SimulatedObjectCommandTests.cpp @@ -32,7 +32,7 @@ namespace EMotionFX return object->GetNumSimulatedJoints(); } - size_t CountChildJoints(const Actor* actor, size_t objectIndex, AZ::u32 jointIndex) + size_t CountChildJoints(const Actor* actor, size_t objectIndex, size_t jointIndex) { const AZStd::shared_ptr& simulatedObjectSetup = actor->GetSimulatedObjectSetup(); const SimulatedObject* object = simulatedObjectSetup->GetSimulatedObject(objectIndex); @@ -55,7 +55,7 @@ namespace EMotionFX CommandSystem::CommandManager commandManager; MCore::CommandGroup commandGroup; - const AZ::u32 actorId = m_actor->GetID(); + const uint32 actorId = m_actor->GetID(); const AZStd::vector jointNames = GetTestJointNames(); // 1. Add simulated object. @@ -106,11 +106,11 @@ namespace EMotionFX // --l_ankle // --l_ball const Skeleton* skeleton = m_actor->GetSkeleton(); - const AZ::u32 l_upLegIdx = skeleton->FindNodeByName("l_upLeg")->GetNodeIndex(); - const AZ::u32 l_upLegRollIdx = skeleton->FindNodeByName("l_upLegRoll")->GetNodeIndex(); - const AZ::u32 l_loLegIdx = skeleton->FindNodeByName("l_loLeg")->GetNodeIndex(); - const AZ::u32 l_ankleIdx = skeleton->FindNodeByName("l_ankle")->GetNodeIndex(); - const AZ::u32 l_ballIdx = skeleton->FindNodeByName("l_ball")->GetNodeIndex(); + const size_t l_upLegIdx = skeleton->FindNodeByName("l_upLeg")->GetNodeIndex(); + const size_t l_upLegRollIdx = skeleton->FindNodeByName("l_upLegRoll")->GetNodeIndex(); + const size_t l_loLegIdx = skeleton->FindNodeByName("l_loLeg")->GetNodeIndex(); + const size_t l_ankleIdx = skeleton->FindNodeByName("l_ankle")->GetNodeIndex(); + const size_t l_ballIdx = skeleton->FindNodeByName("l_ball")->GetNodeIndex(); CommandSimulatedObjectHelpers::AddSimulatedJoints(actorId, {l_upLegIdx, l_upLegRollIdx, l_loLegIdx, l_ankleIdx, l_ballIdx}, 0, false, &commandGroup); EXPECT_TRUE(commandManager.ExecuteCommandGroup(commandGroup, result)); const AZStd::string serialized3_2 = SerializeSimulatedObjectSetup(m_actor.get()); @@ -172,7 +172,7 @@ namespace EMotionFX CommandSystem::CommandManager commandManager; MCore::CommandGroup commandGroup; - const AZ::u32 actorId = m_actor->GetID(); + const uint32 actorId = m_actor->GetID(); const AZStd::vector jointNames = GetTestJointNames(); // 1. Add simulated object @@ -183,8 +183,8 @@ namespace EMotionFX // 2. Add r_upLeg simulated joints const Skeleton* skeleton = m_actor->GetSkeleton(); - const AZ::u32 r_upLegIdx = skeleton->FindNodeByName("r_upLeg")->GetNodeIndex(); - const AZ::u32 r_loLegIdx = skeleton->FindNodeByName("r_loLeg")->GetNodeIndex(); + const size_t r_upLegIdx = skeleton->FindNodeByName("r_upLeg")->GetNodeIndex(); + const size_t r_loLegIdx = skeleton->FindNodeByName("r_loLeg")->GetNodeIndex(); CommandSimulatedObjectHelpers::AddSimulatedJoints(actorId, { r_upLegIdx, r_loLegIdx }, 0, false); EXPECT_EQ(2, CountSimulatedJoints(m_actor.get(), 0)); const AZStd::string serializedUpLeg = SerializeSimulatedObjectSetup(m_actor.get()); diff --git a/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp b/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp index 5f48cc145f..c261f63bc1 100644 --- a/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SimulatedObjectSerializeTests.cpp @@ -32,10 +32,10 @@ namespace EMotionFX Skeleton* skeleton = m_actor->GetSkeleton(); for (const AZStd::string& name : jointNames) { - AZ::u32 skeletonJointIndex; + size_t skeletonJointIndex; const Node* skeletonJoint = skeleton->FindNodeAndIndexByName(name, skeletonJointIndex); ASSERT_NE(skeletonJoint, nullptr); - ASSERT_NE(skeletonJointIndex, MCORE_INVALIDINDEX32); + ASSERT_NE(skeletonJointIndex, InvalidIndex); SimulatedJoint* simulatedJoint = object->AddSimulatedJoint(skeletonJointIndex); simulatedJoint->SetDamping(0.1f); @@ -63,7 +63,7 @@ namespace EMotionFX ASSERT_FLOAT_EQ(loadedObject->GetStiffnessFactor(), 4.0f); for (size_t i = 0; i < jointNames.size(); ++i) { - const SimulatedJoint* loadedJoint = loadedObject->GetSimulatedJoint(static_cast(i)); + const SimulatedJoint* loadedJoint = loadedObject->GetSimulatedJoint(i); ASSERT_STREQ(skeleton->GetNode(loadedJoint->GetSkeletonJointIndex())->GetName(), jointNames[i].c_str()); ASSERT_FLOAT_EQ(loadedJoint->GetDamping(), 0.1f); ASSERT_FLOAT_EQ(loadedJoint->GetMass(), 2.0f); diff --git a/Gems/EMotionFX/Code/Tests/SimulatedObjectSetupTests.cpp b/Gems/EMotionFX/Code/Tests/SimulatedObjectSetupTests.cpp index c8bb4fe6df..f37f571982 100644 --- a/Gems/EMotionFX/Code/Tests/SimulatedObjectSetupTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SimulatedObjectSetupTests.cpp @@ -156,8 +156,8 @@ namespace SimulatedObjectSetupTests struct AddSimulatedJointAndChildrenParams { - AZ::u32 jointIndex; - size_t expectedSimulatedJointCount; + AZ::u32 m_jointIndex; + size_t m_expectedSimulatedJointCount; }; class AddSimulatedJointAndChildrenFixture @@ -177,8 +177,8 @@ namespace SimulatedObjectSetupTests SimulatedObjectSetup setup(&actor); SimulatedObject* object = setup.AddSimulatedObject(); - object->AddSimulatedJointAndChildren(GetParam().jointIndex); - EXPECT_EQ(object->GetSimulatedJoints().size(), GetParam().expectedSimulatedJointCount); + object->AddSimulatedJointAndChildren(GetParam().m_jointIndex); + EXPECT_EQ(object->GetSimulatedJoints().size(), GetParam().m_expectedSimulatedJointCount); } INSTANTIATE_TEST_CASE_P(Test, AddSimulatedJointAndChildrenFixture, diff --git a/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp b/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp index 1af95b0a6a..1252eb36ae 100644 --- a/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SkeletalLODTests.cpp @@ -26,7 +26,7 @@ namespace EMotionFX DisableJointsForLOD(m_disabledJointNames, 1); } - void DisableJointsForLOD(const std::vector& jointNames, AZ::u32 lodLevel) + void DisableJointsForLOD(const std::vector& jointNames, size_t lodLevel) { const Skeleton* skeleton = m_actor->GetSkeleton(); for (const std::string& jointName : jointNames) @@ -38,7 +38,7 @@ namespace EMotionFX } } - static void VerifySkeletalLODFlags(const ActorInstance* actorInstance, const std::vector& disabledJointNames, AZ::u32 lodLevel) + static void VerifySkeletalLODFlags(const ActorInstance* actorInstance, const std::vector& disabledJointNames, size_t lodLevel) { EXPECT_EQ(actorInstance->GetLODLevel(), lodLevel) << "Please note that setting the LOD level is delayed and happend with the next UpdateTransforms()."; @@ -46,13 +46,13 @@ namespace EMotionFX const Actor* actor = actorInstance->GetActor(); const Skeleton* skeleton = actor->GetSkeleton(); - const MCore::Array& enabledJoints = actorInstance->GetEnabledNodes(); - const AZ::u32 numEnabledJoints = enabledJoints.GetLength(); - EXPECT_EQ(actorInstance->GetNumEnabledNodes(), actor->GetNumNodes() - static_cast(disabledJointNames.size())) + const AZStd::vector& enabledJoints = actorInstance->GetEnabledNodes(); + const size_t numEnabledJoints = enabledJoints.size(); + EXPECT_EQ(actorInstance->GetNumEnabledNodes(), actor->GetNumNodes() - disabledJointNames.size()) << "The enabled joints on the actor instance are not in sync with the enabledJoints."; - const AZ::u32 numJoints = skeleton->GetNumNodes(); - for (AZ::u32 i = 0; i < numJoints; ++i) + const size_t numJoints = skeleton->GetNumNodes(); + for (size_t i = 0; i < numJoints; ++i) { const Node* joint = skeleton->GetNode(i); @@ -63,7 +63,7 @@ namespace EMotionFX // Check if the enabled joints on the actor instance is in sync. bool foundInEnabledJoints = false; - for (AZ::u32 j = 0; j < numEnabledJoints; ++j) + for (size_t j = 0; j < numEnabledJoints; ++j) { const AZ::u16 enabledJointIndex = actorInstance->GetEnabledNode(j); const Node* enabledJoint = skeleton->GetNode(enabledJointIndex); diff --git a/Gems/EMotionFX/Code/Tests/SyncingSystemTests.cpp b/Gems/EMotionFX/Code/Tests/SyncingSystemTests.cpp index 985b2eb6c1..a4a89da3ba 100644 --- a/Gems/EMotionFX/Code/Tests/SyncingSystemTests.cpp +++ b/Gems/EMotionFX/Code/Tests/SyncingSystemTests.cpp @@ -24,17 +24,17 @@ namespace EMotionFX { struct SyncParam { - void (*eventFactoryA)(MotionEventTrack* track) = MakeNoEvents; - void (*eventFactoryB)(MotionEventTrack* track) = MakeNoEvents; + void (*m_eventFactoryA)(MotionEventTrack* track) = MakeNoEvents; + void (*m_eventFactoryB)(MotionEventTrack* track) = MakeNoEvents; // 2.0 seconds of simulation, 0.1 increments, 21 playtimes - AZStd::array expectedPlayTimeA {}; - AZStd::array expectedPlayTimeB {}; + AZStd::array m_expectedPlayTimeA {}; + AZStd::array m_expectedPlayTimeB {}; // Expected play times will be calculated based on motion event and duration from AnimGraphNode::SyncUsingSyncTracks(). - AnimGraphObject::ESyncMode syncMode = AnimGraphObject::ESyncMode::SYNCMODE_DISABLED; - float weightParam = 0.0f; - bool reverseMotion = false; + AnimGraphObject::ESyncMode m_syncMode = AnimGraphObject::ESyncMode::SYNCMODE_DISABLED; + float m_weightParam = 0.0f; + bool m_reverseMotion = false; }; class SyncingSystemFixture @@ -45,7 +45,7 @@ namespace EMotionFX void ConstructGraph() override { const SyncParam param = GetParam(); - m_syncMode = param.syncMode; + m_syncMode = param.m_syncMode; AnimGraphFixture::ConstructGraph(); m_blendTreeAnimGraph = AnimGraphFactory::Create(); m_rootStateMachine = m_blendTreeAnimGraph->GetRootStateMachine(); @@ -143,16 +143,16 @@ namespace EMotionFX TEST_P(SyncingSystemFixture, SyncingSystemPlaySpeedTests) { const SyncParam param = GetParam(); - param.eventFactoryA(m_syncTrackA); - param.eventFactoryB(m_syncTrackB); + param.m_eventFactoryA(m_syncTrackA); + param.m_eventFactoryB(m_syncTrackB); GetEMotionFX().Update(0.0f); MCore::AttributeFloat* weightParam = m_animGraphInstance->GetParameterValueChecked(0); - weightParam->SetValue(param.weightParam); + weightParam->SetValue(param.m_weightParam); // Test reverse motion - m_motionNodeA->SetReverse(param.reverseMotion); - m_motionNodeB->SetReverse(param.reverseMotion); + m_motionNodeA->SetReverse(param.m_reverseMotion); + m_motionNodeB->SetReverse(param.m_reverseMotion); uint32 playTimeIndex = 0; const float tolerance = 0.00001f; Simulate(2.0f/*simulationTime*/, 10.0f/*expectedFps*/, 0.0f/*fpsVariance*/, @@ -180,7 +180,7 @@ namespace EMotionFX float factorB; float interpolatedSpeedA; AZStd::tie(interpolatedSpeedA, factorA, factorB) = AnimGraphNode::SyncPlaySpeeds( - motionPlaySpeedA, durationA, motionPlaySpeedB, durationB, param.weightParam); + motionPlaySpeedA, durationA, motionPlaySpeedB, durationB, param.m_weightParam); EXPECT_FLOAT_EQ(statePlaySpeedA, interpolatedSpeedA * factorA) << "Motion playspeeds should match the set playspeed in the motion node throughout blending."; } else if(m_blend2Node->GetSyncMode() == AnimGraphObject::SYNCMODE_TRACKBASED) @@ -188,8 +188,8 @@ namespace EMotionFX const float motionPlayTimeA = m_motionNodeA->GetCurrentPlayTime(animGraphInstance); const float motionPlayTimeB = m_motionNodeB->GetCurrentPlayTime(animGraphInstance); - EXPECT_NEAR(motionPlayTimeA, param.expectedPlayTimeA[playTimeIndex], tolerance) << "Motion node A playtime should match the expected playtime."; - EXPECT_NEAR(motionPlayTimeB, param.expectedPlayTimeB[playTimeIndex], tolerance) << "Motion node B playtime should match the expected playtime."; + EXPECT_NEAR(motionPlayTimeA, param.m_expectedPlayTimeA[playTimeIndex], tolerance) << "Motion node A playtime should match the expected playtime."; + EXPECT_NEAR(motionPlayTimeB, param.m_expectedPlayTimeB[playTimeIndex], tolerance) << "Motion node B playtime should match the expected playtime."; playTimeIndex++; } } diff --git a/Gems/EMotionFX/Code/Tests/TestAssetCode/ActorFactory.h b/Gems/EMotionFX/Code/Tests/TestAssetCode/ActorFactory.h index 73519e079e..198fe4ce49 100644 --- a/Gems/EMotionFX/Code/Tests/TestAssetCode/ActorFactory.h +++ b/Gems/EMotionFX/Code/Tests/TestAssetCode/ActorFactory.h @@ -22,7 +22,7 @@ namespace EMotionFX actor->SetID(0); actor->GetSkeleton()->UpdateNodeIndexValues(0); actor->ResizeTransformData(); - actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*generateOBBs=*/false, /*convertUnitType=*/false); + actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*convertUnitType=*/false); return actor; } }; diff --git a/Gems/EMotionFX/Code/Tests/TestAssetCode/JackActor.cpp b/Gems/EMotionFX/Code/Tests/TestAssetCode/JackActor.cpp index 414879568e..96461826c7 100644 --- a/Gems/EMotionFX/Code/Tests/TestAssetCode/JackActor.cpp +++ b/Gems/EMotionFX/Code/Tests/TestAssetCode/JackActor.cpp @@ -14,7 +14,7 @@ namespace EMotionFX JackNoMeshesActor::JackNoMeshesActor(const char* name) : Actor(name) { - uint32 nodeId = 0; + size_t nodeId = 0; auto root = AddNode(nodeId++, "jack_root"); auto Bip01__pelvis = AddNode(nodeId++, "Bip01__pelvis", root->GetNodeIndex()); auto l_upLeg = AddNode(nodeId++, "l_upLeg", Bip01__pelvis->GetNodeIndex()); diff --git a/Gems/EMotionFX/Code/Tests/TestAssetCode/SimpleActors.cpp b/Gems/EMotionFX/Code/Tests/TestAssetCode/SimpleActors.cpp index 45e9ad8649..3e1dac41c2 100644 --- a/Gems/EMotionFX/Code/Tests/TestAssetCode/SimpleActors.cpp +++ b/Gems/EMotionFX/Code/Tests/TestAssetCode/SimpleActors.cpp @@ -31,7 +31,7 @@ namespace EMotionFX AddNode(i, ("joint" + AZStd::to_string(i)).c_str(), i - 1); Transform transform = Transform::CreateIdentity(); - transform.mPosition = AZ::Vector3(static_cast(i), 0.0f, 0.0f); + transform.m_position = AZ::Vector3(static_cast(i), 0.0f, 0.0f); GetBindPose()->SetLocalSpaceTransform(i, transform); } } @@ -44,7 +44,7 @@ namespace EMotionFX AddNode(i, ("rootJoint" + AZStd::to_string(i)).c_str()); Transform transform = Transform::CreateIdentity(); - transform.mPosition = AZ::Vector3(static_cast(i), 0.0f, 0.0f); + transform.m_position = AZ::Vector3(static_cast(i), 0.0f, 0.0f); GetBindPose()->SetLocalSpaceTransform(i, transform); } } @@ -87,7 +87,7 @@ namespace EMotionFX AddNode(i, ("joint" + AZStd::to_string(i)).c_str(), i - 1); Transform transform = Transform::CreateIdentity(); - transform.mPosition = AZ::Vector3(static_cast(i), 0.0f, 0.0f); + transform.m_position = AZ::Vector3(static_cast(i), 0.0f, 0.0f); GetBindPose()->SetLocalSpaceTransform(i, transform); } } diff --git a/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor b/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor index 5a79fd5f48..20d4ffef85 100644 --- a/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor +++ b/Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin.actor @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:7db74f39a261bb70e1fdbdd546c337107809cdbdd1fc52568a0d30358b0f83d7 -size 30005 +oid sha256:55ecbc78a913c808cd007326b51dfc98b943b196b77fd6dc16aff0892b112e74 +size 16948 diff --git a/Gems/EMotionFX/Code/Tests/TransformUnitTests.cpp b/Gems/EMotionFX/Code/Tests/TransformUnitTests.cpp index 89cbddfb4d..b5f98bc5e8 100644 --- a/Gems/EMotionFX/Code/Tests/TransformUnitTests.cpp +++ b/Gems/EMotionFX/Code/Tests/TransformUnitTests.cpp @@ -52,33 +52,33 @@ namespace EMotionFX TEST(TransformFixture, CreateIdentity) { const Transform transform = Transform::CreateIdentity(); - EXPECT_TRUE(transform.mPosition.IsZero()); - EXPECT_EQ(transform.mRotation, AZ::Quaternion::CreateIdentity()); + EXPECT_TRUE(transform.m_position.IsZero()); + EXPECT_EQ(transform.m_rotation, AZ::Quaternion::CreateIdentity()); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateOne()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateOne()); ) } TEST(TransformFixture, CreateIdentityWithZeroScale) { const Transform transform = Transform::CreateIdentityWithZeroScale(); - EXPECT_TRUE(transform.mPosition.IsZero()); - EXPECT_EQ(transform.mRotation, AZ::Quaternion::CreateIdentity()); + EXPECT_TRUE(transform.m_position.IsZero()); + EXPECT_EQ(transform.m_rotation, AZ::Quaternion::CreateIdentity()); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateZero()); ) } TEST(TransformFixture, CreateZero) { const Transform transform = Transform::CreateZero(); - EXPECT_TRUE(transform.mPosition.IsZero()); - EXPECT_EQ(transform.mRotation, AZ::Quaternion::CreateZero()); + EXPECT_TRUE(transform.m_position.IsZero()); + EXPECT_EQ(transform.m_rotation, AZ::Quaternion::CreateZero()); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateZero()); ) } @@ -86,11 +86,11 @@ namespace EMotionFX TEST(TransformFixture, ConstructFromVec3Quat) { const Transform transform(AZ::Vector3(6.0f, 7.0f, 8.0f), AZ::Quaternion::CreateRotationX(AZ::Constants::HalfPi)); - EXPECT_EQ(transform.mPosition, AZ::Vector3(6.0f, 7.0f, 8.0f)); - EXPECT_THAT(transform.mRotation, IsClose(AZ::Quaternion(sqrt2over2, 0.0f, 0.0f, sqrt2over2))); + EXPECT_EQ(transform.m_position, AZ::Vector3(6.0f, 7.0f, 8.0f)); + EXPECT_THAT(transform.m_rotation, IsClose(AZ::Quaternion(sqrt2over2, 0.0f, 0.0f, sqrt2over2))); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateOne()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateOne()); ) } @@ -148,11 +148,11 @@ namespace EMotionFX TEST_P(TransformConstructFromVec3QuatVec3Fixture, ConstructFromVec3QuatVec3) { const Transform transform(ExpectedPosition(), ExpectedRotation(), ExpectedScale()); - EXPECT_THAT(transform.mPosition, IsClose(ExpectedPosition())); - EXPECT_THAT(transform.mRotation, IsClose(ExpectedRotation())); + EXPECT_THAT(transform.m_position, IsClose(ExpectedPosition())); + EXPECT_THAT(transform.m_rotation, IsClose(ExpectedRotation())); EMFX_SCALECODE ( - EXPECT_THAT(transform.mScale, IsClose(ExpectedScale())); + EXPECT_THAT(transform.m_scale, IsClose(ExpectedScale())); ) } @@ -160,11 +160,11 @@ namespace EMotionFX { Transform transform(AZ::Vector3(5.0f, 6.0f, 7.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(8.0f, 9.0f, 10.0f)); transform.Set(ExpectedPosition(), ExpectedRotation(), ExpectedScale()); - EXPECT_THAT(transform.mPosition, IsClose(ExpectedPosition())); - EXPECT_THAT(transform.mRotation, IsClose(ExpectedRotation())); + EXPECT_THAT(transform.m_position, IsClose(ExpectedPosition())); + EXPECT_THAT(transform.m_rotation, IsClose(ExpectedRotation())); EMFX_SCALECODE ( - EXPECT_THAT(transform.mScale, IsClose(ExpectedScale())); + EXPECT_THAT(transform.m_scale, IsClose(ExpectedScale())); ) } @@ -191,11 +191,11 @@ namespace EMotionFX { Transform transform(AZ::Vector3(5.0f, 6.0f, 7.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(8.0f, 9.0f, 10.0f)); transform.Set(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion::CreateRotationX(AZ::Constants::QuarterPi)); - EXPECT_EQ(transform.mPosition, AZ::Vector3(1.0f, 2.0f, 3.0f)); - EXPECT_THAT(transform.mRotation, IsClose(AZ::Quaternion::CreateRotationX(AZ::Constants::QuarterPi))); + EXPECT_EQ(transform.m_position, AZ::Vector3(1.0f, 2.0f, 3.0f)); + EXPECT_THAT(transform.m_rotation, IsClose(AZ::Quaternion::CreateRotationX(AZ::Constants::QuarterPi))); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateOne()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateOne()); ) } @@ -203,11 +203,11 @@ namespace EMotionFX { Transform transform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); transform.Identity(); - EXPECT_EQ(transform.mPosition, AZ::Vector3::CreateZero()); - EXPECT_EQ(transform.mRotation, AZ::Quaternion::CreateIdentity()); + EXPECT_EQ(transform.m_position, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_rotation, AZ::Quaternion::CreateIdentity()); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateOne()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateOne()); ) } @@ -215,11 +215,11 @@ namespace EMotionFX { Transform transform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); transform.Zero(); - EXPECT_EQ(transform.mPosition, AZ::Vector3::CreateZero()); - EXPECT_EQ(transform.mRotation, AZ::Quaternion::CreateZero()); + EXPECT_EQ(transform.m_position, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_rotation, AZ::Quaternion::CreateZero()); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateZero()); ) } @@ -227,11 +227,11 @@ namespace EMotionFX { Transform transform(AZ::Vector3(1.0f, 2.0f, 3.0f), AZ::Quaternion(0.1f, 0.2f, 0.3f, 0.4f), AZ::Vector3(4.0f, 5.0f, 6.0f)); transform.IdentityWithZeroScale(); - EXPECT_EQ(transform.mPosition, AZ::Vector3::CreateZero()); - EXPECT_EQ(transform.mRotation, AZ::Quaternion::CreateIdentity()); + EXPECT_EQ(transform.m_position, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_rotation, AZ::Quaternion::CreateIdentity()); EMFX_SCALECODE ( - EXPECT_EQ(transform.mScale, AZ::Vector3::CreateZero()); + EXPECT_EQ(transform.m_scale, AZ::Vector3::CreateZero()); ) } @@ -662,54 +662,54 @@ namespace EMotionFX struct ApplyDeltaParams { - const Transform initial; - const Transform a; - const Transform b; - const Transform expected; - const float weight; + const Transform m_initial; + const Transform m_a; + const Transform m_b; + const Transform m_expected; + const float m_weight; }; using TransformApplyDeltaFixture = ::testing::TestWithParam; TEST_P(TransformApplyDeltaFixture, ApplyDelta) { - if (GetParam().weight != 1.0f) + if (GetParam().m_weight != 1.0f) { return; } - Transform transform = GetParam().initial; - transform.ApplyDelta(GetParam().a, GetParam().b); + Transform transform = GetParam().m_initial; + transform.ApplyDelta(GetParam().m_a, GetParam().m_b); EXPECT_THAT( transform, - IsClose(GetParam().expected) + IsClose(GetParam().m_expected) ); } TEST_P(TransformApplyDeltaFixture, ApplyDeltaMirrored) { - if (GetParam().weight != 1.0f) + if (GetParam().m_weight != 1.0f) { return; } const AZ::Vector3 mirrorAxis = AZ::Vector3::CreateAxisX(); - Transform transform = GetParam().initial; - transform.ApplyDeltaMirrored(GetParam().a, GetParam().b, mirrorAxis); + Transform transform = GetParam().m_initial; + transform.ApplyDeltaMirrored(GetParam().m_a, GetParam().m_b, mirrorAxis); EXPECT_THAT( transform, - IsClose(GetParam().expected.Mirrored(mirrorAxis)) + IsClose(GetParam().m_expected.Mirrored(mirrorAxis)) ); } TEST_P(TransformApplyDeltaFixture, ApplyDeltaWithWeight) { - Transform transform = GetParam().initial; - transform.ApplyDeltaWithWeight(GetParam().a, GetParam().b, GetParam().weight); + Transform transform = GetParam().m_initial; + transform.ApplyDeltaWithWeight(GetParam().m_a, GetParam().m_b, GetParam().m_weight); EXPECT_THAT( transform, - IsClose(GetParam().expected) + IsClose(GetParam().m_expected) ); } @@ -774,7 +774,7 @@ namespace EMotionFX AZ::Quaternion(2.0f, 0.0f, 0.0f, 2.0f), AZ::Vector3::CreateOne() ).Normalize(); - EXPECT_FLOAT_EQ(transform.mRotation.GetLength(), 1.0f); + EXPECT_FLOAT_EQ(transform.m_rotation.GetLength(), 1.0f); } TEST(TransformFixture, Normalized) @@ -784,7 +784,7 @@ namespace EMotionFX AZ::Quaternion(2.0f, 0.0f, 0.0f, 2.0f), AZ::Vector3::CreateOne() ).Normalized(); - EXPECT_FLOAT_EQ(transform.mRotation.GetLength(), 1.0f); + EXPECT_FLOAT_EQ(transform.m_rotation.GetLength(), 1.0f); } TEST(TransformFixture, BlendAdditive) @@ -808,39 +808,39 @@ namespace EMotionFX : public ::testing::Test { protected: - const AZ::Vector3 translationA{5.0f, 6.0f, 7.0f}; - const AZ::Quaternion rotationA = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::QuarterPi); - const AZ::Vector3 scaleA = AZ::Vector3::CreateOne(); + const AZ::Vector3 m_translationA{5.0f, 6.0f, 7.0f}; + const AZ::Quaternion m_rotationA = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::QuarterPi); + const AZ::Vector3 m_scaleA = AZ::Vector3::CreateOne(); - const AZ::Vector3 translationB{11.0f, 12.0f, 13.0f}; - const AZ::Quaternion rotationB = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::HalfPi); - const AZ::Vector3 scaleB{3.0f, 4.0f, 5.0f}; + const AZ::Vector3 m_translationB{11.0f, 12.0f, 13.0f}; + const AZ::Quaternion m_rotationB = AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::HalfPi); + const AZ::Vector3 m_scaleB{3.0f, 4.0f, 5.0f}; }; TEST_F(TwoTransformsFixture, Blend) { - const Transform transformA(translationA, rotationA, scaleA); - const Transform transformB(translationB, rotationB, scaleB); + const Transform transformA(m_translationA, m_rotationA, m_scaleA); + const Transform transformB(m_translationB, m_rotationB, m_scaleB); EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Blend(transformB, 0.0f), + Transform(m_translationA, m_rotationA, m_scaleA).Blend(transformB, 0.0f), IsClose(transformA) ); EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Blend(transformB, 0.25f), + Transform(m_translationA, m_rotationA, m_scaleA).Blend(transformB, 0.25f), IsClose(Transform(AZ::Vector3(6.5f, 7.5f, 8.5f), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::Pi * 5.0f / 16.0f), AZ::Vector3(1.5f, 1.75f, 2.0f))) ); EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Blend(transformB, 0.5f), + Transform(m_translationA, m_rotationA, m_scaleA).Blend(transformB, 0.5f), IsClose(Transform(AZ::Vector3(8.0f, 9.0f, 10.0f), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::Pi * 3.0f / 8.0f), AZ::Vector3(2.0f, 2.5f, 3.0f))) ); EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Blend(transformB, 0.75f), + Transform(m_translationA, m_rotationA, m_scaleA).Blend(transformB, 0.75f), IsClose(Transform(AZ::Vector3(9.5f, 10.5f, 11.5f), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisX(), AZ::Constants::Pi * 7.0f / 16.0f), AZ::Vector3(2.5f, 3.25f, 4.0f))) ); EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Blend(transformB, 1.0f), + Transform(m_translationA, m_rotationA, m_scaleA).Blend(transformB, 1.0f), IsClose(transformB) ); } @@ -848,8 +848,8 @@ namespace EMotionFX TEST_F(TwoTransformsFixture, ApplyAdditiveTransform) { EXPECT_THAT( - Transform(translationA, rotationA, scaleA).ApplyAdditive(Transform(translationB, rotationB, scaleB)), - IsClose(Transform(translationA + translationB, rotationA * rotationB, scaleA * scaleB)) + Transform(m_translationA, m_rotationA, m_scaleA).ApplyAdditive(Transform(m_translationB, m_rotationB, m_scaleB)), + IsClose(Transform(m_translationA + m_translationB, m_rotationA * m_rotationB, m_scaleA * m_scaleB)) ); } @@ -857,16 +857,16 @@ namespace EMotionFX { const float factor = 0.5f; EXPECT_THAT( - Transform(translationA, rotationA, scaleA).ApplyAdditive(Transform(translationB, rotationB, scaleB), factor), - IsClose(Transform(translationA + translationB * factor, rotationA.NLerp(rotationA * rotationB, factor), scaleA * AZ::Vector3::CreateOne().Lerp(scaleB, factor))) + Transform(m_translationA, m_rotationA, m_scaleA).ApplyAdditive(Transform(m_translationB, m_rotationB, m_scaleB), factor), + IsClose(Transform(m_translationA + m_translationB * factor, m_rotationA.NLerp(m_rotationA * m_rotationB, factor), m_scaleA * AZ::Vector3::CreateOne().Lerp(m_scaleB, factor))) ); } TEST_F(TwoTransformsFixture, AddTransform) { EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Add(Transform(translationB, rotationB, scaleB)), - IsClose(Transform(translationA + translationB, rotationA + rotationB, scaleA + scaleB)) + Transform(m_translationA, m_rotationA, m_scaleA).Add(Transform(m_translationB, m_rotationB, m_scaleB)), + IsClose(Transform(m_translationA + m_translationB, m_rotationA + m_rotationB, m_scaleA + m_scaleB)) ); } @@ -874,16 +874,16 @@ namespace EMotionFX { const float factor = 0.5f; EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Add(Transform(translationB, rotationB, scaleB), factor), - IsClose(Transform(translationA + translationB * factor, rotationA + rotationB * factor, scaleA + scaleB * factor)) + Transform(m_translationA, m_rotationA, m_scaleA).Add(Transform(m_translationB, m_rotationB, m_scaleB), factor), + IsClose(Transform(m_translationA + m_translationB * factor, m_rotationA + m_rotationB * factor, m_scaleA + m_scaleB * factor)) ); } TEST_F(TwoTransformsFixture, Subtract) { EXPECT_THAT( - Transform(translationA, rotationA, scaleA).Subtract(Transform(translationB, rotationB, scaleB)), - IsClose(Transform(translationA - translationB, rotationA - rotationB, scaleA - scaleB)) + Transform(m_translationA, m_rotationA, m_scaleA).Subtract(Transform(m_translationB, m_rotationB, m_scaleB)), + IsClose(Transform(m_translationA - m_translationB, m_rotationA - m_rotationB, m_scaleA - m_scaleB)) ); } diff --git a/Gems/EMotionFX/Code/Tests/UI/AnimGraphUIFixture.cpp b/Gems/EMotionFX/Code/Tests/UI/AnimGraphUIFixture.cpp index 33c3d0054f..d32c34ea62 100644 --- a/Gems/EMotionFX/Code/Tests/UI/AnimGraphUIFixture.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/AnimGraphUIFixture.cpp @@ -82,7 +82,7 @@ namespace EMotionFX const AnimGraph* targetAnimGraph = (animGraph ? animGraph : m_animGraphPlugin->GetActiveAnimGraph()); //AnimGraph to add Node to const AZStd::string cmd = "AnimGraphCreateNode AnimGraphID " + AZStd::to_string(targetAnimGraph->GetID()) + " -type " + type + " " + args; - AZ::u32 nodeCount = targetAnimGraph->GetNumNodes(); //node count before creating a new node + size_t nodeCount = targetAnimGraph->GetNumNodes(); //node count before creating a new node AZStd::string result; EXPECT_TRUE(CommandSystem::GetCommandManager()->ExecuteCommand(cmd, result)) << result.c_str(); @@ -112,7 +112,7 @@ namespace EMotionFX const EMotionFX::AnimGraphNode* currentNode = GetActiveNodeGraph()->GetModelIndex().data(EMStudio::AnimGraphModel::ROLE_NODE_POINTER).value(); - const int numNodesAfter = currentNode->GetNumChildNodes(); + const size_t numNodesAfter = currentNode->GetNumChildNodes(); if (numNodesAfter == 0) { return nullptr; diff --git a/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToAnimGraphNode.cpp b/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToAnimGraphNode.cpp index 9dd041b2fd..dfd59d83ed 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToAnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToAnimGraphNode.cpp @@ -49,7 +49,7 @@ namespace EMotionFX ASSERT_TRUE(motionSetWindow) << "No motion set window found"; // Check there aren't any motion sets yet. - const AZ::u32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); EXPECT_EQ(numMotionSets, 0); // Find the action to create a new motion set and press it. @@ -58,7 +58,7 @@ namespace EMotionFX QTest::mouseClick(addMotionSetButton, Qt::LeftButton); // Make sure the new motion set has been created. - const AZ::u32 numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); ASSERT_EQ(numMotionSetsAfterCreate, numMotionSets + 1) << "Failed to create motion set."; EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(0); diff --git a/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToMotionSet.cpp b/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToMotionSet.cpp index 0e20d220d4..cd0cfea1dc 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToMotionSet.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanAddMotionToMotionSet.cpp @@ -38,7 +38,7 @@ namespace EMotionFX ASSERT_TRUE(motionSetWindow) << "No motion set window found"; // Check there aren't any motion sets yet. - uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); EXPECT_EQ(numMotionSets, 0); // Find the action to create a new motion set and press it. @@ -47,7 +47,7 @@ namespace EMotionFX QTest::mouseClick(addMotionSetButton, Qt::LeftButton); // Check there is now a motion set. - int numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); + size_t numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); ASSERT_EQ(numMotionSetsAfterCreate, 1); EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(0); @@ -56,7 +56,7 @@ namespace EMotionFX motionSetPlugin->SetSelectedSet(motionSet); // It should be empty at the moment. - int numMotions = static_cast(motionSet->GetNumMotionEntries()); + size_t numMotions = motionSet->GetNumMotionEntries(); EXPECT_EQ(numMotions, 0); // Find the action to add a motion to the set and press it. @@ -65,7 +65,7 @@ namespace EMotionFX QTest::mouseClick(addMotionButton, Qt::LeftButton); // There should now be a motion. - int numMotionsAfterCreate = static_cast(motionSet->GetNumMotionEntries()); + size_t numMotionsAfterCreate = motionSet->GetNumMotionEntries(); ASSERT_EQ(numMotionsAfterCreate, 1); AZStd::unordered_map motions = motionSet->GetMotionEntries(); diff --git a/Gems/EMotionFX/Code/Tests/UI/CanAddReferenceNode.cpp b/Gems/EMotionFX/Code/Tests/UI/CanAddReferenceNode.cpp index 46dae16f19..2e8851d80d 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanAddReferenceNode.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanAddReferenceNode.cpp @@ -47,7 +47,7 @@ namespace EMotionFX addReferenceNodeAction->trigger(); // Check the expected node now exists. - int numNodesAfter= currentNode->GetNumChildNodes(); + size_t numNodesAfter = currentNode->GetNumChildNodes(); EXPECT_EQ(1, numNodesAfter); AnimGraphNode* newNode = currentNode->GetChildNode(0); diff --git a/Gems/EMotionFX/Code/Tests/UI/CanEditParameters.cpp b/Gems/EMotionFX/Code/Tests/UI/CanEditParameters.cpp index 82f509965c..b5ec8be715 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanEditParameters.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanEditParameters.cpp @@ -74,7 +74,7 @@ namespace EMotionFX QTest::mouseClick(createButton, Qt::LeftButton); // Check we only have the one Parameter - int numParameters = static_cast(newGraph->GetNumParameters()); + size_t numParameters = newGraph->GetNumParameters(); EXPECT_EQ(numParameters, 1) << "Not just 1 parameter"; const RangedValueParameter* parameter = reinterpret_cast* >(newGraph->FindValueParameter(0)); diff --git a/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp index 978532505b..f47ad20d23 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanMorphManyShapes.cpp @@ -66,9 +66,9 @@ namespace EMotionFX ); m_morphSetup->AddMorphTarget(morphTarget); - // Without this call, the bind pose does not know about newly added morph target (mMorphWeights.GetLength() == 0) + // Without this call, the bind pose does not know about newly added morph target (m_morphWeights.size() == 0) m_actor->ResizeTransformData(); - m_actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*generateOBBs=*/false, /*convertUnitType=*/false); + m_actor->PostCreateInit(/*makeGeomLodsCompatibleWithSkeletalLODs=*/false, /*convertUnitType=*/false); m_animGraph = AZStd::make_unique(); @@ -99,7 +99,7 @@ namespace EMotionFX // InitAfterLoading() is called morphTargetNode->AddConnection( parameterNode, - parameterNode->FindOutputPortIndex("FloatParam"), + aznumeric_caster(parameterNode->FindOutputPortIndex("FloatParam")), BlendTreeMorphTargetNode::PORTID_INPUT_WEIGHT ); finalNode->AddConnection( @@ -161,13 +161,13 @@ namespace EMotionFX EXPECT_TRUE(morphTarget) << "Cannot access MorphTarget"; // Switch the morphTarget to manual mode - morphTarget->mManualMode->click(); + morphTarget->m_manualMode->click(); // Set the slider to 0.5f; - morphTarget->mSliderWeight->slider()->setValue(0.5f); + morphTarget->m_sliderWeight->slider()->setValue(0.5f); // Get the instance of the MorphTargetInstance - EMotionFX::MorphSetupInstance::MorphTarget* morphTargetInstance = morphTarget->mMorphTargetInstance; + EMotionFX::MorphSetupInstance::MorphTarget* morphTargetInstance = morphTarget->m_morphTargetInstance; ASSERT_TRUE(morphTargetInstance) << "Cannot get Instance of Morph Target"; EXPECT_EQ(morphTargetInstance->GetWeight(), 0.5f) << "Morph Taget Instance is not set to the correct value"; } diff --git a/Gems/EMotionFX/Code/Tests/UI/CanRemoveMotionFromMotionSet.cpp b/Gems/EMotionFX/Code/Tests/UI/CanRemoveMotionFromMotionSet.cpp index c6bec666b1..5bd798ed28 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanRemoveMotionFromMotionSet.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanRemoveMotionFromMotionSet.cpp @@ -41,7 +41,7 @@ namespace EMotionFX ASSERT_TRUE(motionSetWindow) << "No motion set window found"; // Check there aren't any motion sets yet. - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); EXPECT_EQ(numMotionSets, 0); // Find the action to create a new motion set and press it. @@ -50,7 +50,7 @@ namespace EMotionFX QTest::mouseClick(addMotionSetButton, Qt::LeftButton); // Check there is now a motion set. - const int numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); ASSERT_EQ(numMotionSetsAfterCreate, 1); EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(0); @@ -59,7 +59,7 @@ namespace EMotionFX motionSetPlugin->SetSelectedSet(motionSet); // It should be empty at the moment. - const int numMotions = static_cast(motionSet->GetNumMotionEntries()); + const size_t numMotions = motionSet->GetNumMotionEntries(); EXPECT_EQ(numMotions, 0); // Find the action to add a motion to the set and press it. @@ -68,7 +68,7 @@ namespace EMotionFX QTest::mouseClick(addMotionButton, Qt::LeftButton); // There should now be a motion. - const int numMotionsAfterCreate = static_cast(motionSet->GetNumMotionEntries()); + const size_t numMotionsAfterCreate = motionSet->GetNumMotionEntries(); ASSERT_EQ(numMotionsAfterCreate, 1); AZStd::unordered_map motions = motionSet->GetMotionEntries(); @@ -122,7 +122,7 @@ namespace EMotionFX ASSERT_TRUE(motionSetWindow) << "No motion set window found"; // Check there aren't any motion sets yet. - const uint32 numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSets = EMotionFX::GetMotionManager().GetNumMotionSets(); EXPECT_EQ(numMotionSets, 0); // Find the action to create a new motion set and press it. @@ -131,7 +131,7 @@ namespace EMotionFX QTest::mouseClick(addMotionSetButton, Qt::LeftButton); // Check there is now a motion set. - const int numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); + const size_t numMotionSetsAfterCreate = EMotionFX::GetMotionManager().GetNumMotionSets(); ASSERT_EQ(numMotionSetsAfterCreate, 1); EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().GetMotionSet(0); @@ -140,7 +140,7 @@ namespace EMotionFX motionSetPlugin->SetSelectedSet(motionSet); // It should be empty at the moment. - const int numMotions = static_cast(motionSet->GetNumMotionEntries()); + const size_t numMotions = motionSet->GetNumMotionEntries(); EXPECT_EQ(numMotions, 0); // Find the action to add a motion to the set and press it twice. @@ -150,7 +150,7 @@ namespace EMotionFX QTest::mouseClick(addMotionButton, Qt::LeftButton); // There should now be two motion. - const int numMotionsAfterCreate = static_cast(motionSet->GetNumMotionEntries()); + const size_t numMotionsAfterCreate = motionSet->GetNumMotionEntries(); ASSERT_EQ(numMotionsAfterCreate, 2); AZStd::unordered_map motions = motionSet->GetMotionEntries(); diff --git a/Gems/EMotionFX/Code/Tests/UI/CanUseEditMenu.cpp b/Gems/EMotionFX/Code/Tests/UI/CanUseEditMenu.cpp index 673d39ae13..983cb6bc9a 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanUseEditMenu.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanUseEditMenu.cpp @@ -41,7 +41,7 @@ namespace EMotionFX CommandSystem::CreateAnimGraphNode(/*commandGroup=*/nullptr, animGraph, azrtti_typeid(), "Reference", currentNode, 0, 0); // Check the expected node now exists. - uint32 numNodes = currentNode->GetNumChildNodes(); + size_t numNodes = currentNode->GetNumChildNodes(); EXPECT_EQ(1, numNodes); // Undo. @@ -49,7 +49,7 @@ namespace EMotionFX ASSERT_TRUE(undoAction); undoAction->trigger(); - const uint32 numNodesAfterUndo = currentNode->GetNumChildNodes(); + const size_t numNodesAfterUndo = currentNode->GetNumChildNodes(); ASSERT_EQ(numNodesAfterUndo, numNodes - 1); // Redo. @@ -57,7 +57,7 @@ namespace EMotionFX ASSERT_TRUE(redoAction); redoAction->trigger(); - const uint32 numNodesAfterRedo = currentNode->GetNumChildNodes(); + const size_t numNodesAfterRedo = currentNode->GetNumChildNodes(); ASSERT_EQ(numNodesAfterRedo, numNodesAfterUndo + 1); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Tests/UI/CanUseViewMenu.cpp b/Gems/EMotionFX/Code/Tests/UI/CanUseViewMenu.cpp index 49667ee104..62914b83f0 100644 --- a/Gems/EMotionFX/Code/Tests/UI/CanUseViewMenu.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/CanUseViewMenu.cpp @@ -106,7 +106,7 @@ namespace EMotionFX QList actions = viewMenu->findChildren(); int numActions = actions.size() - 1;// -1 as we don't want to include the view menu action itself. - const AZ::u32 numPlugins = pluginManager->GetNumPlugins(); + const size_t numPlugins = pluginManager->GetNumPlugins(); int visiblePlugins = 0; diff --git a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp index 4b48936c88..65bb056654 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp @@ -46,18 +46,6 @@ namespace EMotionFX class LODSystemMock : public SystemMock { - public: - CCamera& GetViewCamera() override - { - return m_camera; - } - void SetViewCameraPosition(Vec3& vec) - { - m_camera.SetPosition(vec); - } - - protected: - CCamera m_camera; }; class LODSkinnedMeshColorFixture @@ -102,7 +90,6 @@ namespace EMotionFX Mesh* lodMesh = actor->GetMesh(0, 0); StandardMaterial* dummyMat = StandardMaterial::Create("Dummy Material"); actor->AddMaterial(0, dummyMat); // owns the material - actor->SetNumLODLevels(numLODs); for (int i = 1; i < numLODs; ++i) { @@ -207,7 +194,6 @@ namespace EMotionFX EXPECT_EQ(actorInstance->GetLODLevel(), 0); Vec3 newVec{ 0,30,0 }; - m_data.m_system.SetViewCameraPosition(newVec); // Tick! AZ::TickBus::Broadcast(&AZ::TickBus::Events::OnTick, 0.0f, AZ::ScriptTimePoint{}); @@ -217,7 +203,6 @@ namespace EMotionFX EXPECT_EQ(actorInstance->GetLODLevel(), 3); newVec.y = 50; - m_data.m_system.SetViewCameraPosition(newVec); // Tick! AZ::TickBus::Broadcast(&AZ::TickBus::Events::OnTick, 0.0f, AZ::ScriptTimePoint{}); diff --git a/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.cpp b/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.cpp index 4e00a2998c..cecd865515 100644 --- a/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.cpp @@ -44,7 +44,7 @@ namespace EMotionFX m_totalTime = 0; m_actionCompletionCallback = completionCallback; - m_MenuActiveCallback = menuCallback; + m_menuActiveCallback = menuCallback; m_timeout = timeout; // Kick a timer off to check whether the menu is open. @@ -84,7 +84,7 @@ namespace EMotionFX } // The menu is now active, inform the calling object. - m_MenuActiveCallback(menu); + m_menuActiveCallback(menu); } void ModalPopupHandler::CheckForPopupWidget() diff --git a/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.h b/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.h index 2ebe5ed2ce..95b3c2c233 100644 --- a/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.h +++ b/Gems/EMotionFX/Code/Tests/UI/ModalPopupHandler.h @@ -162,7 +162,7 @@ namespace EMotionFX void CheckForPopupWidget(); private: - MenuActiveCallback m_MenuActiveCallback = nullptr; + MenuActiveCallback m_menuActiveCallback = nullptr; WidgetActiveCallback m_widgetActiveCallback = nullptr; ActionCompletionCallback m_actionCompletionCallback = nullptr; diff --git a/Gems/EMotionFX/Code/Tests/UI/UIFixture.cpp b/Gems/EMotionFX/Code/Tests/UI/UIFixture.cpp index 1425b87a6f..ea1f1c9148 100644 --- a/Gems/EMotionFX/Code/Tests/UI/UIFixture.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/UIFixture.cpp @@ -73,8 +73,8 @@ namespace EMotionFX { // Plugins have to be created after both the QApplication object and // after the SystemComponent - const uint32 numPlugins = EMStudio::GetPluginManager()->GetNumPlugins(); - for (uint32 i = 0; i < numPlugins; ++i) + const size_t numPlugins = EMStudio::GetPluginManager()->GetNumPlugins(); + for (size_t i = 0; i < numPlugins; ++i) { EMStudio::EMStudioPlugin* plugin = EMStudio::GetPluginManager()->GetPlugin(i); EMStudio::GetPluginManager()->CreateWindowOfType(plugin->GetName()); diff --git a/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp b/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp index 79bb4627d0..e82d10097b 100644 --- a/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UniformMotionDataTests.cpp @@ -243,15 +243,15 @@ namespace EMotionFX EXPECT_FALSE(motionData.FindJointIndexByName("Blah").IsSuccess()); EXPECT_FALSE(motionData.FindMorphIndexByName("Blah").IsSuccess()); EXPECT_FALSE(motionData.FindFloatIndexByName("Blah").IsSuccess()); - EXPECT_TRUE(motionData.FindJointIndexByName("Joint1").IsSuccess()); - EXPECT_TRUE(motionData.FindJointIndexByName("Joint2").IsSuccess()); - EXPECT_TRUE(motionData.FindJointIndexByName("Joint3").IsSuccess()); - EXPECT_TRUE(motionData.FindMorphIndexByName("Morph1").IsSuccess()); - EXPECT_TRUE(motionData.FindMorphIndexByName("Morph2").IsSuccess()); - EXPECT_TRUE(motionData.FindMorphIndexByName("Morph3").IsSuccess()); - EXPECT_TRUE(motionData.FindFloatIndexByName("Float1").IsSuccess()); - EXPECT_TRUE(motionData.FindFloatIndexByName("Float2").IsSuccess()); - EXPECT_TRUE(motionData.FindFloatIndexByName("Float3").IsSuccess()); + ASSERT_TRUE(motionData.FindJointIndexByName("Joint1").IsSuccess()); + ASSERT_TRUE(motionData.FindJointIndexByName("Joint2").IsSuccess()); + ASSERT_TRUE(motionData.FindJointIndexByName("Joint3").IsSuccess()); + ASSERT_TRUE(motionData.FindMorphIndexByName("Morph1").IsSuccess()); + ASSERT_TRUE(motionData.FindMorphIndexByName("Morph2").IsSuccess()); + ASSERT_TRUE(motionData.FindMorphIndexByName("Morph3").IsSuccess()); + ASSERT_TRUE(motionData.FindFloatIndexByName("Float1").IsSuccess()); + ASSERT_TRUE(motionData.FindFloatIndexByName("Float2").IsSuccess()); + ASSERT_TRUE(motionData.FindFloatIndexByName("Float3").IsSuccess()); EXPECT_EQ(motionData.FindJointIndexByName("Joint1").GetValue(), 0); EXPECT_EQ(motionData.FindJointIndexByName("Joint2").GetValue(), 1); EXPECT_EQ(motionData.FindJointIndexByName("Joint3").GetValue(), 2); @@ -320,7 +320,7 @@ namespace EMotionFX // Test morph sampling. AZ::Outcome index = motionData.FindMorphIndexByName("Morph1"); - EXPECT_TRUE(index.IsSuccess()); + ASSERT_TRUE(index.IsSuccess()); if (index.IsSuccess()) { float result = -1.0f; @@ -352,7 +352,7 @@ namespace EMotionFX // Test float sampling. index = motionData.FindFloatIndexByName("Float1"); - EXPECT_TRUE(index.IsSuccess()); + ASSERT_TRUE(index.IsSuccess()); if (index.IsSuccess()) { float result = -1.0f; @@ -406,15 +406,15 @@ namespace EMotionFX EXPECT_FALSE(motionData.IsJointAnimated(3)); EXPECT_STREQ(motionData.GetJointName(3).c_str(), "Joint4"); - EXPECT_THAT(motionData.GetJointPoseTransform(3).mPosition, IsClose(poseTransform.mPosition)); - EXPECT_THAT(motionData.GetJointPoseTransform(3).mRotation, IsClose(poseTransform.mRotation)); + EXPECT_THAT(motionData.GetJointPoseTransform(3).m_position, IsClose(poseTransform.m_position)); + EXPECT_THAT(motionData.GetJointPoseTransform(3).m_rotation, IsClose(poseTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(motionData.GetJointPoseTransform(3).mScale, IsClose(poseTransform.mScale)); + EXPECT_THAT(motionData.GetJointPoseTransform(3).m_scale, IsClose(poseTransform.m_scale)); #endif - EXPECT_THAT(motionData.GetJointBindPoseTransform(3).mPosition, IsClose(bindTransform.mPosition)); - EXPECT_THAT(motionData.GetJointBindPoseTransform(3).mRotation, IsClose(bindTransform.mRotation)); + EXPECT_THAT(motionData.GetJointBindPoseTransform(3).m_position, IsClose(bindTransform.m_position)); + EXPECT_THAT(motionData.GetJointBindPoseTransform(3).m_rotation, IsClose(bindTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(motionData.GetJointBindPoseTransform(3).mScale, IsClose(bindTransform.mScale)); + EXPECT_THAT(motionData.GetJointBindPoseTransform(3).m_scale, IsClose(bindTransform.m_scale)); #endif // Test adding a morph. @@ -549,19 +549,19 @@ namespace EMotionFX sampleSettings.m_actorInstance = m_actorInstance; sampleSettings.m_sampleTime = expectation.first; const Transform sampledResult = motionData.SampleJointTransform(sampleSettings, 0); - EXPECT_THAT(sampledResult.mPosition, IsClose(expectation.second.mPosition)); - EXPECT_THAT(sampledResult.mRotation, IsClose(expectation.second.mRotation)); + EXPECT_THAT(sampledResult.m_position, IsClose(expectation.second.m_position)); + EXPECT_THAT(sampledResult.m_rotation, IsClose(expectation.second.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(sampledResult.mScale, IsClose(expectation.second.mScale)); + EXPECT_THAT(sampledResult.m_scale, IsClose(expectation.second.m_scale)); #endif // Fourth joint has no motion data to apply to our actor, so expect a bind pose. // It has motion data, but there is no joint in the skeleton that matches its name, so it is like motion data for a joint that doesn't exist in our actor. const Transform fourthJointTransform = motionData.SampleJointTransform(sampleSettings, 3); - EXPECT_THAT(fourthJointTransform.mPosition, IsClose(expectedBindTransform.mPosition)); - EXPECT_THAT(fourthJointTransform.mRotation, IsClose(expectedBindTransform.mRotation)); + EXPECT_THAT(fourthJointTransform.m_position, IsClose(expectedBindTransform.m_position)); + EXPECT_THAT(fourthJointTransform.m_rotation, IsClose(expectedBindTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(fourthJointTransform.mScale, IsClose(expectedBindTransform.mScale)); + EXPECT_THAT(fourthJointTransform.m_scale, IsClose(expectedBindTransform.m_scale)); #endif } @@ -578,19 +578,19 @@ namespace EMotionFX // We only verify the first joint, to see if it interpolated fine. const Transform sampledResult = pose.GetLocalSpaceTransform(0); - EXPECT_THAT(sampledResult.mPosition, IsClose(expectation.second.mPosition)); - EXPECT_THAT(sampledResult.mRotation, IsClose(expectation.second.mRotation)); + EXPECT_THAT(sampledResult.m_position, IsClose(expectation.second.m_position)); + EXPECT_THAT(sampledResult.m_rotation, IsClose(expectation.second.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(sampledResult.mScale, IsClose(expectation.second.mScale)); + EXPECT_THAT(sampledResult.m_scale, IsClose(expectation.second.m_scale)); #endif // Fourth joint has no motion data to apply to our actor, so expect a bind pose. // It has motion data, but there is no joint in the skeleton that matches its name, so it is like motion data for a joint that doesn't exist in our actor. const Transform fourthJointTransform = pose.GetLocalSpaceTransform(3); - EXPECT_THAT(fourthJointTransform.mPosition, IsClose(expectedBindTransform.mPosition)); - EXPECT_THAT(fourthJointTransform.mRotation, IsClose(expectedBindTransform.mRotation)); + EXPECT_THAT(fourthJointTransform.m_position, IsClose(expectedBindTransform.m_position)); + EXPECT_THAT(fourthJointTransform.m_rotation, IsClose(expectedBindTransform.m_rotation)); #ifndef EMFX_SCALE_DISABLED - EXPECT_THAT(fourthJointTransform.mScale, IsClose(expectedBindTransform.mScale)); + EXPECT_THAT(fourthJointTransform.m_scale, IsClose(expectedBindTransform.m_scale)); #endif } } diff --git a/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp b/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp index 201fb856a4..26702af550 100644 --- a/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp +++ b/Gems/EMotionFX/Code/Tests/Vector2ToVector3CompatibilityTests.cpp @@ -25,7 +25,7 @@ #include #include #include -#include +#include namespace EMotionFX { diff --git a/Gems/EMotionFX/Code/Tests/Vector3ParameterTests.cpp b/Gems/EMotionFX/Code/Tests/Vector3ParameterTests.cpp index 4dea530624..c98117abd3 100644 --- a/Gems/EMotionFX/Code/Tests/Vector3ParameterTests.cpp +++ b/Gems/EMotionFX/Code/Tests/Vector3ParameterTests.cpp @@ -71,7 +71,7 @@ namespace EMotionFX void ParamSetValue(const AZStd::string& paramName, const inputType& value) { const AZ::Outcome parameterIndex = m_animGraphInstance->FindParameterIndex(paramName); - MCore::Attribute* param = m_animGraphInstance->GetParameterValue(static_cast(parameterIndex.GetValue())); + MCore::Attribute* param = m_animGraphInstance->GetParameterValue(parameterIndex.GetValue()); paramType* typeParam = static_cast(param); typeParam->SetValue(value); } @@ -97,7 +97,7 @@ namespace EMotionFX TEST_P(Vector3ParameterFixture, ParameterOutputsCorrectVector3Floats) { // Parameter node needs to connect to another node, otherwise it will not be updated - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortIndex("vec3Test"), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALPOS); + m_twoLinkIKNode->AddConnection(m_paramNode, aznumeric_caster(m_paramNode->FindOutputPortIndex("vec3Test")), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALPOS); GetEMotionFX().Update(1.0f / 60.0f); // Check correct output for vector3 parameter. @@ -111,7 +111,7 @@ namespace EMotionFX TEST_P(Vector3ParameterFixture, Vec3SetValueOutputsCorrectVector3Floats) { - m_twoLinkIKNode->AddConnection(m_paramNode, m_paramNode->FindOutputPortIndex("vec3Test"), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALPOS); + m_twoLinkIKNode->AddConnection(m_paramNode, aznumeric_caster(m_paramNode->FindOutputPortIndex("vec3Test")), BlendTreeTwoLinkIKNode::PORTID_INPUT_GOALPOS); GetEMotionFX().Update(1.0f / 60.0f); // Shuffle the vector3 parameter values to check changing vector3 values will be processed correctly. diff --git a/Gems/LmbrCentral/Code/Source/Builders/LuaBuilder/LuaBuilderComponent.cpp b/Gems/LmbrCentral/Code/Source/Builders/LuaBuilder/LuaBuilderComponent.cpp index 5a787c480f..0ef02837da 100644 --- a/Gems/LmbrCentral/Code/Source/Builders/LuaBuilder/LuaBuilderComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Builders/LuaBuilder/LuaBuilderComponent.cpp @@ -25,7 +25,7 @@ void LuaBuilder::BuilderPluginComponent::Activate() { AssetBuilderSDK::AssetBuilderDesc builderDescriptor; builderDescriptor.m_name = "Lua Worker Builder"; - builderDescriptor.m_version = 6; + builderDescriptor.m_version = 7; builderDescriptor.m_analysisFingerprint = AZStd::string::format("%d", static_cast(AZ::ScriptAsset::AssetVersion)); builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.lua", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); builderDescriptor.m_busId = azrtti_typeid(); diff --git a/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp b/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp index ef01ba4d9f..c2c05277a8 100644 --- a/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp +++ b/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp @@ -23,7 +23,6 @@ #include "Animation/UiAnimViewDialog.h" #include "Animation/UiAnimViewUndo.h" -#include "RenderViewport.h" #include "Viewport.h" #include "ViewManager.h" diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimUndoManager.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimUndoManager.cpp index 82eb6091e6..025b8c94d8 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimUndoManager.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimUndoManager.cpp @@ -59,7 +59,7 @@ public: virtual bool IsEmpty() const { return m_undoObjects.empty(); }; virtual void Undo(bool bUndo) { - for (int i = m_undoObjects.size() - 1; i >= 0; i--) + for (int i = aznumeric_cast(m_undoObjects.size()) - 1; i >= 0; i--) { m_undoObjects[i]->Undo(bUndo); } diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp index f860725276..2b13132606 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewAnimNode.cpp @@ -18,7 +18,6 @@ #include "UiAnimViewSequenceManager.h" #include "Objects/EntityObject.h" #include "ViewManager.h" -#include "RenderViewport.h" #include "Clipboard.h" #include diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp index d930b4b581..136d405465 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewNodes.cpp @@ -23,7 +23,6 @@ #include "Objects/EntityObject.h" #include "ViewManager.h" -#include "RenderViewport.h" #include "Export/ExportManager.h" #include diff --git a/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp b/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp index caff5d2da0..5a281ba312 100644 --- a/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp +++ b/Gems/LyShine/Code/Editor/AssetTreeEntry.cpp @@ -136,7 +136,7 @@ AssetTreeEntry* AssetTreeEntry::BuildAssetTree(const AZ::Data::AssetType& assetT // product name stored in db is in all lower case, but we want to preserve case here AzFramework::StringFunc::Path::Split(product->GetParent()->GetRelativePath().c_str(), nullptr, &path, &name); // find next character position after default slice path in order to generate hierarchical sub-menus matching the subfolders - int pos = AzFramework::StringFunc::Find(path.c_str(), pathToSearch.c_str()) + pathToSearch.length(); + const size_t pos = AzFramework::StringFunc::Find(path.c_str(), pathToSearch.c_str()) + pathToSearch.length(); assetTree->Insert(path.substr(pos), name, product->GetAssetId()); } return assetTree; diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp index 5359ed6ad5..8baea091a2 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp @@ -415,7 +415,7 @@ namespace NvCloth const MCore::DualQuaternion& skinningDualQuaternion = m_skinningDualQuaternions.at(jointIndex); - float flip = AZ::GetSign(vertexSkinningTransform.mReal.Dot(skinningDualQuaternion.mReal)); + float flip = AZ::GetSign(vertexSkinningTransform.m_real.Dot(skinningDualQuaternion.m_real)); vertexSkinningTransform += skinningDualQuaternion * jointWeight * flip; } // Normalizing the dual quaternion as the GPU shaders do. This will remove the scale from the transform. diff --git a/Gems/NvCloth/Code/Tests/ActorHelper.cpp b/Gems/NvCloth/Code/Tests/ActorHelper.cpp index 5520e8ac53..6742f60956 100644 --- a/Gems/NvCloth/Code/Tests/ActorHelper.cpp +++ b/Gems/NvCloth/Code/Tests/ActorHelper.cpp @@ -28,9 +28,9 @@ namespace UnitTest { } - AZ::u32 ActorHelper::AddJoint( + size_t ActorHelper::AddJoint( const AZStd::string& name, - const AZ::Transform localTransform, + const AZ::Transform& localTransform, const AZStd::string& parentName) { EMotionFX::Node* parentNode = GetSkeleton()->FindNodeByNameNoCase(parentName.c_str()); @@ -38,7 +38,7 @@ namespace UnitTest auto node = AddNode( GetNumNodes(), name.c_str(), - (parentNode) ? parentNode->GetNodeIndex() : MCORE_INVALIDINDEX32); + (parentNode) ? parentNode->GetNodeIndex() : InvalidIndex); GetBindPose()->SetLocalSpaceTransform(node->GetNodeIndex(), localTransform); diff --git a/Gems/NvCloth/Code/Tests/ActorHelper.h b/Gems/NvCloth/Code/Tests/ActorHelper.h index 82d53ae660..1e1145d995 100644 --- a/Gems/NvCloth/Code/Tests/ActorHelper.h +++ b/Gems/NvCloth/Code/Tests/ActorHelper.h @@ -23,9 +23,9 @@ namespace UnitTest explicit ActorHelper(const char* name); //! Adds a node to the skeleton. - AZ::u32 AddJoint( + size_t AddJoint( const AZStd::string& name, - const AZ::Transform localTransform = AZ::Transform::CreateIdentity(), + const AZ::Transform& localTransform = AZ::Transform::CreateIdentity(), const AZStd::string& parentName = ""); //! Adds a collider to the cloh configuration. diff --git a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp index 992a2a3697..d88a5910e2 100644 --- a/Gems/PhysXDebug/Code/Source/SystemComponent.cpp +++ b/Gems/PhysXDebug/Code/Source/SystemComponent.cpp @@ -18,13 +18,13 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include @@ -468,16 +468,25 @@ namespace PhysXDebug RenderBuffers(); } + AZ::Vector3 GetViewCameraPosition() + { + using Camera::ActiveCameraRequestBus; + + AZ::Transform tm = AZ::Transform::CreateIdentity(); + ActiveCameraRequestBus::BroadcastResult(tm, &ActiveCameraRequestBus::Events::GetActiveCameraTransform); + return tm.GetTranslation(); + } + void SystemComponent::UpdateColliderVisualizationByProximity() { if (auto* debug = AZ::Interface::Get(); UseEditorPhysicsScene() && m_settings.m_visualizeCollidersByProximity && debug != nullptr) { - const CCamera& camera = gEnv->pSystem->GetViewCamera(); + const AZ::Vector3& viewPos = GetViewCameraPosition(); const PhysX::Debug::ColliderProximityVisualization data( m_settings.m_visualizeCollidersByProximity, - LYVec3ToAZVec3(camera.GetPosition()), + viewPos, m_culling.m_boxSize * 0.5f); debug->UpdateColliderProximityVisualization(data); } @@ -663,8 +672,7 @@ namespace PhysXDebug AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Physics); // Currently using the Cry view camera to support Editor, Game and Launcher modes. This will be updated in due course. - const CCamera& camera = gEnv->pSystem->GetViewCamera(); - AZ::Vector3 cameraTranslation = LYVec3ToAZVec3(camera.GetPosition()); + const AZ::Vector3 cameraTranslation = GetViewCameraPosition(); if (!cameraTranslation.IsClose(AZ::Vector3::CreateZero())) { diff --git a/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/VersionedProperty.cpp b/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/VersionedProperty.cpp index 59f2ffe58c..e09bdc94a9 100644 --- a/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/VersionedProperty.cpp +++ b/Gems/ScriptEvents/Code/Include/ScriptEvents/Internal/VersionedProperty.cpp @@ -9,7 +9,6 @@ #include "VersionedProperty.h" #include -#include #include #include #include diff --git a/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py b/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py index b5b75508ec..0ac8c12f9b 100644 --- a/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py +++ b/Tools/LyTestTools/ly_test_tools/benchmark/data_aggregator.py @@ -18,31 +18,77 @@ class BenchmarkPathException(Exception): """Custom Exception class for invalid benchmark file paths.""" pass +class RunningStatistics(object): + def __init__(self): + ''' + Initializes a helper class for calculating running statstics. + ''' + self.count = 0 + self.total = 0 + self.max = 0 + self.min = float('inf') + + def update(self, value): + ''' + Updates the statistics with a new value. + + :param value: The new value to update the statistics with. + ''' + self.total += value + self.count += 1 + self.max = max(value, self.max) + self.min = min(value, self.min) + + def getAvg(self): + ''' + Returns the average of the running values. + ''' + return self.total / self.count + + def getMax(self): + ''' + Returns the maximum of the running values. + ''' + return self.max + + def getMin(self): + ''' + Returns the minimum of the running values. + ''' + return self.min + + def getCount(self): + return self.count + class BenchmarkDataAggregator(object): def __init__(self, workspace, logger, test_suite): + ''' + Initializes an aggregator for benchmark data. + + :param workspace: Workspace of the test suite the benchmark was run in + :param logger: Logger used by the test suite the benchmark was run in + :param test_suite: Name of the test suite the benchmark was run in + ''' self.build_dir = workspace.paths.build_directory() self.results_dir = Path(workspace.paths.project(), 'user/Scripts/PerformanceBenchmarks') - self.test_suite = test_suite if os.environ.get('CI') else 'local' + self.test_suite = test_suite if os.environ.get('BUILD_NUMBER') else 'local' self.filebeat_client = FilebeatClient(logger) - def _update_pass(self, pass_stats, entry): + def _update_pass(self, gpu_pass_stats, entry): ''' - Modifies pass_stats dict keyed by pass name with the time recorded in a pass timestamp entry. + Modifies gpu_pass_stats dict keyed by pass name with the time recorded in a pass timestamp entry. - :param pass_stats: dict aggregating statistics from each pass (key: pass name, value: dict with stats) + :param gpu_pass_stats: dict aggregating statistics from each pass (key: pass name, value: dict with stats) :param entry: dict representing the timestamp entry of a pass :return: Time (in nanoseconds) recorded by this pass ''' name = entry['passName'] time_ns = entry['timestampResultInNanoseconds'] - pass_entry = pass_stats.get(name, { 'totalTime': 0, 'maxTime': 0 }) - - pass_entry['maxTime'] = max(time_ns, pass_entry['maxTime']) - pass_entry['totalTime'] += time_ns - pass_stats[name] = pass_entry + pass_entry = gpu_pass_stats.get(name, RunningStatistics()) + pass_entry.update(time_ns) + gpu_pass_stats[name] = pass_entry return time_ns - def _process_benchmark(self, benchmark_dir, benchmark_metadata): ''' Aggregates data from results from a single benchmark contained in a subdirectory of self.results_dir. @@ -50,8 +96,8 @@ class BenchmarkDataAggregator(object): :param benchmark_dir: Path of directory containing the benchmark results :param benchmark_metadata: Dict with benchmark metadata mutated with additional info from metadata file :return: Tuple with two indexes: - [0]: Dict aggregating statistics from frame times (key: stat name) - [1]: Dict aggregating statistics from pass times (key: pass name, value: dict with stats) + [0]: RunningStatistics for GPU frame times + [1]: Dict aggregating statistics from GPU pass times (key: pass name, value: RunningStatistics) ''' # Parse benchmark metadata metadata_file = benchmark_dir / 'benchmark_metadata.json' @@ -62,39 +108,47 @@ class BenchmarkDataAggregator(object): raise BenchmarkPathException(f'Metadata file could not be found at {metadata_file}') # data structures aggregating statistics from timestamp logs - frame_stats = { 'count': 0, 'totalTime': 0, 'maxTime': 0, 'minTime': float('inf') } - pass_stats = {} # key: pass name, value: dict with totalTime and maxTime keys + gpu_frame_stats = RunningStatistics() + cpu_frame_stats = RunningStatistics() + gpu_pass_stats = {} # key: pass name, value: RunningStatistics # this allows us to add additional data if necessary, e.g. frame_test_timestamps.json is_timestamp_file = lambda file: file.name.startswith('frame') and file.name.endswith('_timestamps.json') + is_frame_time_file = lambda file: file.name.startswith('cpu_frame') and file.name.endswith('_time.json') # parse benchmark files for file in benchmark_dir.iterdir(): - if file.is_dir() or not is_timestamp_file(file): + if file.is_dir(): continue - data = json.loads(file.read_text()) - entries = data['ClassData']['timestampEntries'] + if is_timestamp_file(file): + data = json.loads(file.read_text()) + entries = data['ClassData']['timestampEntries'] + + frame_time = sum(self._update_pass(gpu_pass_stats, entry) for entry in entries) + gpu_frame_stats.update(frame_time) - frame_time = sum(self._update_pass(pass_stats, entry) for entry in entries) + if is_frame_time_file(file): + data = json.loads(file.read_text()) + frame_time = data['ClassData']['frameTime'] + cpu_frame_stats.update(frame_time) - frame_stats['totalTime'] += frame_time - frame_stats['maxTime'] = max(frame_time, frame_stats['maxTime']) - frame_stats['minTime'] = min(frame_time, frame_stats['minTime']) - frame_stats['count'] += 1 + if gpu_frame_stats.getCount() < 1: + raise BenchmarkPathException(f'No GPU frame timestamp logs were found in {benchmark_dir}') - if frame_stats['count'] < 1: - raise BenchmarkPathException(f'No frame timestamp logs were found in {benchmark_dir}') + if cpu_frame_stats.getCount() < 1: + raise BenchmarkPathException(f'No CPU frame times were found in {benchmark_dir}') - return frame_stats, pass_stats + return gpu_frame_stats, gpu_pass_stats, cpu_frame_stats - def _generate_payloads(self, benchmark_metadata, frame_stats, pass_stats): + def _generate_payloads(self, benchmark_metadata, gpu_frame_stats, gpu_pass_stats, cpu_frame_stats): ''' Generates payloads to send to Filebeat based on aggregated stats and metadata. :param benchmark_metadata: Dict of benchmark metadata - :param frame_stats: Dict of aggregated frame statistics - :param pass_stats: Dict of aggregated pass statistics + :param gpu_frame_stats: RunningStatistics for GPU frame data + :param gpu_pass_stats: Dict of aggregated pass RunningStatistics + :param cpu_frame_stats: RunningStatistics for CPU frame data :return payloads: List of tuples, each with two indexes: [0]: Elasticsearch index suffix associated with the payload [1]: Payload dict to deliver to Filebeat @@ -103,33 +157,38 @@ class BenchmarkDataAggregator(object): payloads = [] # calculate statistics based on aggregated frame data - frame_time_avg = frame_stats['totalTime'] / frame_stats['count'] - frame_payload = { + gpu_frame_payload = { + 'frameTime': { + 'avg': ns_to_ms(gpu_frame_stats.getAvg()), + 'max': ns_to_ms(gpu_frame_stats.getMax()), + 'min': ns_to_ms(gpu_frame_stats.getMin()) + } + } + cpu_frame_payload = { 'frameTime': { - 'avg': ns_to_ms(frame_time_avg), - 'max': ns_to_ms(frame_stats['maxTime']), - 'min': ns_to_ms(frame_stats['minTime']) + 'avg': cpu_frame_stats.getAvg(), + 'max': cpu_frame_stats.getMax(), + 'min': cpu_frame_stats.getMin() } } # add benchmark metadata to payload - frame_payload.update(benchmark_metadata) - payloads.append(('frame_data', frame_payload)) + gpu_frame_payload.update(benchmark_metadata) + payloads.append(('gpu.frame_data', gpu_frame_payload)) + cpu_frame_payload.update(benchmark_metadata) + payloads.append(('cpu.frame_data', cpu_frame_payload)) # calculate statistics for each pass - for name, stat in pass_stats.items(): - avg_ms = ns_to_ms(stat['totalTime'] / frame_stats['count']) - max_ms = ns_to_ms(stat['maxTime']) - - pass_payload = { + for name, stat in gpu_pass_stats.items(): + gpu_pass_payload = { 'passName': name, 'passTime': { - 'avg': avg_ms, - 'max': max_ms + 'avg': ns_to_ms(stat.getAvg()), + 'max': ns_to_ms(stat.getMax()) } } # add benchmark metadata to payload - pass_payload.update(benchmark_metadata) - payloads.append(('pass_data', pass_payload)) + gpu_pass_payload.update(benchmark_metadata) + payloads.append(('gpu.pass_data', gpu_pass_payload)) return payloads @@ -153,8 +212,8 @@ class BenchmarkDataAggregator(object): 'gitCommitAndBuildDate': f'{git_commit_hash} {build_date}', 'RHI': rhi } - frame_stats, pass_stats = self._process_benchmark(benchmark_dir, benchmark_metadata) - payloads = self._generate_payloads(benchmark_metadata, frame_stats, pass_stats) + gpu_frame_stats, gpu_pass_stats, cpu_frame_stats = self._process_benchmark(benchmark_dir, benchmark_metadata) + payloads = self._generate_payloads(benchmark_metadata, gpu_frame_stats, gpu_pass_stats, cpu_frame_stats) for index_suffix, payload in payloads: self.filebeat_client.send_event( diff --git a/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py b/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py index 29484617d1..0851c63681 100644 --- a/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py +++ b/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py @@ -6,6 +6,8 @@ SPDX-License-Identifier: Apache-2.0 OR MIT """ import pytest +from _pytest.skipping import pytest_runtest_setup as skipping_pytest_runtest_setup + import inspect from typing import List from abc import ABC @@ -333,6 +335,10 @@ class EditorTestSuite(): next(wrap, None) return single_run setattr(self.obj, name, make_test_func(name, test_spec)) + f = make_test_func(name, test_spec) + if hasattr(test_spec, "pytestmark"): + f.pytestmark = test_spec.pytestmark + setattr(self.obj, name, f) # Add the shared tests, for these we will create a runner class for storing the run information # that will be later used for selecting what tests runners will be run @@ -359,6 +365,8 @@ class EditorTestSuite(): return result result_func = make_func(test_spec) + if hasattr(test_spec, "pytestmark"): + result_func.pytestmark = test_spec.pytestmark setattr(self.obj, test_spec.__name__, result_func) runners.append(runner) @@ -450,8 +458,15 @@ class EditorTestSuite(): def filter_session_shared_tests(session_items, shared_tests): # Retrieve the test sub-set that was collected # this can be less than the original set if were overriden via -k argument or similars - collected_elem_names = [test.originalname for test in session_items] - selected_shared_tests = [test for test in shared_tests if test.__name__ in collected_elem_names] + def will_run(item): + try: + skipping_pytest_runtest_setup(item) + return True + except: + return False + + session_items_by_name = { item.originalname:item for item in session_items } + selected_shared_tests = [test for test in shared_tests if test.__name__ in session_items_by_name.keys() and will_run(session_items_by_name[test.__name__])] return selected_shared_tests @staticmethod diff --git a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake index d6e7172324..ab7432e09e 100644 --- a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake +++ b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake @@ -7,7 +7,6 @@ # # shared by other platforms: -ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) @@ -28,3 +27,4 @@ ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-android TARGETS goo ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-android TARGETS GoogleBenchmark PACKAGE_HASH 20b46e572211a69d7d94ddad1c89ec37bb958711d6ad4025368ac89ea83078fb) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-android TARGETS libsamplerate PACKAGE_HASH bf13662afe65d02bcfa16258a4caa9b875534978227d6f9f36c9cfa92b3fb12b) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-android TARGETS OpenSSL PACKAGE_HASH 4036d4019d722f0e1b7a1621bf60b5a17ca6a65c9c78fd8701cee1131eec8480) +ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev1-android TARGETS zlib PACKAGE_HASH 832b163cae0cccbe4fddc5988f5725fac56ef7dba5bfe95bf8c71281fba2e12c) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 7bb2c61774..bb70a54d6f 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -7,7 +7,6 @@ # # shared by other platforms: -ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) 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 assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) @@ -46,3 +45,6 @@ ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-linux ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev2-linux TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 235606f98512c076a1ba84a8402ad24ac21945998abcea264e8e204678efc0ba) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-linux TARGETS SPIRVCross PACKAGE_HASH 7889ee5460a688e9b910c0168b31445c0079d363affa07b25d4c8aeb608a0b80) ly_associate_package(PACKAGE_NAME azslc-1.7.23-rev2-linux TARGETS azslc PACKAGE_HASH 1ba84d8321a566d35a1e9aa7400211ba8e6d1c11c08e4be3c93e6e74b8f7aef1) +ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev1-linux TARGETS zlib PACKAGE_HASH 6418e93b9f4e6188f3b62cbd3a7822e1c4398a716e786d1522b809a727d08ba9) + + diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index bdffbd5dc7..e66dfdaca1 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -7,7 +7,6 @@ # # shared by other platforms: -ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) 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 assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) @@ -44,3 +43,4 @@ ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-mac 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-rev5-mac TARGETS Qt PACKAGE_HASH 9d25918351898b308ded3e9e571fff6f26311b2071aeafd00dd5b249fdf53f7e) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) +ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev1-mac TARGETS zlib PACKAGE_HASH 7fd8a77b3598423d9d6be5f8c60d52aecf346ab4224f563a5282db283aa0da02) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index 0134a45565..4ac5fea18c 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -7,7 +7,6 @@ # # shared by other platforms: -ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) 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 assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) @@ -52,3 +51,4 @@ ly_associate_package(PACKAGE_NAME OpenMesh-8.1-rev1-windows ly_associate_package(PACKAGE_NAME civetweb-1.8-rev1-windows TARGETS civetweb PACKAGE_HASH 36d0e58a59bcdb4dd70493fb1b177aa0354c945b06c30416348fd326cf323dd4) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-windows TARGETS OpenSSL PACKAGE_HASH 9af1c50343f89146b4053101a7aeb20513319a3fe2f007e356d7ce25f9241040) ly_associate_package(PACKAGE_NAME Crashpad-0.8.0-rev1-windows TARGETS Crashpad PACKAGE_HASH d162aa3070147bc0130a44caab02c5fe58606910252caf7f90472bd48d4e31e2) +ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev1-windows TARGETS zlib PACKAGE_HASH 6fb46a0ef8c8614cde3517b50fca47f2a6d1fd059b21f3b8ff13e635ca7f2fa6) diff --git a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake index b058183c5a..ac7a7427ca 100644 --- a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake +++ b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake @@ -7,7 +7,6 @@ # # shared by other platforms: -ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-multiplatform TARGETS RapidJSON PACKAGE_HASH 18b0aef4e6e849389916ff6de6682ab9c591ebe15af6ea6017014453c1119ea1) ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) @@ -29,3 +28,4 @@ ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-ios TARGETS googlet ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-ios TARGETS GoogleBenchmark PACKAGE_HASH c2ffaed2b658892b1bcf81dee4b44cd1cb09fc78d55584ef5cb8ab87f2d8d1ae) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-ios TARGETS libsamplerate PACKAGE_HASH 7656b961697f490d4f9c35d2e61559f6fc38c32102e542a33c212cd618fc2119) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-ios TARGETS OpenSSL PACKAGE_HASH cd0dfce3086a7172777c63dadbaf0ac3695b676119ecb6d0614b5fb1da03462f) +ly_associate_package(PACKAGE_NAME zlib-1.2.11-rev1-ios TARGETS zlib PACKAGE_HASH 20bfccf3b98bd9a7d3506cf344ac48135035eb517752bf9bede1e821f163608d) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 353c015fd3..2b56a1f0b4 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -448,11 +448,15 @@ endfunction() function(ly_setup_runtime_dependencies) # Common functions used by the bellow code - install(CODE + if(COMMAND ly_install_code_function_override) + ly_install_code_function_override() + else() + install(CODE "function(ly_copy source_file target_directory) file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) endfunction()" - ) + ) + endif() unset(runtime_commands) get_property(all_targets GLOBAL PROPERTY LY_ALL_TARGETS) diff --git a/cmake/Platform/Mac/Install_mac.cmake b/cmake/Platform/Mac/Install_mac.cmake index 808299e09d..c7f22e9149 100644 --- a/cmake/Platform/Mac/Install_mac.cmake +++ b/cmake/Platform/Mac/Install_mac.cmake @@ -6,6 +6,34 @@ # # +# This is used to generate a setreg file which will be placed inside the bundle +# for targets that request it(eg. AssetProcessor/Editor). This is the relative path +# to the bundle from the installed engine's root. This will be used to compute the +# absolute path to bundle which may contain dependent dylibs(eg. Gems) used by a project. +set(installed_binaries_path_template [[ +{ + "Amazon": { + "AzCore": { + "Runtime": { + "FilePaths": { + "InstalledBinariesFolder": "bin/Mac/$" + } + } + } + } +}]] +) + +unset(target_conf_dir) +foreach(conf IN LISTS CMAKE_CONFIGURATION_TYPES) + string(TOUPPER ${conf} UCONF) + string(APPEND target_conf_dir $<$:${CMAKE_RUNTIME_OUTPUT_DIRECTORY_${UCONF}}>) +endforeach() + +set(installed_binaries_setreg_path ${target_conf_dir}/Registry/installed_binaries_path.setreg) + +file(GENERATE OUTPUT ${installed_binaries_setreg_path} CONTENT ${installed_binaries_path_template}) + #! ly_install_target_override: Mac specific target installation function(ly_install_target_override) @@ -49,4 +77,26 @@ function(ly_install_target_override) endif() endfunction() +#! ly_install_add_install_path_setreg: Adds the install path setreg file as a dependency +function(ly_install_add_install_path_setreg NAME) + set_property(TARGET ${NAME} APPEND PROPERTY INTERFACE_LY_TARGET_FILES "${installed_binaries_setreg_path}\nRegistry") +endfunction() + +#! ly_install_code_function_override: Mac specific copy function to handle frameworks +function(ly_install_code_function_override) + + install(CODE +"function(ly_copy source_file target_directory) + if(\"\${source_file}\" MATCHES \"\\\\.[Ff]ramework[^\\\\.]\") + + # fixup origin to copy the whole Framework folder + string(REGEX REPLACE \"(.*\\\\.[Ff]ramework).*\" \"\\\\1\" source_file \"\${source_file}\") + get_filename_component(target_filename \"\${source_file}\" NAME) + + endif() + file(COPY \"\${source_file}\" DESTINATION \"\${target_directory}\" FILE_PERMISSIONS ${LY_COPY_PERMISSIONS}) +endfunction()") + +endfunction() + include(cmake/Platform/Common/Install_common.cmake) diff --git a/cmake/Platform/Mac/LYWrappers_mac.cmake b/cmake/Platform/Mac/LYWrappers_mac.cmake index 2254d422b0..578f6fe041 100644 --- a/cmake/Platform/Mac/LYWrappers_mac.cmake +++ b/cmake/Platform/Mac/LYWrappers_mac.cmake @@ -11,6 +11,7 @@ function(ly_apply_platform_properties target) set_target_properties(${target} PROPERTIES BUILD_RPATH "@executable_path/;@executable_path/../Frameworks" + INSTALL_RPATH "@executable_path/;@executable_path/../Frameworks" ) endfunction() diff --git a/cmake/TestImpactFramework/ConsoleFrontendConfig.in b/cmake/TestImpactFramework/ConsoleFrontendConfig.in index e4111fb9cd..17fbd217d7 100644 --- a/cmake/TestImpactFramework/ConsoleFrontendConfig.in +++ b/cmake/TestImpactFramework/ConsoleFrontendConfig.in @@ -1,7 +1,8 @@ { "meta": { "platform": "${platform}", - "timestamp": "${timestamp}" + "timestamp": "${timestamp}", + "build_config": "${build_config}" }, "jenkins": { "use_test_impact_analysis": ${use_tiaf} @@ -32,8 +33,7 @@ "historic": { "root": "${historic_dir}", "relative_paths": { - "last_run_hash_file": "last_run.hash", - "last_build_target_list_file": "LastRunBuildTargets.json" + "data": "historic_data.json" } } }, diff --git a/cmake/TestImpactFramework/LYTestImpactFramework.cmake b/cmake/TestImpactFramework/LYTestImpactFramework.cmake index 61cc8c200a..7dd2617582 100644 --- a/cmake/TestImpactFramework/LYTestImpactFramework.cmake +++ b/cmake/TestImpactFramework/LYTestImpactFramework.cmake @@ -22,10 +22,10 @@ set(LY_TEST_IMPACT_CONSOLE_TARGET "TestImpact.Frontend.Console") set(LY_TEST_IMPACT_WORKING_DIR "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/TestImpactFramework") # Directory for artifacts generated at runtime -set(LY_TEST_IMPACT_TEMP_DIR "${LY_TEST_IMPACT_WORKING_DIR}/Temp") +set(LY_TEST_IMPACT_TEMP_DIR "${LY_TEST_IMPACT_WORKING_DIR}/$/Temp") # Directory for files that persist between runtime runs -set(LY_TEST_IMPACT_PERSISTENT_DIR "${LY_TEST_IMPACT_WORKING_DIR}/Persistent") +set(LY_TEST_IMPACT_PERSISTENT_DIR "${LY_TEST_IMPACT_WORKING_DIR}/$/Persistent") # Directory for static artifacts produced as part of the build system generation process set(LY_TEST_IMPACT_ARTIFACT_DIR "${LY_TEST_IMPACT_WORKING_DIR}/Artifact") @@ -43,7 +43,7 @@ set(LY_TEST_IMPACT_TEST_TYPE_FILE "${LY_TEST_IMPACT_ARTIFACT_DIR}/TestType/All.t set(LY_TEST_IMPACT_GEM_TARGET_FILE "${LY_TEST_IMPACT_ARTIFACT_DIR}/BuildType/All.gems") # Path to the config file for each build configuration -set(LY_TEST_IMPACT_CONFIG_FILE_PATH "${LY_TEST_IMPACT_PERSISTENT_DIR}/tiaf.$.json") +set(LY_TEST_IMPACT_CONFIG_FILE_PATH "${LY_TEST_IMPACT_PERSISTENT_DIR}/tiaf.json") # Preprocessor directive for the config file path set(LY_TEST_IMPACT_CONFIG_FILE_PATH_DEFINITION "LY_TEST_IMPACT_DEFAULT_CONFIG_FILE=\"${LY_TEST_IMPACT_CONFIG_FILE_PATH}\"") @@ -379,6 +379,9 @@ function(ly_test_impact_write_config_file CONFIG_TEMPLATE_FILE BIN_DIR) # Timestamp this config file was generated at string(TIMESTAMP timestamp "%Y-%m-%d %H:%M:%S") + # Build configuration this config file is being generated for + set(build_config "$") + # Instrumentation binary if(NOT LY_TEST_IMPACT_INSTRUMENTATION_BIN) # No binary specified is not an error, it just means that the test impact analysis part of the framework is disabled diff --git a/scripts/build/Jenkins/Jenkinsfile b/scripts/build/Jenkins/Jenkinsfile index 9aa09e136e..30efdc00ad 100644 --- a/scripts/build/Jenkins/Jenkinsfile +++ b/scripts/build/Jenkins/Jenkinsfile @@ -370,7 +370,7 @@ def TestMetrics(Map pipelineConfig, String workspace, String branchName, String def command = "${pipelineConfig.PYTHON_DIR}/python.cmd -u mars/scripts/python/ctest_test_metric_scraper.py " + '-e jenkins.creds.user %username% -e jenkins.creds.pass %apitoken% ' + "-e jenkins.base_url ${env.JENKINS_URL} " + - "${cmakeBuildDir} ${branchName} %BUILD_NUMBER% AR ${configuration} ${repoName} --url ${env.BUILD_URL}" + "${cmakeBuildDir} ${branchName} %BUILD_NUMBER% AR ${configuration} ${repoName} --url ${env.BUILD_URL.replace('%','%%')}" bat label: "Publishing ${buildJobName} Test Metrics", script: command } @@ -695,13 +695,19 @@ finally { ) } node('controller') { - step([ - $class: 'Mailer', - notifyEveryUnstableBuild: true, - recipients: emailextrecipients([ + if("${currentBuild.currentResult}" == "SUCCESS") { + emailBody = "${BUILD_URL}\nSuccess!" + } else { + buildFailure = tm('${BUILD_FAILURE_ANALYZER}') + emailBody = "${BUILD_URL}\n${buildFailure}!" + } + emailext ( + body: "${emailBody}", + subject: "${currentBuild.currentResult}: ${JOB_NAME} - Build # ${BUILD_NUMBER}", + recipientProviders: [ [$class: 'RequesterRecipientProvider'] - ]) - ]) + ] + ) } } catch(Exception e) { } diff --git a/scripts/build/Platform/Windows/build_config.json b/scripts/build/Platform/Windows/build_config.json index 235e1406ab..8ac0b5241c 100644 --- a/scripts/build/Platform/Windows/build_config.json +++ b/scripts/build/Platform/Windows/build_config.json @@ -89,7 +89,7 @@ "CONFIGURATION": "profile", "SCRIPT_PATH": "scripts/build/TestImpactAnalysis/tiaf_driver.py", "SCRIPT_PARAMETERS": - "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/persistent/tiaf.profile.json\" --suite=main --test-failure-policy=continue --src-branch=!BRANCH_NAME! --dst-branch=!CHANGE_TARGET! --pipeline=!PIPELINE_NAME! --dest-commit=!CHANGE_ID! --seeding-branches=!BUILD_SNAPSHOTS! --seeding-pipelines=default" + "--config=\"!OUTPUT_DIRECTORY!/bin/TestImpactFramework/profile/Persistent/tiaf.json\" --src-branch=!BRANCH_NAME! --dst-branch=!BRANCH_NAME! --commit=!CHANGE_ID! --s3-bucket=!TEST_IMPACT_S3_BUCKET! --mars-index-prefix=jonawals --suite=main --test-failure-policy=continue" } }, "debug_vs2019": { diff --git a/scripts/build/TestImpactAnalysis/git_utils.py b/scripts/build/TestImpactAnalysis/git_utils.py index ec31ab1f53..04d994ba4a 100644 --- a/scripts/build/TestImpactAnalysis/git_utils.py +++ b/scripts/build/TestImpactAnalysis/git_utils.py @@ -6,34 +6,67 @@ # # -import os import subprocess import git +import pathlib -# Returns True if the dst commit descends from the src commit, otherwise False -def is_descendent(src_commit_hash, dst_commit_hash): - if src_commit_hash is None or dst_commit_hash is None: - return False - result = subprocess.run(["git", "merge-base", "--is-ancestor", src_commit_hash, dst_commit_hash]) - return result.returncode == 0 - -# Attempts to create a diff from the src and dst commits and write to the specified output file -def create_diff_file(src_commit_hash, dst_commit_hash, output_path): - if os.path.isfile(output_path): - os.remove(output_path) - os.makedirs(os.path.dirname(output_path), exist_ok=True) - # git diff will only write to the output file if both commit hashes are valid - subprocess.run(["git", "diff", "--name-status", f"--output={output_path}", src_commit_hash, dst_commit_hash]) - if not os.path.isfile(output_path): - raise FileNotFoundError(f"Source commit '{src_commit_hash}' and/or destination commit '{dst_commit_hash}' are invalid") - -# Basic representation of a repository +# Basic representation of a git repository class Repo: - def __init__(self, repo_path): - self.__repo = git.Repo(repo_path) + def __init__(self, repo_path: str): + self._repo = git.Repo(repo_path) # Returns the current branch @property def current_branch(self): - branch = self.__repo.active_branch + branch = self._repo.active_branch return branch.name + + def create_diff_file(self, src_commit_hash: str, dst_commit_hash: str, output_path: pathlib.Path): + """ + Attempts to create a diff from the src and dst commits and write to the specified output file. + + @param src_commit_hash: The hash for the source commit. + @param dst_commit_hash: The hash for the destination commit. + @param output_path: The path to the file to write the diff to. + """ + + try: + # Remove the existing file (if any) and create the parent directory + output_path.unlink(missing_ok=True) + output_path.parent.mkdir(exist_ok=True) + except EnvironmentError as e: + raise RuntimeError(f"Could not create path for output file '{output_path}'") + + # git diff will only write to the output file if both commit hashes are valid + subprocess.run(["git", "diff", "--name-status", f"--output={output_path}", src_commit_hash, dst_commit_hash]) + if not output_path.is_file(): + raise RuntimeError(f"Source commit '{src_commit_hash}' and/or destination commit '{dst_commit_hash}' are invalid") + + def is_descendent(self, src_commit_hash: str, dst_commit_hash: str): + """ + Determines whether or not dst_commit is a descendent of src_commit. + + @param src_commit_hash: The hash for the source commit. + @param dst_commit_hash: The hash for the destination commit. + @return: True if the dst commit descends from the src commit, otherwise False. + """ + + if not src_commit_hash and not dst_commit_hash: + return False + result = subprocess.run(["git", "merge-base", "--is-ancestor", src_commit_hash, dst_commit_hash]) + return result.returncode == 0 + + # Returns the distance between two commits + def commit_distance(self, src_commit_hash: str, dst_commit_hash: str): + """ + Determines the number of commits between src_commit and dst_commit. + + @param src_commit_hash: The hash for the source commit. + @param dst_commit_hash: The hash for the destination commit. + @return: The distance between src_commit and dst_commit (if both are valid commits), otherwise None. + """ + + if not src_commit_hash and not dst_commit_hash: + return None + commits = self._repo.iter_commits(src_commit_hash + '..' + dst_commit_hash) + return len(list(commits)) diff --git a/scripts/build/TestImpactAnalysis/mars_utils.py b/scripts/build/TestImpactAnalysis/mars_utils.py new file mode 100644 index 0000000000..69374512a3 --- /dev/null +++ b/scripts/build/TestImpactAnalysis/mars_utils.py @@ -0,0 +1,452 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import datetime +import json +import socket +from tiaf_logger import get_logger + +logger = get_logger(__file__) + +MARS_JOB_KEY = "job" +SRC_COMMIT_KEY = "src_commit" +DST_COMMIT_KEY = "src_commit" +COMMIT_DISTANCE_KEY = "commit_distance" +SRC_BRANCH_KEY = "src_branch" +DST_BRANCH_KEY = "dst_branch" +SUITE_KEY = "suite" +SOURCE_OF_TRUTH_BRANCH_KEY = "source_of_truth_branch" +IS_SOURCE_OF_TRUTH_BRANCH_KEY = "is_source_of_truth_branch" +USE_TEST_IMPACT_ANALYSIS_KEY = "use_test_impact_analysis" +HAS_CHANGE_LIST_KEY = "has_change_list" +HAS_HISTORIC_DATA_KEY = "has_historic_data" +S3_BUCKET_KEY = "s3_bucket" +DRIVER_ARGS_KEY = "driver_args" +RUNTIME_ARGS_KEY = "runtime_args" +RUNTIME_RETURN_CODE_KEY = "return_code" +NAME_KEY = "name" +RESULT_KEY = "result" +NUM_PASSING_TESTS_KEY = "num_passing_tests" +NUM_FAILING_TESTS_KEY = "num_failing_tests" +NUM_DISABLED_TESTS_KEY = "num_disabled_tests" +COMMAND_ARGS_STRING = "command_args" +NUM_PASSING_TEST_RUNS_KEY = "num_passing_test_runs" +NUM_FAILING_TEST_RUNS_KEY = "num_failing_test_runs" +NUM_EXECUTION_FAILURE_TEST_RUNS_KEY = "num_execution_failure_test_runs" +NUM_TIMED_OUT_TEST_RUNS_KEY = "num_timed_out_test_runs" +NUM_UNEXECUTED_TEST_RUNS_KEY = "num_unexecuted_test_runs" +TOTAL_NUM_PASSING_TESTS_KEY = "total_num_passing_tests" +TOTAL_NUM_FAILING_TESTS_KEY = "total_num_failing_tests" +TOTAL_NUM_DISABLED_TESTS_KEY = "total_num_disabled_tests" +START_TIME_KEY = "start_time" +END_TIME_KEY = "end_time" +DURATION_KEY = "duration" +INCLUDED_TEST_RUNS_KEY = "included_test_runs" +EXCLUDED_TEST_RUNS_KEY = "excluded_test_runs" +NUM_INCLUDED_TEST_RUNS_KEY = "num_included_test_runs" +NUM_EXCLUDED_TEST_RUNS_KEY = "num_excluded_test_runs" +TOTAL_NUM_TEST_RUNS_KEY = "total_num_test_runs" +PASSING_TEST_RUNS_KEY = "passing_test_runs" +FAILING_TEST_RUNS_KEY = "failing_test_runs" +EXECUTION_FAILURE_TEST_RUNS_KEY = "execution_failure_test_runs" +TIMED_OUT_TEST_RUNS_KEY = "timed_out_test_runs" +UNEXECUTED_TEST_RUNS_KEY = "unexecuted_test_runs" +TOTAL_NUM_PASSING_TEST_RUNS_KEY = "total_num_passing_test_runs" +TOTAL_NUM_FAILING_TEST_RUNS_KEY = "total_num_failing_test_runs" +TOTAL_NUM_EXECUTION_FAILURE_TEST_RUNS_KEY = "total_num_execution_failure_test_runs" +TOTAL_NUM_TIMED_OUT_TEST_RUNS_KEY = "total_num_timed_out_test_runs" +TOTAL_NUM_UNEXECUTED_TEST_RUNS_KEY = "total_num_unexecuted_test_runs" +SEQUENCE_TYPE_KEY = "type" +IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY = "impact_analysis" +SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY = "safe_impact_analysis" +SEED_SEQUENCE_TYPE_KEY = "seed" +TEST_TARGET_TIMEOUT_KEY = "test_target_timeout" +GLOBAL_TIMEOUT_KEY = "global_timeout" +MAX_CONCURRENCY_KEY = "max_concurrency" +SELECTED_KEY = "selected" +DRAFTED_KEY = "drafted" +DISCARDED_KEY = "discarded" +SELECTED_TEST_RUN_REPORT_KEY = "selected_test_run_report" +DISCARDED_TEST_RUN_REPORT_KEY = "discarded_test_run_report" +DRAFTED_TEST_RUN_REPORT_KEY = "drafted_test_run_report" +SELECTED_TEST_RUNS_KEY = "selected_test_runs" +DRAFTED_TEST_RUNS_KEY = "drafted_test_runs" +DISCARDED_TEST_RUNS_KEY = "discarded_test_runs" +INSTRUMENTATION_KEY = "instrumentation" +EFFICIENCY_KEY = "efficiency" +CONFIG_KEY = "config" +POLICY_KEY = "policy" +CHANGE_LIST_KEY = "change_list" +TEST_RUN_SELECTION_KEY = "test_run_selection" +DYNAMIC_DEPENDENCY_MAP_POLICY_KEY = "dynamic_dependency_map" +DYNAMIC_DEPENDENCY_MAP_POLICY_UPDATE_KEY = "update" +REPORT_KEY = "report" + +class FilebeatExn(Exception): + pass + +class FilebeatClient(object): + def __init__(self, host="127.0.0.1", port=9000, timeout=20): + self._filebeat_host = host + self._filebeat_port = port + self._socket_timeout = timeout + self._socket = None + + self._open_socket() + + def send_event(self, payload, index, timestamp=None, pipeline="filebeat"): + if not timestamp: + timestamp = datetime.datetime.utcnow().timestamp() + + event = { + "index": index, + "timestamp": timestamp, + "pipeline": pipeline, + "payload": json.dumps(payload) + } + + # Serialise event, add new line and encode as UTF-8 before sending to Filebeat. + data = json.dumps(event, sort_keys=True) + "\n" + data = data.encode() + + #print(f"-> {data}") + self._send_data(data) + + def _open_socket(self): + logger.info(f"Connecting to Filebeat on {self._filebeat_host}:{self._filebeat_port}") + + self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._socket.settimeout(self._socket_timeout) + + try: + self._socket.connect((self._filebeat_host, self._filebeat_port)) + except (ConnectionError, socket.timeout): + raise FilebeatExn("Failed to connect to Filebeat") from None + + def _send_data(self, data): + total_sent = 0 + + while total_sent < len(data): + try: + sent = self._socket.send(data[total_sent:]) + except BrokenPipeError: + logging.error("Filebeat socket closed by peer") + self._socket.close() + self._open_socket() + total_sent = 0 + else: + total_sent = total_sent + sent + +def format_timestamp(timestamp: float): + """ + Formats the given floating point timestamp into "yyyy-MM-dd'T'HH:mm:ss.SSSXX" format. + + @param timestamp: The timestamp to format. + @return: The formatted timestamp. + """ + return datetime.datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" + +def generate_mars_timestamp(t0_offset_milliseconds: int, t0_timestamp: float): + """ + Generates a MARS timestamp in the format "yyyy-MM-dd'T'HH:mm:ss.SSSXX" by offsetting the T0 timestamp + by the specified amount of milliseconds. + + @param t0_offset_milliseconds: The amount of time to offset from T0. + @param t0_timestamp: The T0 timestamp that TIAF timings will be offst from. + @return: The formatted timestamp offset from T0 by the specified amount of milliseconds. + """ + + t0_offset_seconds = get_duration_in_seconds(t0_offset_milliseconds) + t0_offset_timestamp = t0_timestamp + t0_offset_seconds + return format_timestamp(t0_offset_timestamp) + +def get_duration_in_seconds(duration_in_milliseconds: int): + """ + Gets the specified duration in milliseconds (as used by TIAF) in seconds (as used my MARS documents). + + @param duration_in_milliseconds: The millisecond duration to transform into seconds. + @return: The duration in seconds. + """ + + return duration_in_milliseconds * 0.001 + +def generate_mars_job(tiaf_result, driver_args): + """ + Generates a MARS job document using the job meta-data used to drive the TIAF sequence. + + @param tiaf_result: The result object generated by the TIAF script. + @param driver_args: The arguments specified to the driver script. + @return: The MARS job document with the job meta-data. + """ + + mars_job = {key:tiaf_result[key] for key in + [ + SRC_COMMIT_KEY, + DST_COMMIT_KEY, + COMMIT_DISTANCE_KEY, + SRC_BRANCH_KEY, + DST_BRANCH_KEY, + SUITE_KEY, + SOURCE_OF_TRUTH_BRANCH_KEY, + IS_SOURCE_OF_TRUTH_BRANCH_KEY, + USE_TEST_IMPACT_ANALYSIS_KEY, + HAS_CHANGE_LIST_KEY, + HAS_HISTORIC_DATA_KEY, + S3_BUCKET_KEY, + RUNTIME_ARGS_KEY, + RUNTIME_RETURN_CODE_KEY + ]} + + mars_job[DRIVER_ARGS_KEY] = driver_args + return mars_job + +def generate_test_run_list(test_runs): + """ + Generates a list of test run name strings from the list of TIAF test runs. + + @param test_runs: The list of TIAF test runs to generate the name strings from. + @return: The list of test run name strings. + """ + + test_run_list = [] + for test_run in test_runs: + test_run_list.append(test_run[NAME_KEY]) + return test_run_list + +def generate_mars_test_run_selections(test_run_selection, test_run_report, t0_timestamp: float): + """ + Generates a list of MARS test run selections from a TIAF test run selection and report. + + @param test_run_selection: The TIAF test run selection. + @param test_run_report: The TIAF test run report. + @param t0_timestamp: The T0 timestamp that TIAF timings will be offst from. + @return: The list of TIAF test runs. + """ + + mars_test_run_selection = {key:test_run_report[key] for key in + [ + RESULT_KEY, + NUM_PASSING_TEST_RUNS_KEY, + NUM_FAILING_TEST_RUNS_KEY, + NUM_EXECUTION_FAILURE_TEST_RUNS_KEY, + NUM_TIMED_OUT_TEST_RUNS_KEY, + NUM_UNEXECUTED_TEST_RUNS_KEY, + TOTAL_NUM_PASSING_TESTS_KEY, + TOTAL_NUM_FAILING_TESTS_KEY, + TOTAL_NUM_DISABLED_TESTS_KEY + ]} + + mars_test_run_selection[START_TIME_KEY] = generate_mars_timestamp(test_run_report[START_TIME_KEY], t0_timestamp) + mars_test_run_selection[END_TIME_KEY] = generate_mars_timestamp(test_run_report[END_TIME_KEY], t0_timestamp) + mars_test_run_selection[DURATION_KEY] = get_duration_in_seconds(test_run_report[DURATION_KEY]) + + mars_test_run_selection[INCLUDED_TEST_RUNS_KEY] = test_run_selection[INCLUDED_TEST_RUNS_KEY] + mars_test_run_selection[EXCLUDED_TEST_RUNS_KEY] = test_run_selection[EXCLUDED_TEST_RUNS_KEY] + mars_test_run_selection[NUM_INCLUDED_TEST_RUNS_KEY] = test_run_selection[NUM_INCLUDED_TEST_RUNS_KEY] + mars_test_run_selection[NUM_EXCLUDED_TEST_RUNS_KEY] = test_run_selection[NUM_EXCLUDED_TEST_RUNS_KEY] + mars_test_run_selection[TOTAL_NUM_TEST_RUNS_KEY] = test_run_selection[TOTAL_NUM_TEST_RUNS_KEY] + + mars_test_run_selection[PASSING_TEST_RUNS_KEY] = generate_test_run_list(test_run_report[PASSING_TEST_RUNS_KEY]) + mars_test_run_selection[FAILING_TEST_RUNS_KEY] = generate_test_run_list(test_run_report[FAILING_TEST_RUNS_KEY]) + mars_test_run_selection[EXECUTION_FAILURE_TEST_RUNS_KEY] = generate_test_run_list(test_run_report[EXECUTION_FAILURE_TEST_RUNS_KEY]) + mars_test_run_selection[TIMED_OUT_TEST_RUNS_KEY] = generate_test_run_list(test_run_report[TIMED_OUT_TEST_RUNS_KEY]) + mars_test_run_selection[UNEXECUTED_TEST_RUNS_KEY] = generate_test_run_list(test_run_report[UNEXECUTED_TEST_RUNS_KEY]) + + return mars_test_run_selection + +def generate_test_runs_from_list(test_run_list: list): + """ + Generates a list of TIAF test runs from a list of test target name strings. + + @param test_run_list: The list of test target names. + @return: The list of TIAF test runs. + """ + + test_run_list = { + TOTAL_NUM_TEST_RUNS_KEY: len(test_run_list), + NUM_INCLUDED_TEST_RUNS_KEY: len(test_run_list), + NUM_EXCLUDED_TEST_RUNS_KEY: 0, + INCLUDED_TEST_RUNS_KEY: test_run_list, + EXCLUDED_TEST_RUNS_KEY: [] + } + + return test_run_list + +def generate_mars_sequence(sequence_report: dict, mars_job: dict, change_list:dict, t0_timestamp: float): + """ + Generates the MARS sequence document from the specified TIAF sequence report. + + @param sequence_report: The TIAF runtime sequence report. + @param mars_job: The MARS job for this sequence. + @param change_list: The change list for which the TIAF sequence was run. + @param t0_timestamp: The T0 timestamp that TIAF timings will be offst from. + @return: The MARS sequence document for the specified TIAF sequence report. + """ + + mars_sequence = {key:sequence_report[key] for key in + [ + SEQUENCE_TYPE_KEY, + RESULT_KEY, + POLICY_KEY, + TOTAL_NUM_TEST_RUNS_KEY, + TOTAL_NUM_PASSING_TEST_RUNS_KEY, + TOTAL_NUM_FAILING_TEST_RUNS_KEY, + TOTAL_NUM_EXECUTION_FAILURE_TEST_RUNS_KEY, + TOTAL_NUM_TIMED_OUT_TEST_RUNS_KEY, + TOTAL_NUM_UNEXECUTED_TEST_RUNS_KEY, + TOTAL_NUM_PASSING_TESTS_KEY, + TOTAL_NUM_FAILING_TESTS_KEY, + TOTAL_NUM_DISABLED_TESTS_KEY + ]} + + mars_sequence[START_TIME_KEY] = generate_mars_timestamp(sequence_report[START_TIME_KEY], t0_timestamp) + mars_sequence[END_TIME_KEY] = generate_mars_timestamp(sequence_report[END_TIME_KEY], t0_timestamp) + mars_sequence[DURATION_KEY] = get_duration_in_seconds(sequence_report[DURATION_KEY]) + + config = {key:sequence_report[key] for key in + [ + TEST_TARGET_TIMEOUT_KEY, + GLOBAL_TIMEOUT_KEY, + MAX_CONCURRENCY_KEY + ]} + + test_run_selection = {} + test_run_selection[SELECTED_KEY] = generate_mars_test_run_selections(sequence_report[SELECTED_TEST_RUNS_KEY], sequence_report[SELECTED_TEST_RUN_REPORT_KEY], t0_timestamp) + if sequence_report[SEQUENCE_TYPE_KEY] == IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY or sequence_report[SEQUENCE_TYPE_KEY] == SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY: + total_test_runs = sequence_report[TOTAL_NUM_TEST_RUNS_KEY] + if total_test_runs > 0: + test_run_selection[SELECTED_KEY][EFFICIENCY_KEY] = (1.0 - (test_run_selection[SELECTED_KEY][TOTAL_NUM_TEST_RUNS_KEY] / total_test_runs)) * 100 + else: + test_run_selection[SELECTED_KEY][EFFICIENCY_KEY] = 100 + test_run_selection[DRAFTED_KEY] = generate_mars_test_run_selections(generate_test_runs_from_list(sequence_report[DRAFTED_TEST_RUNS_KEY]), sequence_report[DRAFTED_TEST_RUN_REPORT_KEY], t0_timestamp) + if sequence_report[SEQUENCE_TYPE_KEY] == SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY: + test_run_selection[DISCARDED_KEY] = generate_mars_test_run_selections(sequence_report[DISCARDED_TEST_RUNS_KEY], sequence_report[DISCARDED_TEST_RUN_REPORT_KEY], t0_timestamp) + else: + test_run_selection[SELECTED_KEY][EFFICIENCY_KEY] = 0 + + mars_sequence[MARS_JOB_KEY] = mars_job + mars_sequence[CONFIG_KEY] = config + mars_sequence[TEST_RUN_SELECTION_KEY] = test_run_selection + mars_sequence[CHANGE_LIST_KEY] = change_list + + return mars_sequence + +def extract_mars_test_target(test_run, instrumentation, mars_job, t0_timestamp: float): + """ + Extracts a MARS test target from the specified TIAF test run. + + @param test_run: The TIAF test run. + @param instrumentation: Flag specifying whether or not instrumentation was used for the test targets in this run. + @param mars_job: The MARS job for this test target. + @param t0_timestamp: The T0 timestamp that TIAF timings will be offst from. + @return: The MARS test target documents for the specified TIAF test target. + """ + + mars_test_run = {key:test_run[key] for key in + [ + NAME_KEY, + RESULT_KEY, + NUM_PASSING_TESTS_KEY, + NUM_FAILING_TESTS_KEY, + NUM_DISABLED_TESTS_KEY, + COMMAND_ARGS_STRING + ]} + + mars_test_run[START_TIME_KEY] = generate_mars_timestamp(test_run[START_TIME_KEY], t0_timestamp) + mars_test_run[END_TIME_KEY] = generate_mars_timestamp(test_run[END_TIME_KEY], t0_timestamp) + mars_test_run[DURATION_KEY] = get_duration_in_seconds(test_run[DURATION_KEY]) + + mars_test_run[MARS_JOB_KEY] = mars_job + mars_test_run[INSTRUMENTATION_KEY] = instrumentation + return mars_test_run + +def extract_mars_test_targets_from_report(test_run_report, instrumentation, mars_job, t0_timestamp: float): + """ + Extracts the MARS test targets from the specified TIAF test run report. + + @param test_run_report: The TIAF runtime test run report. + @param instrumentation: Flag specifying whether or not instrumentation was used for the test targets in this run. + @param mars_job: The MARS job for these test targets. + @param t0_timestamp: The T0 timestamp that TIAF timings will be offst from. + @return: The list of all MARS test target documents for the test targets in the TIAF test run report. + """ + + mars_test_targets = [] + + for test_run in test_run_report[PASSING_TEST_RUNS_KEY]: + mars_test_targets.append(extract_mars_test_target(test_run, instrumentation, mars_job, t0_timestamp)) + for test_run in test_run_report[FAILING_TEST_RUNS_KEY]: + mars_test_targets.append(extract_mars_test_target(test_run, instrumentation, mars_job, t0_timestamp)) + for test_run in test_run_report[EXECUTION_FAILURE_TEST_RUNS_KEY]: + mars_test_targets.append(extract_mars_test_target(test_run, instrumentation, mars_job, t0_timestamp)) + for test_run in test_run_report[TIMED_OUT_TEST_RUNS_KEY]: + mars_test_targets.append(extract_mars_test_target(test_run, instrumentation, mars_job, t0_timestamp)) + for test_run in test_run_report[UNEXECUTED_TEST_RUNS_KEY]: + mars_test_targets.append(extract_mars_test_target(test_run, instrumentation, mars_job, t0_timestamp)) + + return mars_test_targets + +def generate_mars_test_targets(sequence_report: dict, mars_job: dict, t0_timestamp: float): + """ + Generates a MARS test target document for each test target in the TIAF sequence report. + + @param sequence_report: The TIAF runtime sequence report. + @param mars_job: The MARS job for this sequence. + @param t0_timestamp: The T0 timestamp that TIAF timings will be offst from. + @return: The list of all MARS test target documents for the test targets in the TIAF sequence report. + """ + + mars_test_targets = [] + + # Determine whether or not the test targets were executed with instrumentation + if sequence_report[SEQUENCE_TYPE_KEY] == SEED_SEQUENCE_TYPE_KEY or sequence_report[SEQUENCE_TYPE_KEY] == SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY or (sequence_report[SEQUENCE_TYPE_KEY] == IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY and sequence_report[POLICY_KEY][DYNAMIC_DEPENDENCY_MAP_POLICY_KEY] == DYNAMIC_DEPENDENCY_MAP_POLICY_UPDATE_KEY): + instrumentation = True + else: + instrumentation = False + + # Extract the MARS test target documents from each of the test run reports + mars_test_targets += extract_mars_test_targets_from_report(sequence_report[SELECTED_TEST_RUN_REPORT_KEY], instrumentation, mars_job, t0_timestamp) + if sequence_report[SEQUENCE_TYPE_KEY] == IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY or sequence_report[SEQUENCE_TYPE_KEY] == SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY: + mars_test_targets += extract_mars_test_targets_from_report(sequence_report[DRAFTED_TEST_RUN_REPORT_KEY], instrumentation, mars_job, t0_timestamp) + if sequence_report[SEQUENCE_TYPE_KEY] == SAFE_IMPACT_ANALYSIS_SEQUENCE_TYPE_KEY: + mars_test_targets += extract_mars_test_targets_from_report(sequence_report[DISCARDED_TEST_RUN_REPORT_KEY], instrumentation, mars_job, t0_timestamp) + + return mars_test_targets + +def transmit_report_to_mars(mars_index_prefix: str, tiaf_result: dict, driver_args: list): + """ + Transforms the TIAF result into the appropriate MARS documents and transmits them to MARS. + + @param mars_index_prefix: The index prefix to be used for all MARS documents. + @param tiaf_result: The result object from the TIAF script. + @param driver_args: The arguments passed to the TIAF driver script. + """ + + try: + filebeat = FilebeatClient("localhost", 9000, 60) + + # T0 is the current timestamp that the report timings will be offset from + t0_timestamp = datetime.datetime.now().timestamp() + + # Generate and transmit the MARS job document + mars_job = generate_mars_job(tiaf_result, driver_args) + filebeat.send_event(mars_job, f"{mars_index_prefix}.tiaf.job") + + if tiaf_result[REPORT_KEY]: + # Generate and transmit the MARS sequence document + mars_sequence = generate_mars_sequence(tiaf_result[REPORT_KEY], mars_job, tiaf_result[CHANGE_LIST_KEY], t0_timestamp) + filebeat.send_event(mars_sequence, f"{mars_index_prefix}.tiaf.sequence") + + # Generate and transmit the MARS test target documents + mars_test_targets = generate_mars_test_targets(tiaf_result[REPORT_KEY], mars_job, t0_timestamp) + for mars_test_target in mars_test_targets: + filebeat.send_event(mars_test_target, f"{mars_index_prefix}.tiaf.test_target") + except FilebeatExn as e: + logger.error(e) + except KeyError as e: + logger.error(f"The report does not contain the key {str(e)}.") \ No newline at end of file diff --git a/scripts/build/TestImpactAnalysis/tiaf.py b/scripts/build/TestImpactAnalysis/tiaf.py index ce869b975a..3c94c2b5f4 100644 --- a/scripts/build/TestImpactAnalysis/tiaf.py +++ b/scripts/build/TestImpactAnalysis/tiaf.py @@ -6,237 +6,301 @@ # # -import os import json import subprocess import re -import git_utils +import uuid +import pathlib from git_utils import Repo -from enum import Enum +from tiaf_persistent_storage_local import PersistentStorageLocal +from tiaf_persistent_storage_s3 import PersistentStorageS3 +from tiaf_logger import get_logger -# Returns True if the specified child path is a child of the specified parent path, otherwise False -def is_child_path(parent_path, child_path): - parent_path = os.path.abspath(parent_path) - child_path = os.path.abspath(child_path) - return os.path.commonpath([os.path.abspath(parent_path)]) == os.path.commonpath([os.path.abspath(parent_path), os.path.abspath(child_path)]) +logger = get_logger(__file__) class TestImpact: - def __init__(self, config_file, dst_commit, src_branch, dst_branch, pipeline, seeding_branches, seeding_pipelines): - # Commit - self.__dst_commit = dst_commit - print(f"Commit: '{self.__dst_commit}'.") - self.__src_commit = None - self.__has_src_commit = False - # Branch - self.__src_branch = src_branch - print(f"Source branch: '{self.__src_branch}'.") - self.__dst_branch = dst_branch - print(f"Destination branch: '{self.__dst_branch}'.") - print(f"Seeding branches: '{seeding_branches}'.") - if self.__src_branch in seeding_branches: - self.__is_seeding_branch = True - else: - self.__is_seeding_branch = False - print(f"Is seeding branch: '{self.__is_seeding_branch}'.") - # Pipeline - self.__pipeline = pipeline - print(f"Pipeline: '{self.__pipeline}'.") - print(f"Seeding pipelines: '{seeding_pipelines}'.") - if self.__pipeline in seeding_pipelines: - self.__is_seeding_pipeline = True - else: - self.__is_seeding_pipeline = False - print(f"Is seeding pipeline: '{self.__is_seeding_pipeline}'.") - # Config - self.__parse_config_file(config_file) - # Sequence - if self.__is_seeding_branch and self.__is_seeding_pipeline: - self.__is_seeding = True - else: - self.__is_seeding = False - print(f"Is seeding: '{self.__is_seeding}'.") - if self.__use_test_impact_analysis and not self.__is_seeding: - self.__generate_change_list() - - # Parse the configuration file and retrieve the data needed for launching the test impact analysis runtime - def __parse_config_file(self, config_file): - print(f"Attempting to parse configuration file '{config_file}'...") - with open(config_file, "r") as config_data: - config = json.load(config_data) - self.__repo_dir = config["repo"]["root"] - self.__repo = Repo(self.__repo_dir) - # TIAF - self.__use_test_impact_analysis = config["jenkins"]["use_test_impact_analysis"] - print(f"Is using test impact analysis: '{self.__use_test_impact_analysis}'.") - self.__tiaf_bin = config["repo"]["tiaf_bin"] - if self.__use_test_impact_analysis and not os.path.isfile(self.__tiaf_bin): - raise FileNotFoundError("Could not find tiaf binary") - # Workspaces - self.__active_workspace = config["workspace"]["active"]["root"] - self.__historic_workspace = config["workspace"]["historic"]["root"] - self.__temp_workspace = config["workspace"]["temp"]["root"] - # Last commit hash - last_commit_hash_path_file = config["workspace"]["historic"]["relative_paths"]["last_run_hash_file"] - self.__last_commit_hash_path = os.path.join(self.__historic_workspace, last_commit_hash_path_file) - print("The configuration file was parsed successfully.") - - # Restricts change lists from checking in test impact analysis files - def __check_for_restricted_files(self, file_path): - if is_child_path(self.__active_workspace, file_path) or is_child_path(self.__historic_workspace, file_path) or is_child_path(self.__temp_workspace, file_path): - raise ValueError(f"Checking in test impact analysis framework files is illegal: '{file_path}''.") - - def __read_last_run_hash(self): - self.__has_src_commit = False - if os.path.isfile(self.__last_commit_hash_path): - print(f"Previous commit hash found at '{self.__last_commit_hash_path}'.") - with open(self.__last_commit_hash_path) as file: - self.__src_commit = file.read() - self.__has_src_commit = True - - def __write_last_run_hash(self, last_run_hash): - os.makedirs(self.__historic_workspace, exist_ok=True) - f = open(self.__last_commit_hash_path, "w") - f.write(last_run_hash) - f.close() - - # Determines the change list bewteen now and the last tiaf run (if any) - def __generate_change_list(self): - self.__has_change_list = False - self.__change_list_path = None + def __init__(self, config_file: str): + """ + Initializes the test impact model with the commit, branches as runtime configuration. + + @param config_file: The runtime config file to obtain the runtime configuration data from. + """ + + self._has_change_list = False + self._parse_config_file(config_file) + + def _parse_config_file(self, config_file: str): + """ + Parse the configuration file and retrieve the data needed for launching the test impact analysis runtime. + + @param config_file: The runtime config file to obtain the runtime configuration data from. + """ + + logger.info(f"Attempting to parse configuration file '{config_file}'...") + try: + with open(config_file, "r") as config_data: + self._config = json.load(config_data) + self._repo_dir = self._config["repo"]["root"] + self._repo = Repo(self._repo_dir) + + # TIAF + self._use_test_impact_analysis = self._config["jenkins"]["use_test_impact_analysis"] + self._tiaf_bin = pathlib.Path(self._config["repo"]["tiaf_bin"]) + if self._use_test_impact_analysis and not self._tiaf_bin.is_file(): + logger.warning(f"Could not find TIAF binary at location {self._tiaf_bin}, TIAF will be turned off.") + self._use_test_impact_analysis = False + else: + logger.info(f"Runtime binary found at location {self._tiaf_bin}") + + # Workspaces + self._active_workspace = self._config["workspace"]["active"]["root"] + self._historic_workspace = self._config["workspace"]["historic"]["root"] + self._temp_workspace = self._config["workspace"]["temp"]["root"] + logger.info("The configuration file was parsed successfully.") + except KeyError as e: + logger.error(f"The config does not contain the key {str(e)}.") + return + + def _attempt_to_generate_change_list(self, last_commit_hash, instance_id: str): + """ + Attempts to determine the change list bewteen now and the last tiaf run (if any). + + @param last_commit_hash: The commit hash of the last TIAF run. + @param instance_id: The unique id to derive the change list file name from. + """ + + self._has_change_list = False + self._change_list_path = None + # Check whether or not a previous commit hash exists (no hash is not a failure) - self.__read_last_run_hash() - if self.__has_src_commit == True: - if git_utils.is_descendent(self.__src_commit, self.__dst_commit) == False: - print(f"Source commit '{self.__src_commit}' and destination commit '{self.__dst_commit}' are not related.") + self._src_commit = last_commit_hash + if self._src_commit: + if self._repo.is_descendent(self._src_commit, self._dst_commit) == False: + logger.info(f"Source commit '{self._src_commit}' and destination commit '{self._dst_commit}' are not related.") return - diff_path = os.path.join(self.__temp_workspace, "changelist.diff") + self._commit_distance = self._repo.commit_distance(self._src_commit, self._dst_commit) + diff_path = pathlib.Path(pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{instance_id}.diff")) try: - git_utils.create_diff_file(self.__src_commit, self.__dst_commit, diff_path) - except FileNotFoundError as e: - print(e) + self._repo.create_diff_file(self._src_commit, self._dst_commit, diff_path) + except RuntimeError as e: + logger.error(e) return + # A diff was generated, attempt to parse the diff and construct the change list - print(f"Generated diff between commits '{self.__src_commit}' and '{self.__dst_commit}': '{diff_path}'.") - change_list = {} - change_list["createdFiles"] = [] - change_list["updatedFiles"] = [] - change_list["deletedFiles"] = [] + logger.info(f"Generated diff between commits '{self._src_commit}' and '{self._dst_commit}': '{diff_path}'.") with open(diff_path, "r") as diff_data: lines = diff_data.readlines() for line in lines: match = re.split("^R[0-9]+\\s(\\S+)\\s(\\S+)", line) if len(match) > 1: # File rename - self.__check_for_restricted_files(match[1]) - self.__check_for_restricted_files(match[2]) # Treat renames as a deletion and an addition - change_list["deletedFiles"].append(match[1]) - change_list["createdFiles"].append(match[2]) + self._change_list["deletedFiles"].append(match[1]) + self._change_list["createdFiles"].append(match[2]) else: match = re.split("^[AMD]\\s(\\S+)", line) - self.__check_for_restricted_files(match[1]) if len(match) > 1: if line[0] == 'A': # File addition - change_list["createdFiles"].append(match[1]) + self._change_list["createdFiles"].append(match[1]) elif line[0] == 'M': # File modification - change_list["updatedFiles"].append(match[1]) + self._change_list["updatedFiles"].append(match[1]) elif line[0] == 'D': # File Deletion - change_list["deletedFiles"].append(match[1]) + self._change_list["deletedFiles"].append(match[1]) + # Serialize the change list to the JSON format the test impact analysis runtime expects - change_list_json = json.dumps(change_list, indent = 4) - change_list_path = os.path.join(self.__temp_workspace, "changelist.json") + change_list_json = json.dumps(self._change_list, indent = 4) + change_list_path = pathlib.PurePath(self._temp_workspace).joinpath(f"changelist.{instance_id}.json") f = open(change_list_path, "w") f.write(change_list_json) f.close() - print(f"Change list constructed successfully: '{change_list_path}'.") - print(f"{len(change_list['createdFiles'])} created files, {len(change_list['updatedFiles'])} updated files and {len(change_list['deletedFiles'])} deleted files.") + logger.info(f"Change list constructed successfully: '{change_list_path}'.") + logger.info(f"{len(self._change_list['createdFiles'])} created files, {len(self._change_list['updatedFiles'])} updated files and {len(self._change_list['deletedFiles'])} deleted files.") + # Note: an empty change list generated due to no changes between last and current commit is valid - self.__has_change_list = True - self.__change_list_path = change_list_path + self._has_change_list = True + self._change_list_path = change_list_path else: - print("No previous commit hash found, regular or seeded sequences only will be run.") - self.__has_change_list = False + logger.error("No previous commit hash found, regular or seeded sequences only will be run.") + self._has_change_list = False return - # Runs the specified test sequence - def run(self, suite, test_failure_policy, safe_mode, test_timeout, global_timeout): + def _generate_result(self, s3_bucket: str, suite: str, return_code: int, report: dict, runtime_args: list): + """ + Generates the result object from the pertinent runtime meta-data and sequence report. + + @param The generated result object. + """ + + result = {} + result["src_commit"] = self._src_commit + result["dst_commit"] = self._dst_commit + result["commit_distance"] = self._commit_distance + result["src_branch"] = self._src_branch + result["dst_branch"] = self._dst_branch + result["suite"] = suite + result["use_test_impact_analysis"] = self._use_test_impact_analysis + result["source_of_truth_branch"] = self._source_of_truth_branch + result["is_source_of_truth_branch"] = self._is_source_of_truth_branch + result["has_change_list"] = self._has_change_list + result["has_historic_data"] = self._has_historic_data + result["s3_bucket"] = s3_bucket + result["runtime_args"] = runtime_args + result["return_code"] = return_code + result["report"] = report + result["change_list"] = self._change_list + return result + + def run(self, commit: str, src_branch: str, dst_branch: str, s3_bucket: str, suite: str, test_failure_policy: str, safe_mode: bool, test_timeout: int, global_timeout: int): + """ + Determins the type of sequence to run based on the commit, source branch and test branch before running the + sequence with the specified values. + + @param commit: The commit hash of the changes to run test impact analysis on. + @param src_branch: If not equal to dst_branch, the branch that is being built. + @param dst_branch: If not equal to src_branch, the destination branch for the PR being built. + @param s3_bucket: Location of S3 bucket to use for persistent storage, otherwise local disk storage will be used. + @param suite: Test suite to run. + @param test_failure_policy: Test failure policy for regular and test impact sequences (ignored when seeding). + @param safe_mode: Flag to run impact analysis tests in safe mode (ignored when seeding). + @param test_timeout: Maximum run time (in seconds) of any test target before being terminated (unlimited if None). + @param global_timeout: Maximum run time of the sequence before being terminated (unlimited if None). + """ + args = [] - seed_sequence_test_failure_policy = "continue" - # Suite - args.append(f"--suite={suite}") - print(f"Test suite is set to '{suite}'.") - # Timeouts - if test_timeout != None: - args.append(f"--ttimeout={test_timeout}") - print(f"Test target timeout is set to {test_timeout} seconds.") - if global_timeout != None: - args.append(f"--gtimeout={global_timeout}") - print(f"Global sequence timeout is set to {test_timeout} seconds.") - if self.__use_test_impact_analysis: - print("Test impact analysis is enabled.") - # Seed sequences - if self.__is_seeding: + persistent_storage = None + self._has_historic_data = False + self._change_list = {} + self._change_list["createdFiles"] = [] + self._change_list["updatedFiles"] = [] + self._change_list["deletedFiles"] = [] + + # Branches + self._src_branch = src_branch + self._dst_branch = dst_branch + logger.info(f"Src branch: '{self._src_branch}'.") + logger.info(f"Dst branch: '{self._dst_branch}'.") + + # Source of truth (the branch from which the coverage data will be stored/retrieved from) + if not self._dst_branch or self._src_branch == self._dst_branch: + # Branch builds are their own source of truth and will update the coverage data for the source of truth after any instrumented sequences complete + self._is_source_of_truth_branch = True + self._source_of_truth_branch = self._src_branch + else: + # PR builds use their destination as the source of truth and never update the coverage data for the source of truth + self._is_source_of_truth_branch = False + self._source_of_truth_branch = self._dst_branch + + logger.info(f"Source of truth branch: '{self._source_of_truth_branch}'.") + logger.info(f"Is source of truth branch: '{self._is_source_of_truth_branch}'.") + + # Commit + self._dst_commit = commit + logger.info(f"Commit: '{self._dst_commit}'.") + self._src_commit = None + self._commit_distance = None + + # Generate a unique ID to be used as part of the file name for required runtime dynamic artifacts. + instance_id = uuid.uuid4().hex + + if self._use_test_impact_analysis: + logger.info("Test impact analysis is enabled.") + try: + # Persistent storage location + if s3_bucket: + persistent_storage = PersistentStorageS3(self._config, suite, s3_bucket, self._source_of_truth_branch) + else: + persistent_storage = PersistentStorageLocal(self._config, suite) + except SystemError as e: + logger.warning(f"The persistent storage encountered an irrecoverable error, test impact analysis will be disabled: '{e}'") + persistent_storage = None + + if persistent_storage: + if persistent_storage.has_historic_data: + logger.info("Historic data found.") + self._attempt_to_generate_change_list(persistent_storage.last_commit_hash, instance_id) + else: + logger.info("No historic data found.") + # Sequence type - args.append("--sequence=seed") - print("Sequence type is set to 'seed'.") - # Test failure policy - args.append(f"--fpolicy={seed_sequence_test_failure_policy}") - print(f"Test failure policy is set to '{seed_sequence_test_failure_policy}'.") - # Impact analysis sequences - else: - if self.__has_change_list: - # Change list - args.append(f"--changelist={self.__change_list_path}") - print(f"Change list is set to '{self.__change_list_path}'.") - # Sequence type - args.append("--sequence=tianowrite") - print("Sequence type is set to 'tianowrite'.") - # Integrity failure policy - args.append("--ipolicy=continue") - print("Integration failure policy is set to 'continue'.") + if self._has_change_list: + if self._is_source_of_truth_branch: + # Use TIA sequence (instrumented subset of tests) for coverage updating branches so we can update the coverage data with the generated coverage + sequence_type = "tia" + else: + # Use TIA no-write sequence (regular subset of tests) for non coverage updating branche + sequence_type = "tianowrite" + # Ignore integrity failures for non coverage updating branches as our confidence in the + args.append("--ipolicy=continue") + logger.info("Integration failure policy is set to 'continue'.") # Safe mode if safe_mode: args.append("--safemode=on") - print("Safe mode set to 'on'.") + logger.info("Safe mode set to 'on'.") else: args.append("--safemode=off") - print("Safe mode set to 'off'.") + logger.info("Safe mode set to 'off'.") + # Change list + args.append(f"--changelist={self._change_list_path}") + logger.info(f"Change list is set to '{self._change_list_path}'.") else: - args.append("--sequence=regular") - print("Sequence type is set to 'regular'.") - # Test failure policy - args.append(f"--fpolicy={test_failure_policy}") - print(f"Test failure policy is set to '{test_failure_policy}'.") - else: - print("Test impact analysis is disabled.") - # Sequence type - args.append("--sequence=regular") - print("Sequence type is set to 'regular'.") - # Seeding job - if self.__is_seeding: - # Test failure policy - args.append(f"--fpolicy={seed_sequence_test_failure_policy}") - print(f"Test failure policy is set to '{seed_sequence_test_failure_policy}'.") - # Non seeding job + if self._is_source_of_truth_branch: + # Use seed sequence (instrumented all tests) for coverage updating branches so we can generate the coverage bed for future sequences + sequence_type = "seed" + # We always continue after test failures when seeding to ensure we capture the coverage for all test targets + test_failure_policy = "continue" + else: + # Use regular sequence (regular all tests) for non coverage updating branches as we have no coverage to use nor coverage to update + sequence_type = "regular" + # Ignore integrity failures for non coverage updating branches as our confidence in the + args.append("--ipolicy=continue") + logger.info("Integration failure policy is set to 'continue'.") else: - # Test failure policy - args.append(f"--fpolicy={test_failure_policy}") - print(f"Test failure policy is set to '{test_failure_policy}'.") - - print("Args: ", end='') - print(*args) - result = subprocess.run([self.__tiaf_bin] + args) + # Use regular sequence (regular all tests) when the persistent storage fails to avoid wasting time generating seed data that will not be preserved + sequence_type = "regular" + else: + # Use regular sequence (regular all tests) when test impact analysis is disabled + sequence_type = "regular" + args.append(f"--sequence={sequence_type}") + logger.info(f"Sequence type is set to '{sequence_type}'.") + + # Test failure policy + args.append(f"--fpolicy={test_failure_policy}") + logger.info(f"Test failure policy is set to '{test_failure_policy}'.") + + # Sequence report + report_file = pathlib.PurePath(self._temp_workspace).joinpath(f"report.{instance_id}.json") + args.append(f"--report={report_file}") + logger.info(f"Sequence report file is set to '{report_file}'.") + + # Suite + args.append(f"--suite={suite}") + logger.info(f"Test suite is set to '{suite}'.") + + # Timeouts + if test_timeout is not None: + args.append(f"--ttimeout={test_timeout}") + logger.info(f"Test target timeout is set to {test_timeout} seconds.") + if global_timeout is not None: + args.append(f"--gtimeout={global_timeout}") + logger.info(f"Global sequence timeout is set to {test_timeout} seconds.") + + # Run sequence + unpacked_args = " ".join(args) + logger.info(f"Args: {unpacked_args}") + runtime_result = subprocess.run([str(self._tiaf_bin)] + args) + report = None + # If the sequence completed (with or without failures) we will update the historical meta-data - if result.returncode == 0 or result.returncode == 7: - print("Test impact analysis runtime returned successfully.") - if self.__is_seeding: - print("Writing historical meta-data...") - self.__write_last_run_hash(self.__dst_commit) - print("Complete!") + if runtime_result.returncode == 0 or runtime_result.returncode == 7: + logger.info("Test impact analysis runtime returned successfully.") + if self._is_source_of_truth_branch and persistent_storage is not None: + persistent_storage.update_and_store_historic_data(self._dst_commit) + with open(report_file) as json_file: + report = json.load(json_file) else: - print(f"The test impact analysis runtime returned with error: '{result.returncode}'.") - return result.returncode - \ No newline at end of file + logger.error(f"The test impact analysis runtime returned with error: '{runtime_result.returncode}'.") + + return self._generate_result(s3_bucket, suite, runtime_result.returncode, report, args) \ No newline at end of file diff --git a/scripts/build/TestImpactAnalysis/tiaf_driver.py b/scripts/build/TestImpactAnalysis/tiaf_driver.py index 77fc8c1fc2..5ad16abaa0 100644 --- a/scripts/build/TestImpactAnalysis/tiaf_driver.py +++ b/scripts/build/TestImpactAnalysis/tiaf_driver.py @@ -7,60 +7,138 @@ # import argparse +import mars_utils +import sys +import pathlib +import traceback from tiaf import TestImpact +from tiaf_logger import get_logger -import sys -import os -import datetime -import json -import socket +logger = get_logger(__file__) def parse_args(): - def file_path(value): - if os.path.isfile(value): + def valid_file_path(value): + if pathlib.Path(value).is_file(): return value else: raise FileNotFoundError(value) - def timout_type(value): + def valid_timout_type(value): value = int(value) if value <= 0: raise ValueError("Timer values must be positive integers") return value - def test_failure_policy(value): + def valid_test_failure_policy(value): if value == "continue" or value == "abort" or value == "ignore": return value else: raise ValueError("Test failure policy must be 'abort', 'continue' or 'ignore'") parser = argparse.ArgumentParser() - parser.add_argument('--config', dest="config", type=file_path, help="Path to the test impact analysis framework configuration file", required=True) - parser.add_argument('--src-branch', dest="src_branch", help="The branch that is being build", required=True) - parser.add_argument('--dst-branch', dest="dst_branch", help="For PR builds, the destination branch to be merged to, otherwise empty") - parser.add_argument('--seeding-branches', dest="seeding_branches", type=lambda arg: arg.split(','), help="Comma separated branches that seeding will occur on", required=True) - parser.add_argument('--pipeline', dest="pipeline", help="Pipeline the test impact analysis framework is running on", required=True) - parser.add_argument('--seeding-pipelines', dest="seeding_pipelines", type=lambda arg: arg.split(','), help="Comma separated pipeline that seeding will occur on", required=True) - parser.add_argument('--dest-commit', dest="dst_commit", help="Commit to run test impact analysis on (ignored when seeding)", required=True) - parser.add_argument('--suite', dest="suite", help="Test suite to run", required=True) - parser.add_argument('--test-failure-policy', dest="test_failure_policy", type=test_failure_policy, help="Test failure policy for regular and test impact sequences (ignored when seeding)", required=True) - parser.add_argument('--safeMode', dest="safe_mode", action='store_true', help="Run impact analysis tests in safe mode (ignored when seeding)") - parser.add_argument('--testTimeout', dest="test_timeout", type=timout_type, help="Maximum run time (in seconds) of any test target before being terminated", required=False) - parser.add_argument('--globalTimeout', dest="global_timeout", type=timout_type, help="Maximum run time of the sequence before being terminated", required=False) - parser.set_defaults(test_timeout=None) - parser.set_defaults(global_timeout=None) + + # Configuration file path + parser.add_argument( + '--config', + type=valid_file_path, + help="Path to the test impact analysis framework configuration file", + required=True + ) + + # Source branch + parser.add_argument( + '--src-branch', + help="Branch that is being built", + required=True + ) + + # Destination branch + parser.add_argument( + '--dst-branch', + help="For PR builds, the destination branch to be merged to, otherwise empty", + required=False + ) + + # Commit hash + parser.add_argument( + '--commit', + help="Commit that is being built", + required=True + ) + + # S3 bucket + parser.add_argument( + '--s3-bucket', + help="Location of S3 bucket to use for persistent storage, otherwise local disk storage will be used", + required=False + ) + + # MARS index prefix + parser.add_argument( + '--mars-index-prefix', + help="Index prefix to use for MARS, otherwise no data will be tramsmitted to MARS", + required=False + ) + + # Test suite + parser.add_argument( + '--suite', + help="Test suite to run", + required=True + ) + + # Test failure policy + parser.add_argument( + '--test-failure-policy', + type=valid_test_failure_policy, + help="Test failure policy for regular and test impact sequences (ignored when seeding)", + required=True + ) + + # Safe mode + parser.add_argument( + '--safe-mode', + action='store_true', + help="Run impact analysis tests in safe mode (ignored when seeding)", + required=False + ) + + # Test timeout + parser.add_argument( + '--test-timeout', + type=valid_timout_type, + help="Maximum run time (in seconds) of any test target before being terminated", + required=False + ) + + # Global timeout + parser.add_argument( + '--global-timeout', + type=valid_timout_type, + help="Maximum run time of the sequence before being terminated", + required=False + ) + args = parser.parse_args() return args if __name__ == "__main__": + try: args = parse_args() - tiaf = TestImpact(args.config, args.dst_commit, args.src_branch, args.dst_branch, args.pipeline, args.seeding_branches, args.seeding_pipelines) - return_code = tiaf.run(args.suite, args.test_failure_policy, args.safe_mode, args.test_timeout, args.global_timeout) + tiaf = TestImpact(args.config) + tiaf_result = tiaf.run(args.commit, args.src_branch, args.dst_branch, args.s3_bucket, args.suite, args.test_failure_policy, args.safe_mode, args.test_timeout, args.global_timeout) + + if args.mars_index_prefix: + logger.info("Transmitting report to MARS...") + mars_utils.transmit_report_to_mars(args.mars_index_prefix, tiaf_result, sys.argv) + + logger.info("Complete!") # Non-gating will be removed from this script and handled at the job level in SPEC-7413 - #sys.exit(return_code) + #sys.exit(result.return_code) sys.exit(0) except Exception as e: # Non-gating will be removed from this script and handled at the job level in SPEC-7413 - print(f"Exception caught by TIAF driver: {e}") + logger.error(f"Exception caught by TIAF driver: '{e}'.") + traceback.print_exc() diff --git a/scripts/build/TestImpactAnalysis/tiaf_logger.py b/scripts/build/TestImpactAnalysis/tiaf_logger.py new file mode 100644 index 0000000000..0acb9349d4 --- /dev/null +++ b/scripts/build/TestImpactAnalysis/tiaf_logger.py @@ -0,0 +1,20 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import logging +import sys + +def get_logger(name: str): + logger = logging.getLogger(name) + logger.setLevel(logging.INFO) + handler = logging.StreamHandler(sys.stdout) + handler.setLevel(logging.DEBUG) + formatter = logging.Formatter('[%(asctime)s][TIAF][%(levelname)s] %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + return logger \ No newline at end of file diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py new file mode 100644 index 0000000000..18ea25091f --- /dev/null +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage.py @@ -0,0 +1,118 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import json +import pathlib +from abc import ABC, abstractmethod +from tiaf_logger import get_logger + +logger = get_logger(__file__) + +# Abstraction for the persistent storage required by TIAF to store and retrieve the branch coverage data and other meta-data +class PersistentStorage(ABC): + def __init__(self, config: dict, suite: str): + """ + Initializes the persistent storage into a state for which there is no historic data available. + + @param config: The runtime configuration to obtain the data file paths from. + @param suite: The test suite for which the historic data will be obtained for. + """ + + # Work on the assumption that there is no historic meta-data (a valid state to be in, should none exist) + self._last_commit_hash = None + self._has_historic_data = False + + try: + # The runtime expects the coverage data to be in the location specified in the config file (unless overridden with + # the --datafile command line argument, which the TIAF scripts do not do) + self._active_workspace = pathlib.Path(config["workspace"]["active"]["root"]) + unpacked_coverage_data_file = config["workspace"]["active"]["relative_paths"]["test_impact_data_files"][suite] + except KeyError as e: + raise SystemError(f"The config does not contain the key {str(e)}.") + + self._unpacked_coverage_data_file = self._active_workspace.joinpath(unpacked_coverage_data_file) + + def _unpack_historic_data(self, historic_data_json: str): + """ + Unpacks the historic data into the appropriate memory and disk locations. + + @param historic_data_json: The historic data in JSON format. + """ + + self._has_historic_data = False + + try: + historic_data = json.loads(historic_data_json) + self._last_commit_hash = historic_data["last_commit_hash"] + + # Create the active workspace directory where the coverage data file will be placed and unpack the coverage data so + # it is accessible by the runtime + self._active_workspace.mkdir(exist_ok=True) + with open(self._unpacked_coverage_data_file, "w", newline='\n') as coverage_data: + coverage_data.write(historic_data["coverage_data"]) + + self._has_historic_data = True + except json.JSONDecodeError: + logger.error("The historic data does not contain valid JSON.") + except KeyError as e: + logger.error(f"The historic data does not contain the key {str(e)}.") + except EnvironmentError as e: + logger.error(f"There was a problem the coverage data file '{self._unpacked_coverage_data_file}': '{e}'.") + + def _pack_historic_data(self, last_commit_hash: str): + """ + Packs the current historic data into a JSON file for serializing. + + @param last_commit_hash: The commit hash to associate the coverage data (and any other meta data) with. + @return: The packed historic data in JSON format. + """ + + try: + # Attempt to read the existing coverage data + if self._unpacked_coverage_data_file.is_file(): + with open(self._unpacked_coverage_data_file, "r") as coverage_data: + historic_data = {"last_commit_hash": last_commit_hash, "coverage_data": coverage_data.read()} + return json.dumps(historic_data) + else: + logger.info(f"No coverage data exists at location '{self._unpacked_coverage_data_file}'.") + except EnvironmentError as e: + logger.error(f"There was a problem the coverage data file '{self._unpacked_coverage_data_file}': '{e}'.") + except TypeError: + logger.error("The historic data could not be serialized to valid JSON.") + + return None + + @abstractmethod + def _store_historic_data(self, historic_data_json: str): + """ + Stores the historic data in the designated persistent storage location. + + @param historic_data_json: The historic data (in JSON format) to be stored in persistent storage. + """ + pass + + def update_and_store_historic_data(self, last_commit_hash: str): + """ + Updates the historic data and stores it in the designated persistent storage location. + + @param last_commit_hash: The commit hash to associate the coverage data (and any other meta data) with. + """ + + historic_data_json = self._pack_historic_data(last_commit_hash) + if historic_data_json: + self._store_historic_data(historic_data_json) + else: + logger.info("The historic data could not be successfully stored.") + + @property + def has_historic_data(self): + return self._has_historic_data + + @property + def last_commit_hash(self): + return self._last_commit_hash \ No newline at end of file diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py new file mode 100644 index 0000000000..ba9b58fbf3 --- /dev/null +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_local.py @@ -0,0 +1,56 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import pathlib +import logging +from tiaf_persistent_storage import PersistentStorage +from tiaf_logger import get_logger + +logger = get_logger(__file__) + +# Implementation of local persistent storage +class PersistentStorageLocal(PersistentStorage): + def __init__(self, config: str, suite: str): + """ + Initializes the persistent storage with any local historic data available. + + @param config: The runtime config file to obtain the data file paths from. + @param suite: The test suite for which the historic data will be obtained for. + """ + + super().__init__(config, suite) + try: + # Attempt to obtain the local persistent data location specified in the runtime config file + self._historic_workspace = pathlib.Path(config["workspace"]["historic"]["root"]) + historic_data_file = pathlib.Path(config["workspace"]["historic"]["relative_paths"]["data"]) + + # Attempt to unpack the local historic data file + self._historic_data_file = self._historic_workspace.joinpath(historic_data_file) + if self._historic_data_file.is_file(): + with open(self._historic_data_file, "r") as historic_data_raw: + historic_data_json = historic_data_raw.read() + self._unpack_historic_data(historic_data_json) + + except KeyError as e: + raise SystemError(f"The config does not contain the key {str(e)}.") + except EnvironmentError as e: + raise SystemError(f"There was a problem the historic data file '{self._historic_data_file}': '{e}'.") + + def _store_historic_data(self, historic_data_json: str): + """ + Stores then historical data in historic workspace location specified in the runtime config file. + + @param historic_data_json: The historic data (in JSON format) to be stored in persistent storage. + """ + + try: + self._historic_workspace.mkdir(exist_ok=True) + with open(self._historic_data_file, "w") as historic_data_file: + historic_data_file.write(historic_data_json) + except EnvironmentError as e: + logger.error(f"There was a problem the historic data file '{self._historic_data_file}': '{e}'.") \ No newline at end of file diff --git a/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py new file mode 100644 index 0000000000..75c4bc93d5 --- /dev/null +++ b/scripts/build/TestImpactAnalysis/tiaf_persistent_storage_s3.py @@ -0,0 +1,87 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +import boto3 +import botocore.exceptions +import zlib +import logging +from io import BytesIO +from tiaf_persistent_storage import PersistentStorage +from tiaf_logger import get_logger + +logger = get_logger(__file__) + +# Implementation of s3 bucket persistent storage +class PersistentStorageS3(PersistentStorage): + def __init__(self, config: dict, suite: str, s3_bucket: str, branch: str): + """ + Initializes the persistent storage with the specified s3 bucket. + + @param config: The runtime config file to obtain the data file paths from. + @param suite: The test suite for which the historic data will be obtained for. + @param s3_bucket: The s3 bucket to use for storing nd retrieving historic data. + """ + + super().__init__(config, suite) + + try: + # We store the historic data as compressed JSON + object_extension = "json.zip" + + # historic_data.json.zip is the file containing the coverage and meta-data of the last TIAF sequence run + historic_data_file = f"historic_data.{object_extension}" + + # The location of the data is in the form / so the build config of each branch gets its own historic data + self._dir = f'{branch}/{config["meta"]["build_config"]}' + self._historic_data_key = f'{self._dir}/{historic_data_file}' + + logger.info(f"Attempting to retrieve historic data for branch '{branch}' at location '{self._historic_data_key}' on bucket '{s3_bucket}'...") + self._s3 = boto3.resource("s3") + self._bucket = self._s3.Bucket(s3_bucket) + + # There is only one historic_data.json.zip in the specified location + for object in self._bucket.objects.filter(Prefix=self._historic_data_key): + logger.info(f"Historic data found for branch '{branch}'.") + + # Archive the existing object with the name of the existing last commit hash + archive_key = f"{self._dir}/archive/{self._last_commit_hash}.{object_extension}" + logger.info(f"Archiving existing historic data to {archive_key}...") + self._bucket.copy({"Bucket": self._bucket.name, "Key": self._historic_data_key}, archive_key) + + # Decode the historic data object into raw bytes + response = object.get() + file_stream = response['Body'] + + # Decompress and unpack the zipped historic data JSON + historic_data_json = zlib.decompress(file_stream.read()).decode('UTF-8') + self._unpack_historic_data(historic_data_json) + + return + except KeyError as e: + raise SystemError(f"The config does not contain the key {str(e)}.") + except botocore.exceptions.BotoCoreError as e: + raise SystemError(f"There was a problem with the s3 bucket: {e}") + except botocore.exceptions.ClientError as e: + raise SystemError(f"There was a problem with the s3 client: {e}") + + def _store_historic_data(self, historic_data_json: str): + """ + Stores then historical data in specified s3 bucket at the location //historical_data.json.zip. + + @param historic_data_json: The historic data (in JSON format) to be stored in persistent storage. + """ + + try: + data = BytesIO(zlib.compress(bytes(historic_data_json, "UTF-8"))) + logger.info(f"Uploading historic data to location '{self._historic_data_key}'...") + self._bucket.upload_fileobj(data, self._historic_data_key) + logger.info("Upload complete.") + except botocore.exceptions.BotoCoreError as e: + logger.error(f"There was a problem with the s3 bucket: {e}") + except botocore.exceptions.ClientError as e: + logger.error(f"There was a problem with the s3 client: {e}") \ No newline at end of file diff --git a/scripts/build/tools/upload_to_s3.py b/scripts/build/tools/upload_to_s3.py index 57ac9c4e76..b80170df52 100755 --- a/scripts/build/tools/upload_to_s3.py +++ b/scripts/build/tools/upload_to_s3.py @@ -25,6 +25,7 @@ import re import json import time import boto3 +import pathlib from optparse import OptionParser @@ -97,8 +98,15 @@ def get_files_to_upload(base_dir, regex, search_subdirectories): return regex_files_to_upload -def s3_upload_file(client, file, bucket, key_prefix=None, extra_args=None, max_retry=1): - key = file if key_prefix is None else f'{key_prefix}/{file}' +def s3_upload_file(client, base_dir, file, bucket, key_prefix=None, extra_args=None, max_retry=1): + try: + # replicate the local folder structure relative to search root in the bucket path + s3_file_path = pathlib.Path(file).relative_to(base_dir).as_posix() + except ValueError as err: + print(f'Unexpected file error: {err}') + return False + + key = s3_file_path if key_prefix is None else f'{key_prefix}/{s3_file_path}' error_message = None for x in range(max_retry): @@ -140,7 +148,7 @@ if __name__ == "__main__": failure = [] success = [] for file in files_to_upload: - if not s3_upload_file(client, file, options.bucket, options.key_prefix, extra_args, 2): + if not s3_upload_file(client, options.base_dir, file, options.bucket, options.key_prefix, extra_args, 2): failure.append(file) else: success.append(file) diff --git a/scripts/o3de/o3de/engine_template.py b/scripts/o3de/o3de/engine_template.py index 4f026e86d8..802641bd3a 100755 --- a/scripts/o3de/o3de/engine_template.py +++ b/scripts/o3de/o3de/engine_template.py @@ -1299,6 +1299,7 @@ def create_project(project_path: pathlib.Path, keep_license_text: bool = False, replace: list = None, force: bool = False, + no_register: bool = False, system_component_class_id: str = None, editor_system_component_class_id: str = None, module_id: str = None) -> int: @@ -1657,9 +1658,10 @@ def create_project(project_path: pathlib.Path, d.write('# {END_LICENSE}\n') - # Register the project with the global o3de_manifest.json and set the project.json "engine" field to match the + # Register the project with the either o3de_manifest.json or engine.json + # and set the project.json "engine" field to match the # engine.json "engine_name" field - return register.register(project_path=project_path) + return register.register(project_path=project_path) if not no_register else 0 def create_gem(gem_path: pathlib.Path, @@ -1676,6 +1678,7 @@ def create_gem(gem_path: pathlib.Path, keep_license_text: bool = False, replace: list = None, force: bool = False, + no_register: bool = False, system_component_class_id: str = None, editor_system_component_class_id: str = None, module_id: str = None) -> int: @@ -2035,7 +2038,8 @@ def create_gem(gem_path: pathlib.Path, d.write('#\n') d.write('# SPDX-License-Identifier: Apache-2.0 OR MIT\n') d.write('# {END_LICENSE}\n') - return 0 + # Register the gem with the either o3de_manifest.json, engine.json or project.json based on the gem path + return register.register(gem_path=gem_path) if not no_register else 0 def _run_create_template(args: argparse) -> int: @@ -2086,6 +2090,7 @@ def _run_create_project(args: argparse) -> int: args.keep_license_text, args.replace, args.force, + args.no_register, args.system_component_class_id, args.editor_system_component_class_id, args.module_id) @@ -2106,6 +2111,7 @@ def _run_create_gem(args: argparse) -> int: args.keep_license_text, args.replace, args.force, + args.no_register, args.system_component_class_id, args.editor_system_component_class_id, args.module_id) @@ -2370,6 +2376,9 @@ def add_args(subparsers) -> None: ' uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') create_project_subparser.add_argument('-f', '--force', action='store_true', default=False, help='Copies over instantiated template directory even if it exist.') + create_project_subparser.add_argument('--no-register', action='store_true', default=False, + help='If the project template is instantiated successfully, it will not register the' + ' project with the global or engine manifest file.') create_project_subparser.set_defaults(func=_run_create_project) # creation of a gem from a template (like create from template but makes gem assumptions) @@ -2463,6 +2472,9 @@ def add_args(subparsers) -> None: ' default is a random uuid Ex. {b60c92eb-3139-454b-a917-a9d3c5819594}') create_gem_subparser.add_argument('-f', '--force', action='store_true', default=False, help='Copies over instantiated template directory even if it exist.') + create_gem_subparser.add_argument('--no-register', action='store_true', default=False, + help='If the gem template is instantiated successfully, it will not register the' + ' gem with the global, project or engine manifest file.') create_gem_subparser.set_defaults(func=_run_create_gem) diff --git a/scripts/o3de/o3de/register.py b/scripts/o3de/o3de/register.py index 7e182b5d2d..5822cc926c 100644 --- a/scripts/o3de/o3de/register.py +++ b/scripts/o3de/o3de/register.py @@ -285,14 +285,14 @@ def register_o3de_object_path(json_data: dict, manifest_data = None if engine_path: - manifest_data = manifest.get_engine_json_data(None, engine_path) + manifest_data = manifest.get_engine_json_data(engine_path=engine_path) if not manifest_data: logger.error(f'Cannot load engine.json data at path {engine_path}') return 1 save_path = engine_path / 'engine.json' elif project_path: - manifest_data = manifest.get_project_json_data(None, project_path) + manifest_data = manifest.get_project_json_data(project_path=project_path) if not manifest_data: logger.error(f'Cannot load project.json data at path {project_path}') return 1 @@ -367,6 +367,11 @@ def register_external_subdirectory(json_data: dict, :return An integer return code indicating whether registration or removal of the external subdirectory completed successfully """ + # If a project path or engine path has not been supplied auto detect which manifest to register the input path with + if not project_path and not engine_path: + project_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('project.json'), external_subdir_path) + if not project_path: + engine_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('engine.json'), external_subdir_path) return register_o3de_object_path(json_data, external_subdir_path, 'external_subdirectories', '', None, remove, engine_path, project_path) @@ -376,6 +381,11 @@ def register_gem_path(json_data: dict, remove: bool = False, engine_path: pathlib.Path = None, project_path: pathlib.Path = None) -> int: + # If a project path or engine path has not been supplied auto detect which manifest to register the input path with + if not project_path and not engine_path: + project_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('project.json'), gem_path) + if not project_path: + engine_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('engine.json'), gem_path) return register_o3de_object_path(json_data, gem_path, 'external_subdirectories', 'gem.json', validation.valid_o3de_gem_json, remove, engine_path, project_path) @@ -384,6 +394,11 @@ def register_project_path(json_data: dict, project_path: pathlib.Path, remove: bool = False, engine_path: pathlib.Path = None) -> int: + # If an engine path has not been supplied auto detect if the project should be register with the engine.json + # or the ~/.o3de/o3de_manifest.json + if not engine_path: + engine_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('engine.json'), project_path) + result = register_o3de_object_path(json_data, project_path, 'projects', 'project.json', validation.valid_o3de_project_json, remove, engine_path, None) @@ -419,6 +434,11 @@ def register_template_path(json_data: dict, template_path: pathlib.Path, remove: bool = False, engine_path: pathlib.Path = None) -> int: + # If a project path or engine path has not been supplied auto detect which manifest to register the input path + if not project_path and not engine_path: + project_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('project.json'), template_path) + if not project_path: + engine_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('engine.json'), template_path) return register_o3de_object_path(json_data, template_path, 'templates', 'template.json', validation.valid_o3de_template_json, remove, engine_path, None) @@ -427,6 +447,11 @@ def register_restricted_path(json_data: dict, restricted_path: pathlib.Path, remove: bool = False, engine_path: pathlib.Path = None) -> int: + # If a project path or engine path has not been supplied auto detect which manifest to register the input path + if not project_path and not engine_path: + project_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('project.json'), restricted_path) + if not project_path: + engine_path = utils.find_ancestor_dir_containing_file(pathlib.PurePath('engine.json'), restricted_path) return register_o3de_object_path(json_data, restricted_path, 'restricted', 'restricted.json', validation.valid_o3de_restricted_json, remove, engine_path, None) diff --git a/scripts/o3de/o3de/utils.py b/scripts/o3de/o3de/utils.py index 629a473b8a..18f80584cc 100755 --- a/scripts/o3de/o3de/utils.py +++ b/scripts/o3de/o3de/utils.py @@ -8,7 +8,7 @@ """ This file contains utility functions """ - +import sys import uuid import pathlib import shutil @@ -123,4 +123,51 @@ def download_zip_file(parsed_uri, download_zip_path: pathlib.Path) -> int: download_zip_path.unlink() return 1 - return 0 \ No newline at end of file + return 0 + + +def find_ancestor_file(target_file_name: pathlib.PurePath, start_path: pathlib.Path, + max_scan_up_range: int=0) -> pathlib.Path or None: + """ + Find a file with the given name in the ancestor directories by walking up the starting path until the file is found. + + :param target_file_name: Name of the file to find. + :param start_path: path to start looking for the file. + :param max_scan_up_range: maximum number of directories to scan upwards when searching for target file + if the value is 0, then there is no max + :return: Path to the file or None if not found. + """ + current_path = pathlib.Path(start_path) + candidate_path = current_path / target_file_name + + max_scan_up_range = max_scan_up_range if max_scan_up_range else sys.maxsize + + # Limit the number of directories to traverse, to avoid infinite loop in path cycles + for _ in range(max_scan_up_range): + if candidate_path.exists(): + # Found the file we wanted + break + + parent_path = current_path.parent + if parent_path == current_path: + # Only true when we are at the directory root, can't keep searching + break + candidate_path = parent_path / target_file_name + current_path = parent_path + + return candidate_path if candidate_path.exists() else None + +def find_ancestor_dir_containing_file(target_file_name: pathlib.PurePath, start_path: pathlib.Path, + max_scan_up_range: int=0) -> pathlib.Path or None: + """ + Find nearest ancestor directory that contains the file with the given name by walking up + from the starting path. + + :param target_file_name: Name of the file to find. + :param start_path: path to start looking for the file. + :param max_scan_up_range: maximum number of directories to scan upwards when searching for target file + if the value is 0, then there is no max + :return: Path to the directory containing file or None if not found. + """ + ancestor_file = find_ancestor_file(target_file_name, start_path, max_scan_up_range) + return ancestor_file.parent if ancestor_file else None diff --git a/scripts/o3de/tests/unit_test_enable_gem.py b/scripts/o3de/tests/unit_test_enable_gem.py index 9165fd5d08..c765f74731 100644 --- a/scripts/o3de/tests/unit_test_enable_gem.py +++ b/scripts/o3de/tests/unit_test_enable_gem.py @@ -124,7 +124,7 @@ class TestEnableGemCommand: return json.loads(TEST_O3DE_MANIFEST_JSON_PAYLOAD) return None - def get_project_json_data(json_data: pathlib.Path, project_path: pathlib.Path): + def get_project_json_data(project_path: pathlib.Path): return self.enable_gem.project_data def get_gem_json_data(gem_path: pathlib.Path, project_path: pathlib.Path): diff --git a/scripts/o3de/tests/unit_test_engine_template.py b/scripts/o3de/tests/unit_test_engine_template.py index 25c418b0ff..16ac24d74c 100755 --- a/scripts/o3de/tests/unit_test_engine_template.py +++ b/scripts/o3de/tests/unit_test_engine_template.py @@ -263,6 +263,7 @@ class TestCreateTemplate: s.write(templated_contents) template_dest_path = engine_root / instantiated_name + # Skip registeration in test with patch('uuid.uuid4', return_value=uuid.uuid5(uuid.NAMESPACE_DNS, instantiated_name)) as uuid4_mock: result = create_from_template_func(template_dest_path, template_path=template_default_folder, force=True, keep_license_text=keep_license_text, **create_from_template_kwargs) @@ -345,7 +346,7 @@ class TestCreateTemplate: template_json_contents = json.dumps(template_json_dict, indent=4) self.instantiate_template_wrapper(tmpdir, engine_template.create_project, 'TestProject', concrete_contents, templated_contents, keep_license_text, force, expect_failure, - template_json_contents, template_file_map, project_name='TestProject') + template_json_contents, template_file_map, project_name='TestProject', no_register=True) @pytest.mark.parametrize( @@ -379,6 +380,8 @@ class TestCreateTemplate: "isTemplated": True, "isOptional": False }) + #Convert dict back to string + template_json_contents = json.dumps(template_json_dict, indent=4) self.instantiate_template_wrapper(tmpdir, engine_template.create_gem, 'TestGem', concrete_contents, templated_contents, keep_license_text, force, expect_failure, - template_json_contents, gem_name='TestGem') + template_json_contents, template_file_map, gem_name='TestGem', no_register=True) diff --git a/scripts/o3de/tests/unit_test_register.py b/scripts/o3de/tests/unit_test_register.py index 075eef5079..36139c0afa 100644 --- a/scripts/o3de/tests/unit_test_register.py +++ b/scripts/o3de/tests/unit_test_register.py @@ -112,3 +112,139 @@ class TestRegisterThisEngine: result = register._run_register(args) assert result == expected_result + +TEST_GEM_JSON_PAYLOAD = ''' +{ + "gem_name": "TestGem", + "display_name": "TestGem", + "license": "What license TestGem uses goes here: i.e. https://opensource.org/licenses/MIT", + "origin": "The primary repo for TestGem goes here: i.e. http://www.mydomain.com", + "type": "Code", + "summary": "A short description of TestGem.", + "canonical_tags": [ + "Gem" + ], + "user_tags": [ + "TestGem" + ], + "icon_path": "preview.png", + "requirements": "" +} +''' + +TEST_PROJECT_JSON_PAYLOAD = ''' +{ + "project_name": "TestProject", + "engine": "o3de", + "external_subdirectories": [] +} +''' + +TEST_ENGINE_JSON_PAYLOAD = ''' +{ + "engine_name": "o3de", + "external_subdirectories": [], + "projects": [], + "templates": [] +} +''' + +TEST_O3DE_MANIFEST_JSON_PAYLOAD = ''' +{ + "o3de_manifest_name": "testuser", + "origin": "C:/Users/testuser/.o3de", + "default_engines_folder": "C:/Users/testuser/.o3de/Engines", + "default_projects_folder": "C:/Users/testuser/.o3de/Projects", + "default_gems_folder": "C:/Users/testuser/.o3de/Gems", + "default_templates_folder": "C:/Users/testuser/.o3de/Templates", + "default_restricted_folder": "C:/Users/testuser/.o3de/Restricted", + "default_third_party_folder": "C:/Users/testuser/.o3de/3rdParty", + "projects": [], + "external_subdirectories": [], + "templates": [], + "restricted": [], + "repos": [], + "engines": [], + "engines_path": {} +} +''' +@pytest.fixture(scope='class') +def init_register_gem_data(request): + request.cls.o3de_manifest_data = json.loads(TEST_O3DE_MANIFEST_JSON_PAYLOAD) + request.cls.project_data = json.loads(TEST_PROJECT_JSON_PAYLOAD) + request.cls.engine_data = json.loads(TEST_ENGINE_JSON_PAYLOAD) + + +@pytest.mark.usefixtures('init_register_gem_data') +class TestRegisterGem: + engine_path = pathlib.PurePath('o3de') + project_path = pathlib.PurePath('TestProject') + + @staticmethod + def get_gem_json_data(gem_path: pathlib.Path = None): + return json.loads(TEST_GEM_JSON_PAYLOAD) + + @pytest.mark.parametrize("gem_path, expected_manifest_file, expected_result", [ + pytest.param(pathlib.PurePath('TestGem'), pathlib.PurePath('o3de_manifest.json'), 0), + pytest.param(project_path / 'TestGem', pathlib.PurePath('project.json'), 0), + pytest.param(engine_path / 'TestGem', pathlib.PurePath('engine.json'), 0), + ]) + def test_register_gem_auto_detects_manifest_update(self, gem_path, expected_manifest_file,expected_result): + + def save_o3de_manifest(manifest_data: dict, manifest_path: pathlib.Path = None) -> bool: + if manifest_path == TestRegisterGem.project_path / 'project.json': + self.project_data = manifest_data + elif manifest_path == TestRegisterGem.engine_path / 'engine.json': + self.engine_data = manifest_data + else: + self.o3de_manifest_data = manifest_data + return True + + def load_o3de_manifest(manifest_path: pathlib.Path = None) -> dict: + if manifest_path == TestRegisterGem.project_path: + return self.project_data + elif manifest_path == TestRegisterGem.engine_path: + return self.engine_data + return self.o3de_manifest_data + + def get_engine_json_data(engine_path: pathlib.Path = None): + return json.loads(TEST_ENGINE_JSON_PAYLOAD) + + def get_project_json_data(project_path: pathlib.Path = None): + return json.loads(TEST_PROJECT_JSON_PAYLOAD) + + def find_ancestor_dir(target_file_name: pathlib.PurePath, start_path: pathlib.Path): + try: + if target_file_name == pathlib.PurePath('project.json')\ + and start_path.relative_to(TestRegisterGem.project_path): + return TestRegisterGem.project_path + except ValueError: + pass + try: + if target_file_name == pathlib.PurePath('engine.json')\ + and start_path.relative_to(TestRegisterGem.engine_path): + return TestRegisterGem.engine_path + except ValueError: + pass + return None + + with patch('o3de.manifest.load_o3de_manifest', side_effect=load_o3de_manifest) as _1,\ + patch('o3de.manifest.save_o3de_manifest', side_effect=save_o3de_manifest) as _2,\ + patch('o3de.manifest.get_engine_json_data', side_effect=get_engine_json_data) as _3,\ + patch('o3de.manifest.get_project_json_data', side_effect=get_project_json_data) as _4,\ + patch('o3de.manifest.get_gem_json_data', side_effect=TestRegisterGem.get_gem_json_data) as _5,\ + patch('o3de.utils.find_ancestor_dir_containing_file', side_effect=find_ancestor_dir) as _6,\ + patch('pathlib.Path.is_dir', return_value=True) as _7,\ + patch('o3de.validation.valid_o3de_gem_json', return_value=True) as _8: + result = register.register(gem_path=gem_path) + assert result == expected_result + + if expected_manifest_file == pathlib.PurePath('o3de_manifest.json'): + assert gem_path in map(lambda subdir: pathlib.PurePath(subdir), + self.o3de_manifest_data.get('external_subdirectories', [])) + elif expected_manifest_file == pathlib.PurePath('project.json'): + assert gem_path in map(lambda subdir: pathlib.PurePath(TestRegisterGem.project_path) / subdir, + self.project_data.get('external_subdirectories', [])) + elif expected_manifest_file == pathlib.PurePath('engine.json'): + assert gem_path in map(lambda subdir: pathlib.PurePath(TestRegisterGem.engine_path) / subdir, + self.engine_data.get('external_subdirectories', []))

Event ID: 

Local Event Time: 

%.3f seconds

%.3f seconds

Event Trigger Time: 

%.3f seconds

%.3f seconds

Is Ranged Event: 

%s

%s

Global Weight: 

%.3f

%.3f

Local Weight: 

%.3f

%.3f

Emitted By: 

%s

Node Path: 

Child Nodes: 

%d

%zu

Recursive Children: 

%d

%zu